text string | label_name string | labels int64 |
|---|---|---|
[cfg(any(armv6m, armv8m_base))]
assert!(
System::CPU_LOCK_PRIORITY_MASK == 0,
"`CPU_LOCK_PRIORITY_MASK` must be zero because the target architecture \
does not have a BASEPRI register"
);
}
<gh_stars>10-100
// Copyright 2019-2020 Parity Protocol.
// This file is part of Parity.
// Pari... | Rust | 0 |
0d65944ee913e3c784669dd201b1985ef3577f7f123a5f9bcffa176c8f557c4f729133cac518642f27d9b22ca9b97faaafe5b669a10b79ace4a7d5727df146c77ce681357d69f9c2d65b4401bd73cd113387e3b3a05d897adad7a24c485e7b").unwrap();
let input = decode("a644ca6e7cc076e87eb2929fd257693fce0f6fb64fd632f7f07c648ebd03696c8e262e6a810d7b7c4e5eef8c65b5323... | Rust | 0 |
commit", &[]).unwrap().to_string();
let commit1 = Commit::get_commit(&oid1).unwrap();
assert!(matches!(commit1, Commit { parent: None, .. }));
assert_eq!(commit1.message, "test".to_string());
let commit2 = Commit::get_commit(&oid2).unwrap();
assert!(matches!(
commit2,
Commit {
... | Rust | 0 |
queta de columna repetida, que la hay: T8-P8
s = df.columns.to_series()
df.columns = s + s.groupby(s).cumcount().astype(str).replace({'0':''})
assert(len(df)//256 == file_duration)
# df.to_hdf(f'CHBMIT/chb12/signal_chb12.h5', key='data_frame', format='table', mode='w')
# df.to_hdf(f'CHBMIT/chb12/si... | Python | 1 |
util::PreVec;
//For sweep and prune type algorithms, we can narrow down which bots
//intersection in one dimension. We also need to check the other direction
//because we know for sure they are colliding. That is the purpose of
//this object.
struct OtherAxisCollider<'a, A: Axis + 'a, F: CollisionHandler + 'a> {
a... | Rust | 0 |
import torch
from unaiverse.agent import Agent
from unaiverse.dataprops import Data4Proc
from unaiverse.modules.networks import CNN
from unaiverse.networking.node.node import Node
# Agent
net = CNN(d_dim=10, in_channels=1, seed=42)
net.transforms = lambda x: x # Processing tensor data
agent = Agent(proc=net,
... | Python | 1 |
# そのため、次がhuman_review_nodeの場合、ツールの呼び出しが失敗したことをStateに追加
# 参考: https://langchain-ai.github.io/langgraph/how-tos/human_in_the_loop/review-tool-calls/#give-feedback-to-a-tool-call
if self.is_next_human_review_node(thread_id):
last_message = self.get_messages(thread_id)[-1]
tool_re... | Python | 1 |
c_ip,
server_identifier,
};
Some(ClientState::Renew(p_state))
}
_ => None
}.map(|new_state| self.state = new_state);
config
}
fn egress<DeviceT: for<'d> Device<'d>>(&mut self, iface: &mut Interface<DeviceT>, raw_socket... | Rust | 0 |
#!/usr/bin/python
# ---------------------------------------------------------------------------------------------------------------------
# Author : Peter Heijligers
#
# Date Ini Description
# ---------- --- -----------------------------------------------------------------------------------------------------... | Python | 1 |
# Copyright (c) 2024 Cisco Systems, Inc. and its affiliates
#
# 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 limitation the rights to
# use, copy, modi... | Python | 1 |
of parenthesized expressions in the compiled regular expression.
///
/// This returns `None` if [`RegexCFlags::NOSUB`] was passed to [`Self::compile()`].
#[inline]
pub fn nsub(&self) -> Option<usize> {
if self.nosub {
None
} else {
Some(unsafe { *(&self.preg as *... | Rust | 0 |
import datetime
from gazette.items import Gazette
from gazette.spiders.base import BaseGazetteSpider
class GoAparecidaDeGoianiaSpider(BaseGazetteSpider):
TERRITORY_ID = "5201405"
name = "go_aparecida_de_goiania"
allowed_domains = ["aparecida.go.gov.br"]
start_urls = ["https://webio.aparecida.go.gov.b... | Python | 1 |
ERROR_MSG = "Something went wrong.Please contact the administrator."
NOT_CANTEEN_MANAGER_MSG = "You Should be a CANTEEN MANAGER to access this API"
NOT_TEACHER_MSG = "You Should be a TEACHER to access this API"
NOT_STUDENT_MSG = "You Should be a STUDENT to access this API"
NOT_DELIVERY_AGENT_MSG = "You Should be a DELI... | Python | 1 |
rking')
try:
n_yag2 = electrons.getNode('\\knobs:pulses_q_2').data()
except:
n_yag2 = 0
print('Laser 2 may not be working')
dark = electrons.getNode('\\n_dark_prior').data()
n_total = electrons.getNode('\\n_total').data()
# dark = OMFITmdsValue(server='CMOD', shot=shot, tre... | Python | 1 |
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# สร้างตารางสำหรับผลการวิเคราะห์
cursor.execute('''
CREATE TABLE IF NOT EXISTS dm_analysis_results (
id INTEGER PRIMARY KEY AUTOINCREMENT,
analysis_type TEXT,
... | Python | 1 |
"system/xbin" in i) or ("vendor/bin" in i):
gid = '2000'
else:
gid = '0'
mode = '0755'
if ".sh" in i:
mode = "0750"
else:
for s in ["/bin/su", "/xbin/su", "disable_selinux.... | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# 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... | Python | 1 |
_W - 1, int(dots[i][0] * scale_factor_w))] = 1
# resized_density = ndimage.gaussian_filter(resized_density, sigma=4, radius=7, order=0)
resized_density = ndimage.gaussian_filter(resized_density, sigma=4, order=0)
resized_density = torch.from_numpy(resized_density) * 60
# Crop bboxes and... | Python | 1 |
ath = Path(trainer.checkpoint_callback.best_model_path)
assert ckpt_path.exists()
callback = OldStatefulCallback(state=222)
trainer = Trainer(default_root_dir=tmp_path, max_steps=2, callbacks=[callback])
trainer.fit(model, ckpt_path=ckpt_path)
assert callback.state == 111
def test_resume_incomple... | Python | 1 |
xtern "C" {
pub fn rd_kafka_CreateTopics_result_topics(
result: *const rd_kafka_CreateTopics_result_t,
cntp: *mut size_t,
) -> *mut *const rd_kafka_topic_result_t;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rd_kafka_DeleteTopic_s {
_unused: [u8; 0],
}
pub type rd_kafka_DeleteTopic... | Rust | 0 |
{
let mut length_refs = Vec::new();
for _ in 0..num_threads { length_refs.push(AtomicUsize::new(0)); }
BalancingScheduler {
thread_counter: AtomicUsize::new(0),
length_refs: Arc::new(length_refs),
}
}
}
unsafe impl Send for BalancingScheduler {}
unsafe impl Sync for BalancingScheduler {}
impl Schedul... | Rust | 0 |
writer = csv.DictWriter(csv_file, fieldnames=list(field_mapping.values()))
if not file_exists:
writer.writeheader()
writer.writerows(filtered_items)
print("Data successfully written to output.csv")
else:
print("No items found in the dataset.")
return fi... | Python | 1 |
_some());
Ok(())
}
#[rstest]
fn get_svg_qrcode(#[from(server_no_stderr)] server: TestServer) -> Result<(), Error> {
// Ok
let resp = reqwest::blocking::get(server.url().join("/?qrcode=test")?)?;
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers()["Content-Type"], "image/svg+xml")... | Rust | 0 |
nner = VecDeque::new();
let mut current = root;
while match current {
Some(node) => {
match range.start_bound() {
Bound::Excluded(start) if node.key.borrow().le(start) => {
current = node.right.as_ref()
}
... | Rust | 0 |
sphere` - The Sphere to check for intersections with the ray
///
/// # Examples
///
/// 1. A ray intersects a sphere at two points
/// ```
/// use sugar_ray::{
/// ray::Ray,
/// math::{
/// point::Point,
/// vector::Vector,
/// },
/// ... | Rust | 0 |
ek_case" => CaseStyle::SnakeCase,
"kebab_case" | "kebab-case" => CaseStyle::KebabCase,
"SCREAMING-KEBAB-CASE" => CaseStyle::ScreamingKebabCase,
"shouty_snake_case" | "shouty_snek_case" | "SCREAMING_SNAKE_CASE" => {
CaseStyle::ShoutySnakeCase
}
... | Rust | 0 |
with requests.post(API_URL, headers=headers, json=payload, timeout=(10, 120)) as response:
response.raise_for_status() # 如果状态码不是2xx,则抛出异常
data = response.json()
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
return ... | Python | 1 |
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as patches
def get(name):
return np.genfromtxt(name).transpose()
##################
# create figures #
##################
# energy
def get_energy():
fig_energy = plt.figure()
fig_energy.set_facecolor("white")
ax_energy = fig_energy.a... | Python | 1 |
read_contents')
_alias( Page, 'rotation_matrix')
_alias( Page, 'search_for')
_alias( Page, 'set_cropbox', 'setCropBox')
_alias( Page, 'set_mediabox', 'setMediaBox')
_alias( Page, 'set_rotation')
_alias( Page, 'show_pdf_page', 'showPDFpage')
_alias( Page, 'transf... | Python | 1 |
delete_child, ret) = recurse(&mut **target.as_mut().unwrap(),
&(*key >> (tree.skip_len as usize + 1)),
key_len - tree.skip_len as usize - 1);
if delete_child {
target.take();
... | Rust | 0 |
#taken from Tunic
from typing import Any, TYPE_CHECKING
#from .options import
#from .options import BFMOptions, LuminaRandomized
if TYPE_CHECKING:
from . import BFMWorld
def setup_options_from_slot_data(world: "BFMWorld") -> None:
if hasattr(world.multiworld, "re_gen_passthrough"):
if "Brave Fencer... | Python | 1 |
import torch
def r_squared(target, pred):
return 1 - torch.mean((target - pred) ** 2, dim=0) / torch.mean(
(target - torch.mean(target, dim=0, keepdim=True)) ** 2, dim=0
)
| Python | 1 |
import sys
import os
import subprocess
sys.path.append(os.path.join(os.path.dirname(__file__), 'srcFiles'))
import argparse
import Tokenizer as tokenizer
import parser as par
from SemanticAnalyzer import SemanticAnalyzer
from CodeGenerator import CodeGenerator
from Optimizer import Optimizer
def read_pseudocode(file... | Python | 1 |
"""Dataset loading (JSON / JSONL) for new architecture."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import orjson
def load_dataset(path: Path) -> list[dict[str, Any]]:
if path.suffix == ".jsonl":
out: list[dict[str, Any]] = []
with path.open(... | Python | 1 |
.bind_buffer(GL::ELEMENT_ARRAY_BUFFER, Some(&index_buffer));
gl.buffer_data_with_array_buffer_view(
GL::ELEMENT_ARRAY_BUFFER,
&indices_array,
GL::STATIC_DRAW,
);
}
}
#[cfg(test)]
mod tests {
#[test]
fn fo() {}
}
<gh_stars>0
use std::fs::File;
use std::io... | Rust | 0 |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class Slot(models.Model):
pronite_choices = (
('S', 'Spectrum'),
('K', 'Kaleidoscope'),
('M', 'Melange'),
('D', 'Dhoom'),
)
eligibility_choi... | Python | 1 |
let mut request_items = HashMap::new();
request_items.insert(self.table.clone(), items);
let input = BatchWriteItemInput {
request_items,
..Default::default()
};
let _res = self.dynamodb.batch_write_item(input).await?;
Ok(())
}
pub async fn ... | Rust | 0 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use t... | Python | 1 |
let highest_confirmed_root = block_commitment_cache
.read()
.unwrap()
.highest_confirmed_root();
let highest_confirmed_root_bank = bank_forks.get(highest_confirmed_root);
assert!(highest_confirmed_root_bank.is_some());
// Add additional banks beyond lockout ... | Rust | 0 |
# Yappatron - Build and run language models quickly and easily
# Copyright (C) 2025 COHEJH <jcohenkadosh@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 version 3 of the Licen... | Python | 1 |
}
}
/// Return the numerical bit flags corresponding to the structure (as described in the Vulkan specs).
pub fn to_u32(&self) -> u32 {
0
}
/// Create a structure corresponding to the specified numerical bit flags.
pub fn from_u32(value: u32) -> Self {
... | Rust | 0 |
ecode;
mod imported_encode;
mod decode;
mod encode;
pub use self::decode::Reader;
pub use self::encode::Writer;
}
#[derive(Clone)]
pub struct Segment {
/// First value part of the segment.
low: u32,
/// First value >= low **not** part of the segment.
next: u32,
}
impl Segment {
... | Rust | 0 |
record.collection_date,
record.donate_world_work,
record.local_congregation_expenses,
record.receipt_type_fk,
record.created_at,
record.updated_at,
)
})
.collect::<Vec<_>... | Rust | 0 |
u need to run `git submodule \
update --init --recursive` first to build the project.",
module
);
}
}
}
fn is_directory_empty<P: AsRef<Path>>(p: P) -> Result<bool, io::Error> {
let mut entries = fs::read_dir(p)?;
Ok(entries.next().is_none())
}
fn trim_s... | Rust | 0 |
import pandas as pd
df = pd.read_csv('D:/results.csv')
colum = [col for col in df.columns if col not in ['Player', 'Nation', 'Team', 'Pos', 'Age']]
for col in colum:
df[col] = pd.to_numeric(df[col].astype(str).str.replace(',', ''), errors='coerce')
# Tính trung bình của các chỉ số theo từng đội
team_means = df.g... | Python | 1 |
text.push(Spans::from(vec![Span::styled(
format!(
"{} • {} • {}",
(*service).service_id,
(*service).instance_id,
(*service).event_id
),
style,
)]));
}
let paragraph = Paragraph::new(text)
.blo... | Rust | 0 |
from setup import nx
import time
edges = [
(0, 1, 2),
(1, 2, -1),
(2, 3, 3),
(3, 4, 2),
(4, 5, 1),
(0, 2, 4),
(2, 4, 2),
(1, 3, 7),
(3, 1, -2) # This edge introduces a negative weight
]
edges_1 = [
(0, 1, 2),
(1, 2, -1),
(2, 3, 3),
(3, 4, 2),
(4, 5, 1),
(5,... | Python | 1 |
// thus the path resolver could be split out of other module
let path_res = explorer.get_path_result().unwrap();
println!("finish path get");
// create Ctrl. serve for cm handshakes
let _ctrl =
RCtrl::create(remote_service_id, &mut ALLRCONTEXTS.get_mut()[0]).unwrap();
// create RC at on... | Rust | 0 |
except IndexError:
# Need at least two major ticks to find minor tick locations
# TODO: Figure out a way to still be able to display minor
# ticks without two major ticks visible. For now, just display
# no ticks at all.
return []
if self.ndivs... | Python | 1 |
let mut character_style = MonoTextStyleBuilder::new().text_color(Rgb888::WHITE);
if args.strikethrough {
character_style = character_style.strikethrough_with_color(Rgb888::CSS_TOMATO);
}
if args.underline {
character_style = character_style.underline_with_color(Rgb888::CSS_CORNFLOWER_BLUE)... | Rust | 0 |
# cook your dish here
n = int(input())
nearest_multiple = round(n/3)*3
print(nearest_multiple)
| Python | 1 |
# Resource object code (Python 3)
# Created by: object code
# Created by: The Resource Compiler for Qt version 6.6.2
# WARNING! All changes made in this file will be lost!
from PyQt6 import QtCore
qt_resource_data = b"\
\x00\x00\x16\xe7\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00*\x00\x00\x00*\x08\x0... | Python | 1 |
_candidate(&mut subject, 2, 8);
add_pruned_candidate(&mut subject, 2, 9);
assert_eq!(subject.enabled_queue.len(), 0);
// The bounds we're exploring for waste 3 are 14..=16:
let lower_bounds = vec![4, 8, 12, 14];
let upper_bounds = vec![4, 8, 12, 16];
// We've just move... | Rust | 0 |
<'a> for T { }
// given a type with the attribute of Serialize, this trait
// will support serializing the public data members into properly
// formatted json
pub trait JsonSerialize : Serialize + Sized {
fn to_json(&self) -> Result<String, Error> {
to_string(self)
}
}
// this impl adds json seraliza... | Rust | 0 |
f" - {vuln['service']} {vuln['version']} on port {vuln['port']}: {vuln['vulnerability']}")
else:
print("No known vulnerabilities found.")
if __name__ == "__main__":
# Input Targets to scan
targets_input = input("Enter Domain name or IP address of the target(s) (separated by commas):... | Python | 1 |
rn_batch_at(dialogues, ENC, None)
# NOTE: encoder_turns contains all previous dialogue context, |num_context|
# decides how many turns to use
batch_seq = [
self._create_one_batch(
encoder_turns=encoder_turns_all[:i+1],
decoder_turns=self._get_turn_bat... | Python | 1 |
import numpy as np
import polars as pl
from datetime import datetime, timedelta
def churn_dataset_generator(df, user_id, feature_pipeline,
info_period=180,
checking_period=180,
start_date=datetime(2007, 1, 1),
... | Python | 1 |
from game.game_engine import GameEngine
import os
class CLIInterface:
"""
Command-line interface for the Trivia Game.
Handles user interaction, question display, and game loop for terminal-based play.
"""
def __init__(self):
"""
Initializes the CLI interface and loads questions into... | Python | 1 |
"""auto-vote
Revision ID: 970461fd338e
Revises: 6647340dbc5f
Create Date: 2024-03-10 12:14:26.022753
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '970461fd338e'
down_revision: Union[str, None] = '6647340dbc5f'
branch_... | Python | 1 |
use_blocks, vectorize=vectorize)
if (use_blocks is True) or (vectorize is True):
enc_shape = encoded.shape[0]
else:
enc_shape = sum([len(enc) for enc in encoded])
print('Encoded shape', enc_shape)
decoded, decoded_raw = prior_entropy_model.decompress(encoded, means, scales,
... | Python | 1 |
path__curveto(cpa, cpt, &mut p0, &mut p1, &mut p2)
}
#[no_mangle]
pub unsafe extern "C" fn pdf_dev_vcurveto(
mut x0: f64,
mut y0: f64,
mut x1: f64,
mut y1: f64,
) -> i32 {
let mut gss: *mut m_stack = &mut gs_stack;
let mut gs: *mut pdf_gstate = m_stack_top(gss) as *mut pdf_gstate;
let mut cp... | Rust | 0 |
Result<(), Error> {
self.client.notify_with("transfer", json!({
"transfers": vec![transfer]
}))?;
Ok(())
}
}
<gh_stars>0
// This file is part of Substrate.
// Copyright (C) 2022 UNIVERSALDOT FOUNDATION.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache Licens... | Rust | 0 |
import django.utils.timezone
from django.db import models
class TransactionStatus(models.TextChoices):
PENDING = 'PENDING',
CLEARED = 'CLEARED',
REJECTED = 'REJECTED',
class TransactionType(models.TextChoices):
DIRECT = 'DIRECT',
REQUEST = 'REQUEST',
class Transaction(models.Model):
sender... | Python | 1 |
n = 0
p = 0
c = 0
senha = '1234'
while c <= p:
n =
c += 1
if c <= p:
| Python | 1 |
from lc import *
# biweekly-contest-123 Q2/Q4
# https://leetcode.com/problems/maximum-good-subarray-sum
class Solution:
def maximumSubarraySum(self, n: List[int], k: int) -> int:
m,p,v = -inf,0,defaultdict(lambda:inf)
for i,x in enumerate(n):
if v[x] > p:
v[x] = p
... | Python | 1 |
[cfg(test)]
mod test {
use super::*;
#[test]
fn timestamp_format() {
use chrono::offset::TimeZone;
let t = chrono::Utc.ymd(2020, 8, 2).and_hms_milli(20, 0, 1, 444);
let formatted_t = view_timestamp(&t);
assert_eq!("August 02 - 20:00 UTC", formatted_t.to_string());
}
}
<g... | Rust | 0 |
select_bitmask(k, rol, src.as_i64x8()))
}
/// Rotate the bits in each packed 64-bit integer in a to the left by the number of bits specified in imm8, and store the results in dst using zeromask k (elements are zeroed out when the corresponding mask bit is not set).
///
/// [Intel's documentation](https://software.inte... | Rust | 0 |
# Copyright (c) 2016 Cisco and/or its affiliates.
# 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 ag... | Python | 1 |
a = 2");
let (console, storage) = (tester.get_console(), tester.get_storage());
block_on(try_load_autoexec(tester.get_machine(), console, storage)).unwrap();
tester
.run("")
.expect_var("a", 1)
.expect_prints(["Loading AUTOEXEC.BAS..."])
.expect_fi... | Rust | 0 |
#[derive(Debug)]
pub struct ResizeBuffer<T: bytemuck::Pod> {
/// cpu-side buffer
pub data: Vec<T>,
/// gpu-side buffer
pub buffer: wgpu::Buffer,
/// capacity of buffer
capacity: usize,
/// length of the buffer the last time it's written
old_len: usize,
/// index for inserting new entries
insert_index: usize,
... | Rust | 0 |
.examples, &s2.examples, "examples");
merge_map(&mut s1.request_bodies, &s2.request_bodies, "request_bodies");
merge_map(&mut s1.headers, &s2.headers, "headers");
merge_map(
&mut s1.security_schemes,
&s2.security_schemes,
"security_sche... | Rust | 0 |
import torch
import numpy as np
import random
from collections import deque
import matplotlib.pyplot as plt
from dqn_agent_infer import DQNAgent, DoubleDQN, Memory
from junqi_env_infer import JunQiEnvInfer
from junqi_env_setup import JunQiEnvSetUp
from dqn_agent_setup import DQNAgent as DQNAgentSetUp
from tqdm import t... | Python | 1 |
),
Some(
symbol
.filename
.unwrap_or_else(std::path::PathBuf::new)
.to_str()
.unwrap_or("")
.to_string(),
),
None,
symbol.lineno,
))
}
}
<repona... | Rust | 0 |
#
# Copyright (c) 2018 Intel Corporation
#
# 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... | Python | 1 |
real, score_img = nd.split(score, num_outputs=2, axis=-1)
score = mx.nd.sqrt(score_real * score_real + score_img * score_img + self.eps).sum(-1)
return gamma - score
return fn
else:
def fn(heads, relations, tails, num_chunks, chunk_size, neg_sample_size)... | Python | 1 |
rivate/var/folders/vy/31wknkcs30l6xb2fzgwnrkh80000gn/T/pip-build-VQoj4y/pip/pip/_vendor/distlib/metadata.pyR s c
C s3 | j r | j s t i | j d 6| j d 6} | j j t } xF d D]> } | | k rL | d k rs d } n | } | | | | <qL qL W| j d
g } | d g k r ... | Python | 1 |
pth > 20: # Prevent deep recursion
return
if isinstance(obj, dict):
for key, value in obj.items():
if key.lower() in ['text', 'message', 'content', 'body', 'item_text']:
if isinstance(value, str) and self.is_real_message_text(valu... | Python | 1 |
assert_eq!(
johnson_sparse::<_, Q>(4, edges),
Err(NegativeCycleError::new()),
)
}
}
<filename>src/method/trailing_unicode/character_sets.rs
/// This trait is used for reading unicode set data.
///
/// New sets should implement `get_set` which provides the array with
/// unicode chara... | Rust | 0 |
import os
import subprocess
import multiprocessing
import importlib
git_base = subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).decode().strip()
def walk_and_ignore_pycache(directory):
list = []
for root, dirnames, files in os.walk(directory, topdown=True):
# This line removes any __p... | Python | 1 |
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
from typing import Protocol, TypeAlias
@dataclass
class ChargePointInformation:
vendor: str
model: str
@dataclass
class ChargingProfilePoint:
time: int
power: float
StatusHandler: TypeAlias = Callable[[str, str], Cor... | Python | 1 |
nerated_captions(cap_file, image_id_key:str, caption_key:str):
#Read in captions
# it should be list of dict
ext = os.path.splitext(cap_file)[-1]
if ext == '.json':
caps = json.load(open(cap_file))
elif ext == '.jsonl':
caps = [json.loads(s) for s in open(cap_file)]
else:... | Python | 1 |
# coding: utf-8
"""
Jupyter Server API
Server API
The version of the OpenAPI document: 5
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
import datetime
from nbserv_client.models.api_kernelspecs_get200_response ... | Python | 1 |
Option<Run> {
let file: std::fs::File;
match OpenOptions::new().read(true).write(true).create(true).open(filename) {
Ok(x) => {
file = x;
}
Err(_) => {
return None;
}
}
let run = from_reader(&file);
... | Rust | 0 |
from setuptools import setup, find_packages
from codecs import open
from os import path
import re
here = path.abspath(path.dirname(__file__))
def get_version():
return re.search("__version__ = \"([\d\.]+)\"", open("prt.py").read()).groups()[0]
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
... | Python | 1 |
"dataTraceEnabled")
.boolean(input.data_trace_enabled);
}
if input.detailed_metrics_enabled {
object
.key("detailedMetricsEnabled")
.boolean(input.detailed_metrics_enabled);
}
if let Some(var_308) = &input.logging_level {
object.key("loggingLevel").str... | Rust | 0 |
alive()]
if not alive_readers:
break
for reader in alive_readers:
reader.join(1)
except (KeyboardInterrupt, SystemExit):
# catch ctrl-C and stop inventory before disconnecting
logger.info("Exit detected! Stopping readers...")
... | Python | 1 |
detached_service.detach();
service_mgr_clone.write().unregister_service(®_handle_clone);
};
Ok((ids, closed_fut))
}
/// Creates a new connection if the requested `psm` is registered by this peer.
/// Updates the relevant `ConnectionReceiver` with one end of the ... | Rust | 0 |
size, &'input str, usize),
__2: (usize, Box<Term>, usize),
__3: (usize, &'input str, usize),
) -> Term
{
let __start0 = __1.2.clone();
let __end0 = __2.0.clone();
let __temp0 = __action16(
input,
&__start0,
&__end0,
);
let __temp0 = (__start0, __temp0, __end0);
__... | Rust | 0 |
usy_codec::Encode for #name #ty_generics #where_clause {
fn encode_to<EncOut: _susy_codec::Output>(&#self_, #dest_: &mut EncOut) {
#encoding
}
}
};
let mut new_name = "_IMPL_ENCODE_FOR_".to_string();
new_name.push_str(name.to_string().trim_start_matches("r#"));
let dummy_const = Ident::new(&new_name, S... | Rust | 0 |
ime.len())
/ (zebra_test::vectors::DUMMY_INPUT1[..].len() - 1);
if oversized {
max_inputs_in_tx += 1;
}
let mut outputs = Vec::new();
// Create inputs to be just below the limit
let inputs = std::iter::repeat(input)
.take(max_inputs_in_tx)
.collect::<Vec<_>>();
... | Rust | 0 |
unsupported format
/// * `n` modes you can query [enum_adapter_modes] for
///
/// ### Example
///
/// ```rust
/// # use dev::d3d9::*; let d3d = d3d_test();
/// for fmt in [Format::X8R8G8B8, Format::A8R8G8B8].iter().copied() {
/// let modes = d3d.get_adapter_mode_count(0, fm... | Rust | 0 |
ensor.modules.comp.Components'>
"""
fmodule = self._fmodule # the base free module
return Components(fmodule._ring, basis, 1, start_index=fmodule._sindex,
output_formatter=fmodule._output_formatter)
def _new_instance(self):
r"""
Create an instanc... | Python | 1 |
CONVERT_ALL_TO_USDC = False # convert all balances to USDC only
THREADS = 1 # Enter amount of threads
DELAY_BETWEEN_TRADE = (1, 2) # Execute delay between every trade (Buy -> Delay -> Sell -> Buy -> Delay ...)
DELAY_BETWEEN_DEAL = (0, 0) # Execute delay between full trade (Buy -> Sell -> Delay -> Buy -> Sell -> De... | Python | 1 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from datetime import datetime
import random
import time
def selection_class(index, id):
index_c = str(index + 1)
id_c = str(id) + "_01"
font_name = driver.find_element(
By.XPATH,
f"//table[@border='0' and @width='10... | Python | 1 |
#!/usr/bin/env python3
import serial
import time
class DriveController:
def __init__(self, listener,
steering_port='/dev/ttyUSB1', throttle_port='/dev/ttyUSB0',
steering_baudrate=115200, throttle_baudrate=230400):
# Save the shared input listener.
self.listener = l... | Python | 1 |
mut rng)).collect();
let H: Vec<RistrettoPoint> = (0..n).map(|_| RistrettoPoint::random(&mut rng)).collect();
let Q = RistrettoPoint::hash_from_bytes::<Sha3_512>(b"test point");
let mut prover_transcript = Transcript::new(b"lmpa_no_zk");
// t = Aw
let A = rand_matrix(n);
let w: Vec<Scalar> = (... | Rust | 0 |
= self.learning_rate;
let max_iterations = self.max_iterations;
let extx = Matrix::one_vector(x.rows()).cr(x);
let mut theta = Matrix::new(extx.cols(), 1, vec![0.0f64; extx.cols()]);
let error_f = |theta : &Matrix<f64>| -> Matrix<f64> {
&extx * theta - y
};
let cost_f = |error : &Matrix<f... | Rust | 0 |
type()),
],
U512::cl_type(),
EntryPointAccess::Public,
EntryPointType::Contract,
);
let undelegate_proxy_call = EntryPoint::new(
METHOD_UNDELEGATE_PROXY_CALL,
vec![
Parameter::new(auction::ARG_DELEGATOR, PublicKey::cl_type()),
Parameter::n... | Rust | 0 |
components::page("templates", &content);
HttpResponse::Ok()
.content_type("text/html")
.body(view.into_string())
}
fn get_stylesheet() -> String {
"
".to_owned()
}<filename>contracts/governance/src/common/tests/instantiate.rs
use cosmwasm_std::{Env, MessageInfo, Response};
use valkyrie::common::Con... | Rust | 0 |
jsonify({'error': 'Router not found'}), 404
# Log activity before deletion
activity = ActivityLog(
user_id=user_id,
action='Deleted router',
target_type='router',
target_id=router.id,
details=f'Deleted router: {router.model} ({router.s... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.