text string | label_name string | labels int64 |
|---|---|---|
import pytest
from stupidb.associative.bitset import BitSet
def test_construction() -> None:
bs = BitSet()
assert not bs
assert len(bs) == 0
bs = BitSet({1, 2})
assert len(bs) == 2
assert list(bs) == [1, 2]
with pytest.raises(ValueError):
BitSet({2, -1})
def test_repr() -> Non... | Python | 1 |
^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
//! ...
//! | let more_results = ocaml_call!(another_ocaml_function(cr, result)).unwrap();
//! | ------ immutable borrow later used here
//! |
//! ```
//!
//! There is no need to keep values that are... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Generating different waveforms
"""
from __future__ import print_function, division
import tellurium as te
from roadrunner import Config
# We do not want CONSERVED MOIETIES set to true in this case
Config.setValue(Config.LOADSBMLOPTIONS_CONSERVED_MOIETIES, False)
model = '''
model wavefo... | Python | 1 |
: i16::from_be_bytes([data[3], data[4]]),
temperature: i16::from_be_bytes([data[6], data[7]]),
}
}
}
/// Raw signal measurement. Raw signals include the standard signals.
#[derive(Debug, Copy, Clone)]
pub struct RawSignals {
pub standard: Signals,
/// Raw VOC output ticks as read from t... | Rust | 0 |
# from https://github.com/ALBERT-Inc/blog_nerf/blob/master/NeRF.ipynb
import torch
import torch.nn as nn
import torch.nn.functional as F
def _init_weights(m):
if type(m) == nn.Linear:
nn.init.kaiming_normal_(m.weight)
nn.init.zeros_(m.bias)
class RadianceField(nn.Module):
"""Radiance Field ... | Python | 1 |
since we just checked `s.is_empty`.
.split_at(val.len() - 1);
// gRPC spec specifies `TimeoutValue` will be at most 8 digits
// Caping this at 8 digits also prevents integer overflow from ever occurring
if timeout_value.len() > 8 {
return Err(val);
... | Rust | 0 |
ess(pid))
}
lazy_static! {
static ref SYSTEM: RwLock<System> = {
let mut s = System::new();
s.refresh();
RwLock::new(s)
};
}
struct System {
system: sysinfo::System,
}
// Mark our private `System` wrapper as `Send` and `Sync`, we can make a global.
//
// We may mark the type as `S... | Rust | 0 |
le_name).linear.pp_block
if pp_rank == current_pp_rank:
# We already have the weights locally
non_linear = model.get_submodule(module_name).linear.pp_block
torch.testing.assert_close(
non_linear.weight.grad,
reference_no... | Python | 1 |
import pandas as pd
import numpy as np
import sys
# LightGBM是实现GBDT算法(梯度提升决策树,一种回归算法)的框架
# 其中LGBMRegressor类是专门用于解决回归问题的模型(连续值的回归)
from lightgbm import LGBMRegressor as LGBR
from sklearn.model_selection import GridSearchCV
import warnings
# 后面用KFold测测性能
from sklearn.model_selection import KFold
from preprocess import pr... | Python | 1 |
let bg_thresh = 180.0;
let fg_thresh = 70.0;
let secondary_min = 160.0;
let secondary_max = 160.0;
let bg = adjust_lighten(pal[temp2[0].0], temp2[0].1, bg_thresh);
let fg = adjust_darken(pal[temp2[colors - 1].0], temp2[colors - 1].1, fg_thresh);
let secondary = adjust_li... | Rust | 0 |
y3qpk as wv8aoc0axy6, s67zd825frt, xamo2przrxq, yy7jz6s103g as yoj7x2eil6j, iy9q2nronfz as f1yjryknly8, znh__bwah1r
@{False for mdtso73q8_7 in w9ngaw1vlut if 0.0 for i6c1thi8u_z in w3xt9wz21hi if '' for f62akf0wcag in oppf2ouguxy if None}
@{h9rmqisdkvz, ru2t5s2nec7, b'', 0j, dsqcqw00vx5}
def bd25sb9qgpd(oxgj5a2jfex: gn... | Python | 1 |
Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Statement": [
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
... | Rust | 0 |
state = self.state[p]
# State initialization
if len(state) == 0:
state['step'] = 0
# Exponential moving average of gradient values
state['exp_avg'] = torch.zeros_like(p.data)
# Exponential moving average o... | Python | 1 |
return Err(anyhow!("Empty separator cannot be used for partitioning"));
}
if let Some(offset) = this.typed.find(needle.typed) {
let offset2 = offset + needle.typed.len();
Ok((
heap.alloc(this.typed.get(..offset).unwrap()),
needle.value,
... | Rust | 0 |
jects
# Notifications groups
# Agent capabilities
# Module compliance
# Export all MIB objects to the MIB builder
mibBuilder.exportSymbols(
"A3COM-HUAWEI-TUNNEL-MIB",
**{"H3cTunnelType": H3cTunnelType,
"h3cTunnel": h3cTunnel,
"h3cTunnelMIBObjects": h3cTunnelMIBObjects,
"h3cTunnelTa... | Python | 1 |
grel'.format(new_data_name)
geo = pd.read_csv(geo_file)
rel = pd.read_csv(rel_file)[['orig_geo_id', 'dest_geo_id']]
geo_uids = list(geo['id'])
geo_to_ind = {}
ind_to_geo = {}
for index, geo_uid in enumerate(geo_uids):
geo_to_ind[geo_uid] = index
ind_to_geo[index] = geo_uid
... | Python | 1 |
def f1():
print('Hello this is from module1 present in com')
| Python | 1 |
ap => 5,
TSEncoding::GorillaV1 => 6,
TSEncoding::Regular => 7,
TSEncoding::Gorilla => 8,
}
}
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum TSCompressionType {
UNCOMPRESSED = 0,
SNAPPY = 1,
GZIP = 2,
LZO = 3,
SDT = 4,
PAA... | Rust | 0 |
vaswani_wmt_en_de_big(args)
@register_model_architecture(
"transformer_pointer_generator", "transformer_pointer_generator_wmt_en_de_big"
)
def transformer_pointer_generator_wmt_en_de_big(args):
args.attention_dropout = getattr(args, "attention_dropout", 0.1)
transformer_pointer_generator_vaswani_wmt_en_de... | Python | 1 |
matches: &getopts::Matches) -> Result<keys::Key, anyhow::Error> {
if let Some(k) = cli_to_opt_key(matches)? {
Ok(k)
} else {
anyhow::bail!("please set --key, BUPSTASH_KEY or BUPSTASH_KEY_COMMAND");
}
}
fn cli_to_opt_key(matches: &getopts::Matches) -> Result<Option<keys::Key>, anyhow::Error>... | Rust | 0 |
"""
Provides .props file.
"""
import os
from .constants import *
__all__ = ["get_props_layout"]
PYTHON_PROPS_NAME = "python.props"
PROPS_DATA = {
"PYTHON_TAG": VER_DOT,
"PYTHON_VERSION": os.getenv("PYTHON_NUSPEC_VERSION"),
"PYTHON_PLATFORM": os.getenv("PYTHON_PROPS_PLATFORM"),
"PYTHON_TARGET": "",
... | Python | 1 |
avajo","ha":"Navajo","haw":"Navajo","hmn":"Navajo","ig":"Najo","ku":"Navajo","ny":"Navajo","or":"ନାଭାଜୋ","ps":"ناوا","sd":"نوواجو","sm":"Navajo","sn":"Navajo","so":"Nadii qorrax","st":"Navajo","ug":"ناۋا","yo":"Navajo"},"x":{"t":"living","scope":"individual"}},"naw":{"3":"naw","e":"Nawuri","x":{"t":"living","scope":"in... | Python | 1 |
.subcommand(
SubCommand::with_name("ram")
.about("Dump current active settings (RAM) as yaml"),
),
)
.subcommand(SubCommand::with_name("snoop").about("Snoop MIDI messages"))
.subcommand(
SubCommand::with_name... | Rust | 0 |
from abc import ABC, abstractmethod
from typing import List, Set
from marie.extract.models.base import Blob
from marie.extract.models.definition import ExecutionContext, FieldMapping, Layer
from marie.extract.models.match import MatchFieldRow, MatchSection, Span
class RowExtractionHandler(ABC):
"""
Row Extra... | Python | 1 |
are represented by ndarray's
/// [Dimension](https://docs.rs/ndarray/latest/ndarray/trait.Dimension.html) trait.
///
/// Typically, you can use `Ix1, Ix2, ..` for fixed size arrays, and use `IxDyn` for dynamic
/// dimensioned arrays. They're re-exported from `ndarray` crate.
///
/// You can also use various type alias... | Rust | 0 |
the Safaricom API docs [here](https://developer.safaricom.co.ke/docs#b2b-api)
///
/// Requires an `initiator_name`, the credential/ username used to authenticate the transaction request
///
/// # Example
/// ```ignore
/// let response = client.b2b("testapi496")
/// .party_a("600496")
... | Rust | 0 |
# thyroid/models.py
from django.db import models
class Thyroid(models.Model):
MALE = 'male'
FEMALE = 'female'
GENDER_CHOICES = [
(MALE, 'Male'),
(FEMALE, 'Female'),
]
YES = 'yes'
NO = 'no'
DONT_KNOW = "don't know"
STATUS_CHOICES = [
(YES, 'Yes'),
(N... | Python | 1 |
)?;
let server_appender =
Appender::builder().build("server".to_owned(), Box::new(server_appender));
config = config.appender(server_appender);
if log_to_console {
let console_appender = AsyncConsoleAppender::builder()
.encoder(Box::new(make_pattern(sho... | Rust | 0 |
d::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use id_arena::Arena;
use crate::common::analyze_resource::peachili_type::Type;
use crate::common::option;
use crate::common::{ast, peachili_type, three_address_code as tac};
type ValueCache = BTreeMap<ast::ExpressionNode, tac::ValueId>;
/// 4つ組生成のメインルーチン
pub fn... | Rust | 0 |
t::InputState::new(window.inner_size());
let event_bucket = input::EventBucket(Vec::new());
#[cfg(feature = "rd")]
rd.start_frame_capture(std::ptr::null(), std::ptr::null());
let size = window.inner_size().to_physical(window.hidpi_factor());
let aspect = (size.width / size.height) as f32;
let... | Rust | 0 |
=> x.parameters(),
State::Fail(x) => x.parameters(),
State::Pass(x) => x.parameters(),
State::Parallel(x) => x.parameters(),
State::Map(x) => x.parameters(),
}
}
fn result_selector(&self) -> io::Template {
match self {
State::Task(x) ... | Rust | 0 |
nothing with it.
fn double_drop(self, _: T);
}
// Implement `DoubleDrop<T>` for any generic parameter `T` and
// caller `U`.
impl<T, U> DoubleDrop<T> for U {
// This method takes ownership of both passed arguments,
// deallocating both.
fn double_drop(self, _: T) {}
... | Rust | 0 |
from random import *
from easygui import*
import time
import os
while True:
msgbox("欢迎",title="Desktop4.1")
n = enterbox("请选择功能,打开,质数判断,随机数,加密解密,抛硬币模拟器,退出",title="Desktop4.1")
if n == "随机数":
w = enterbox("请输入随机数最小值",title="Desktop4.1")
v = enterbox("请输入随机数最大值",title="Desktop4.1")
x ... | Python | 1 |
cted =
ServiceGroup::new("blue-ocean", "track-from_album", Some("f-l_y".to_string()));
let actual = ServiceGroup::from_str("blue-ocean.track-from_album@f-l_y").unwrap();
assert_eq!(expected, actual);
}
#[test]
#[should_panic(expected = "not.allowed@")]
fn from_str_ending_wit... | Rust | 0 |
oin(args.in_dir, "*.wav")) + glob.glob(
os.path.join(args.in_dir, "*.flac")
)
audio_f = [x for x in audio_f if re.search(args.mic_regex, Path(x).stem)]
if args.uem_file:
uem_map = read_uem(args.uem_file)
# joint diarization of all mics
sess2audio = {}
for audio_file ... | Python | 1 |
trix multiplication-esque thing between the two arrays
# Instead of summing, we want the equality, so we reduce in that way
# The rows correspond to GT triplets, columns to pred triplets
keeps = intersect_2d(gt_triplets, pred_triplets)
gt_has_match = keeps.any(1)
pred_to_gt = [[] for x in range(pred... | Python | 1 |
calibration_dataset=psm_list_cal_df,
reference_dataset=reference_dataset,
per_charge=calibrate_per_charge,
use_charge_state=use_charge_state,
)
LOGGER.info("Calibration applied successfully.")
excep... | Python | 1 |
self.deleted = True
def set_expiry(self, value):
self.expiry_time = value
self.cookie.expiry_time = value
def _is_not_expiry(self, accessed_time, expiry_time):
return time.time() < accessed_time + expiry_time
def _check(f):
def _func(self, *args, ... | Python | 1 |
in self.nodes:
return
dist = levenstein_distance(word, cur_node.word)
if dist not in cur_node.next:
self.nodes[word] = cur_node.next[dist] = BurkhardKellerNode(word)
else:
self.__add(cur_node.next[dist], word)
def add(self, word: str):
"""Insert ... | Python | 1 |
# click_xpath calls into scroll=True.
self.do_scroll_to_grammar_field(mid)
self.test_case.click_xpath(
f"(//*[@mid='{mid}' "
"and "
"@data-testid='form-move-down-field-action-custom-field'])"
)
def do_scroll_to_grammar_field(self, mid: MID) -> None:
... | Python | 1 |
X86,
/// 64-х разрядная
X64,
}
impl V8Arch {
/// Осуществляет попытку определения разрядности платформы 1С. Логика определения различается в
/// зависимости от текущей ОС:
/// * Windows - по файлу 1cv8s.exe находящегося в папке bin. Читается его PE
/// [сигнатура](https://docs.microsoft.co... | Rust | 0 |
import torch
def expand(ori_path, new_path):
st_dict = torch.load(ori_path)
st_dict['net.geolayoutlm_model.text_encoder.embeddings.position_ids'] = \
torch.cat(
(st_dict['net.geolayoutlm_model.text_encoder.embeddings.position_ids'],
st_dict['net.geolayoutlm_model.text_encoder.... | Python | 1 |
fn set_hp(&mut self, hp: Meter<i32>) {
if let Some(f) = self.sel {
match self.combatants[f] {
BattleRow::Done(ref mut c) => c.hp = hp,
BattleRow::Building(ref mut cb) => cb.hp = Some(hp),
}
}
}
/// Heal the selected combatant.
fn heal(... | Rust | 0 |
then(|q| q.r#type).unwrap_or(NumberType::Decimal);
match t {
NumberType::Decimal => {
let context = DefaultContext::new_decimal();
let functions = services::get_functions(&context);
Ok(HttpResponse::Ok().json(functions))
}
NumberType::Float => {
... | Rust | 0 |
rd::Iesna1995,
"IESNA:LM-63-2002" => IesStandard::Iesna2002,
_ => IesStandard::Iesna1986,
}
}
}
impl From<String> for IesStandard {
fn from(str: String) -> Self {
Self::from(str.as_str())
}
}
impl std::fmt::Display for IesStandard {
fn fmt(&self, f: &mut std::fm... | Rust | 0 |
import torch
'''adpated from domainbed.algorithms MMD'''
class MMD():
def __init__(self, gaussian=True):
if gaussian:
self.kernel_type = 'gaussian'
else:
self.kernel_type = 'mean_cov'
def my_cdist(self, x1, x2):
x1_norm = x1.pow(2).sum(dim=-1, keepdim=True)
... | Python | 1 |
ss="button_link" target="_blank">👄 App 7: WER speech feedback</a>', unsafe_allow_html=True)
with tab6:
st.header('Explore the resources below')
st.write("to improve your English pronunciation skills.")
st.markdown("---")
# Dictionary of useful links and their descriptions
... | Python | 1 |
teral(char: &char) -> bool {
!NON_LITERAL_CHARS.contains(char)
&& !NEWLINE_CHARS.contains(char)
&& !WHITESPACE_CHARS.contains(char)
}
fn potential_eol(char: &char) -> bool {
NEWLINE_CHARS.contains(char)
}
fn potential_whitespace(char: &char) -> bool {
WHITESPACE_CHARS.contains(char)
}<filename>j... | Rust | 0 |
th is None:
continue # Skip unresolved libraries
# Look for ``libnss3.so``.
if os.path.basename(lib_path).startswith('libnss3.so'):
# Find the location of NSS: given a ``/path/to/libnss.so``, search ``/path/to/nss/*.so`` to get the
... | Python | 1 |
'''
Names: nick nojiri & ariel winkler
Date: 2/27/2025
Description: moving square on a 20x20 grid program
'''
import check_input
import rectangle
def display_grid(grid):
""" displays the 20x20 grid of dots and the rectangle """
for row in grid:
for item in row:
print(item, end="")
... | Python | 1 |
{
#[cfg(feature = "log")]
log::trace!("retro_core_options_update_display_callback_fn()");
if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
return wrapper.core.on_core_options_update_display();
}
panic!("retro_core_options_update_display_callback_fn: Core has not been initialized yet!");
}... | Rust | 0 |
from ChainBuilder import ChainBuilder
from Exrop import Exrop
from Gadget import *
import sys
import code
from keystone import *
def asm_ins(code):
ks = Ks(KS_ARCH_X86, KS_MODE_64)
insns = bytes(ks.asm(code)[0])
return insns
if len(sys.argv) == 1:
print("use: {} test_file".format(sys.argv[0]))
sys... | Python | 1 |
fn
def get_score_fn(sde, model, train=False, continuous=False):
"""Wraps `score_fn` so that the model output corresponds to a real time-dependent score function.
Args:
sde: An `sde_lib.SDE` object that represents the forward SDE.
model: A score model.
train: `True` for training and `False` for evalua... | Python | 1 |
00:00");
let acpi_root_bus_path = String::from("/devices/pci0000:00");
let mut acpi_sysfs_dir = String::from(SYSFS_DIR);
let mut sysfs_dir = String::from(SYSFS_DIR);
let mut start_root_bus_path = String::from("/devices/platform/");
let end_root_bus_path = String::from("/pci0000:00");
// check ... | Rust | 0 |
from odoo import _, models, api
class AccountMoveSend(models.AbstractModel):
_inherit = 'account.move.send'
@api.model
def _get_l10n_ke_edi_tremol_warning_moves(self, moves):
return moves.filtered(lambda m: m.country_code == 'KE' and not m._l10n_ke_fiscal_device_details_filled())
@api.model
... | Python | 1 |
.push(((x1, y1), (x2, y2)));
}
Ok(result)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_part1() {
let input = read_input_from_file("example1.txt").expect("failed to read input");
assert_eq!(5, part1(&input));
}
#[test]
fn test_part2() {
let input = ... | Rust | 0 |
mut arr = [first, 0x90, 0xa0, 0xb0];
let extra = first.extra_utf8_bytes().unwrap();
for corrupt in (1..extra).rev() {
let expected = NotAContinuationByte(corrupt);
for &bad in &[0x00, 0x3f, 0x40, 0x7f, 0xc0, 0xff] {
arr[corrupt] = bad;
assert_eq!... | Rust | 0 |
fn allocates(&self) -> bool { true }
fn display_op(&self, _: bool) -> String { format!("nullable({}, {})", self.data, self.present) }
}
use std::fmt;
packable_newtype! {
/// Attribute Handle.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Handle(u16);
}
impl Handle {
/// Const... | Rust | 0 |
rguments in element-creation macros, and handle
/// each type appropriately.
pub trait UpdateEl<Ms> {
fn update_el(self, el: &mut El<Ms>);
}
/// Similar to `UpdateEl`, specialized for `Iterator`.
#[allow(clippy::module_name_repetitions)]
pub trait UpdateElForIterator<Ms> {
fn update_el(self, el: &mut El<Ms>);
... | Rust | 0 |
entity_id,
Entity::new(
entity_id,
1,
"entity",
root_id,
parts,
Transform2F::from_translation(Vector2F::splat(200.0)),
0.0,
),
);
let state = State {
... | Rust | 0 |
+str(data.loc[row,'title'])))
except:
pass
new_word_list2=[]
for i in new_word_list:
if len(i)<30 and len(i)>0:
new_word_list2.append(i)
new_word=pd.DataFrame({'word':list(keyword)+list(new_word_list2)+list(newword)})
new_word.to_csv('../data/newword.txt',header=None,index=None)
print (new_word... | Python | 1 |
.to_dict(), mnemonic).map_err(|err| Error::from(err))?;
let size_words = size / 32 * 3;
let words_count = mnemonics.get_type().mnemonic_count();
if size_words > words_count {
return Err(Error::MnemonicToShort(words_count, size_words));
}
if size_words < words_count {
return Err(Error::MnemonicToLong(w... | Rust | 0 |
)
.await?;
create_row(
&runner,
r#"{ id: 2, b: null, key: "abc2", c: { create: { id: 2, c: "C2" } } }"#,
)
.await?;
run_query!(
&runner,
r#"mutation {
updateOneA(
where: { b: "abc" }
data: ... | Rust | 0 |
st, may be empty.",
)
parser.add_argument(
"--stargazer-ts-snapshot-inpath",
default="",
metavar="PATH",
help="Read snapshot-based stargazer time series from CSV file "
"(helps accounting for the 40k limit). File not required to exist. ",
)
parser.add_argument(
... | Python | 1 |
nd 10+ Hours. """)
waste_bag = tab3.selectbox('What is the size of your waste bag?', ['small', 'medium', 'large', 'extra large'])
waste_count = tab3.slider('How many waste bags do you trash out in a week?', 0, 10, 0)
recycle = tab3.multiselect('Do you recycle any materials below?', ['Plastic', 'Paper', 'Me... | Python | 1 |
# Atividade 10:
# Soma até 50:
# Escreva um programa que use um laço while para somar
# números consecutivos começando de 1 e termine quando
# a soma atingir ou ultrapassar 50.
c = 0
n = 0
s = 0
while c < 50:
c += 1
s += c
print(s) | Python | 1 |
# 如果你是Python36。请删除37、38、39的pyd文件,其他版本同理
# 小提示:因为Pycharm无法识别pyd文件,这句话可能会报红,无视或配置一下就行了,不影响使用
from WeChatPYAPI import WeChatPYApi
import time
import logging
from queue import Queue
import os
# 当前目录路径
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
logging.basicConfig(level=logging.INFO) # 日志器
msg_queue = Queue... | Python | 1 |
SYMBOLS);
test_layout!(test_symbols_layout_norwegian, LAYOUT_NORWEGIAN, SYMBOLS);
test_layout!(
test_symbols_layout_united_kingdom,
LAYOUT_UNITED_KINGDOM,
SYMBOLS
);
<reponame>gky360/acick
use std::collections::BTreeMap;
use acick_util::{regex, select};
use anyhow::Context as _;
use once_cell::sync::Lazy;
... | Rust | 0 |
pub struct Scalar(pub [u8; BYTES]);
#[derive(Debug)]
pub struct GroupElement(pub [u8; BYTES]);
pub fn scalarmult_base(n: &Scalar) -> GroupElement {
lazy_static::initialize(&super::SODIUM);
let mut q = GroupElement([0; BYTES]);
unsafe {
crypto_scalarmult_curve25519_b... | Rust | 0 |
}
}
fn get_parameter(&self, offset: usize, instr: Instruction) -> IntCodeCell {
let index = self.pc + offset;
match instr.modes[offset - 1] {
Position => self.memory[self.memory[index]],
Immediate => self.memory[index],
Relative => self.memory[self.memory[in... | Rust | 0 |
dkg_tag,
target_subnet: NiDkgTargetSubnet::Remote(target_id),
},
max_corrupt_dealers: NumberOfNodes::new(0),
dealers: nodes_in_subnet.iter().copied().take(1).collect(),
max_corrupt_receivers: number_of_nodes_from_usize(max_corrupt_receivers),
... | Rust | 0 |
use crate::section_0110::max_quarterword;
use crate::section_0110::min_halfword;
use crate::section_0110::min_quarterword;
use crate::section_0920::trie_pointer;
use crate::section_0925::hyph_pointer;
use crate::section_1306::undump;
use crate::section_1306::undump_hh;
use crate::section_130... | Rust | 0 |
ESCE_ADAPTIVE_TX", "coalesce-adaptive-tx"),
("NM_ETHTOOL_OPTNAME_COALESCE_PKT_RATE_HIGH", "coalesce-pkt-rate-high"),
("NM_ETHTOOL_OPTNAME_COALESCE_PKT_RATE_LOW", "coalesce-pkt-rate-low"),
("NM_ETHTOOL_OPTNAME_COALESCE_RX_FRAMES", "coalesce-rx-frames"),
("NM_ETHTOOL_OPTNAME_COALESCE_RX_FRAMES_HIGH", "coa... | Rust | 0 |
ways be
/// called first, unless WebPGetFeatures() is to be called.
/// Returns false in case of mismatched version.
#[allow(non_snake_case)]
#[inline]
pub unsafe extern "C" fn WebPInitDecoderConfig(config: *mut WebPDecoderConfig) -> c_int {
WebPInitDecoderConfigInternal(config, WEBP_DECODER_ABI_VERSION)
}
#[cfg(t... | Rust | 0 |
fn size_to_coord(size: Size) -> COORD {
COORD{
Y: to_short(size.lines),
X: to_short(size.columns),
}
}
fn has_alt(state: DWORD) -> bool {
state & (wincon::LEFT_ALT_PRESSED | wincon::RIGHT_ALT_PRESSED) != 0
}
fn has_ctrl(state: DWORD) -> bool {
state & (wincon::LEFT_CTRL_PRESSED | winc... | Rust | 0 |
Configuration, self.direction_mask)
}
}
use super::Generator;
use crate::particles::*;
use crate::quantity::{ScalarQuantity, Units};
use crate::vector::Vector3;
use rand::distributions::Standard;
use rand::prelude::*;
use rand_distr::{Distribution, Normal};
use std::f64::consts::PI;
/// Struct that handles creatio... | Rust | 0 |
box,
transform, 0i32 as libc::c_float,
(*plane).matrix.as_mut_ptr() as
*const libc::c_float);
wlr_renderer_begin(rend, (*plane).surf.width as libc::c_int,
(*plane).surf.height as libc::c_i... | Rust | 0 |
ame"]
name: String
}
fn main() {}
use middle::ir::MOpcode;
use middle::ssa::cfg_traits::CFG;
use middle::ssa::ssa_traits::*;
use middle::ssa::ssastorage::SSAStorage;
use petgraph::graph::NodeIndex;
use std::collections::HashSet;
pub fn run(ssa: &mut SSAStorage) -> () {
loop {
let copies = CopyInfo::... | Rust | 0 |
SOURCES_INTERNATIONAL = [
{"url": "https://www.espn.com/espn/rss/soccer/news", "label": "ESPN FC"},
{"url": "https://www.skysports.com/rss/12040", "label": "Sky Sports Football"},
{"url": "https://www.skysports.com/rss/12037", "label": "Sky Sports Tennis"},
{"url": "https://www.skysports.com/rss/12038",... | Python | 1 |
stretch::style::Node {
width: stretch::style::Dimension::Percent(0.5),
..Default::default()
},
],
..Default::default()
};
let layout = stretch::compute(&node);
println!("{:#?}", layout);
}
<gh_stars>0
//! This library adapts the bl... | Rust | 0 |
let lines = LINES_WRITTEN.swap(0, Ordering::Relaxed);
println!(
"LINES PER SECOND: {} | TOTAL PACKETS PER SECOND: {}",
lines, packets
);
let second = time::Duration::from_millis(1000);
thread::sleep(second);
}
}
fn main() {
let matches = App::new... | Rust | 0 |
nator::recognize;
use combine::parser::range::{take_while, take_while1};
use combine::parser::repeat::escaped;
use combine::parser::Parser;
use combine::{
attempt, choice, eof, many, many1, one_of, optional, parser, satisfy, skip_many1, value,
};
use once_cell::sync::Lazy;
use regex::Regex;
use super::user_input_a... | Rust | 0 |
}
#[test]
// Test where keys create the longest path
fn insert_longest_path() {
let db = MemoryDb::new();
let mut trie = Trie::new(TestConfig::new(db));
let key_a = [0u8; 32];
let mut key_b = [0u8; 32];
key_b[30] = 1;
trie.insert_single(key_a, key_a);
... | Rust | 0 |
#!/usr/bin/env python3
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
def bin_to_decimal(binary):
try:
decimal = int(binary, 2)
return decimal
except ValueError:
return None
def decimal_to_bin(decimal):
try:
... | Python | 1 |
SCORE_MIN_NEG : # or 1 == 1 :
# from XTB_api import xtb_api
# thr_xtb = threading.Thread(target=xtb_api.xtb_operate_Lock_thread, args=(S, df_mul[1:].to_dict('list'), _KEYS_DICT.Op_buy_sell.POS, list_models_to_predict_POS), name='XTB_POS')
# thr_xtb.start()
# xtb_api.xtb_operate_Lock_thre... | Python | 1 |
G, state: S, n: usize, f: fn(&'a G, &S, usize) -> P) -> Self {
Generate {
generator,
state,
range: 0..n,
f,
}
}
}
impl<'a, G, S, P> Iterator for Generate<'a, G, S, P>
where
G: 'a,
{
type Item = P;
fn next(&mut self) -> Option<Self::Item> ... | Rust | 0 |
<< 16usize) + 3 {
return Err(Error::InvalidSignature(format!("dss too long. (len = {})", dss.len())));
}
if dss.len() < 4 {
return Err(Error::InvalidSignature(format!("Invalid dss: {}\n Too short. Expected at least 4 bytes.", &utils::u8_to_hex(dss))));
}
let sig_type = u16::from_be_bytes([dss[0], dss... | Rust | 0 |
s.spawn(
DEFAULT_STACK_SIZE_BYTES,
move |_| {
let _r = timelog1.push((Environment::tid(), Instant::now()));
Environment::thread().sleep(t1_waittime);
let _r = timelog1.push((Environment::tid(), Instant::now()));
},
ptr::nul... | Rust | 0 |
# Created for BADS 2018
# See README.md for details
# Python 3
import math
import sys
from itu.algs4.fundamentals.stack import Stack
from itu.algs4.stdlib import stdio
def evaluate():
ops = Stack()
vals = Stack()
while not stdio.isEmpty():
# Read token, push if operator
s = stdio.readSt... | Python | 1 |
its);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
... | Rust | 0 |
in bytes."""
class StringType(core.ModelBase):
"""StringType"""
type: typing.Literal["string"] = "string"
StructFieldName = str
"""The name of a field in a `Struct`."""
class TimestampType(core.ModelBase):
"""TimestampType"""
type: typing.Literal["timestamp"] = "timestamp"
TotalCount = core.Lo... | Python | 1 |
project_id = os.getenv("AGENT_ENV_PROJECT_ID")
dataplex_region = os.getenv("AGENT_ENV_DATAPLEX_REGION")
messages = []
url = f"https://dataplex.googleapis.com/v1/projects/{project_id}/locations/{dataplex_region}/dataScans/{knowledge_engine_scan_name}?view=FULL"
if "projects/" in knowledge_engine_scan_... | Python | 1 |
#Problem: Print All Sub-arrays of an Array
#Declaring the Function
def print_all_subarrays(arr):
n = len(arr)
for start in range(n):
for end in range(start, n):
print(arr[start:end+1])
#Implementation
array = [1, 2, 3, 4]
print_all_subarrays(array)
| Python | 1 |
points")
print("Elapsed time for the entire processing: {:.2f} s".format(stop - start))
###############################################################################
# The processing time only corresponds to the execution of the ``max``
# function. The internal call to ``costly_compute_cached`` is reloading the
# re... | Python | 1 |
#leetcode easy difficulty problem, https://leetcode.com/problems/two-sum/description/
#given a list of numbers and a target number, find the two numbers in the list that add up to the target
def twoSum(nums, target):
dict = {}
for index, val in enumerate(nums):
if val in dict.values():
retur... | Python | 1 |
let animdata_file = std::fs::File::open(&animdata_path)?;
let animdata_type: u8 = match animdata_path.extension().and_then(OsStr::to_str).unwrap() {
"json" => 1,
"js" => 2,
_ => return Err("Can't find animation data".into()), // TODO better animdata_type matching
};
let json: HashM... | Rust | 0 |
: [
{
"id": "0",
"label": "Person",
"properties": {
"name": "Harry"
}
},
... | Python | 1 |
\[[docs.microsoft.com](https://docs.microsoft.com/en-us/windows/win32/api/d3d11shader/nf-d3d11shader-id3d11moduleinstance-bindconstantbufferbyname)\]
/// ID3D11ModuleInstance::BindConstantBufferByName
///
/// Rebinds a constant buffer by name to a destination slot.
///
/// ### Arguments
/// * ... | Rust | 0 |
ken}'}
# Request a date far in the future where no data exists
future_date = (date.today() + timedelta(days=30)).strftime("%Y-%m-%d")
res = client.get(f'/calendar-report?start_date={future_date}&end_date={future_date}', headers=headers)
assert res.status_code == 200
progress_data = re... | Python | 1 |
# -*- coding: utf-8 -*-
from odoo import api, fields, models
class ResCurrency(models.Model):
_inherit = 'res.currency'
_order = 'active desc, sequence, name'
sequence = fields.Integer('Sequence', default=10, help="Determine the display order. Sort ascending.")
def rmb_upper(self, value):
""... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.