text string | label_name string | labels int64 |
|---|---|---|
el szlerr9ru5i
return s6848vqr64x
'# alloys_kites_grasp -> compressors_recruit_audit'
pass
nonlocal x200_m9i3pz
zn5eqthqnpt.n4u0scoi3sw: 0 = None
from yy2n0mq4vf6 import pqn_qikfgpo as gneis4vvphw, x0q07wcxf6b
'# alloys_kites_grasp -> compressors_recruit_audit'
zhhh2_ii_kb
fxam5sbriv... | Python | 1 |
import os
import torch
import random
import numpy as np
from tqdm import tqdm
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from stable_baselines3.common.atari_wrappers import MaxAndSkipEnv
from stable_baselines3.common.buffers import ReplayBuffer
import ale_py
import gymnasium a... | Python | 1 |
', 'improve conversions'],
'current_performance': 'moderate'
}
strategic_insights = await ai_engine.generate_strategic_insights(analysis_data)
if strategic_insights:
logger.info(f"✅ Strategic insights generated: {len(strategic_insights)} insights")
else:
... | Python | 1 |
import pyaudio
import wave
class AudioRecording:
def __init__(self, format=pyaudio.paInt16, channels=1, rate=44100, chunk=1024, record_seconds=None):
self.FORMAT = format # Format of audio samples (16-bit signed integers)
self.CHANNELS = channels # Number of... | Python | 1 |
Self::MissingSchemeOrAuthority => "Missing scheme or authority",
Self::MissingUriComponents => "Cannot find URI components",
Self::InvalidUriScheme => "Invalid URI scheme",
Self::InvalidUri => "Not a URI",
Self::Custom { desc } => desc,
}
}
}
impl fmt::Displa... | Rust | 0 |
from __future__ import annotations
from prefect import flow
from prefect.logging import get_run_logger
from infrahub.context import InfrahubContext # noqa: TC001 needed for prefect flow
from infrahub.core.registry import registry
from infrahub.pools.tasks import validate_schema_number_pools
from infrahub.services i... | Python | 1 |
im = _fuzzy_match_ratio(candidate, cmd)
else:
candidate = ' '.join(message_words)
current_sim = _fuzzy_match_ratio(candidate, cmd)
if current_sim > max_similarity and current_sim >= config.similarity_rate:
max_similarity = current_sim
best_cmd = cmd
... | Python | 1 |
lt<T = ()> = Result<T, SbiError>;
impl From<SbiReturn> for SbiResult<usize> {
fn from(ret: SbiReturn) -> Self {
match ret.error {
SbiError::Success => Ok(ret.value),
err => Err(err),
}
}
}
#[inline(always)]
fn sbi_call(ext_id: usize, func_id: usize, arg0: usize, arg1: u... | Rust | 0 |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( arr , n ) :
arr.sort ( )
max_count = 1 ; res = arr [ 0 ] ; curr_count = 1
for i in range ( 1 , n ) :
... | Python | 1 |
);
fasync::Task::spawn(async move {
let deadline = Duration::from_nanos(task.as_ref().deadline as u64);
let start = executor.as_ref().start;
fasync::Timer::new(start + deadline.into()).await;
(task.as_ref().handler)(executor.as_ref().cb_executor, task.0, ZX_OK)
})
.detach();
... | Rust | 0 |
new(0.0, 0.0, -1.0),
color: Color::new(255, 255, 255),
intensity: 1.0,
})],
objects: vec![Object {
material: Material::new(
Coloring::Color(Color::new(60, 60, 60)),
0.38,
SurfaceKind::Diffuse,
),
... | Rust | 0 |
>
where
T: Real + Scalar,
D: DimName + DimNameSub<U1>,
DefaultAllocator: Allocator<T, D> + Allocator<T, DimNameDiff<D, U1>>,
{
fn truncate(self) -> (VectorN<T, DimNameDiff<D, U1>>, T) {
let n = self.len();
let x = *self.get(n - 1).unwrap();
(
VectorN::<_, DimNameDiff<... | Rust | 0 |
import json
import yaml
import sys
import argparse
# Argument parser setup
parser = argparse.ArgumentParser(description="Check for unexpected test results based on an exclusion list.")
parser.add_argument("report_json", help="Path to the hive report JSON file.")
parser.add_argument("--exclusion", required=True, help="... | Python | 1 |
",
"struct Foo { baz: String }
impl Foo {
fn new(baz: String) -> Self { Self { baz } }<|>
}
",
);
check_assist(
add_new,
"struct Foo { baz: String, qux: Vec<i32> <|>}",
"struct Foo { baz: String, qux: Vec<i32> }
impl Foo {
fn new(baz: String, qux: Vec<i32>) -> Self { Self { baz, qu... | Rust | 0 |
into()).collect())
}
}
pub use client::*;
mod client;
pub mod sms;
pub const RAKNET_PROTOCOL_VERSION : u8 = 10;
//the MTU is minecraft bedrock 1.18.2 give me
pub const RAKNET_CLIENT_MTU : u16 = 1400;
pub const RECEIVE_TIMEOUT : i64 = 60000;
pub enum Endian {
Big,
Little,
}
pub fn cur_timestamp_millis()... | Rust | 0 |
new_header_builder.add(
"",
[append_mur_macros],
)
new_header_builder.add(
source.finalization_mixes,
[transform_finalization_mixes],
)
new_header_builder.add(
source.finalization_x64_128,
[generate_hasher_diges... | Python | 1 |
# Now send a normal query and expect a JSON response with data
qid = "auth_ok_1"
await ws.send_str(
json.dumps({"type": "json", "sql": "select 1 as x", "queryId": qid})
)
got_result = False
query_debug = []
for _ in rang... | Python | 1 |
# Copyright (C) 2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Test of CSPLayer."""
import torch
from torch.nn import BatchNorm2d, Conv2d
from otx.backend.native.models.detection.layers import ChannelAttention
from otx.backend.native.models.detection.layers.csp_layer import CSPLayer, CSPNeXtBlock, Da... | Python | 1 |
h pytest.raises(ValueError, match=err_msg):
search.fit(X, [])
@pytest.mark.parametrize("SearchCV", [HalvingGridSearchCV, HalvingRandomSearchCV])
def test_select_best_index(SearchCV):
"""Check the selection strategy of the halving search."""
results = { # this isn't a 'real world' result dict
... | Python | 1 |
_val = A::min_value();
let mut sum = A::zero();
let mut len = A::zero();
x.iter().for_each(|x| {
let x_val = *x;
if x_val != skip_val {
sum = sum + *x;
len = len + A::one();
}
});
sum / len
};
pool2d(inpu... | Rust | 0 |
let port = node.get_host_port(5432).expect("Test port acquisition error");
fun(format!("postgres://postgres:123456@localhost:{}/test", port)).await
}
pub fn postgres_custom<'a>(init_script_path: Option<&str>, docker: &'a Cli) -> Container<'a, Cli, GenericImage> {
if init_script_path.is_some() {... | Rust | 0 |
2 = Arc::clone(&gpio_22_thread);
let air_arc2 = Arc::clone(&gpio_27_thread);
let tn = Arc::clone(&term_now);
thread::spawn(|| {
aog::web::init_command_api(uv_arc2, air_arc2, tn);
});
// Start video thread(s)
aog::video::init_all();
// No ars triggers an interactive A.O.G. command ... | Rust | 0 |
from checkOut import checkOut
class checkOutUI:
def addCheckIn():
TCOGid = int(input("\nenter the transaction id of the guest.."))
TCOname = input("\nenter the name of the guest...")
TCOaddres = input("\nenter the address of guest... ")
TCOcontact = input("\nenter the cont... | Python | 1 |
import paramak
from cadquery import Workplane
# makes a rectangle that overlaps the lower blanket under the plasma
# the intersection of this and the layers will form the lower divertor
points = [(300, -700), (300, 0), (400, 0), (400, -700)]
divertor_lower = Workplane("XZ", origin=(0, 0, 0)).polyline(points).close().r... | Python | 1 |
class Solution:
def maxArea(self, height: List[int]) -> int:
l = 0
r = len(height) -1
res = 0
while l < r:
area = (r-l) * min(height[l],height[r])
res = max(res,area)
if height[l] < height[r]:
l+=1
else:
... | Python | 1 |
.iter.next();
}
if let Some(range) = self.current.take() {
if range.len() > self.bound {
let (new_range, remaining) = range.split_at(self.bound).unwrap();
self.current = Some(remaining);
Some(new_range)
} else {
Some... | Rust | 0 |
is_core::{CodepointInfo, DerivedPropertyValue, Error};
use precis_profiles::UsernameCaseMapped;
use std::borrow::Cow;
#[test]
fn prepare() {
let profile = UsernameCaseMapped::new();
// Preparation does no apply case mapping rule
let res = profile.prepare("XxXxX");
asser... | Rust | 0 |
_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
Ok(TupleSerializer::new(Cow::Borrowed(self.node), "", len))
}
fn serialize_tuple_struct(
self,
name: &'static str,
len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
Ok(TupleSeria... | Rust | 0 |
#*****************************************************************************
# Copyright (C) 2016 The IPython Team <ipython-dev@scipy.org>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#********************************************... | Python | 1 |
subnet_id=dict(type="str"),
description=dict(type="str"),
security_groups=dict(default=[], type="list", elements="str"),
device_index=dict(default=0, type="int"),
state=dict(default="present", choices=["present", "absent"]),
force_detach=dict(default="no", type="bool"),
... | Python | 1 |
import matplotlib.pyplot as plt
import sys
from scipy.interpolate import spline
import re
import numpy as np
from sumolib.output import parse_fast
def movingaverage(interval, window_size):
window= np.ones(int(window_size))/float(window_size)
return np.convolve(interval, window, 'same')
if __name__ == '__ma... | Python | 1 |
arch(&self) -> std::result::Result<Results, Box<dyn std::error::Error>> {
let url = self.build_url()?;
let result_string = reqwest::get(url)?.text()?;
let result: Results = serde_json::from_str(&result_string)?;
Ok(result)
}
}
/*!
`crypto_stream_salsa2012` (Salsa20/12), a particul... | Rust | 0 |
run()
elif 'help' in userinput[:1]:
helpMe()
elif 'invoke' in userinput[:1]:
comm.invokeModule(options.Call)
return None
elif 'back' in userinput[:1] or 'exit' in userinput[:1]:
return None
else:
command = str(userinput[:1]).strip('[]\'')
print(bc.WAR... | Python | 1 |
distance: i32 = nums.into_iter().map(|n| (median - n).abs()).sum();
distance as usize
}
pub fn parse2(s: &str) -> usize {
let nums: Vec<i32> = s.trim().split(',').map(|s| s.parse().unwrap()).collect();
let min = nums.iter().min().unwrap();
let max = nums.iter().max().unwrap();
let min: i32 = (*mi... | Rust | 0 |
) [],
// ]
}
const TRNG_BASE: StaticRef<TRNGRegisters> =
unsafe { StaticRef::new(0x400CC000 as *const TRNGRegisters) };
pub struct TRNG<'a> {
registers: StaticRef<TRNGRegisters>,
client: OptionalCell<&'a dyn hil::entropy::Client32>,
ccm: &'static crate::ccm::Ccm,
}
impl<'a> TRNG<'a> {
pub con... | Rust | 0 |
# This program shows that without using pandas getting answers on below questions is hard and not convinient
# (1) Max temperature in New York in month of January
# (2) List of days when it rained
# (3) Average speed of wind in month of january
__parsed_rows = []
def parse_csv():
import csv
__file_path = "nyc_... | Python | 1 |
cl, bin_edges_cl, binnumber = scipy.stats.binned_statistic(
carb_Cl_distances[j].flatten(),
c_charges[j, adsorbed_an_indices[j], :].flatten(),
statistic="std",
bins=nbins,
)
# remove nan from empty bins
mean_charge_na_tmp = mean_charge_na
... | Python | 1 |
ref, est = ref[:, :T], est[:, :T]
else:
T = min(ref.shape[-1], est.shape[-1])
ref, est = ref[:T], est[:T]
# 去直流分量(零均值化)
ref_zm = ref - ref.mean(-1, keepdim=True)
est_zm = est - est.mean(-1, keepdim=True)
# 计算参考信号能量
ref_energy = torch.sum(ref_zm *... | Python | 1 |
import os
from sqlalchemy import text
from sqlalchemy.engine import URL, make_url
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from pathlib import Path
from {{cookiecutter.project_name}}.settings import settings
{% if cookiecutter.db_info.na... | Python | 1 |
Win32_Devices_DeviceAndDriverInstallation\"`*"]
pub type SP_INF_STYLE = u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAndDriverInstallation\"`*"]
pub const INF_STYLE_NONE: SP_INF_STYLE = 0u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAndDriverInstallation\"`*"]
pub const INF_STYLE_OLDNT: SP_INF_ST... | Rust | 0 |
from AXUI.logger import LOGGER
class _Step(object):
'''represent one step element in the function element
'''
def __init__(self, xml_element, app_map):
self.xml_element = xml_element
self.type = xml_element.attrib["type"]
self.command = xml_element.attrib["cmd"]
try:
... | Python | 1 |
lt_refill_rate")
return {
"capacity": capacity,
"refill_rate": refill_rate
}
@classmethod
def is_token_bucket_enabled(cls, db: Session) -> bool:
"""检查是否启用 token bucket"""
return cls.get_config(db, "enable_token_bucket", True)
@classm... | Python | 1 |
# Copyright 2016 The TensorFlow Authors. 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 required by applica... | Python | 1 |
inary')
else:
l_precision,l_recall,l_fscore,_ = precision_recall_fscore_support(l_A_labels, l_preds,\
average='micro')
precision = l_precision
recall = l_recall
fscore = l_fscore
precision_list.append(precision)
recall_list.append(recall)
... | Python | 1 |
2() {
run_test(&Instruction { mnemonic: Mnemonic::VBROADCASTF32X2, operand1: Some(Direct(YMM7)), operand2: Some(IndirectScaledDisplaced(ECX, Eight, 340025082, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some... | Rust | 0 |
from ipaddress import ip_network, ip_address
ip1 = ip_address('112.117.107.70')
ip2 = ip_address('112.117.121.80')
for mask in range(32):
net1 = ip_network(f'{ip1}/{mask}', False)
net2 = ip_network(f'{ip2}/{mask}', False)
if net1 == net2:
if ip1 not in [net1.network_address, net1.broadcast_address]... | Python | 1 |
Objects/Symbol/Symbol
pub(crate) fn constructor(
new_target: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. If NewTarget is not undefined, throw a TypeError exception.
if !new_target.is_undefined() {
return context.throw_type... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2024 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 |
status_code=status.HTTP_400_BAD_REQUEST, detail=str(error))
return item.first()
# Delete an order by ID
# Parameters:
# - db: Database session
# - item_id: ID of the order to delete
# Returns:
# - A 204 No Content response if successful
def delete(db: Session, item_id):
try:
item = db.query(model... | Python | 1 |
role.permissions.kick_members,
role.permissions.administrator,
)
):
return True
if role.guild.me.top_role <= role:
return True
if issuers_top_role:
return role >= issuers_top_role
else:
return False
def ge... | Python | 1 |
Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.inner, f)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.inner, f)
}
}
impl Fail for Error {
fn cause(&self) -> Option<... | Rust | 0 |
ek"},
)
def test_initialize_openrouter_deepseek(
clean_env, mock_openai, mock_deepseek_reasoner, monkeypatch
):
"""Test OpenRouter DeepSeek model initialization."""
monkeypatch.setenv("OPENROUTER_API_KEY", "test-key")
# Test with DeepSeek R1 model
_model = initialize_llm("openrouter", "deepse... | Python | 1 |
# Generated by Django 3.2.15 on 2022-12-29 15:55
from django.conf import settings
import django.contrib.auth.models
from django.db import migrations, models
import django.db.models.deletion
import kobo.apps.project_views.fields
import kpi.fields.kpi_uid
class Migration(migrations.Migration):
initial = True
... | Python | 1 |
impl MmuTranslationBase for ArmPageTableBase {
fn get_pt_by_virt_addr(&self, addr: Address) -> Address {
//TODO: handle for Arm 32
if (addr.to_umem().to_be() & 1) == 1 {
self.1
} else {
self.0
}
}
fn get_pt_by_index(&self, idx: usize) -> (Address, us... | Rust | 0 |
_excel('5.3.xlsx')
# result_df = process_data(df, 5000)
# result_df.to_csv('output.csv', index=False)
# df_csv = pd.read_csv('output.csv')
# # Convert DataFrame to Excel
# df_csv.to_excel('output.xlsx', index=False)
# # Open the Excel file
# wb = load_workbook('output.xlsx')
# ws = w... | Python | 1 |
vec![1, 0, 0, 0]);
let w = g.add_vertex_with_phase(VType::Z, Rational::new(-1,2));
for &v in verts {
g.add_to_phase(v, Rational::new(-1,4));
g.add_edge_with_type(v, w, EType::N);
}
g
}
fn replace_phi1(g: &G, verts: &[V]) -> G {
// println!("rep... | Rust | 0 |
aise znkba_q78hi
global eu2oay86pl0
'# strain_batteries_message -> battery_recipient_pole'
del hodzhfif_a1
from ge11wn3qdev import llb1p6rk9nr, t7tuzr0cvdf as xx98ptvw4bj
0.0[b''] %= loh_0yzn592
0 .nsd_u5fxsju: v4ty8l1aajt = ysh2vquj4qo
'# strain_batteries_message -> battery_recipient_pole'
... | Python | 1 |
ity(
hours: int = Query(1, ge=1, le=24, description="Hours of system activity"),
limit: int = Query(50, ge=1, le=200),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Get recent system activity across all organizations (admin only)"""
# TODO: Add admin role ch... | Python | 1 |
def fts5_term(term):
"""Convert a Google search like query into a FTS5 query, i.e. to not
trigger the column filter misfeature. We don't try to make invalid queries
work, just make queries that would be interpreted as column filters or the
like work.
EBNF:
query = word
word = [not space]+
query = phras... | Python | 1 |
PADR => Code::Padr,
PADS => Code::Pads,
PADT => Code::Padt,
_ => return Err(ParseError::InvalidPppoeCode(code)),
})
}
}
fn ensure_minimal_buffer_length(buffer: &[u8]) -> Result<(), ParseError> {
if buffer.len() < 6 {
return Err(ParseError::BufferToo... | Rust | 0 |
le, kept_row_ids[20:30], 1)
batch_table.append(self._generate_test_batch(3, row_ids="keep"))
assert_last_batch(batch_table, kept_row_ids[30:], 1)
# No RowID available
batch_table = kt.BatchOutputTable.create(row_ids="keep")
with self.assertRaises(TypeError):
batch_ta... | Python | 1 |
percentage": gpt_pass_percentage,
"trials": completion_entry["trials"],
"chosen_trial": completion_entry["chosen_trial"],
"metadata": completion_entry["metadata"]
}
combined_results.append(saved_entry)
# Save the combined results to a new file
output_file = os.path.join(args.output... | Python | 1 |
) {
let occurence: Occurrences = Occurrences::OnceOrUpTo(42);
occurence.check(0).unwrap();
}
#[test]
fn test_none_or_up_to_none_zero() {
let occurence: Occurrences = Occurrences::NoneOrMore;
occurence.check(0).unwrap();
}
#[test]
fn test_none_or_up_to_none_large(... | Rust | 0 |
) -> fmt::Result {
f.debug_tuple("PeekMinMut")
.field(&self.heap.0[0])
.finish()
}
}
impl<'a, T: Ord> Drop for PeekMinMut<'a, T> {
fn drop(&mut self) {
if !self.removed {
self.heap.trickle_down_min(0);
}
}
}
impl<'a, T: Ord> Deref for PeekMinMut<'a, T>... | Rust | 0 |
right: -10px; /* Position de la pointe */
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 20px solid red;
transform: translateY(-50%);
}
... | Python | 1 |
#!/usr/bin/env python3
"""
Implementación REAL del operador H en base log-wave
Construcción genuinamente no circular del operador universal
Sin referencia a ζ(s) o números primos
NOTA: Esta es una versión simplificada que demuestra el concepto.
Una implementación completa requeriría integración numérica costosa del nú... | Python | 1 |
from odoo.tests import new_test_user
from odoo.tests.common import TransactionCase, tagged
@tagged("post_install", "-at_install")
class TestLiveChatResUsers(TransactionCase):
def test_livechat_create_res_users(self):
access_user = new_test_user(
self.env,
login="admin_access",
... | Python | 1 |
UnaryOp};
use crate::sst::{Exp, ExpX, Stm, StmX};
use crate::util::box_slice_map;
use air::ast::{CommandX, Commands, DeclarationX, Expr, ExprX, LogicalOp, QueryX, Stmt, StmtX};
use std::rc::Rc;
pub const SUFFIX_USER_ID: &str = "@";
fn suffixed_id(ident: &Ident) -> Ident {
Rc::new(ident.to_string() + SUFFIX_USER_... | Rust | 0 |
-> Result<web::Json<UserResponse>> {
let name: String = rand::thread_rng().sample_iter(rand::distributions::Alphanumeric).take(32).map(char::from).collect();
let url = base64::decode(url)?;
let url = String::from_utf8(url)?;
let payload = MineskinRequest {
url,
name,
... | Rust | 0 |
tested.
///
/// See the documentation of the [`TTouchbar`](trait.TTouchbar.html) trait for usage.
///
/// # Example
///
/// ```
/// extern crate rubrail;
/// use rubrail::TTouchbar;
/// fn main() {
/// let controller = rubrail::Touchbar::alloc("test");
/// }
/// ```
pub type Touchbar = Box<RustTouchbarDelegateWrappe... | Rust | 0 |
import numpy as np
import pandas as pd
import yfinance as yf
import joblib
from keras.models import Model
from keras.layers import Input, MultiHeadAttention, LayerNormalization, Dropout, Dense, GlobalAveragePooling1D
# -------- 1. 載入資料,這邊用 yf 範例
ticker = "2330.TW"
start_date = "2021-12-01"
end_date = "2023-08-08"
df =... | Python | 1 |
from app.db.dao.current_dataset_dao import CurrentDatasetDAO
from app.db.dao.current_dataset_metrics_dao import CurrentDatasetMetricsDAO
from app.db.dao.model_dao import ModelDAO
from tests.commons.db_integration import DatabaseIntegration
from tests.commons.db_mock import (
get_sample_current_dataset,
get_samp... | Python | 1 |
r, screenShader, cubeVAO, quadVAO, framebuffer, intermediateFBO, screenTexture) = unsafe {
// configure global opengl state
// -----------------------------
gl::Enable(gl::DEPTH_TEST);
// build and compile our shader program
// ------------------------------------
let sh... | Rust | 0 |
def _on_port_added(self):
if not self.__input.is_open():
self._reconnect(self.__input, self.input_name(), midi_input_names())
if not self.__output.is_open():
self._reconnect(
self.__output, self.output_name(), midi_output_names()
)
def _reconnec... | Python | 1 |
test_storage;
mod test_titan;
<filename>src/platform/linux-types/uapi_stat.rs<gh_stars>0
// Copyright (c) 2020 <NAME> <<EMAIL>>. All rights reserved.
// Use of this source is governed by Apache-2.0 License that can be found
// in the LICENSE file.
use super::types::*;
pub const S_IFMT: mode_t = 0o0_170_000;
pub cons... | Rust | 0 |
# 2. MOMENTUM SIGNALS
momentum_signals = []
# RSI signals
if 'rsi' in latest.index:
if latest['rsi'] > 70:
momentum_signals.append(-1) # Overbought
elif latest['rsi'] < 30:
momentum_signals.append(1) # Oversold
... | Python | 1 |
"""Classes shared among Wemo entities."""
from __future__ import annotations
from collections.abc import Generator
import contextlib
import logging
from pywemo.exceptions import ActionException
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.update_coordinator import Coordinat... | Python | 1 |
from df_maker import df_maker
import openpyxl
def main():
sheet_name = '購入品リスト1'
numbers , pieces = read_xl(sheet_name)
df = df_maker(numbers,pieces)
print(df)
write_xl(sheet_name,numbers,df)
def write_xl(sheet_name,numbers,df):
workbook = openpyxl.load_workbook("購入品リスト.xlsx")
sheet = work... | Python | 1 |
import os
# ❌ Disable GPU BEFORE importing TensorFlow
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import tensorflow as tf
import numpy as np
import os, pdb
from torch.utils.data import RandomSampler
from data.module import EyeTrackingDataModule
from data.utils import load_yaml_config
# Path
path_to_run = "./output/r... | Python | 1 |
with caplog.at_level(logging.WARNING):
assert _test_compare_metrics_files(expected=data, actual=data, tmp_path=tmp_path) == ""
assert len(caplog.messages) == 0
def _compare_and_check(
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
expected: Dict[str, Any],
actual: Dict[str, Any],
ex... | Python | 1 |
Colors
pub const WHITE: Color = Color(0);
pub const BLACK: Color = Color(1);
pub const US: Color = Color(0);
pub const THEM: Color = Color(1);
pub const COLORS: [Color; 2] = [WHITE, BLACK];
// Piece types
pub const PAWN: PieceType = PieceType(0);
pub const KNIGHT: PieceType = PieceType(1);
pub const BISHOP: PieceTyp... | Rust | 0 |
s > 1 else 'day'}, {int(uptime_hours)} {'hours' if uptime_hours > 1 else 'hour'}"
def toggle_overview_widget(self):
if self.hq.is_visible():
self.hq.hide()
self.memory.children.clear()
else:
# Run the command
output = os.popen("ps -eo pid,comm,%mem -... | Python | 1 |
12 Interrupt enable for the inside of window of the Window comparator"]
#[inline(always)]
pub fn adc12inie(&mut self) -> ADC12INIE_W {
ADC12INIE_W { w: self }
}
#[doc = "Bit 2 - ADC12 Interrupt enable for lower threshold of the Window comparator"]
#[inline(always)]
pub fn adc12loie(&mut ... | Rust | 0 |
import numpy as np
import pandas as pd
import plotly.express as px
# Constants and variables
mu = 0.03
length = 2.0
tension_values = np.linspace(10, 40, 100)
# Mathematical expressions
tension, wave_speed, frequency = symbols('tension wave_speed frequency')
wave_speed_eq = Eq(wave_speed, sqrt(tension / mu))
frequency... | Python | 1 |
from langchain_community.utilities.google_serper import GoogleSerperAPIWrapper
__all__ = ["GoogleSerperAPIWrapper"]
| Python | 1 |
success = False
# spells+="Spelling error: %s (%s)\n" % (w,str(hobj.suggest(w)))
prevs = (t,s,e)
p = subprocess.Popen(['java','-jar','/home/jg/programs/LanguageTool-2.5/languagetool-commandline.jar','-l','en','-d',",".join(lt_exclusions),'-'],stdin = subprocess.PIPE, stdout = subprocess.PIPE)
out, e... | Python | 1 |
OfPFHadrons = cms.bool(False)
),
vertexTrackFiltering = cms.bool(False),
vxAssocQualityCuts = cms.PSet(
maxTrackChi2 = cms.double(1000.0),
maxTransverseImpactParameter = cms.double(0.2),
minGammaEt = cms.double(0... | Python | 1 |
(Usize(_), Usize(Us64(0))) => Err(zerr),
(Infer(_), Infer(0)) => Err(zerr),
(I8(::std::i8::MIN), I8(-1)) => Err(Overflow(op)),
(I16(::std::i16::MIN), I16(-1)) => Err(Overflow(op)),
(I32(::std::i32::MIN), I32(-1)) => Err(Overflow(op)),
(I64(::std::i64::MIN), I64(-1)) => E... | Rust | 0 |
<'de> for DurationVisitor {
type Value = Duration;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a duration in milliseconds")
}
fn visit_i64<E>(self, value: i64) -> Result<Duration, E>
where E: de::Error
{
... | Rust | 0 |
ith pytest.raises(DatabaseError, match="Cannot connect to database"):
DatabaseHandler(temp_db)
def test_query_with_comments_and_whitespace(self, temp_db):
"""Test query execution with comments and extra whitespace."""
handler = DatabaseHandler(temp_db)
query = """
... | Python | 1 |
import os
import pandas as pd
from datetime import datetime
from data.data_fetcher import get_recent_ohlc_window
from data.data_analyzer import add_bbands, add_adx, basic_summary
# --- Configuration ---
symbol = "NSE:NIFTY50-INDEX"
resolution = "5" # 5-minute candles
minutes_back = 180 # Fetch last 3 hours
# --- Fe... | Python | 1 |
;
type F = <C as GenericConfig<D>>::F;
let x_ff = FF::rand();
let y_ff = FF::rand();
let product_ff = x_ff * y_ff;
let config = CircuitConfig::standard_ecc_config();
let pw = PartialWitness::new();
let mut builder = CircuitBuilder::<F, D>::new(config);
l... | Rust | 0 |
from django.db import models
# Create your models here.
class Student(models.Model):
name = models.CharField(max_length=40)
roll_no = models.IntegerField()
marks = models.IntegerField()
dob = models.DateField()
age = models.IntegerField()
dept = models.CharField(max_length=40)
email = model... | Python | 1 |
breakpad_info) = dump.get_stream::<MinidumpBreakpadInfo>() {
breakpad_info.print(stdout).unwrap();
}
// TODO: MemoryInfoList
for &(stream, name) in streams!(
LinuxCmdLine,
LinuxEnviron,
LinuxLsbRelease,
L... | Rust | 0 |
from __future__ import annotations
import typing as t
from .base import BlockId, DataBlock
NumberValue = t.Union[str, int, float]
class BigNumber(DataBlock):
"""
A single number or change can often be the most important thing in an app.
The `BigNumber`block allows you to present KPIs, changes, and sta... | Python | 1 |
rs of Hashtag'] = set(data['Users of Hashtag'])
data['Mentions'] = set(data['Mentions'])
data['Hashtags'] = set(data['Hashtags'])
# Remove key (i.e. this particular hashtag) from set of hashtags in a given tweet
data['Hashtags'].remove(key)
# Collect Aggregate data
data[... | Python | 1 |
,'h w f -> f h w')
superpixels.append(th.from_numpy(seg))
grid = tv_utils.make_grid(superpixels)
vid_io.save_image(grid,"output/figures/sample_superpixel/examples")
# -- save marked region --
seg = mark_boundaries(ftrs_w.cpu().numpy(),labels_w,mode=mode)
seg = irz(rearrange(seg,'h w c -> c ... | Python | 1 |
::Not),
_ => None,
};
let bop = match &nodes[0] {
Node::Atom(s) if s.to_string() == "=>" => Some(BinaryOp::Implies),
Node::Atom(s) if s.to_string() == "=" => Some(BinaryOp::Eq),
Node::Atom(s) if s.to_string() == "<=" => Some(BinaryO... | Rust | 0 |
DY_EXISTS => Status::FileAlreadyExists,
FILE_NOT_FOUND => Status::FileNotFound,
GP_AUTH_FAILED => Status::GPAuthFailed,
HALTED => Status::Halted,
INCONSISTENT_FILE => Status::InconsistentFile,
INCORRECT_DATA => Status::IncorrectData,
INCORRECT_LENG... | Rust | 0 |
found = True
assert found
def test_gpu_feature():
# Use records to build a complicated GPU program
json_records = "\n".join(
(
"""{"i": [["[\\"matmul_auto_scheduler_test\\", 512, 512, 512]", "cuda"], [[], [["CHW", 2, "local"], ["SP", 2, 0, 512, [1, 16, 32, 1], 1], ["SP"... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.