text string | label_name string | labels int64 |
|---|---|---|
import pandas as pd
import openpyxl
import re
# 定义文件路径
ALL_FILTERED = 'filtered_excel/merge_llm_entries.xlsx'
UNIQUE_FILTERED = 'excluded_excel/merge_llm_filtered.xlsx'
LLM_TOP_VENUES = 'filtered_excel/llm_top_venues.xlsx'
# 读取excel文件
df = pd.read_excel(ALL_FILTERED)
df_llm = pd.read_excel(LLM_TOP_VENUES)
df['SAME_T... | Python | 1 |
import logging
from manufacturing import import_csv, calc_ppk, ppk_plot
import matplotlib.pyplot as plt
logging.basicConfig(level=logging.INFO)
# First, we will pull in the simplest data with no limits contained in the column
# headers. The return type will be a pandas.Series, which we store in `data`:
data = import... | Python | 1 |
iled projects - must be pending
status_lines.extend(
[
"⏳ **Sync operations pending**",
"",
"File synchronization has been queued but hasn't started yet.",
"This us... | Python | 1 |
test_datetime)
_, _, this_module = __name__.rpartition(".")
self.assertIn(this_module, warnings_cm.filename)
self.assertIn(
"datetime instances will no longer be accepted",
str(warnings_cm.warning),
)
def test_allow_none_false_allow_datetime_false(self):
... | Python | 1 |
y!(linename)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<_mjvFigure>())).xaxispixel as *const _ as usize
},
812404usize,
concat!(
"Offset of field: ",
stringify!(_mjvFigure),
"::",
stringify!(xaxispixel)
... | Rust | 0 |
pcd = BasicPointCloud(points=pcd.vertices[point_id], colors=pcd.colors[point_id][:,:3].astype(np.float32)/255, normals=None)
except:
pcd = None
scene_info = SceneInfo(point_cloud=pcd,
train_cameras=train_cam_infos,
test_cameras=... | Python | 1 |
# -*- coding: utf-8 -*-
# @Project: Hello Python!
# @File : exp
# @Author : Tr0jAn <Tr0jAn@birkenwald.cn>
# @Date : 2020-11-22
import struct
import binascii
class FAT32Parser(object):
def __init__(self, vhdFileName):
with open(vhdFileName, 'rb') as f:
self.diskData = f.read()
self.DBR_off = self.Ge... | Python | 1 |
ensus::{engine::*, driver::Driver};
pub struct Poet2Driver {
engine: Box<Engine>,
}
impl Driver for Poet2Driver {
fn new(engine: Box<Engine>) -> Self {
Poet2Driver { engine }
}
fn start(&self, _endpoint: &str) -> Result<(), Error> {
Ok(())
}
fn stop(&self) {}
}
//! Decimal floating-point ... | Rust | 0 |
"""All binary_sensor entities."""
from homeassistant.helpers.entity import EntityDescription
from . import FiskerButtonEntityDescription
BUTTON_ENTITIES: list[EntityDescription] = [
FiskerButtonEntityDescription(
key="doors_unlock",
name="Doors Unlock",
translation_key="doors_unlock",
... | Python | 1 |
true;
}
} else if l.value() > 9 {
**l = l.split();
return true;
}
if r.is_node() {
if r.try_split() {
return true;
}
} else if r.value() > 9 {
**r = r.split();
return true;
}
false
}
... | Rust | 0 |
---")
log.info("-----Launching federating learning breach experiment! --------")
launch_time = time.time()
if cfg.seed is None:
cfg.seed = 233 # The benchmark seed is fixed by default!
if cfg.case.user.user_type == "local_update":
# we split data evenly across mini-batches
cfg.... | Python | 1 |
,
Belgium = 21,
Belize = 22,
Benin = 23,
Bermuda = 24,
Bhutan = 25,
Bolivia = 26,
Botswana = 27,
BouvetIsland = 28,
Brazil = 29,
BritishIndianOceanTerritory = 30,
BritishVirginIslands = 31,
Brunei = 32,
Bulgaria = 33,
Burkina = 34,
Burma = 35,
Burundi = 36... | Rust | 0 |
-2.0
pub use crate::{
DecoderBuffer, DecoderBufferMut, DecoderError, DecoderValue, DecoderValueMut, Encoder,
EncoderBuffer, EncoderLenEstimator, EncoderValue,
};
#[derive(Clone, Debug)]
pub struct Error(String);
impl From<DecoderError> for Error {
fn from(err: DecoderError) -> Self {
Self(err.to_... | Rust | 0 |
}
}
if let Some(var_6) = &input.fields {
let mut inner_writer = scope
.start_el("Fields")
.write_ns("http://cloudfront.amazonaws.com/doc/2020-05-31/", None)
.finish();
for list_item_7 in var_6 {
{
let mut inner_writer = inner_write... | Rust | 0 |
CargoCmdType::ClippyFix);
}
}
assert!(
clippy_output.status.success(),
"Clippy needs to be run, please run 'cargo clippy -- --deny=clippy::pedantic'."
);
}
/// Fail if cargo clippy hasn't been run on testutils.
#[test]
fn testutils_clippy() {
let current_dir = env::current_dir... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2019 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 |
rst.is_empty() {
tokens.append(Ident::new(first, Span::call_site()));
}
for next in iter {
let ident = Ident::new(next, Span::call_site());
tokens.append_all(quote! { :: #ident });
}
}
}
}
<gh_stars>0
use na::{Pnt3, Vec3};
u... | Rust | 0 |
e_in_junction(LANE1))),
# only_in_lane(LANE_VEHICLE1, LANE1)
# )),
# ("only_in_junction", is_in_a_junction(LANE_VEHICLE1)),
# ("only_in_lane2", only_in_lane2),
# ("lane1_match_lane2", partial(P.logic_not, lanes_match(LANE1, LANE2)))
# ],
# [LANE_VEHICLE1, LANE1, LANE... | Python | 1 |
mocks::get_gvt_predicate()];
let encoded_attributes = issuer::mocks::get_gvt_attributes();
let schema = issuer::mocks::get_gvt_schema();
let res = Prover::_init_proof(&pk, &schema, &claim, &encoded_attributes, &revealed_attrs, &predicates, &m1_t, Some(m2_t));
assert!(res.is_ok());
}... | Rust | 0 |
an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = Fal... | Python | 1 |
import os, random, sys, ctypes
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent))
import rust_sssp
from ctypes import Structure, c_uint32, byref
class BucketStats(Structure):
_fields_=[('buckets_visited',c_uint32),('light_pass_repeats',c_uint32),('max_bucket_index',c_uint32),('restarts'... | Python | 1 |
().unwrap().borrow().val,
f => min(f, n.right.as_ref().unwrap().borrow().val)
},
n =>
match (find_second_minimum_value(Some(n.left.as_ref().unwrap().clone())),
find_second_minimum_value(Some(n.right.as_ref().unwrap().clone()))) {
... | Rust | 0 |
n open file object.
r Nr r r r r r )r rY r r{ r r s r1
parseFragmentr w #G,!'*$
$
&&r*F M ""4(M
M A//
A>c ` U( a [ U5 nO[ U5 nUR U... | Python | 1 |
"Offset of field: ",
stringify!(__va_list_tag),
"::",
stringify!(overflow_arg_area)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__va_list_tag>())).reg_save_area as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
... | Rust | 0 |
are drawn.
!!! info "About Plotting"
`plot_spectra` is a wrapper around the `seaborn.lineplot` and
`seaborn.regplot` function. Furthermore, the `MultiCursor` widget is used
to create an interactive plot, for picking the energy and intensity of the
spectrum. the ... | Python | 1 |
identifier for the code span.
Each code span also comes with the line numbers for you to better understand the context. It's possible that the code span are not sufficient to fix the issue, adjust your score accordingly.
- You are given the candidate patch that tries to resolve the target issue.
For your conv... | Python | 1 |
atch self {
FrameType::Beacon => write!(f, "Beacon"),
FrameType::Data => write!(f, "Data"),
FrameType::Acknowledgement => write!(f, "Ack"),
FrameType::MacCommand => write!(f, "MAC command"),
FrameType::Multipurpose => write!(f, "Multipurpose"),
Fra... | Rust | 0 |
let rrule_result = convert_to_rrule(rrule_string);
match rrule_result {
Ok(rrule) => Ok(rrule.get_all_iter_dates_iso8601(count, interval)),
Err(_) => Err(RuleParseError),
}
}
pub fn get_all_iter_dates_from_today(
rrule_string: &str,
count: &str,
interval: &str,
) -> Result<Vec<Stri... | Rust | 0 |
from scapy.all import Ether, IP, TCP, Raw, wrpcap
import base64
# flag Cearation
def create_flag():
flag = b"AzCTF{ua_header_leak}"
b64 = base64.b64encode(flag).decode()
# HTTP split
part1 = b"GET / HTTP/1.1\r\nHost: halib-al-khair.com\r\nUser-Agent: " + b64[:8].encode()
part2 = b64[8:].encode() + ... | Python | 1 |
abel_data["psr"]["position"] = {}
sus_label_data["psr"]["position"]["x"] = float(list_data[i, 0])
sus_label_data["psr"]["position"]["y"] = float(list_data[i, 1])
sus_label_data["psr"]["position"]["z"] = float(list_data[i, 2])
sus_label_data["psr"]["rotation"] = {}
... | Python | 1 |
return-client-request-id", return_client_request_id.to_string());
}
if let Some(ocp_date) = ocp_date {
req_builder = req_builder.header("ocp-date", ocp_date);
}
if let Some(if_match) = if_match {
req_builder = req_builder.header("If-Match", if_match);
}
... | Rust | 0 |
", "64", suffix)
} else if cfg!(target_os = "linux") {
(LINUX_PATH.to_owned(), "/", "86_64", "")
} else {
panic!("unknown/unsupported target OS")
};
let core_inc = "-I".to_owned() + &api_root + &format!(r#"core{}inc"#, path_delimiter);
let studio_inc = "-... | Rust | 0 |
# -*- coding: UTF-8 -*-
#/**
# * Software Name : pycrate
# * Version : 0.4
# *
# * Copyright 2018. Benoit Michau. ANSSI. P1sec.
# *
# * This library is free software; you can redistribute it and/or
# * modify it under the terms of the GNU Lesser General Public
# * License as published by the Free Software Foundation; e... | Python | 1 |
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
AON_PROG2_EVR::NONE => 63,
AON_PROG2_EVR::AUX_COMPB_ASYNC_N => 56,
AON_PROG2_EVR::AUX_COMPB_ASYNC => 55,
AON_PROG2_EVR::BATMON_VOLT => 54,
AON_PR... | Rust | 0 |
ow self.soup is set by the time feed() is called.
assert self.soup is not None
encoding = self.soup.original_encoding
try:
self.parser = self.parser_for(encoding)
self.parser.feed(markup)
self.parser.close()
except (UnicodeDecodeError, LookupError, etr... | Python | 1 |
from typing import Callable, Optional
import torch
from tha4.shion.core.cached_computation import TensorCachedComputationFunc, ComputationState
from tha4.shion.core.loss import Loss
class L1Loss(Loss):
def __init__(self,
expected_func: TensorCachedComputationFunc,
actual_func: ... | Python | 1 |
_base_ = [
"../_base_/models/convnext_upernet.py",
"../_base_/datasets/grass.py",
"../_base_/default_runtime.py",
"../_base_/schedules/grass_schedule.py",
]
data_preprocessor = dict(size=(256, 256))
model = dict(
data_preprocessor=data_preprocessor,
decode_head=dict(num_classes=5),
auxiliar... | Python | 1 |
istribution = 0x10,
// Resistance = 0x12,
// EncoderResults = 0x13,
// Inductances = 0x14,
CalibrateEZero(CalibrateEZeroCmd),
// EZero = 0x16,
TorqueControl(TorqueControlCmd),
PosVelControl,
BeginStateStream(StartStreamCmd),
SensorState,
EndStateStream,
Unknown,
}
impl Mess... | Rust | 0 |
del using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
... | Python | 1 |
# Copyright 2021 Tencent
# SPDX-License-Identifier: BSD-3-Clause
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, x, y):
x = F.avg_pool3d(x, kernel_size=3)
x = F.avg_pool3d(x,... | Python | 1 |
Origin::signed(1)));
assert_eq!(Kitties::kitties(1).is_some(), true);
assert_eq!(Kitties::owner(1), Some(1));
assert_ok!(Kitties::transfer(Origin::signed(1), 8, 1));
assert_eq!(Kitties::owner(1), Some(8));
assert_eq!(Balances::reserved_balance(1), 0);
assert_eq!(Balances::reserved_balance(8), ReserveAmou... | Rust | 0 |
get_result = gd_refmut.tqueue_lock_dict.get(address);
}else{
panic!("unknown kind is passed at get_lock_obj");
}
let ret_val_cloned: ArRmRs<bool> =
match get_result {
None => {
// まだ存在しなかった
if kind == "ninfo" {
le... | Rust | 0 |
#print("当前进程号 : {}, 处理数据cid: {}".format(os.getpid(), cid))
# 使用 Input_Preparation 类准备输入
prepared_inputs = input_preparation.prepare_inputs(options, sentences, question)
print(prepared_inputs)
data['qas'][0]['options_evidence'] = prepared_inputs
batch_prepared_inputs.append(data... | Python | 1 |
pl GasSizeOf for str {
fn gas_size_of(&self) -> Gas {
self.len().saturating_into()
}
}
impl GasSizeOf for String {
fn gas_size_of(&self) -> Gas {
self.as_str().gas_size_of()
}
}
impl<K, V, S> GasSizeOf for std::collections::HashMap<K, V, S>
where
K: GasSizeOf,
V: GasSizeOf,
{
... | Rust | 0 |
# *********************************************************************
# FUNCTION TO CONVERT TEMPLATE GRID COORDINATES TO GEOGRAPHIC COORDs
#
# Copyright (c) 2014-2019: HILARY R. MARTENS, LUIS RIVERA, MARK SIMONS
#
# This file is part of LoadDef.
#
# LoadDef is free software: you can redistribute it and/o... | Python | 1 |
"""The FiveM sensor platform."""
from dataclasses import dataclass
from homeassistant.components.sensor import SensorEntity, SensorEntityDescription
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
fr... | Python | 1 |
("zero", true, false),
("zero", false, false),
("not_true", false, false),
("not_on", true, false),
// check empty arguments return true
("empty_but_true", false, true),
// check other values return true
("should_be_true", false, true),... | Rust | 0 |
from textblob import TextBlob
print("Welcome to AI Mood Dedector")
name = input("Enter your name: ")
print(f"Nice to meet you, {name} Let us find out the sentiment of your sentence")
print("Type exit to quit\n")
while True:
sentence = input("Enter your sentence: ")
if sentence.lower() == "exit":
print... | Python | 1 |
self.y /= other;
self.z /= other;
self.w /= other;
}
}
}
);
);
#[allow(non_camel_case_types)]
pub type f32m4x4 = Mat4x4<f32>;
impl_mat4x4!(f32);
#[allow(non_camel_case_types)]
pub type f64m4x4 = Mat4x4<f64>;
impl_mat4x4!... | Rust | 0 |
shape:
raise ValueError("Incompatible data and labels shapes.")
data = cp.atleast_3d(img_as_float(data))[..., cp.newaxis]
else:
if data.ndim not in (3, 4):
raise ValueError(
"For multichannel input, data must have 3 or 4 " "dimensions."
)
i... | Python | 1 |
os;
import ClearMap.IO as io
import ClearMap.Settings as settings
import ClearMap.ImageProcessing.Ilastik as il;
reload(il);
ilp = os.path.join(settings.ClearMapPath, 'Test/Ilastik/Test.ilp')
src = os.path.join(settings.ClearMapPath, 'Test/Data/ImageAnalysis/cfos-substack.tif');
#out = os.path.join(se... | Python | 1 |
"SEND_ACTIVATION_EMAIL": True,
"SERIALIZERS": {
"user_create": "apps.users.serializers.CreateUserSerializer,",
"user": "apps.users.serializers.UserSerializer",
"current_user": "apps.users.serializers.UserSerializer",
"user_delete": "djoser.serializers.UserDeleteSerializer",
... | Python | 1 |
# -*- coding: utf-8 -*-
from __future__ import print_function
'''Selection of entities inside a geometric object. Home made test.'''
__author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AO_O)"
__copyright__= "Copyright 2015, LCPT and AO_O"
__license__= "GPL"
__version__= "3.0"
__email__= "l.pereztato@ciccp.es ana.or... | Python | 1 |
0
use persia_libs::bytes::Buf;
use persia_libs::{hyper, lz4, tokio, url};
use persia_speedy::{Readable, Writable};
use snafu::{ensure, Backtrace, ResultExt, Snafu};
use std::ops::Add;
#[derive(Snafu, Debug)]
#[snafu(visibility = "pub")]
pub enum PersiaRpcError {
#[snafu(display("serialization error"))]
Seriali... | Rust | 0 |
"""variable_func.py: Contains functions for adding variables to the optimization model."""
import gurobipy as gp
from gurobipy import GRB
import pandas as pd
from pownet.data_utils import (
get_capacity_value,
)
def add_var_with_variable_ub(
model: gp.Model,
varname: str,
timesteps: range,
step_... | Python | 1 |
for attention_mask (shape {attention_mask.shape})'
)
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
# masked positions, this operation will create a tensor which is 0.0 for
# positions we want to attend and -10000.0 for masked positions.
# Since w... | Python | 1 |
# # -*- coding: utf-8 -*-
# from setuptools import setup
# packages = \
# ['casino']
# package_data = \
# {'': ['*']}
# install_requires = \
# ['cython>=0.29.35,<0.30.0', 'numba>=0.57.0,<0.58.0', 'numpy>=1.24.3,<2.0.0']
# setup_kwargs = {
# 'name': 'casino',
# 'version': '0.1.0',
# 'description': 'Casin... | Python | 1 |
q_func.parameters(), lr=self._config.critic_learning_rate
)
self._impl = TD3PlusBCImpl(
observation_shape=observation_shape,
action_size=action_size,
policy=policy,
q_func=q_func,
actor_optim=actor_optim,
critic_optim=critic_optim... | Python | 1 |
nbf: now,
user_id,
user_lastname,
user_firstname,
user_email,
};
let token = encode(&header, &payload, &EncodingKey::from_secret(secret_key.as_bytes()))?;
Ok((token, now))
}
// Parse JWT
pub fn parse(token: String, secret_key: Stri... | Rust | 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 writing, software
# d... | Python | 1 |
se.
extern crate map_model;
mod building;
mod intersection;
mod map;
mod parcel;
mod road;
mod turn;
use ezgui::canvas;
use geom;
use graphics::types::Color;
pub use render::map::DrawMap;
pub use render::road::DrawRoad;
pub use render::turn::DrawTurn;
use std::f64;
// These are all in meters
const PARCEL_BOUNDARY_T... | Rust | 0 |
) -> syn::Result<Self> {
Ok(Self {
_if_tok: input.parse()?,
_let_tok: input.parse()?,
pat: input.parse()?,
_eq_tok: input.parse()?,
expr: input.parse()?,
_semi_tok: input.parse()?,
})
}
}
impl Parse for IfGuard {
fn parse(i... | Rust | 0 |
"c" math_sub, math_unary: [];
]);
assert_parsed!("a_b^c" math_token: [
"a" math_unary: [];
"b" math_sub, math_unary: [];
"c" math_sup, math_unary: [];
]);
assert_parsed!("a^b" math_token: [
"a" math_unary: [];
"b" math_sup, math_unary: [];
]);
asse... | Rust | 0 |
):
"""Fix up BMCs that had their SIP's nullified in pre_save.
These BMCs were identified in pre_save and stored in the instance for
reference in this handler.
"""
instance.__previous_ip = instance.ip
for bmc in instance.__bmcs_to_update:
# Save the BMC so it can re-extract its IP from p... | Python | 1 |
de__.co_flags & inspect.CO_ITERABLE_COROUTINE)
self.assertFalse(gen.__code__.co_flags & inspect.CO_COROUTINE)
g = gen()
self.assertTrue(g.gi_code.co_flags & inspect.CO_ITERABLE_COROUTINE)
self.assertFalse(g.gi_code.co_flags & inspect.CO_COROUTINE)
self.assertIs(types.coroutine(... | Python | 1 |
# type: ignore
"""Add proces to icp
Revision ID: 72c7103fb4ad
Revises: 4465ac8d0d07
Create Date: 2024-11-27 13:44:27.013596+00:00
"""
from __future__ import annotations
import warnings
from typing import TYPE_CHECKING
import sqlalchemy as sa
from alembic import op
from advanced_alchemy.types import EncryptedString,... | Python | 1 |
HashSet;
use crate::bluetooth;
use crate::bluetooth::ConnectedBluetoothPeripheral;
use crate::models::thermostats::{Thermostats, Thermostat};
use crate::models::thermostat_names::*;
pub fn execute(arguments: Vec<String>) {
if arguments.len() != 1 {
panic!("Expected just one parameter to read. Got {}.", ar... | Rust | 0 |
sert_eq!(doc.field_values().len(), 1);
}
}
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
use core::ffi::c_void;
use lib_redos::ThreadID;
use user_lib::redos::{create_thread, sleep};
#[no_mangle]
pub fn main() -> usize {
let mut t: ThreadID = 0;
create_thread(&mut t, thread_fn, core::ptr::nul... | Rust | 0 |
>) {
unsafe {
WRITE8_HOOKS.push(Hook::Closure(transmute(hook)));
}
self.emulator
.set_exec_write8_hook(write8_hooks_wrapper::<I, QT, S>);
}
pub fn write_n_execution(&self, hook: DynamicLenHookFn<QT, S>) {
unsafe {
WRITE_N_HOOKS.push(Hook::Func... | Rust | 0 |
inline]
fn vec(vec: Vec<u8>) -> Self::TBin {
// can't do much here...
RcBin::from_vec(vec)
}
#[inline]
fn overhead_bytes_for_vec() -> usize {
RcBin::overhead_bytes()
}
}
/// re-integrator for `SyncBin`.
struct SyncBinReIntegrator {}
impl ReIntegrator for SyncBinReIntegrato... | Rust | 0 |
str = "s/us";
client.publish(
DEVICE_CREATE_PUBLISH_TOPIC,
QoS::ExactlyOnce,
false,
format!("100,{},{}", device_id, device_type).as_bytes(),
)?;
Ok(())
}
fn load_root_certs(
root_store: &mut rustls_0_19::RootCertStore,
cert_dir: FilePath,
) -> Result<(), ConnectError... | Rust | 0 |
self.classifier = nn.Sequential(
nn.Linear(channels[0], channels[0]),
nn.BatchNorm1d(channels[0]),
nn.ReLU(inplace=True),
nn.Linear(channels[0], num_classes)
)
self.init_weights()
def forward(self, feats, xyz, offset, batch, neighbor_i... | Python | 1 |
import dataclasses
import torch
import k_diffusion
@dataclasses.dataclass
class Scheduler:
name: str
label: str
function: any
default_rho: float = -1
need_inner_model: bool = False
aliases: list = None
def uniform(n, sigma_min, sigma_max, inner_model, device):
return inner_model.get_s... | Python | 1 |
out.push(parsed);
*state = StringState::Norm;
}
}
StringState::Hex2 {
digit_start, num, ..
} => {
if num == 2 {
let parsed = u64::from_str_radix(&full[digit_start..idx], 16).unwrap... | Rust | 0 |
"""
INF601 - Advanced Programming in Python
Sam Boutros
Prof. Zeller
FHSU - Fall 2022
11/1/2022
https://samsclass.info/124/proj14/VP110.htm
"""
# Download these two files:
# https://samsclass.info/124/proj14/VP110-3a
# https://samsclass.info/124/proj14/VP110-3b
# Add the bytes in the two files together to construct a ... | Python | 1 |
oken_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model]
x = x + m.positional_embedding.to(cast_dtype)
x = x.permute(1, 0, 2) # NLD -> LND
x = m.transformer(x, attn_mask=m.attn_mask)
x = x.permute(1, 0, 2) # LND -> NLD
x = m.ln_final(x) # [batch_size, n_ctx, transf... | Python | 1 |
@staticmethod
def load_model_safely(pt_file: str, cfg_path: str, device: torch.device):
"""
Load a YOLO model from a .pt file containing a pre-saved state_dict.
Args:
pt_file (str): Path to the .pt file.
cfg_path (str): Path to the YAML configuration file.
... | Python | 1 |
+ 'static,
C::Api: kumandra_primitives::KumandraSessionApi<B>,
B: Block,
BE: Backend<B> + 'static,
{
fn authorities(&self, num: NumberFor<B>) -> Option<Vec<AuthorityId>> {
self.client
.runtime_api()
.authorities(&BlockId::Number(num))
.ok()
}
fn next... | Rust | 0 |
from const import *
def from_mpsz(s):
hand = []
type = None
for c in reversed(s):
if c.isspace():
continue
if c in "mpsz":
type = c
elif c.isdigit():
tile = int(c) - 1
if type == "m":
tile = Tile.RedManzu5 if tile == -... | Python | 1 |
.unwrap()
.try_apply_eui_hack()
.and_then(|chunk| {
self.0[6..8].copy_from_slice(&u16::to_be_bytes(chunk.into()));
Some(self)
}),
_ => None,
}
}
fn reverse_eui48_hack(mut self) -> Option<Self> {
... | Rust | 0 |
h/ClojureRS
use crate::ifn::IFn;
use crate::value::{ToValue, Value};
use std::rc::Rc;
use crate::error_message;
use crate::type_tag::TypeTag;
/// clojure.string/includes? ; returns true if string contains substring
#[derive(Debug, Clone)]
pub struct IncludesFn {}
impl ToValue for IncludesFn {
fn to_value(&self) -... | Rust | 0 |
);
let file_id = lookup_file(&self.db, path).ok_or_else(|| {
CompileError::FileSystemError(FileSystemError::FileDoesNotExist(path.to_owned()))
})?;
let _hir = self.db.get_hir(file_id);
Ok(())
}
pub fn interned_name(&self, name: Name) -> String {
self.db.lo... | Rust | 0 |
# Copyright(C) 2013-2014 Florent Fourcot
#
# This file is part of a woob module.
#
# This woob module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your ... | Python | 1 |
, Clone)]
pub struct cx_groestl_s {
pub header: cx_hash_header_s,
pub output_size: cty::c_uint,
pub ctx: hashState_s,
}
impl Default for cx_groestl_s {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
pub type cx_groestl_t = cx_groestl_s;
extern "C" {
pub fn cx_groestl_init_no... | Rust | 0 |
rmat.
audience: string, The audience, 'aud', that this JWT should contain. If
None then the JWT's 'aud' parameter is not verified.
Returns:
dict, The deserialized JSON payload in the JWT.
Raises:
AppIdentityError if any checks are failed.
"""
segments = jwt.split('.')
if (len(segments) !=... | Python | 1 |
: Pipe
, ; + - * / % & # ## | ~ ^ $ @ § = == < <= > >= ( ) [ ] { } \\
^
sdk/foo/foo.fidl: 10:27: Tilde
, ; + - * / % & # ## | ~ ^ $ @ § = == < <= > >= ( ) [ ] { } \\
^
sdk/foo/foo.fidl: 10:29: Caret
, ; + - * / % & # ## | ~ ^ $ @ § = == < <= > >= ( ) [ ] { } \\
... | Rust | 0 |
ver(branch):
current_dir = os.path.join(RELEASES, "current")
branch_dir = os.path.join(RELEASES, branch)
run('rm -rf %s' % branch_dir)
run('mkdir %s' % branch_dir)
run('s3cmd get s3://kite-deploys/%s/release %s' % (branch, branch_dir))
run('rm -f %s' % current_dir)
run('ln -s %s %s' % (bra... | Python | 1 |
")
.value_name("FILE")
.help("specifies a zakopane config")
.takes_value(true),
)
.arg(
Arg::with_name(DEFAULT_POLICY_ARG_NAME)
.short("d")
.long("d... | Rust | 0 |
with_types(&env, &func.args)
} else {
return Err(error_invalid_data!("Expected arguments but found none."));
}
}
}
.map_err(|e| error_invalid_data!("Unable to serialize Candid values: {}", e))?;
Ok(typed_... | Rust | 0 |
"""
You have m types of coins available in infinite quantities
where the value of each coins is given in the array S=[S0,... Sm-1]
Can you determine number of ways of making change for n units using
the given types of coins?
https://www.hackerrank.com/challenges/coin-change/problem
"""
from __future__ import print_func... | Python | 1 |
branch {}",
match branch_type {
git2::BranchType::Local => "local",
git2::BranchType::Remote => "remote",
},
branch_name
))?)
}
fn name_without_remote(&self) -> &str {
let components: Vec<&str> = self.name.split("/").collect();
assert!(components.len() == 1 || compone... | Rust | 0 |
import os
import json
import streamlit as st
from pymongo import MongoClient
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Get MongoDB URI
mongo_uri = os.getenv("MONGODB_URI", "mongodb://localhost:27017/")
# Connect to MongoDB
try:
client = MongoClient(mongo_uri)
client.server_i... | Python | 1 |
delete().from_table(Item::Table).and_where(Expr::col(Item::CategoryId).eq(id)).done(), Some(&mut tx)).await?;
tx.commit().await?;
BIOSResp::ok("", None)
}
#[derive(Deserialize, Validate)]
pub struct CategoryListReq {
#[validate(length(min = 2, max = 10))]
name: Option<String>,
}
#[derive(Deserialize,... | Rust | 0 |
from manim import *
from manim_voiceover import VoiceoverScene
from manim_voiceover.services.gtts import GTTSService
import os
class Scene0(VoiceoverScene, Scene):
def construct(self):
self.set_speech_service(GTTSService(lang="en"))
# Load all logo images from the imgs/ directory
img_dir =... | Python | 1 |
import xmltodict
import json
def xml_json_file(xml_file_path, json_file_path):
with open(xml_file_path, "r") as xml_file:
xml_content = xml_file.read()
parsed_data = xmltodict.parse(xml_content)
json_data = json.dumps(parsed_data, indent=4)
with open(json_file_path, "+w") as json_file... | Python | 1 |
// TODO: RelocatedNodeConnection_Reset
self.start_check_elder_timeout()
}
fn vote_parsec_check_elder(&mut self) {
self.0.action.vote_parsec(ParsecVote::CheckElder);
}
fn vote_parsec_neighbour_merge(&mut self, section_info: SectionInfo) {
self.0
.action
.... | Rust | 0 |
),
mem::transmute_copy(&new),
success,
failure,
))
}
_ => fallback::atomic_compare_exchange(dst, current, new),
}
}
#[inline]
pub unsafe fn atomic_compare_exchange_weak<T>(
dst: *mut T,
current: T,
new: T,
success: Ordering... | Rust | 0 |
"""
Test custom Django management commands.
"""
from unittest.mock import patch
from psycopg2 import OperationalError as Psycopg2Error
from django.core.management import call_command
from django.db.utils import OperationalError
from django.test import SimpleTestCase
@patch('core.management.commands.wait_for_db.Comm... | Python | 1 |
#[derive(Debug)]
pub enum _NFC_HAL_EVENT_ {
NFC_HAL_READER_PRESENT = 1,
NFC_HAL_READ = 2,
NFC_HAL_WRITE = 4,
NFC_HAL_ERR = 8,
NFC_HAL_CACHE_RD = 16,
}
pub type NFC_CB_EVENT = _NFC_HAL_EVENT_;
pub type PNFC_CB_EVENT = *mut _NFC_HAL_EVENT_;
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug)]
pub struc... | Rust | 0 |
}
}
}
}
#[doc = "Reader of register RFADDRH"]
pub type R = crate::R<u32, super::RFADDRH>;
#[doc = "Reader of field `MACADDR4`"]
pub type MACADDR4_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:7 - MACADDR4"]
#[inline(always)]
pub fn macaddr4(&self) -> MACADDR4_R {
MACADDR4_R::new((self.bits & 0... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.