text string | label_name string | labels int64 |
|---|---|---|
](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [intclr](intclr) module"]
pub type INTCLR = crate::Reg<u32, _INTCLR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTCLR;
#[doc = "`write(|w| ..)` method takes [intc... | Rust | 0 |
null() => &"null",
BRANCH_TAG => {
let branch: *mut Branch = as_ptr(ptr).cast();
// Safety: check if it's a branch pointer.
unsafe { &*branch }
}
PROCESS_TAG => &"process",
READY_TO_RUN => &"marke... | Rust | 0 |
t == "top":
pocketmod_layout = POCKETMOD_LAYOUT_TOP
# Iterate through the imposition map to place each page
for panel_info in pocketmod_layout:
# Get the information for the current panel
if repeat:
source_page_idx = 0
else:
source_page_idx = panel_info["... | Python | 1 |
Decl::Typedef(..) => None,
})
.and_then(|cls| {
cls.static_methods.iter().rev().find_map(|meth| {
if meth.name.id() == method_name {
Some(meth.ty.clone())
} else {
None
}
... | Rust | 0 |
#!/usr/bin/env python3
"""
Test runner script for bookmark processor.
Provides various test execution options and reporting.
"""
import sys
import subprocess
import argparse
from pathlib import Path
def run_command(cmd, description):
"""Run a command and handle errors."""
print(f"🔄 {description}...")
r... | Python | 1 |
t_eq!(
(test.0 >> 24) & u32::MAX as u128,
0x3333_3333,
"field 3 mismatch"
);
assert_eq!(
(test.0 >> 56) & u64::MAX as u128,
0x4444_4444_4444_4444,
"field 4 mismatch"
);
assert_eq!((test.0 >> 120) & u8::MAX as u128, 0x55, "field 5 mismatch");
}
fn get_fiel... | Rust | 0 |
import os
from server.bean.base_model import BaseModel
from server.bean.inference_task.obj_inference_task import ObjInferenceTask
from server.bean.inference_task.obj_inference_task_audio import ObjInferenceTaskAudio
from server.bean.inference_task.obj_inference_task_compare_params import ObjInferenceTaskCompareParams
... | Python | 1 |
, points, level)
}
}
// This was originally developed and tested for pathops: see SkOpTypes.h
// returns true if (a <= b <= c) || (a >= b >= c)
fn between(a: f32, b: f32, c: f32) -> bool {
(a - b) * (c - b) <= 0.0
}
pub struct AutoConicToQuads {
pub points: [Point; 64],
pub len: u8, // the number of ... | Rust | 0 |
hape[0])
if V.shape[0] != A.shape[0]:
print(f"[Align] length mismatch: video={V.shape[0]}, audio={A.shape[0]} → clip to {T_tokens}")
V = V[:T_tokens]
A = A[:T_tokens]
dt = 1.0 / args.fps
print(f"[Ready] V {V.shape}, A {A.shape}, dt={dt:.3f}s")
# 인퍼런스-추출 한 번에 실행할 경우 위의 코드들은 주석처리 하시면... | Python | 1 |
)
def compute_dense_reward(self, obs: any, action: torch.Tensor, info: dict):
tcp_to_obj_dist = torch.linalg.norm(
self.obj.pose.p - self.agent.tcp.pose.p, axis=1
)
reaching_reward = 1 - torch.tanh(5 * tcp_to_obj_dist)
reward = reaching_reward
is_grasped = info[... | Python | 1 |
::Other,
"malformed HTTP response",
)),
}
}
// Note max_retries only retries ConnectionClosed. ConnectionClosed represents too many requests for IS.
async fn make_call<TUri, TRequest>(
client: &hyper::Client<super::Connector, hyper::Body>,
method: http::Method,
uri: TUri,
header... | Rust | 0 |
@pytest.mark.parametrize(('columns', 'num_nodes', 'peak_ram',
'input_shape_0', 'scope_1', 'output_shape_3'), [(['weight', 'bias',
'input_shape', 'output_shape', 'in_tensors', 'out_tensors',
'active_blocks', 'ram', 'scope'], 8, 262144, [1, 3, 32, 32], 'relu1', [
1, 32, 32, 32])])
def test_ram_profiling(c... | Python | 1 |
generate colors for all peripherals.
for peripheral in peripherals {
write!(
writer,
"\\pgfmathsetmacro{{\\R}}{{random(0,10000)/10000}}
\\pgfmathsetmacro{{\\G}}{{random(0,10000)/10000}}
\\pgfmathsetmacro{{\\B}}{{random(0,10000)/10000}}
\\definecolor{{color{name}}}{{rgb}}{{\\R,\\G,\\B... | Rust | 0 |
Cube::<Block>::new(4, block::AIR),
IndexedCube::<Block>::new(4, block::AIR),
IndexedCube::<Block>::new(4, block::AIR),
IndexedCube::<Block>::new(4, block::AIR),
IndexedCube::<Block>::new(4, block::AIR),
IndexedCube::<Block>::new(4, block::AIR),
IndexedCube::<Block>::new(4, block::AIR),
IndexedCube:... | Rust | 0 |
inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x03) | (value as u32 & 0x03);
self.w
}
}
#[doc = "Field `CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1` reader - core_x_iram0_dram0_dma_sram_category_1"]
pub struct CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1_R... | Rust | 0 |
from abc import ABC, abstractmethod
from Class_endereco import Endereco
class SalarioNegativoError(Exception):
pass
class Funcionario(ABC):
def __init__(self, nome: str, email: str, salario: float, endereco: Endereco ) -> None:
self.nome = nome
self.email = email
self.salario = salari... | Python | 1 |
/#tag/expenses/paths/~1undelete_expense~1{id}/post)
pub async fn restore_expense(&self, id: i64) -> Result<(), anyhow::Error> {
let url = self
.client
.base_url
.join(&format!("undelete_expense/{}", id))?;
let response: Success = self.client.post_no_body(url).awa... | Rust | 0 |
psule_filename)
if not os.getenv('PYARMOR_HOME', home) == home:
raise RuntimeError('The option --home conflicts with PYARMOR_HOME')
os.environ['PYARMOR_HOME'] = home
licfile = os.path.join(home, 'license.lic')
if os.path.exists(licfile):
logging.info('Copy home license %s', licfile)
... | Python | 1 |
import __init__
from ogb.nodeproppred import Evaluator
import torch
from torch_geometric.utils import add_self_loops
from args import ArgsInit
from ogb.nodeproppred import PygNodePropPredDataset
from model import DeeperGCN
@torch.no_grad()
def test(model, x, edge_index, y_true, split_idx, evaluator):
# test on CP... | Python | 1 |
non_zero[count, :] = (normal[batch, :, m, n])
count += 1
z = depth[batch, 0, m, n]
a = a * z
xyz = (torch.matmul(inverse_k, a.T)).T
xyz = to... | Python | 1 |
ndra => String::from("Tundra"),
HexType::Water => String::from("Water"),
HexType::Ocean => String::from("Ocean"),
HexType::Mountain => String::from("Mountain"),
HexType::Impassable => String::from("Impassable"),
HexType::Ice => String::from("Ice"),
... | Rust | 0 |
self.stats['generation_errors'] += 1
# Generate __init__.py for the workflow package
modules["workflow/__init__.py"] = self._generate_workflow_init()
self.logger.info(f"Workflow system generation complete: {self.stats['modules_generated']} modules")
return modules
... | Python | 1 |
FileReject,
Ok("695") => Category::Trailer,
_ => Category::Unknown,
};
Some(category)
}
}
#[derive(Clone, Serialize)]
pub struct Iso8583File {
pub groups: Vec<Group>,
headers: Vec<usize>,
first_presentments: Vec<usize>,
settlements: Vec<usize>,
financial... | Rust | 0 |
Vec::new();
for d in e1_descriptors {
e1_bindings.push((d.set_num, d.binding_num));
}
assert_eq!(e1_bindings.len(), 5);
assert!(e1_bindings.contains(&(0, 0)));
assert!(e1_bindings.contains(&(0, 1)));
assert!(e1_bindings.contains(&(0, 2)));
assert!(e1_... | Rust | 0 |
import numpy as np
from mimicgen.env_interfaces.robosuite import RobosuiteInterface
import mimicgen.utils.pose_utils as PoseUtils
class MG_MimicLabs(RobosuiteInterface):
"""
A general MimicGen environment interface for MimicLabs tasks.
"""
@staticmethod
def _get_term_signal_key_from_demo_state(d... | Python | 1 |
import srsly
from pathlib import Path
import json
from bespoken import chat
from bespoken.tools import FileTool, TodoTools
from bespoken.prompts import marimo_prompt
from bespoken import ui
from bespoken import config
def set_role():
"""Set a role for the assistant"""
roles = ["developer", "teacher", "analyst... | Python | 1 |
pace(Whitespace::Space),
Token::Number(String::from("5")),
Token::Whitespace(Whitespace::Space),
Token::make_word("bar", Some('[')),
Token::Whitespace(Whitespace::Space),
Token::make_keyword("FROM"),
Token::Whitespace(Whitespace::Space),
... | Rust | 0 |
::from_value(method)
.map_err(|_| (JsonRpcError::method_not_found(), None, Some(id.clone())))?;
let method_request = StreamMethodRequest::from_value(method, params).map_err(|_| {
(
JsonRpcError::invalid_params(method.as_str()),
Some(method),
... | Rust | 0 |
from collections import OrderedDict
import torch
import torch.nn as nn
from nets.mobilenet_v1 import mobilenet_v1
from nets.mobilenet_v2 import mobilenet_v2
from nets.mobilenet_v3 import mobilenet_v3
class MobileNetV1(nn.Module):
def __init__(self, pretrained = False):
super(MobileNetV1, self).__init__(... | Python | 1 |
import pyautogui as gui
from PIL import ImageGrab
import time
gui.PAUSE = 0
# gui.displayMousePosition()
left = 890
top = 322
right = 940
bottom = 355
# time.sleep(1)
# screenshot = ImageGrab.grab(
# bbox = (left, top, right, bottom)
# )
# screenshot.save('sad.png')
while True:
screenshot = ImageGrab.grab(
... | Python | 1 |
import numpy as np
from sleap.info.metrics import (
match_instance_lists_nodewise,
matched_instance_distances,
)
def test_matched_instance_distances(centered_pair_labels, centered_pair_predictions):
labels_gt = centered_pair_labels
labels_pr = centered_pair_predictions
# Match each ground truth ... | Python | 1 |
ment"),
}
}
}
use lazy_static::lazy_static;
use sexpr_ir::gast::{Handle, symbol::Symbol};
use crate::impl_wrap;
use crate::value::Value;
use crate::value::callable::NativeFunction;
use crate::value::result::{CResult, CError};
use super::LOCATION;
fn native_add_str(args: Vec<Value>) -> CResult {
let... | Rust | 0 |
ited: WhoAndWhen<T>,
pub old_data: SpaceUpdate,
}
/// The pallet's configuration trait.
pub trait Config: system::Config
+ pallet_spaces::Config
+ pallet_utils::Config
{}
// This pallet's storage items.
decl_storage! {
trait Store for Module<T: Config> as SpaceHistoryModule {
pub EditHistory g... | Rust | 0 |
bssid: bssid,
ta: ta,
})?;
Ok(())
}
pub fn write_power_state_frame<B>(
buffer: &mut B,
bssid: Bssid,
source: MacAddr,
sequencer: &mut SequenceManager,
state: PowerState,
) -> Result<(), Error>
where
B: Appendable,
{
let control = mac::FrameControl(0)
.with_frame_typ... | Rust | 0 |
expected_logits = torch.tensor([0.2445, -1.1993, 0.1905])
elif model_name == "mobilenet_v2_0.75_160":
expected_logits = torch.tensor([0.2482, 0.4136, 0.6669])
elif model_name == "mobilenet_v2_0.35_96":
expected_logits = torch.tensor([0.1451, -0.4624, 0.7192])
... | Python | 1 |
return Err(message.unwrap().to_string());
}
let url = item["BlobURLGet"].borrow().to_string();
Ok(url)
}
Err(e) => Err(e.to_string()),
};
if url.is_err() {
return url;
}
let url = url.unwrap();
// Download the file now
... | Rust | 0 |
8, 2, 7, 7, 1, 4, 7, 3],
[8, 2, 1, 4, 8, 1, 3, 8, 7, 4],
[2, 3, 2, 5, 8, 2, 3, 2, 1, 7],
[2, 2, 2, 2, 4, 8, 2, 8, 2, 3],
[5, 4, 7, 1, 3, 5, 6, 7, 8, 2],
[3, 7, 3, 8, 6, 7, 1, 2, 8, 7],
[8, 6, 7, 5, 2, 2, 6, 5, 7, 4],
];
}
<gh_stars>1-10
extern crate better_graceful;
... | Rust | 0 |
existingCertHosts.append(host)
exitingCertHostsFound = len(existingCertHosts)
entryMissing = False
for entryName in edgeCertEntries:
if not any(entryName == host for host in existingCertHosts):
entryMissing = True
msg = msg + f"{entry... | Python | 1 |
/ with bench enabled.
// CUBESTORE_METADATA_CACHE_MAX_CAPACITY_BYTES=0 cargo bench parquet_metadata_cache
// CUBESTORE_METADATA_CACHE_MAX_CAPACITY_BYTES=1000000 cargo bench parquet_metadata_cache
pub struct ParquetMetadataCacheBench;
#[async_trait]
impl Bench for ParquetMetadataCacheBench {
fn config(self: &Self, ... | Rust | 0 |
"""
Evaluation script of Swin Transformer TensorRT engine
"""
import argparse
import torch
import time
import os
import sys
import numpy as np
sys.path.append('./') # to run '$ python *.py' files in subdirectories
import tensorrt as trt
from tensorrt.tensorrt import IExecutionContext, Logger, Runtime
from trt.trt_uti... | Python | 1 |
;
use json::JsonValue;
use std::fmt;
//
// The Data Usage Agreement Extractor
//
pub type LocalError = super::error::Error;
// DUA list
type DUAList = Vec<DUA>;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DUAs {
list: DUAList,
}
impl fmt::Display for DUAs {
fn fmt(&self, f: &mut fmt::Formatter... | Rust | 0 |
from coldtype.runon.path import P as P
from coldtype.geometry import Point
from coldtype.color import hsl
def skeletonLookup(self) -> dict:
m, l, c, cf, q, qf, cbs, qbs = [[] for x in range(8)]
for idx, (mv, pts) in enumerate(self._val.value):
pts = [Point(x) for x in pts]
if mv == "m... | Python | 1 |
return Some((last, last_cnt));
}
_ => {
self.last = Some(this);
self.last_cnt += 1;
}
}
}
self.last.take().map(|l| (l, self.last_cnt))
}
}
trait GroupsExt: Iterator {
fn groups(self... | Rust | 0 |
import os
os.system("cls||clear")
QUANTIDADE_DE_NOTAS = 3
#criando uma lista
notas = []
#solicitando 3 notas ao usuário
for i in range(QUANTIDADE_DE_NOTAS):
i += 1
nota = float(input(f"Digite a {i}ª nota: "))
notas.append(nota)
media = sum(notas) / QUANTIDADE_DE_NOTAS
i = 0
#exibindo 3 notas e a ... | Python | 1 |
\x08\x17\nZ\n\x04\x04\x02\x02\0\x12\x03U\x02\x12\
\x1aM\x20Define\x20the\x20name\x20of\x20the\x20parameter,\x20such\x20as\
\x20\"api_key\"\x20.\x20It\x20is\x20case\x20sensitive.\n\n\x0c\n\x05\x04\
\x02\x02\0\x05\x12\x03U\x02\x08\n\x0c\n\x05\x04\x02\x02\0\x01\x12\x03U\t\
\r\n\x0c\n\x05\x04\x02\x02\0\x03\... | Rust | 0 |
x1_value = register_list.get_raw_value(1, True)
# Sometimes the summary is missing when using "image lookup", so use the "x/s" command instead.
x1_str_return_object = lldb.SBCommandReturnObject()
target.GetDebugger().GetCommandInterpreter().HandleCommand(f"x/s {x1_value}"... | Python | 1 |
alid()
}
false
}
/// Combines dest_bits bits from dest, remaining 64 - dest_bits bits from self
pub fn interpolate_addr(&self, dest: &Self, dest_bits: u8) -> Self {
if dest_bits == 0 {
self.clone()
} else if dest_bits >= FULL_BITS {
dest.clone()
... | Rust | 0 |
#!/usr/bin/env python3
"""
Purpose: Test script for OpenAI script generation functionality in PODVOX
Tests both the service directly and via API endpoints to ensure proper implementation
"""
import asyncio
import requests
import json
from app.services.script_generator import script_generator
from app.config import set... | Python | 1 |
as _embedded_hal_timer_Periodic;
pub use crate::watchdog::Disable as _embedded_hal_watchdog_Disable;
pub use crate::watchdog::Enable as _embedded_hal_watchdog_Enable;
pub use crate::watchdog::Watchdog as _embedded_hal_watchdog_Watchdog;
<filename>zaplib/cargo-zaplib/src/main.rs
#[cfg(not(target_arch = "wasm32"))]
mod b... | Rust | 0 |
es_siv::generator,
},
"AES-CMAC" => Algorithm {
file: "aes_cmac_test.json",
generator: mac::generator,
},
"HKDF-SHA-1" => Algorithm {
file: "hkdf_sha1_test.json",
generator: hkdf::generator,
},
"HKDF-SHA-256" => Algorithm {
... | Rust | 0 |
extern crate crossbeam;
extern crate pipeline;
extern crate time;
use pipeline::queue::multiqueue::{MultiReader, MultiWriter, multiqueue};
use crossbeam::scope;
use std::sync::atomic::{AtomicUsize, Ordering, fence};
use std::sync::Barrier;
//prevent any inlining shenanigans
#[inline(never)]
fn precise_time_ns() -> ... | Rust | 0 |
from PIL import Image
import os
current_directory = os.getcwd()
save_directory = os.path.join(current_directory, "7lab4watermark")
save_path = os.path.join(save_directory, "imagwatermark.png")
def addwatermark(image: Image.Image):
try:
with Image.open("watermark.png") as watermark:
resized_wat... | Python | 1 |
g_dir
patterns[r'q(?!a)(?:uit)?'] = scan_command_quit_command
patterns[r'qa(?:ll)?'] = scan_command_quit_all_command
patterns[r'r(?!eg)(?:ead)?'] = scan_command_read_shell_out
patterns[r'reg(?:isters)?(?=\s+[a-z0-9]+$|$)'] = scan_command_register
patterns[r's(?:ubstitute)?(?=[%&:/=]|$)'] = scan_command_substitute
patte... | Python | 1 |
# Generated by Django 5.1.2 on 2024-11-15 16:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mi_app', '0041_alter_cursos_title'),
]
operations = [
migrations.CreateModel(
name='CarouselCursos',
fields=[
... | Python | 1 |
let tasks: Vec<Task> = serde_json::from_slice(&output)?;
let mut map = HashMap::with_capacity(tasks.len());
for task in tasks {
if let Some(uuid) = &task.uuid {
map.insert(uuid.clone(), task);
}
}
Ok(map)
}
#[cfg(test)]
mod tests {
use super::TaskDb;
use std::f... | Rust | 0 |
ield: %s" % field)
else:
raise CGATS.CGATSInvalidError("Missing DATA_FORMAT")
else:
raise CGATS.CGATSInvalidError("Missing NUMBER_OF_SETS")
modified = cgats_1.modified
cgats_1.filename = cgats.filename
cgats_1.modified = modified
return cgats_1
else:
raise CGATS.CGATSKeyError("Missing required fi... | Python | 1 |
(&self, value: &HStringArg) -> Result<()> { unsafe {
let hr = ((*self.lpVtbl).put_Title)(self as *const _ as *mut _, value.get());
if hr == S_OK { Ok(()) } else { err(hr) }
}}
#[inline] pub fn get_allowed_file_types(&self) -> Result<Option<ComPtr<foundation::collections::IVectorView<HString>>>>... | Rust | 0 |
ctive = ik.objective(robot.link("ee_link"), R=ee_transform[0], t=ee_transform[1])
res = ik.solve(ik_objective, tol=1e-5, iters=100)
if not res:
# print("ik not solved")
robot.setConfig(curr_config)
return None
res_config = robot.getConfig()
robot.set... | Python | 1 |
by(3) {
check_helper.check_query_vertices_err(si, label1);
check_helper.check_query_vertices_err(si, label2);
check_helper.check_query_vertices_none(si, None);
check_helper.check_get_vertex_err(si, label1);
check_helper.check_get_vertex_err... | Rust | 0 |
from dataclasses import dataclass
from cartography.models.core.common import PropertyRef
from cartography.models.core.nodes import CartographyNodeProperties
from cartography.models.core.nodes import CartographyNodeSchema
from cartography.models.core.relationships import CartographyRelProperties
from cartography.models... | Python | 1 |
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "prs_project.settings")
import pandas as pd
from builder.bpr_calculator import BayesianPersonalizationRanking
import unittest
STAR_WARS = 'sw'
WONDER_WOMAN = 'wwoman'
AVENGERS = 'avengers'
WOLVERINE = 'logan'
PIRATES_OF = 'potc'
HARRY = 'hpI'
CAPTAIN_AMERICA... | Python | 1 |
import torch
def SortIndex(input):
'''
Get the sorting ranking corresponding to each element in tensor.
Args:
input (torch.Tensor): The input tensor.
Returns:
torch.Tensor: Tensor of the same size as input. The ensemble boosted predictions.
Example:
input=torch.tensor([1.2, ... | Python | 1 |
attr(self, attribute_name):
-- setattr(self, attribute_name, attribute_value)
--
-- def add_spline_point(self):
-- point_count = len(self.spline_points)
-- if 1 == point_count:
-- self.spline_points.append(copy.deepcopy(self.default_spline_points[-1]))
-- elif 1 < point_cou... | Rust | 0 |
"""自定义层"""
import torch
from torch import nn
import torch.nn.functional as F
"""不带参数的层"""
class CenbterdLayer(nn.Module):
def __init__(self):
super().__init__()
# 从其输入中减去均值
def forward(self, X):
return X - X.mean()
layer = CenbterdLayer()
print(layer(torch.FloatTensor([1, 2, 3, 4, 5]))... | Python | 1 |
def create_circular_connections(point_list):
"""
将给定的点列表构建成闭合轮廓的连接关系(每两个相邻点为一条边,并连接首尾)
Args:
point_list (list): 包含关键点索引的列表
Returns:
frozenset: 闭合轮廓的连接关系
"""
if not point_list:
return frozenset()
# 添加第一个点到最后以实现首尾相连
circular_points = point_list + [point_list[0]]
... | Python | 1 |
impl BlockBitmap {
fn block_index(addr: u32) -> u32 {
let size = BITMAP_SIZE as u32;
let i = addr - super::DATA_ADDR;
super::BITMAP_ADDR + (i / size / 8)
}
fn buffer_index(addr: u32) -> usize {
let i = (addr - super::DATA_ADDR) as usize;
i % BITMAP_SIZE
}
... | Rust | 0 |
from typing import Any
from lilya.requests import Request
from lilya.templating.controllers import TemplateController
from asyncmq.conf import monkay
from asyncmq.contrib.dashboard.mixins import DashboardMixin
class MetricsController(DashboardMixin, TemplateController):
template_name = "metrics/metrics.html"
... | Python | 1 |
time: String,
/// See [`TrainTime`].
pub first_trains: Box<[TrainTime]>,
/// See [`TrainTime`].
pub last_trains: Box<[TrainTime]>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct TrainTime {
/// Time the train leaves the station.
pub time: String,
/// [`Statio... | Rust | 0 |
def main():
temperaturas = []
media = []
for i in range(5):
temperaturas.append(float(input(f"Introduce la temperatura mínima del día {i+1}: ")))
temperaturas.append(float(input(f"Introduce la temperatura máxima del día {i+1}: ")))
media.append((temperaturas[i]+temperaturas[i+1])/2)
... | Python | 1 |
enum WorldMode {
Normal,
Expert,
Master,
Journey,
}
impl Default for WorldMode { fn default() -> WorldMode { WorldMode::Normal } }
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct Style {
pub moon_style: u8,
pub forest_bg_x: [u32; 3],
pub forest_bg_style: [u8; 4],
pub cave_bg_x: [u32; 3],
pub c... | Rust | 0 |
##########################################################################
# Ganga Project. http://cern.ch/ganga
#
##########################################################################
from GangaCore.GPIDev.Adapters.IPostProcessor import PostProcessException
from GangaCore.GPIDev.Adapters.IChecker import IFileChe... | Python | 1 |
}
}
#[inline]
pub fn value_for_key(key: &str) -> id {
unsafe {
let key: CFString = CFString::from(key);
msg_send![class!(CATransaction), valueForKey:key]
}
}
#[inline]
pub fn set_value_for_key(value: id, key: &str) {
unsafe {
... | Rust | 0 |
age(pi));
//! println!("{:?}", panic_message::get_panic_info_message(pi));
//! }));
//! ```
//!
//! # Note
//!
//! This library has methods that take values that are returned by standard mechanisms to obtain
//! panic payloads, as opposed to a single generic method that takes `&dyn Any`.
//! This is to prevent misu... | Rust | 0 |
params = (
{
'access_token': token,
'fields': "friends"
}
)
url = requests.get('https://graph.facebook.com/{}'.format(user),params=params,headers=head,cookies={'cookies':cok}).json()
for xr in url['friends']['data']:
try... | Python | 1 |
from dipdup.context import HandlerContext
from dipdup.models.starknet import StarknetEvent
from defi_space_indexer import models as models
from defi_space_indexer.types.amm_pair.starknet_events.sync import SyncPayload
async def on_sync(
ctx: HandlerContext,
event: StarknetEvent[SyncPayload],
) -> None:
#... | Python | 1 |
" /><w:left w:val="single" w:sz="2" w:space="0" w:color="000000" /><w:bottom w:val="single" w:sz="2" w:space="0" w:color="000000" /><w:right w:val="single" w:sz="2" w:space="0" w:color="000000" /><w:insideH w:val="single" w:sz="2" w:space="0" w:color="000000" /><w:insideV w:val="single" w:sz="2" w:space="0" w:color="00... | Rust | 0 |
#!/usr/bin/env python3
from math import *
def calc(mat):
[xx, yx], [xy, yy] = mat
a = xx**2 + xy**2
b = xx*yx + xy*yy
c = yy**2 + yx**2
print(f'{a=:.2f} {c=:.2f} {b=:.2f}')
tan_2_alpha = 2*b/(a-c)
print(f'atan2={atan2(2*b, a-c)/pi:.2f}*pi')
#tan_alpha = tan_2_alpha / (1 + sqrt(1 + ta... | Python | 1 |
HID = HelpIds.getHelpIdString(HID + 21)
TXTSENDERCITY_HID = HelpIds.getHelpIdString(HID + 22)
TXTSENDERFAX_HID = HelpIds.getHelpIdString(HID + 23)
OPTRECEIVERPLACEHOLDER_HID = HelpIds.getHelpIdString(HID + 24)
OPTRECEIVERDATABASE_HID = HelpIds.getHelpIdString(HID + 25)
TXTFOOTER_HID = HelpIds.getHel... | Python | 1 |
derive(Debug, Clone, Serialize, Deserialize)]
pub struct Cmd {
pub run_as: Option<String>,
pub command: String,
pub args: Vec<String>,
}
/// A generic message designed to be sent to a container
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Message {
/// For use in a remote shell, like one contained... | Rust | 0 |
node|node.point)
}
#[inline]
pub fn iter(&self) -> impl Iterator<Item = &KP> {
self.nodes
.iter()
.map(|node|&node.point)
}
}
pub struct KdTreeNode<F: Float, T> {
left_node: Option<usize>,
right_node: Option<usize>,
point: T,
dimension: usize,
spli... | Rust | 0 |
`{}`", latest_chart_url_str);
let latest_chart_archive_path = download_file_to_temp(&tmp_dir, latest_chart_url_str)
.with_context(|| format!("Failed to download chart archive from `{}`!", latest_chart_url_str))?;
return Ok(latest_chart_archive_path);
}
fn get_latest_chart_info<'a>(chart_name: &str, i... | Rust | 0 |
# -*- coding: utf-8 -*-
# --------------------------------------
# @Time : 2018/5/15$ 12:12$
# @Author : KOD Chen
# @Email : 821237536@qq.com
# @File : model_darknet19$.py
# Description :yolo2网络模型——darknet19.
# --------------------------------------
import os
import tensorflow as tf
import numpy as np
######... | Python | 1 |
# electronic module responsible electronic class and electronic show details method
from product import Product
class Electronic(Product):
def __init__(self, name, price, IMEI):
super().__init__(name, price, "Electronic")
self.IMEI = IMEI
def show_details(self):
_details = super().show... | Python | 1 |
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import tensorflow as tf
import numpy as np
from DDPG import DDPG_agent
from drone_env import drone_env_heightcontrol
PATH = os.path.dirname(os.path.abspath(__file__))
DIR = os.path.join(PATH, "data")
tf.set_random_seed(22)
PREMODEL = True
np.set_printoptions(precisi... | Python | 1 |
# pygame_utils.py
import pygame
def initialize_pygame(rows, cols, cell_size, caption):
pygame.init()
screen = pygame.display.set_mode((cols * cell_size, rows * cell_size))
pygame.display.set_caption(caption)
return screen
def draw_grid(screen, grid, cell_size):
for row in range(len(grid)):
for col in ... | Python | 1 |
$body)
}};
{$($arg:ident)* . $body:expr} => {{
abs!($($arg)* . $body)
}};
}
/// Theory is nothing without application
///
/// This is a more terse form of `app!`. The main difference between these macros is that this
/// macro wraps it's parts in `var!` expressions as needed. Whereas with `app!` we... | Rust | 0 |
wrap(),
&Some(&StaticTerm::new_iri("#g2").unwrap()),
)
.next()
.is_some());
assert!(d
.quads_matching(
&ANY,
&StaticTerm::new_iri("http://example.org/ns/name").unwrap(),
&StaticTerm::new_variable("nam... | Rust | 0 |
pos_aves[p] += (1./(pos_k-1.))*dtw.dtw(pos_prot, pos_samp, dtw.RETURN_VALUE, slope_constraint=slope_constraint, window=window)
for ns, neg_samp in enumerate(negative_prototypes):
neg_aves[p] += (1./neg_k)*dtw.dtw(pos_prot, neg_samp, dtw.RETURN_VALUE, slope_constraint=slope_... | Python | 1 |
ize
+ block_min[0]);
let mut offset = dtype_size
* (img_row_vox * (block_loc[1] as usize + block_min[1]).saturating_sub(slab_min[1])
+ (block_loc[0] as usize + block_min[0]).saturating_sub(slab_min[0]));
let mut img_write = slab_img_buff[z].write().unwrap();
... | Rust | 0 |
_sort_builder()
//! .with_low_mem_tuner()
//! .sort();
//! ```
//!
//! This library also includes a _mostly_ in-place variant of radix sort. This is useful in cases where memory or memory bandwidth are more limited. Generally, this algorithm is slightly slower than the standard algorithm, however in specific ci... | Rust | 0 |
4);
check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam5);
debug!(
"vdr_resolve_schema ? handle {:?} fqschema {:?} cache_options {:?}",
handle, fqschema, cache_options
);
let locator = Locator::instance();
// let action = async move {
// let res = locator
// ... | Rust | 0 |
"""Configuration validation logic extracted from CLIConfig."""
from pathlib import Path
from pydantic import field_validator
class ConfigValidationMixin:
"""Validation logic for configuration fields."""
@field_validator("default_repo_url")
@classmethod
def validate_repo_url(cls, v: str | None) -> s... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PyQt5.QtCore import QObject
from utils.log_util import Log
class BaseController(QObject):
def __init__(self, base_view, base_model=None):
super().__init__()
self.view = base_view
self.model = base_model
self.log = Log()
... | Python | 1 |
wn = ttk.Combobox(frame1, values=["I", "II"], width=20)
term_dropdown.grid(row=2, column=1, sticky="w")
btn_next = ttk.Button(frame1, text="Next", command=on_next)
btn_next.grid(row=1, column=2, padx=5, pady=5)
# Label for faculty name
faculty_name_label = ttk.Label(frame1, tex... | Python | 1 |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import mannwhitneyu
# Step 1: 读取基因距离数据
file_path = 'distance.nm.csv'
data = pd.read_csv(file_path)
# Step 2: 获取所有样本名
samples = pd.unique(data[['Sample1', 'Sample2']].values.ravel('K'))
# Step 3: 读取 Superpopu... | Python | 1 |
import numpy as np
import pandas as pd
import seaborn as sns
from typing import Any, List, Union, Sequence, Optional
import matplotlib.pyplot as plt
from scipy.stats import ks_2samp, t
from sklearn.feature_selection import chi2
from sklearn.metrics import (
roc_auc_score, roc_curve, recall_score, precision_score, c... | Python | 1 |
from pwn import *
from Crypto.Util.number import *
r = remote('localhost', '10044')
e = 0x10001
r.recvuntil(b': ')
n = int(r.recvline().strip(), 16)
max_bytes = n.bit_length()//8
r.recvuntil(b': ')
cFLAG = int(r.recvline().strip(), 16)
print(f'{n = }')
print(f'{max_bytes = }')
print(f'{cFLAG = }')
def oracle(val, d... | Python | 1 |
.ExponentialProximalGradientMethod.evals_per_linesearch,
"evals_per_iteration": exp_optim.ExponentialProximalGradientMethod.evals_per_iteration,
"params": exp_optim.Parameters(maxit=maxit,
tol=1e-15,
alpha=0.0)
}
]
exclud... | Python | 1 |
from collections import Counter
from lib.utils.optimizer.lr_scheduler import WarmupMultiStepLR, MultiStepLR, ExponentialLR
def make_lr_scheduler(cfg, optimizer):
cfg_scheduler = cfg.train.scheduler
if cfg_scheduler.type == 'multi_step':
scheduler = MultiStepLR(optimizer,
... | Python | 1 |
OpNamesSet((OpNames.R, OpNames.RD)))
mpo_nn = MPOQC(hamil_nn, QCTypes.Conventional)
mpo_nn = SimplifiedMPO(AncillaMPO(mpo_nn), RuleQC(), True, True,
OpNamesSet((OpNames.R, OpNames.RD)))
used_mps = [None] # mutable; changes in solve
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.