text string | label_name string | labels int64 |
|---|---|---|
sh", "fish"];
const FUNC_POSSIBLE_VALUES: &[&str] = &["url::open", "welcome", "widget::last_command", "map::expand"];
const INFO_POSSIBLE_VALUES: &[&str] = &["cheats-example", "cheats-path", "config-path", "config-example"];
impl FromStr for Shell {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self... | Rust | 0 |
irstValue | BuiltInWindowFunction::LastValue => {
Signature::any(1, Volatility::Immutable)
}
BuiltInWindowFunction::Ntile => {
Signature::exact(vec![DataType::UInt64], Volatility::Immutable)
}
BuiltInWindowFunction::NthValue => Signature::any(2, Volatility::Immuta... | Rust | 0 |
../trait.Entity.html) extended interface.
///
/// Rather than add a non-standard member to the [`Document`](../trait.Document.html) trait
/// this function takes a `Document` as the first parameter.
///
pub fn create_notation(
owner_document: RefNode,
notation_name: &str,
public_id: Option<&str>,
system... | Rust | 0 |
# coding=utf-8
# Copyright 2025 The Google Research Authors.
#
# 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 applicab... | Python | 1 |
in lemma_results:
final = final + lemma
final_dict[word] = final
if self.understand_query_part(word) == "token+tag":
# query looks like token+feature_type=feature_value
token_and_tags = word.split("+")
token = token_and_ta... | Python | 1 |
from typing import List
def closedIsland(grid: List[List[int]]) -> int:
"""
Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.
Return the number of clo... | Python | 1 |
o
qg @ s$ d dl mZ d dlmZ ddgZdS ) )SparseDtype)SparseArrayr r N)pandas.core.dtypes.dtypesr pandas.core.arrays.sparser __all__ r r eC:\Users\devid\Desktop\Daily-Practice\Attendance App\venv\lib\site-packages\pandas\core\sparse\api.py<module> ... | Python | 1 |
enderingFlagBits = 4;
pub const VK_RENDERING_FLAG_BITS_MAX_ENUM: VkRenderingFlagBits = 2147483647;
pub type VkRenderingFlagBits = ::std::os::raw::c_uint;
pub type VkRenderingFlags = VkFlags;
pub type VkFormatFeatureFlags2 = VkFlags64;
pub type VkFormatFeatureFlagBits2 = VkFlags64;
pub const VK_FORMAT_FEATURE_2_SAMPLED_... | Rust | 0 |
p} count={}", sem, count);
sem
}
pub unsafe extern "C" fn sem_free(sem: *mut lkl_sem) {
trace!("lkl sem_free {:p}", sem);
let to_free = Box::from_raw(sem);
drop(to_free);
}
pub unsafe extern "C" fn sem_up(sem: *mut lkl_sem) {
trace!("{:?} lkl sem_up {:p}", Environment::tid(), sem);
let sem = ... | Rust | 0 |
urn 0, window_size
else:
return length - window_size, length
def gather_features(was, pred_track_indice, pred_visibility, i, k, start, end):
feats = []
for j in range(start, end):
if pred_visibility[j, k] > 0:
coords = pred_track_indice[j, k]
feats.append(was[j, :, c... | Python | 1 |
d_add (second.exponent).and_then (| total | total.checked_add (64)).is_none() {
return TestResult::discard()
}
TestResult::from_bool (((first*second)/second).includes (&first))
}
fn divide (first: Range, second: Range)->TestResult {
if second.includes_0() {
return TestResult::d... | Rust | 0 |
2_val,
zp_loss_val,
d_loss1_val,
d_loss2_val)
x_hat_batch_val, total_loss_batch_val = sess.run([x_hat_batch, total_loss_batch], feed_dict=feed_dict)
best_keeper.re... | Python | 1 |
et length: Index = 8;
let head: Index = 0;
let tail: Index = head + CAPACITY;
let _src_index: Index = 0;
test.ab.put::<i64>(HEAD_COUNTER_INDEX, head as i64);
test.ab.put::<i64>(TAIL_COUNTER_INDEX, tail as i64);
let err = test
.ring_buffer
.write(... | Rust | 0 |
let account = ensure_signed(origin)?;
let domain_count = DomainCount::get();
ensure!(domain_count < MAX_DOMAINS, Error::<T>::DomianLimitReached);
// We don't want to add duplicate domains, so we check whether the potential new
// domain is already pres... | Rust | 0 |
, isEqual = true and the matchTree can be used
// in place of the regex r. If singleLine = true, then the matchTree and all
// its children only match terms on the same line. singleLine is used during
// recursion to decide whether to return an andLineMatchTree (singleLine = true)
// or a andMatchTree (singleLine = fal... | Rust | 0 |
{
self.visit_str(v.as_str())
}
}
impl<'de> Deserialize<'de> for UniformDate {
fn deserialize<D>(deserializer: D) -> Result<UniformDate, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(UniformDateVisitor)
}
}
}
... | Rust | 0 |
as_raw_DAISY(), y, x, orientation, descriptor) }.into_result()
}
/// ## Parameters
/// * y: position y on image
/// * x: position x on image
/// * orientation: orientation on image (0->360)
/// * descriptor: supplied array for descriptor storage
/// * H: homography matrix for warped grid
fn get_unnormalized_d... | Rust | 0 |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_price = float('inf')
max_profit = 0
for p in prices:
if p < min_price:
min_price = p # buy cheaper if we can
elif p - min_price > max_profit:
max_profit = p - m... | Python | 1 |
type Ux = u32;
}
#[doc = "`read()` method returns [gpio_cfgctl14::R](R) reader structure"]
impl crate::Readable for GPIO_CFGCTL14_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [gpio_cfgctl14::W](W) writer structure"]
impl crate::Writable for GPIO_CFGCTL14_SPEC {
type Writer = W;
}
#[doc = "`... | Rust | 0 |
fn update_dependent(&mut self) {}
}
dyn_clone::clone_trait_object!(<T: StateContract> State<T>);
use crate::{Error, Result, SubgraphConfig};
use apollo_federation_types::SubgraphDefinition;
use camino::Utf8PathBuf;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fs};
/// The configuration... | Rust | 0 |
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
return self.search(url ,season ,episode)
def sources(self, url, hostDict, hostprDict):
sources = []
try:
if url == None: return sources
headers = {
'U... | Python | 1 |
previous = pickle.load(open("result.pickle", "rb"))
except IOError:
previous = {}
results = {}
d = 0.0
d += run_test(rep, "VARIANT()", previous=previous, results=results)
d += run_test(rep, "VARIANT(by_var)", previous=previous, results=results)
d += run_test(rep, "VARIANT(ptr_var)"... | Python | 1 |
import duckdb, numpy as np, logging
from web_scraper.config import ENV,S3_BUCKET,STORAGE_ROOT
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def get_local(duck_con,table_name):
full_path = STORAGE_ROOT + table_name
processed = check_files(duck_con,full_path)
return processed
... | Python | 1 |
g_item(config_key)
if not target_downloaders:
return target_downloader_ids
for target_downloader in target_downloaders:
if target_downloader == 'default':
target_downloader = settings.DEFAULT_DOWNLOADER
if target_downloader and target_downloader not in... | Python | 1 |
KEY.trim_end().into(),
};
let config = LoraConfig::new()
.region(LoraRegion::EU868)
.lora_mode(LoraMode::WAN)
.spreading_factor(SpreadingFactor::SF9);
defmt::info!("Configuring with config {:?}", config);
static mut RADIO_BUFFER: [u8; 256] = [0; 256];
let lora = unsafe {
... | Rust | 0 |
: live variables = %s, weak live variables = %s"
% (index, sorted(yp.live_vars), sorted(yp.weak_live_vars)),
file=file)
def render_dot(self, filename_prefix="numba_ir", include_ir=True):
"""Render the CFG of the IR with GraphViz DOT via the
``graphviz`` python bi... | Python | 1 |
import logging
import spacy
from spacy.matcher import PhraseMatcher
log = logging.getLogger(__name__)
nlp = spacy.blank("en")
nlp.vocab.lex_attr_getters = {}
def build_term_vocab(terms: list[str]):
"""Builds nlp vocabulary."""
for v in terms:
texts = [v, v.lower(), v.upper(), v.title()]
for... | Python | 1 |
'''
Ossim Action Responses Framework (Cisco)
This script requires snmpset
You need a list of valid devices/communities
'''
import os
import sys
import commands
import re
device = '192.168.1.252'
comm = 'private'
#Close a specific tty
def closeTTY(tty):
os.system('snmpset -c %s -v 1 %s 1.3.6.1.4.1.9.2.9.10.0 integer... | Python | 1 |
# -*- coding: utf-8 -*-
"""
.. _example_explore_database_vaex:
================================
Explore Line Database Parameters
================================
Database will be downloaded automatically and can be edited locally.
The :ref:`Download HITRAN Database example <example_download_hitemp>` showed
how to do... | Python | 1 |
trace!(system_run_mode = "splinter");
let mut bindings = self.make_bindings_storage(inputs)?;
let mut total_count = 0;
let mut stopped = false;
'firing: for rule in &self.rules {
total_count += runtime::splinter_rule(rule, tx, &mut bindings, |new_tx| {
let re... | Rust | 0 |
().unwrap().as_raw_fd()).reregister(poll, token, interest, opts)
}
fn deregister(&self, poll: &Poll) -> std::io::Result<()> {
EventedFd(&self.read.lock().unwrap().as_raw_fd()).deregister(poll)
}
}
#[cfg(target_os = "macos")]
impl SpawnQueue {
fn new_impl() -> Fallible<Self> {
let spawn... | Rust | 0 |
import pytest
from unittest.mock import patch, MagicMock
import os
from app.core.query_parser import QueryParser
from app.core.llm_client import LLMClient
from app.models.metadata import QueryMetadata
def test_query_parsing_integration():
"""测试查询解析的集成流程"""
# 创建一个模拟的查询文本
sample_query_text = "寻找3年以上经验的Pyth... | Python | 1 |
# flake8: noqa
from pre_award.fund_store.config.fund_loader_config.cof.cof_r4 import (
APPLICATION_BASE_PATH_COF_R4_W1,
)
from pre_award.fund_store.config.fund_loader_config.cof.cof_r4 import (
ASSESSMENT_BASE_PATH_COF_R4_W1,
)
from pre_award.fund_store.config.fund_loader_config.cof.cof_r4 import COF_ROUND_4_WI... | Python | 1 |
number {
1 => {
::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.registration)?;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
},
... | Rust | 0 |
son: List of the labels for x_poison.
:return: A pair of poisoned samples, B-score (cosine similarity of the gradients).
"""
self.backdoor_model.compile(loss=None, optimizer=self.optimizer)
callbacks = [self.lr_schedule]
if self.verbose > 0:
from tqdm.keras import Tq... | Python | 1 |
#[inline(always)]
pub fn cfg(&mut self) -> CFG_W {
CFG_W { w: self }
}
}
<gh_stars>1-10
#![cfg(feature = "cloudformation")]
extern crate rusoto_core;
extern crate rusoto_cloudformation;
use rusoto_cloudformation::{CloudFormation, CloudFormationClient, ListStacksInput};
use rusoto_core::{DefaultCredent... | Rust | 0 |
00F
"#;
pub trait VecLike<T>: AsRef<[T]> {
fn clear(&mut self);
fn push(&mut self, item: T);
}
impl<T> VecLike<T> for Vec<T> {
#[inline]
fn clear(&mut self) {
Vec::clear(self)
}
#[inline]
fn push(&mut self, item: T) {
Vec::push(self, item)
}
}
impl<A: Array> VecLike<... | Rust | 0 |
::{
Builder,
Env
};
use futures::{
prelude::*,
select
};
#[async_std::main]
async fn main() -> Result<(), Box<dyn Error>> {
Builder::from_env(Env::default().default_filter_or("info")).init();
println!("GOSSIP SUB");
let local_key = identity::Keypair::generate_ed25519();
let local_pe... | Rust | 0 |
"""Сделайте сценарий для добавления нового товара (продукта) в учебном приложении litecart (в админке).
Для добавления товара нужно открыть меню Catalog, в правом верхнем углу нажать кнопку "Add New Product",
заполнить поля с информацией о товаре и сохранить.
Достаточно заполнить только информацию на вкладках General, ... | Python | 1 |
= ref_33266 # MOV operation
ref_36732 = ref_33370 # MOV operation
ref_37630 = ref_17346 # MOV operation
ref_37714 = ref_36732 # MOV operation
ref_37718 = ref_37630 # MOV operation
ref_37720 = (ref_37718 | ref_37714) # OR operation
ref_37821 = ref_37720 # MOV operation
ref_37835 = (ref_37821 >> (0x1 & 0x3F)) # SHR oper... | Python | 1 |
import os
import torch
from torchlogic.nn import LukasiewiczChannelAndBlock, LukasiewiczChannelOrBlock, Predicates, ConcatenateBlocksLogic
from pytest import fixture
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
PARENT_DIR = os.path.abspath(ROOT_DIR)
class TestLukasiewiczChannelBlock:
@fixture
def... | Python | 1 |
gEnabled: DWORD,
FlightingLevel: DWORD,
DynamicConfig: PVOID,
AutoSampleSubmission: DWORD,
EnableThreatLogging: DWORD,
ProductName: PWCHAR,
PassiveMode: DWORD,
SenseEnabled: DWORD,
SenseOrgId: PWCHAR,
Attributes: DWORD,
BlockAtFirstSeen: DWORD,
PUAProtection: DWORD,
SideBySidePassiveMode: DWORD,... | Rust | 0 |
"""
def __init__(self, data_path, custom_grouping=None, **kwargs):
"""
"""
if custom_grouping is None:
num_classes = 601
label_mapping = None
else:
num_classes = len(custom_grouping)
label_mapping = get_label_mapping("custom_imagen... | Python | 1 |
icalize & store chunks
assert isinstance(chunks, dict)
op._chunks = {
pxu.as_canonical_axes(
ax,
rank=op.dim_rank,
)[0]: chunk_size
for (ax, chunk_size) in chunks.items()
}
# Update op.apply() to perform re-chunking
def op_apply(_, arr: pxt.NDArray) -... | Python | 1 |
RI, 1, env);
function!(global, name::ENCODE_URI_COMPONENT, Global_encodeURIComponent, 1, env);
value!(global, name::NAN, JsValue::new_number(f64::NAN), false, false, false, env);
value!(global, name::INFINITY, JsValue::new_number(f64::INFINITY), false, false, false, env);
value!(global, name::UNDEF... | Rust | 0 |
{
if let Some(p) = $val.get(&$index) {
match p {
Value::Array(arr) => {
let mut ret = vec![];
for v in arr {
if let Value::String(s) = v {
ret.push(s.clone());
}
... | Rust | 0 |
$crate::interpreter::Value::Intrinsic(
$crate::interpreter::Intrinsic($name),
),
);)*
hm
};
}
};
}
macro_rules! intrinsics {
(
pkg $pkg_name:tt as $ty_name:ident;
$(mod $module_name:tt as $mod_name:i... | Rust | 0 |
alloc, heap);
impl<'a, T : Clone+'a> HeapPrealloc<'a, T> {
fn make_freelist(freelist_size : usize) -> std::boxed::Box<[&'a mut[T]]> {
let mut retval = Vec::<&'a mut[T]>::with_capacity(freelist_size);
for _i in 0..freelist_size {
retval.push(&mut[]);
}
return retval.into_... | Rust | 0 |
{
return Err(error::NetworkManager::Config(error::Config::NotSupported {
msg: "Invalid mac address".to_string(),
}));
}
Ok(lifmgr::DhcpReservation {
id: ElementId::default(),
name,
address: allocations.ip_address,
ma... | Rust | 0 |
..Default::default()
},
],
stats: vec![
Stat::new(StatName::Damage, 10.0),
],
modifier: vec![
ModifierBase::Poison(Poison::new(Entity::new(0), 5.0, 2.0, 5)),
],
};
let ron_file_data = ron::ser::to_string_pretty(&sword, ... | Rust | 0 |
raw_text!("foo")],
soydoc_params: vec![],
}],
},
),
];
cases.iter().for_each(|(input, expected)| {
assert_eq!(
parse!(input, (soy_file, parse_soyfile)).unwrap(),
*expected,
"\n{}",
input
);
... | Rust | 0 |
from pypalace import Config, Domains, Boundaries, Solver
my_sim = Config("Eigenmode",Output="eigenmode_output")
my_sim.add_Model("eigenmode_example.bdf")
# define materials
silicon = Domains.Material([1],1.0,11.45,0.0)
air = Domains.Material([2],1.0,1.0,0.0)
my_materials = [silicon,air] # material list for input into... | Python | 1 |
) -> c_int {
*(hdpa as *mut c_int) -= 1;
*(hdpa as *mut c_int)
}
#[inline]
pub unsafe fn DPA_AppendPtr(hdpa: HDPA, pitem: *mut c_void) -> c_int {
DPA_InsertPtr(hdpa, DA_LAST, pitem)
}
extern "system" {
pub fn DPA_GetSize(hdpa: HDPA) -> ULONGLONG;
pub fn DPA_Sort(hdpa: HDPA, pfnCompare: PFNDACOMPARE,... | Rust | 0 |
x_y_z
return bool(v_to_blocks[x] & v_to_blocks[y] & v_to_blocks[z])
# Check that every quadruple contains an even number of triples
for quad in combinations(range(T.num_points()), 4):
if sum(map(has_triple, combinations(quad, 3))) % 2:
return False
return True
def twograph_d... | Python | 1 |
tuff["name"]
}
def main(args):
split = args.split
name = args.name
print(f"{split}.{name}")
results = []
with open("data.jsonl", "r") as f:
opinions = f.readlines()
opinions = [get_opinions(x) for x in opinions]
opinions = [x for x in opinions if len(x["text"]) > 3000]
... | Python | 1 |
m_envs, 12, device='cuda:0'), delta_pos, torch.zeros(num_envs, 2, device='cuda:0')], dim=-1) + dof_states[:, 0].view(num_envs, 20)
gym.set_dof_position_target_tensor(sim, gymtorch.unwrap_tensor(pos))
else:
gym.set_dof_actuation_force_tensor(sim, gymtorch.unwrap_tensor(torch.cat([u, torch... | Python | 1 |
み層
"""
def __init__(self, in_channels, out_channels, kernel_size=9, dilation=1, conv='edge', act='relu',
norm=None, bias=True, stochastic=False, epsilon=0.0, r=1):
super(DyGraphConv2d, self).__init__(in_channels, out_channels, conv, act, norm, bias)
self.k = kernel_size # カーネルサ... | Python | 1 |
instream.close()
pairpath = pairsam_path.replace('.pairsam.gz', '.pairs.gz')
if SAM:
bampath = pairsam_path.replace('.pairsam.gz', '.bam')
split_command = ['pairtools', 'split', '--output-pairs', pairpath,
'--output-sam', bampath, pairsam_path]
subprocess.check_... | Python | 1 |
ator]
worker_truth = truth_matrix[truth_matrix['worker'] == annotator]
k = get_k(worker_votes)
q = get_real_q(worker_truth, 'conf_mat').to_list()
# if only one human label, then q[0] and q[1] is same
if len(q) == 1:
q.append(q[0])
#... | Python | 1 |
raise ValueError(f"Invalid longitude: {value}")
return float(value)
# Type checking helpers
def is_geohash_series(obj: object) -> bool:
"""Check if object is a pandas Series of geohashes."""
if not _HAS_PANDAS:
return False
from pandas import Series
return isinstance(obj, Series) ... | Python | 1 |
2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C208%2C753%2C0%5D)
#[bitfield]
#[derive(Debug, Copy, Clone, BitfieldSpecifier)]
pub struct BSCFG {
pub bs_pre_ki: BsPreKi,
pub bs_pre_kp: BsPreKp,
pub bs_post_ki: BsPostKi,
pub bs_post_kp: BsPostKp,
pub bs_limit: BsLimit,
}
/// [AGC Control 2](http... | Rust | 0 |
Vec<X> */
fn std_group_unzip<X: Eq + Ord + Clone + Hash + PartialEq + PartialOrd,Y: Eq + Ord + Clone + Hash + PartialEq + PartialOrd>(g: & std_Group<(X, Y)>) -> (std_Vec<X>, std_Vec<Y>)
{ let ref mut xs : std_Vec<X> = std_vec_empty();
let ref mut ys : std_Vec<Y> = std_vec_empty();
for ref v in g.iter() {
... | Rust | 0 |
_split_list:
segment_validation_cnt += df_validation[civ_list[i].var_name][df_validation[civ_list[i].var_name] == m].count()
psi_dict['segment_validation_cnt'].append(segment_validation_cnt)
psi_dict['segment_validation_percentage'].append(float(segment_validation_cn... | Python | 1 |
"cost": 25.00,
"estimated_delivery": "2025-01-20",
"tracking_number": "SF1234567890"
}
}
},
"analytics": {
"source": "web",
"campaign": "新年促销",
"device_ty... | Python | 1 |
p.map_pos, dir);
let v2 = geom::map_pos_to_world_pos(p2).extend(0.0);
WorldPos{v: (v + v2) / 2.0}
}
SlotId::WholeTile => {
WorldPos{v: v + index_to_circle_vertex_rnd(n, 0, p.map_pos).v * 0.2}
}
SlotId::Air => {
let v = v + vec3_z(2.0);
... | Rust | 0 |
#!/usr/bin/python
#
# knn_hand_written.py
# Test the hand written classification with KNN
#
# Author : Ashing Tsai
# Date : 2016/11/17
# Origin : http://arbu00.blogspot.tw/2016/11/1-opencv-knn.html
# Usage : DO "python knn_ocr_sample.py" BEFORE "python knn_hand_written.py"
import numpy as np
import cv2
from matplot... | Python | 1 |
"""
Emonoda -- A set of tools to organize and manage your torrents
Copyright (C) 2015 Devaev Maxim <mdevaev@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either vers... | Python | 1 |
rentialIntegrity;
use pretty_assertions::assert_eq;
#[test]
fn must_error_if_multiple_datasources_are_defined() {
let dml = indoc! {r#"
datasource db1 {
provider = "postgresql"
url = "postgresql://localhost"
}
datasource db2 {
provider = "mysql"
url ... | Rust | 0 |
::exit;
mod cli;
mod event;
///
/// User will pass in a command file, this could be a raw file or a location to the file
///
/// cli could create a script from some yaml file, but for now we will just expect the script to be in the FS OR passed in raw
/// cli will read file and determine some things
/// the type of j... | Rust | 0 |
, 10, 10) != 0;
self.vpm_read.size = get_bits_u32(command, 9, 8) as usize;
self.vpm_read.addr = get_bits_u32(command, 7, 0) as usize;
if self.vpm_read.num == 0 {
self.vpm_read.num = 16;
}
if self.vpm_read.stride == 0 {
... | Rust | 0 |
d_at = alerts.get('retrieved_at')
return process_alert_data(response, retrieved_at)
@display_spinner('Getting alerts for zone...')
def get_alerts_by_zone(session: CachedSession, zone: str) -> List[Alert]:
alerts = api_request(session, NWS_API_ALERTS_ZONE + zone)
response = alerts.get('response')
retrieved_at = al... | Python | 1 |
import glob
import logging
import os
import numpy as np
class FeatureHolder:
"""
Looks at the folder and load all .npy files as users/items features.
File formats:
<user/item>_<modality>_features.npy where modality can be text, image, audio, cf etc.
"""
def __init__(self, da... | Python | 1 |
def solve(grid):
h = len(grid)
w = len(grid[0]) if h>0 else 0
out = [row[:] for row in grid]
shape_coords = [(i,j) for i in range(h) for j in range(w) if grid[i][j]==3]
pink_coords = [(i,j) for i in range(h) for j in range(w) if grid[i][j]==6]
if not shape_coords or not pink_coords:
retu... | Python | 1 |
me = "ai_accuracy_report.pdf"
# except ValueError as e:
# # Handle error if no reports found or any issues during PDF generation
# return {"error": str(e)}
# # Email content
# email_body = "<h2>Your Weekly AI Emotion Accuracy Report</h2><p>Attached is your detailed report for the week from ... | Python | 1 |
Step};
use hbbft::NetworkInfo;
use network::{Adversary, MessageScheduler, NodeId, SilentAdversary, TestNetwork, TestNode};
type QHB = QueueingHoneyBadger<usize, NodeId, Vec<usize>>;
/// Proposes `num_txs` values and expects nodes to output and order them.
fn test_queueing_honey_badger<A>(mut network: TestNetwork<A,... | Rust | 0 |
32) over `Rate` type to minimize internal division
/// operation.
#[pallet::constant]
type GetStableCurrencyExchangeFee: Get<(u32, u32)>;
/// The limit for length of trading path
#[pallet::constant]
type TradingPathLimit: Get<u32>;
/// The DEX's module id, keep all assets in DEX.
#[pallet::constant]
... | Rust | 0 |
from pathlib import Path
from tempfile import mkstemp
import pytest
from madminer.models import Observable
from madminer.utils.interfaces.hdf5 import EMPTY_EXPR
from madminer.utils.interfaces.hdf5 import _load_observables
from madminer.utils.interfaces.hdf5 import _save_observables
@pytest.fixture(scope="function")... | Python | 1 |
sert!(filepath.as_path().starts_with("/home/"));
assert!(filepath
.as_path()
.ends_with(".revault_coordinatord/config.toml"));
}
}
}
<gh_stars>1-10
/// Reports an intersection back to the traversal infrastructure.
///
/// If the intersection occurred within the cu... | Rust | 0 |
from unittest import TestCase, main, skip
from c2py.core import CXXParser
from c2py.core.cxxparser import Arch, CXXParserExtraOptions
class ConstantType(TestCase):
@skip("always false: I don't know to to deal with this")
def test_undef(self):
src = """
#define A 1234
#undef A
... | Python | 1 |
ers: Default::default(),
timestamps: Default::default(),
analog_channels: Default::default(),
status_channels: Default::default(),
line_frequency: Default::default(),
sampling_rates: Default::default(),
start_time: NaiveDateTime::from_timestamp(0, ... | Rust | 0 |
if overwrite_learner_info:
result["info"].update(
{
"learner_queue": self.learner_queue_size.stats(),
LEARNER_INFO: copy.deepcopy(self.learner_info),
"timing_breakdown": {
"learner_grad_time_ms": ti... | Python | 1 |
= 8388608;
pub const VK_PIPELINE_STAGE_COMMAND_PREPROCESS_BIT_NV: VkPipelineStageFlagBits = 131072;
pub const VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV: VkPipelineStageFlagBits = 2097152;
pub const VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV: VkPipelineStageFlagBits = 33554432;
pub const VK_PIPELINE_STAGE_... | Rust | 0 |
import logging
from flask import render_template
from itsdangerous import URLSafeTimedSerializer
from redash import settings
from redash.tasks import send_mail
from redash.utils import base_url
logger = logging.getLogger(__name__)
serializer = URLSafeTimedSerializer(settings.SECRET_KEY)
def invite_token(user):
... | Python | 1 |
: HashMap::new(),
scratch_registers: SCRATCH_REGISTERS.iter().map(|r| (*r, false)).collect(),
label_idx: 0,
ctx: Context::default(),
functions: HashMap::new(),
generating_functions: vec![],
}
}
}
use crate::schrage::jobs::{Job, JobList, SchrageJobT... | Rust | 0 |
> 0:
stats['blue_side_avg_pick_pos'] = round(stats['blue_side_avg_pick_pos'] / stats['blue_side_pick_count'], 1)
stats['blue_side_winrate'] = round((stats['blue_side_win_count'] / stats['blue_side_pick_count']) * 100, 2)
if stats['red_side_pick_count'] > 0:
s... | Python | 1 |
use std::path::PathBuf;
use utils::*;
use std::hash::Hash;
use std::sync::{Mutex, Arc};
use std::cmp::min;
use serde::{Deserialize, Serialize};
use serde_json::json;
use flare_utils::file_utils::open_file;
use call_tree::*;
use std::ops::{Index, Deref, DerefMut};
use flare_utils::stopwatch::*;
use std::str::FromStr;
u... | Rust | 0 |
day - 1) % 7];
fish_per_day[(day - 1) % 7] += new_fish;
if day == final_day {
break;
}
}
fish_per_day.iter().sum::<usize>() + fish1 + fish2
}
pub fn part1() -> usize {
run(80)
}
pub fn part2() -> usize {
run(256)
}
#[cfg(test)]
mod tests {
use super::*;
... | Rust | 0 |
per::*;
pub trait AsAny {
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
}
impl<T: Any> AsAny for T {
fn as_any(&self) -> &dyn Any {
return self;
}
fn as_any_mut(&mut self) -> &mut dyn Any {
return self;
}
}
/// Trait for Building a Widget
pub trait Widget: AsAny + 'static {
// T... | Rust | 0 |
n32_System_IO"))]
pub fn ProcessSocketNotifications(completionport: super::super::Foundation::HANDLE, registrationcount: u32, registrationinfos: *mut SOCK_NOTIFY_REGISTRATION, timeoutms: u32, completioncount: u32, completionportentries: *mut super::super::System::IO::OVERLAPPED_ENTRY, receivedentrycount: *mut u32) ... | Rust | 0 |
128.0 would be completely filled in.
/// The value can be changed by clicking and dragging on the shape.
#[derive(Clone, CloneRef, Debug)]
pub struct NumberPicker {
/// Public FRP api of the Component.
pub frp: Rc<number::Frp>,
model: Rc<Model>,
/// Reference to the application the Component belongs ... | Rust | 0 |
# type: (Optional[str]) -> None
if node in path:
# We hit a cycle, so we'll break it here.
return
# Time to visit the children!
path.add(node)
for child in graph.iter_children(node):
visit(child)
path.remove(node)
last_known_pare... | Python | 1 |
s raised.
:param max_failed_attempts: The maximum number of times to an attempt
at making a request should be done before throwing an exception.
:param reattempt_pause_base: The base of the exponential backoff -- the
time between each attempt.
**Warning**: This function assumes ... | Python | 1 |
if args.test_repeats==1:
current_iou, current_acc = metric.evaluate(pred_logit.numpy(),
gt.numpy(),
dataset=labelset_name,
... | Python | 1 |
from functools import total_ordering
@total_ordering
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def __str__(self):
return f"Name is {self.name}\nSalary is {self.salary}"
# it also works for != (not equal to)
def __eq__(self, other... | Python | 1 |
network: Option<String>,
}
pub fn exec(env: &dyn Environment, opts: CanisterBuildOpts) -> DfxResult {
let env = create_agent_environment(env, opts.network)?;
let logger = env.get_logger();
// Read the config.
let config = env.get_config_or_anyhow()?;
// Check the cache. This will only insta... | Rust | 0 |
C/' + args.model + '.ckpt'
restore_path = './models/' + args.model + '.ckpt'
logs_path = './logs'
tf.reset_default_graph()
CAE = ConvAE(n_input=n_input, n_hidden=n_hidden, reg_constant1=reg1, re_constant2=reg2, \
kernel_size=kernel_size, batch_size=batch_size, model_path=model_path, res... | Python | 1 |
"Rover's GraphQL linter package does not seem to be located here:\n{}",
&npm_lint_directory
));
}
Ok(Self {
runner,
npm_installer_package_directory,
npm_lint_directory,
})
}
/// prepares our npm installer pac... | Rust | 0 |
#!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2010 VoltDB L.L.C.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limita... | Python | 1 |
from src.core.models import Issue, WorkflowState
from src.core.platform import AutonomyPlatform, BaseWorkflow
from src.planning.config import PlanningConfig
class DummyWorkflow(BaseWorkflow):
def _build_graph(self):
return {"step": self.do_step}
def do_step(self, state):
state["done"] = True
... | Python | 1 |
Commits
def uncommittedChangesMessage(self) -> str:
""" Can be overridden """
summaryText = _("Working Directory") + " "
# Append change count if available
numChanges = self.repoModel.numUncommittedChanges
if numChanges == 0:
summaryText += _("(Clean)")
e... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.