text string | label_name string | labels int64 |
|---|---|---|
een(
prev_week_start.date(),
(last_week_start - pd.Timedelta(days=1)).date()
)]
last_month_data = df[df['date'].between(
last_month_start.date(),
last_month_end.date()
)]
prev_month_data = df[df['date'].between(
prev_month_start.date(),
prev_month_end.da... | Python | 1 |
STRATEGY_NUMBER_LESS => value < query,
_ => panic!("vectime - strategy type not supported: {}", strategy)
}
} else {
false
}
}
/// This method consolidates information in the tree. Given a set of entries, this function generates
/// a new index entry that represents all ... | Rust | 0 |
import pytest
import allure
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from allure_commons... | Python | 1 |
_button,
simple_fui_button,
skewed_fui_button,
simple_skewed_fui_button,
green_fui_button,
disabled_fui_button,
spinner: Spinner::new(),
animate_list: AnimateList::new_with_content(
Self::animate_list_content(),
... | Rust | 0 |
Unknown or invalid GeoIP record type"),
};
DB.with(|db| {
match db
.borrow()
.as_ref()
.map_err(MaybeBorrowed::Borrowed)
.and_then(|db| {
record
.lookup(lua, db, ip_addr)
.map_err(MaybeBorrowed::Owned)
}) {
Ok(_) => 1,
Err(err) => {
lua.push_nil();
lua.push_string(&err.as... | Rust | 0 |
le_func
def pdf(self,x):
return self.pdf_func(x)
def sample(self,Ndata):
return self.sample_func(Ndata)
if __name__ == "__main__":
import matplotlib.pyplot as plt
Ndata = 2**4
dist1 = Beta(1,5,5,loc = -0.5,scale =2 * np.pi)
dist2 = Uniform(1,- 2 * np.pi, 4 * np.pi)
... | Python | 1 |
отдельно онлайн и оффлайн клиентов
online_sorted = sorted(online_clients, key=ip_key)
offline_sorted = sorted(offline_clients, key=lambda x: x.get("name", "").lower())
# Объединяем: сначала онлайн, потом оффлайн
clients_sorted = online_sorted + offline_sorted
def on_wol_clicked(_, mac):
p... | Python | 1 |
#!/usr/bin/env python3
import os
import cgi
import cgitb
from http import cookies
from common import load_sessions, find_user
cgitb.enable()
form = cgi.FieldStorage()
data = form.getvalue("data", "").strip()
print("Content-Type: text/html; charset=utf-8")
# Parse cookies
cookie = cookies.SimpleCookie(os.environ.get... | Python | 1 |
'''Watches AWS metadata API for spot termination notices on spot nodes.
Uses kubectl to drain nodes once their termination notice is present.'''
from os import getenv
from time import sleep
from subprocess import call
from requests import get
def main():
'''Watch for termination notices on spot instance nodes on... | Python | 1 |
def export_to_markdown(messages: list[dict], export_path: str):
markdown = messages_to_markdown(messages)
with open(export_path, 'w') as f:
f.write(markdown)
print(f"Exported current conversation to {export_path}")
def messages_to_markdown(messages: list[dict]) -> str:
# Convert interpreter.me... | Python | 1 |
#input()will always takes an input as a string:
#Division Result will always be of type float.
num1 = int(input('Enter num1')) #20
num2 = int(input('Enter num2')) #10
print(f'Addition of {num1} and {num2} is {num1+num2}') #30
print(f'Subtraction of {num1} and {num2} is {num1-num2}') #10
print(f'Multiplication of {num1}... | Python | 1 |
# Section 5.17.2 Self Check snippets
# Exercise 5
plt.cla()
%recall 5
rolls = [random.randrange(1, 7) for i in range(6000000)]
%recall 6-13
values, frequencies = np.unique(rolls, return_counts=True)
title = f'Rolling a Six-Sided Die {len(rolls):,} Times'
sns.set_style('whitegrid')
axes = sns.barplot(values, freque... | Python | 1 |
);
return
}
// current element dropped
Solution::backtrack(start+1, curr.clone(), nums, result);
// current element picked
curr.push(nums[start]);
Solution::backtrack(start+1, curr, nums, result);
}
}
// submission codes end
#[cfg(test)]
mod tests {
... | Rust | 0 |
nitial_shift"] is not None
assert list(coreg_method.meta["inputs"]["affine"]["initial_shift"])[2] == 0
else:
coreg_method = xdem.coreg.NuthKaab(initial_shift=shift) # type: ignore
if shift is not None:
if len(shift) == 2:
shift += (0,)... | Python | 1 |
'\u{1d7a8}', Script::Common), ('\u{1d7a9}', '\u{1d7a9}', Script::Common),
('\u{1d7aa}', '\u{1d7c2}', Script::Common), ('\u{1d7c3}', '\u{1d7c3}', Script::Common),
('\u{1d7c4}', '\u{1d7cb}', Script::Common), ('\u{1d7ce}', '\u{1d7ff}', Script::Common),
('\u{1d800}', '\u{1d9ff}', Script::Sign... | Rust | 0 |
据
:param conn: 数据库连接
:param wheres: 条件键值对, 要求键值包含操作符,如: { 'column1 like': 'xyz', 'column2 =': 'abc' }
:return: 数据模型实例队列(若多个满足则返回第 1 个,没有满足则返回 None)
"""
bean = None
try:
cursor = conn.cursor()
sql = self._append(self.SQL_SELECT, wheres.keys())
... | Python | 1 |
urn;
}
mem.insert(node.clone());
match &*node.borrow() {
Node::Input(_) | Node::Const(_) => {}
Node::Not(e) => fetch_tmp_values(e.clone(), tmp_values, mem),
Node::Slice(e, _, _) => fetch_tmp_values(e.clone(), tmp_values, mem),
Node::BiOp(_, e1, e2) => {
fetch_tmp_... | Rust | 0 |
or')
plt.axvline(upper_percentile_95, color = 'red', label = '95% CI')
plt.axvline(lower_percentile_95, color = 'red')
plt.axvline(upper_percentile_50, color = 'gold', label = '50% CI')
plt.axvline(lower_percentile_50, color = 'gold')
plt.axvline(mob_value, color = 'limegreen', ... | Python | 1 |
ffer(state_dim, action_dim, device)
eval_cnt = 0
eval_src_return = eval_policy(policy, src_env, eval_cnt=eval_cnt)
eval_tar_return = eval_policy(policy, tar_eval_env, eval_cnt=eval_cnt)
eval_cnt += 1
tar_state, tar_done = tar_env.reset(), False
tar_episode_timesteps, tar_episode_num, tar_... | Python | 1 |
f` on each command,
/// ideal for chaining commands together.
pub mod owned;
/// A remote interface for a `RedisClient` that borrows `self` on each command. This is ideal for
/// use within a wrapping struct that manages ownership over inner values.
pub mod borrowed;<reponame>rawkode/tremor-runtime
// Copyright 2020-2... | Rust | 0 |
0xFF, 0xFF, 0xFF];
let mut db = RarReader::new(::std::io::Cursor::new(data));
db.consume(8);
assert_eq!(db.fill_buf().unwrap(), &data[8..]);
}
#[test]
fn test_seek() {
let data = [0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x01, 0x00, 0xFF, 0xFF, 0xFF];
let mut db = RarReader::new(::std::io::Cursor::ne... | Rust | 0 |
WASI doesn't have Unix-style mode flags.
const IXUSR = libc::S_IXUSR;
/// `S_IRWXG`
#[cfg(not(target_os = "wasi"))] // WASI doesn't have Unix-style mode flags.
const IRWXG = libc::S_IRWXG;
/// `S_IRGRP`
#[cfg(not(target_os = "wasi"))] // WASI doesn't have Unix-style mo... | Rust | 0 |
from typing import List, Dict, Optional
from pathlib import Path
from loguru import logger
def load_aql_queries(
directory: Path, include_queries: Optional[List[str]] = None
) -> List[Dict]:
"""Load AQL queries from .aql files in the specified directory."""
example_queries = []
for file_path in direct... | Python | 1 |
Returns a code indicating the severity of the last error. See
* @ref TJERR "Error codes".
*
* @param handle a handle to a TurboJPEG compressor, decompressor or
* transformer instance
*
* @return a code indicating the severity of the last error. See
* @re... | Rust | 0 |
ame}`\n\n" if user.last_name else ""
caption += f"__👁 User Name:__ @{user.username}\n\n" if user.username else ""
caption += f"__👤 User Id:__ `{user.id}`\n\n"
caption += f"__💬 DC ID:__ {user.dc_id}\n\n" if user.dc_id else ""
await send_msg.delete()
... | Python | 1 |
ChangePolicyUpdateDefaultVotePolicy { },
ChangePolicyUpdateParameters { },
AddMemberToRole { member_id: AccountId },
RemoveMemberFromRole { },
FunctionCall { },
UpgradeSelf { },
UpgradeRemote { },
Transfer { },
SetStakingContract { },
AddBounty { },
BountyDone { },
... | Rust | 0 |
ic_mark_bit(graphic, x, y, stride=6):
"""expressly sets the bit in the give graphic object"""
graphic[(y * stride) + int(x / 8)] |= 1 << (x % 8)
def graphic_unmark_bit(graphic, x, y, stride=6):
"""expressly unsets the bit in the give graphic object"""
graphic[(y * stride) + int(x / 8)] &= ~(1 << (x % ... | Python | 1 |
from flask import Flask, request, jsonify
from web3 import Web3
import json
import os
app = Flask(__name__)
# Connect to Ethereum node
ETH_NODE_URL = os.getenv('ETH_NODE_URL', 'https://your.ethereum.node')
w3 = Web3(Web3.HTTPProvider(ETH_NODE_URL))
# Load smart contract ABI and address
CONTRACT_ADDRESS = os.getenv('... | Python | 1 |
or_else(|| anyhow!("Empty platform"))?
.1
.remove("disk")
.ok_or_else(|| anyhow!("Missing 'disk' entry for platform"))?;
validate_artifact(a)
}
impl TryFrom<Stream> for RiverDelta {
type Error = anyhow::Error;
fn try_from(mut s: Stream) -> Result<Self, Self::Error> {
let st... | Rust | 0 |
) -> Self {
let t1 = cast::<_, u32x8>(self);
let t2 = cast::<_, u32x8>(
(t1 & u32x8::from(0x007FFFFF)) | u32x8::from(0x3F000000),
);
cast::<_, f32x8>(t2)
}
fn is_zero_or_subnormal(self) -> Self {
let t = cast::<_, i32x8>(self);
let t = t & i32x8::splat(0x7F800000);
i32x8::round_fl... | Rust | 0 |
{ (ctrls, cursors) move |_, e| {
let elem: FrameworkElement = ctrls.rectangle.cast()?;
let e = e.as_ref().unwrap();
let pointer = e.Pointer()?;
if !is_pointer_captured_by_element(&elem, &pointer) {
set_core_window_cursor(&cursors.hand)?;
}
... | Rust | 0 |
# after Safari 16.4!
import os
import frida
def check() -> frida.core.Device:
dev = frida.get_local_device()
if dev.query_system_parameters()['os']['id'] != 'macos':
raise RuntimeError('This script is only for Mac OS')
if "enabled" in os.popen("csrutil status").read():
raise RuntimeError(... | Python | 1 |
"""Init and utils."""
from zope.i18nmessageid import MessageFactory
_ = MessageFactory("collective.contentrules.telegram")
| Python | 1 |
et actual progress metrics
progress_metrics = await self.get_metrics(
metric_type=target_metric_type, metric_name=goal_name
)
if not progress_metrics:
current_value = 0.0
else:
current_value = sum(
float(m.value)
for m ... | Python | 1 |
); //TODO new??
let m: Basis3<f32> = Rotation3::from_axis_angle(v, Rad(a));
/*
let c = a.cos();
let s = a.sin();
let nc = 1.0 - c;
m[0][0] = v.x * v.x * nc + c;
m[0][1] = v.x * v.y * nc - v.z * s;
m[0][2] = v.x * v.z * nc + v.y * s;
m[1][0] = v.y * v.x * nc + v.z * s;
m[1][1] = v.y * v.y * nc + c;... | Rust | 0 |
_qualified,
)
.route(
"/depot/channels/{origin}/{channel}/pkgs/{pkg}/{version}/{release}/promote",
Method::PUT,
promote_package,
)
.route(
"/depot/channels/{origin}/{channel}/pkgs/{pkg}/{version}/{release}/de... | Rust | 0 |
elf, partition):
assert partition < self._n_partitions
return self._flux_handles[partition]
@property
def n_partitions(self):
return self._n_partitions
def can_launch(self, task):
raise RuntimeError('method cannot be used on Flux LM')
def get_launch_cmds(self, task,... | Python | 1 |
926ffe927f691893fb79a96b067"),
aad: b"",
ciphertext: &hex!("133fc15751621b5f325c7ff71ce08324"),
tag: &hex!("ec4e87e0cf74a13618d0b68636ba9fa7"),
},
TestVector {
key: &hex!("<KEY>"),
nonce: &hex!("2bb92fcb726c278a2fa35a88"),
plaintext: &hex!("f562509ed139a6bbe7ab545... | Rust | 0 |
metadata.
type: complex
spec:
description:
- spec describes the desired state of this TemplateInstance.
type: complex
status:
description:
- status describes the current state of this TemplateInstance.
type: complex
'''
def main():
try:
module = OpenShiftA... | Python | 1 |
;
schedule[62] = _mm_add_epi32(w14, _mm_set1_epi32(K32[62] as i32));
SCHEDULE_ROUND!(schedule, i, w0, w13, w15, w8);
schedule[63] = _mm_add_epi32(w15, _mm_set1_epi32(K32[63] as i32));
}
#[cfg(target_feature = "sse4.1")]
unsafe fn compress_4ways(state: &mut [u32; 8], schedule: &[__m128i; 64]) {
use supe... | Rust | 0 |
>.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// Portions... | Rust | 0 |
from django.utils.translation import gettext_lazy as _
from django.db import models
from django.contrib.auth import get_user_model
from django.db.models import Sum
from django.core.validators import MinValueValidator, MaxValueValidator
User = get_user_model()
class FinancialProfile(models.Model):
user = models.O... | Python | 1 |
productions.push(Production::builder()
.producing(LuaNonterminal::TableConstructor)
.from(seq!(
t!(LeftBrace),
maybe!(n!(FieldList)),
t!(RightBrace)))
.with_handler(&reduce_production)
.build()
.unwrap());
productions.push(Production... | Rust | 0 |
ode {
ctx.set_visuals(Visuals::dark());
} else {
ctx.set_visuals(Visuals::light());
}
if !self.api_key_initialized {
self.render_config(ctx);
} else {
self.preload_articles();
self.render_top_panel(ctx, frame);
Cen... | Rust | 0 |
{
($name:ident, $param:ident) => {{
let mut runner = proptest::test_runner::TestRunner::default();
let params = nfuint_tests::props::U256PairParameters::$param;
let strategy = nfuint_tests::props::U256Pair::arbitrary_with(params);
let mut val = strategy.new_tree(&mut runner).unwrap(... | Rust | 0 |
change in future
let kconfig_str_allow = regex::Regex::new(r"IDF_TARGET")?;
let cfg_args = build::CfgArgs {
args: build_output
.kconfig_args
.filter(|(key, value)| {
matches!(value, kconfig::Value::Tristate(kconfig::Tristate::True))
|| kconfi... | Rust | 0 |
86: u32 = 0;
fiat_p256_cmovznz_u32(&mut x686, x680, x673, x655);
let mut x687: u32 = 0;
fiat_p256_cmovznz_u32(&mut x687, x680, x675, x657);
let mut x688: u32 = 0;
fiat_p256_cmovznz_u32(&mut x688, x680, x677, x659);
out1[0] = x681;
out1[1] = x682;
out1[2] = x683;
out1[3] = x684;
out1[4] = x685;
out... | Rust | 0 |
}
// },
// {
// "identifier": {
// "cas": "74-82-8",
// "name": "methane",
// "iupac_name": "methane",
// "smiles": "C",
// "inchi": "InChI=1/CH4/h1H4",
// "for... | Rust | 0 |
position[1] + circle_radius], fill=line_color)
draw_text_with_shadow(background, draw, (text_x_position, 400), "00:00", arial, (255, 255, 255))
draw_text_with_shadow(background, draw, (1080, 400), duration, arial, (255, 255, 255))
play_icons = Image.open("alicex/assets/play_icons.png")... | Python | 1 |
"""
Neo4j图数据库管理器
负责图数据的存储、查询和管理
"""
import yaml
import logging
from typing import Optional, Dict, Any, List, Union
from neo4j import GraphDatabase, Driver, Session, Result
from neo4j.exceptions import Neo4jError
import json
class Neo4jManager:
"""Neo4j图数据库管理器"""
def __init__(self, config_path: str = 'con... | Python | 1 |
#!/usr/bin/env python3
import time
from trackball import TrackBall
from drv2605 import DRV2605
print("""This Pimoroni Breakout Garden example requires a
DRV2605L Haptic Breakout and a Trackball Breakout.
This example demonstrates how to generate haptic feedback
as the trackball is scrolled/pressed.
Press Ctrl+C to... | Python | 1 |
We got some new columns. Apply the operation to the rest of the row */
row_mul::with_accel::<Accel>(aug, &mut matrix.tiles[trow*tstride+tcol .. trow*tstride+ttotal]);
perm_matrix_cumulative = perm;
} else {
/* Move the new progress to the act... | Rust | 0 |
def fetch_middle(llists):
a = []
for i in llists:
if len(i)% 2 == 0:
m = i[len(i)//2]
l = i[(len(i)//2)-1]
x = (m+l)/2
a.append(x)
else:
n = len(i)//2
a.append(i[n])
return a
| Python | 1 |
': 'SonicAndKnuckles3-Genesis', 'state': 'CarnivalNightZone.Act1'},
{'game': 'SonicAndKnuckles3-Genesis', 'state': 'MushroomHillZone.Act2'},
{'game': 'SonicAndKnuckles3-Genesis', 'state': 'MushroomHillZone.Act1'},
{'game': 'SonicAndKnuckles3-Genesis', 'state': 'AngelIslandZone.Act1'}
]
#... | Python | 1 |
`_010`"]
#[inline]
pub fn is_010(&self) -> bool {
*self == MATCFGR::_010
}
#[doc = "Checks if the value of the field is `_011`"]
#[inline]
pub fn is_011(&self) -> bool {
*self == MATCFGR::_011
}
#[doc = "Checks if the value of the field is `_100`"]
#[inline]
pub ... | Rust | 0 |
Runs one-off command with inherited [`Stdio`](std::process::Stdio). Prints headline (witn [`Cmd::msg`](Cmd::msg), if provided) to stderr.
pub async fn run(&self) -> Result<()> {
eprintln!("{}", crate::headline!(self));
self.spawn(Stdio::inherit(), Stdio::inherit()).await?;
Ok(())
}
... | Rust | 0 |
class Solution:
def romanToInt(self, s: str) -> int:
ans = 0
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50,
'C': 100, 'D': 500, 'M': 1000}
for a, b in zip(s, s[1:]):
if roman[a] < roman[b]:
ans -= roman[a]
else:
ans += roman[a]
return ans + roman[s[-1]]
| Python | 1 |
validLatchStatus(u16),
#[error("Invalid value for cancel reason: {0:#04x}")]
InvalidCancelReason(u16),
}
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuntimeError {
#[error("Detachment preconditions not fulfilled")]
NotFeasible,
#[error("Detach operation timed out")]
... | Rust | 0 |
let f: extern "system" fn(GLenum) -> () = unsafe { transmute(p) };
f(func)
}
static glDepthMask_p: AtomicPtr<c_void> = AtomicPtr::new(null_mut());
/// Khronos: [glDepthMask](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glDepthMask.xhtml)
#[inline(always)]
pub fn glDepthMask(flag: GLboolean) -> () {
... | Rust | 0 |
data["width"],
"height": self.metadata["height"],
"fps": self.metadata["fps"],
}
if fixed_subgoals:
for index, subgoal in enumerate(result["subgoals"]):
subgoal["original_title"] = subgoal["title"]
subgoal["title"] ... | Python | 1 |
[postgres(oid = "3615", array_oid = "3645")]
pub struct Tsquery;
#[derive(Clone, Copy, SqlType)]
#[postgres(oid = "3614", array_oid = "3643")]
pub struct Tsvector;
#[derive(SqlType)]
#[postgres(type_name = "regconfig")]
pub struct Regconfig;
}
#[allow(deprecated)]
mod functions {
use ... | Rust | 0 |
': product.id,
'name': product.name,
'total_sold': product.total_sold,
'revenue': str(product.price * product.total_sold)
}
for product in top_products
]
return Response(top_products_data)
class TopCustomersView(generics.GenericA... | Python | 1 |
# SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""Definition for the Spacemit K1 chip"""
| Python | 1 |
UM_EPISODES
# Add bsuite_ids to corresponding tag sweeps.
for tag in experiment_package.TAGS:
if tag not in _TAGS:
_TAGS[tag] = []
_TAGS[tag].extend(results)
_SWEEP.extend(results)
return tuple(results)
# bsuite_ids broken down by environment.
BANDIT = _parse_sweep(bandit_sweep)
BANDIT_NOISE = ... | Python | 1 |
# Copyright 2022 The HuggingFace Team. 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 applicabl... | Python | 1 |
None => syn::Ident::from(idx),
}).collect();
quote! {
match index {
#(
#index => _runtime_fmt::codegen::combine::<__F, Self, #ty, _>(
|this| &this.#ident
),
)*
_ => panic!("bad index {}", index)
}
... | Rust | 0 |
p: &Program, use_strict_aliasing: bool) -> Set<Id> {
let mut independent = Set::default();
for (x, t) in &p.tyenv {
if t.is_array() || t.is_tuple() {
independent.insert(x.clone());
}
}
eliminate_dependent(&p.global_init, &p.tyenv, &mut independent);
for Fundef { args, ... | Rust | 0 |
import hashlib
from pathlib import Path
from typing import Iterable, Union
import srsly
from wasabi import msg
def get_hash(data, exclude: Iterable[str] = tuple()) -> str:
"""Get the hash for a JSON-serializable object.
data: The data to hash.
exclude (Iterable[str]): Top-level keys to exclude if data i... | Python | 1 |
est::ListenData(*route, address, send);
let sender = self.send_requests.clone();
let sent = async move {
sender.send(Request::External(request)).await
.map_err(|_| RallyPointError::NotActive)?;
Ok(())
};
sent.into_stream()
.try_filter_m... | Rust | 0 |
tor(DBIterator<Arc<DB>>);
impl FoundationdbEngineIterator {
pub fn from_raw(iter: DBIterator<Arc<DB>>) -> FoundationdbEngineIterator {
FoundationdbEngineIterator(iter)
}
}
impl einsteindb_promises::Iterator for FoundationdbEngineIterator {
fn seek(&mut self, key: einsteindb_promises::SeekKey) -> R... | Rust | 0 |
import pygame
from game_components.scene_manager import SceneManager
from game_components.game_state import GameState
from game_components.audio_manager import AudioManager
from game_components.scenes import *
from game_components.objects.camera import Camera
import os
# Initialize Pygame
pygame.init()
# Set up the s... | Python | 1 |
WaitCertificate> = None;
let mut blocks: Vec<Entry> = Vec::new();
let mut current_id = block_id;
loop{
let mut block_ = svc.get_block(¤t_id);
let block: Block;
if block_.is_ok(){
block = block_.unwrap();
}
else{
break;
... | Rust | 0 |
)
self.prev_is_grasped = self._sim.gripper.is_grasped
self.prev_geo_dist = None
self.update_metric(*args, task=task, episode=episode, **kwargs)
def update_metric(
self,
*args,
task: RearrangeNavTask,
episode: RearrangeEpisode,
**kwargs
):
... | Python | 1 |
ENCRYPTION_MODE_AES_128_ECB: ENCRYPTION_MODE = 2;
pub const ENCRYPTION_MODE_AES_256_XTS: ENCRYPTION_MODE = 3;
pub const ENCRYPTION_MODE_SM4_128_ECB: ENCRYPTION_MODE = 4;
pub const ENCRYPTION_MODE_MODE_END: ENCRYPTION_MODE = 5;
pub type ENCRYPTION_MODE = ::std::os::raw::c_uint;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
p... | Rust | 0 |
rror_counters = {level: 0 for level in ErrorLevel}
self._save_to_session_state()
def add_callback(self, callback: Callable[[ErrorEntry], None]) -> None:
"""에러 발생 시 호출될 콜백 추가"""
self._callbacks.append(callback)
def remove_callback(self, callback: Callable[[ErrorEntry], None]) ->... | Python | 1 |
import math
from torch import nn
def glorot_weight_zero_bias(model):
"""Initialize parameters of all modules by initializing weights with
glorot
uniform/xavier initialization, and setting biases to zero. Weights from
batch norm layers are set to 1.
Parameters
----------
model: Module
... | Python | 1 |
TenantAwareAdmin, admin.ModelAdmin):
list_display = ['project', 'metric', 'name', 'created_at']
@admin.register(ComputationStatus, site=admin_site)
class ComputationStatusAdmin(TenantAwareAdmin, admin.ModelAdmin):
list_display = ['project', 'status', 'created_at', 'updated_at']
@admin.register(Notification, s... | Python | 1 |
}
/// Alliance Memory AS4C16M32MSA SDRAM
#[allow(unused)]
pub mod as4c16m32msa_6 {
use crate::sdram::{SdramChip, SdramConfiguration, SdramTiming};
const BURST_LENGTH_1: u16 = 0x0000;
const BURST_LENGTH_2: u16 = 0x0001;
const BURST_LENGTH_4: u16 = 0x0002;
const BURST_LENGTH_8: u16 = 0x0004;
con... | Rust | 0 |
,
parse_brport_mcast_to_ucast,
parse_brport_vlan_tunnel,
parse_brport_bast_flood,
parse_brport_group_fwd_mask,
parse_brport_neigh_suppress,
parse_brport_isolated,
parse_brport_backup_port,
];
pub(crate) fn parse_bridge_port_info(
raw: &[u8],
) -> Result<BridgePortInfo, NisporError> {
... | Rust | 0 |
alsatimer/src/auto/enums.rs
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use glib::error::ErrorDomain;
use glib::translate::*;
use glib::value::FromValue;
use glib::value::ToValue;
use glib::Quark;
use glib::StaticType;... | Rust | 0 |
# Copyright 2025 © BeeAI a Series of LF Projects, LLC
# SPDX-License-Identifier: Apache-2.0
from datetime import datetime
from typing import Any
from zoneinfo import ZoneInfo
import pytest
from pydantic import BaseModel, ValidationError
from beeai_framework.template import (
PromptTemplate,
PromptTemplateErr... | Python | 1 |
#!/usr/bin/env python
import logging
import unittest
from hummingbot.core.data_type.order_book import OrderBook
import numpy as np
class OrderBookUnitTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.order_book_dex = OrderBook(dex=True)
cls.order_book_cex = OrderBook(dex=False)
... | Python | 1 |
from glob import glob
if __name__ == "__main__":
folders = ['gilani-2017', 'varol-icwsm']
paths = []
for folder in folders:
if 'political' in folder:
continue
user_folders = f"{folder}/users/*"
users = glob(user_folders)
paths = paths + [k + "\n" for k in ... | Python | 1 |
nnahmen__renten__aus_berufsständischen_versicherungen_m
),
parameters=anrechnungsfreier_anteil_private_renteneinkünfte,
xnp=xnp,
)
upper = grundsicherung__regelbedarfsstufen.rbs_1 / 2
return (
einnahmen__renten__sonstige_private_vorsorge_m
+ einnahmen__renten__geförd... | Python | 1 |
ax,m)
exit()
tst_integral_triple_zernike2d(nmax)
comp_Cnm_calculations(nmax)
exit()
t1=time.time()
tst_2d_zm(41,1)
t2=time.time()
print("xy: ", t2-t1)
tst_2d_zernike_mom(41,1)
t3=time.time()
print("rt: ", t3-t2)
exit()
tst_2d_poly(51,19)
exit()
t1 = time.time()
args = sys.argv[1:]... | Python | 1 |
![no_main]
#[macro_use]
extern crate libfuzzer_sys;
use std::str::Chars;
use std::cell::RefCell;
use std::rc::Rc;
use unicode_normalization::{char::canonical_combining_class, UnicodeNormalization};
const MAX_NONSTARTERS: u32 = 30;
#[derive(Debug)]
struct Counter<'a> {
iter: Chars<'a>,
value: Rc<RefCell<u32>... | Rust | 0 |
# Copyright (c) 2024 Airbyte, Inc., all rights reserved.
from enum import Enum
_TERMINAL = True
class AsyncJobStatus(Enum):
RUNNING = ("RUNNING", not _TERMINAL)
COMPLETED = ("COMPLETED", _TERMINAL)
FAILED = ("FAILED", _TERMINAL)
TIMED_OUT = ("TIMED_OUT", _TERMINAL)
def __init__(self, value: st... | Python | 1 |
e(
(example[self.time_delay:, :],
np.repeat(example[-1, :][np.newaxis], repeats=self.time_delay, axis=0)), axis=0)
if "continuous_label" not in feature:
example = self.transform_dict[feature](np.asarray(example, dtype=np.float32))
return example
def lo... | Python | 1 |
nitor_activity(&self) -> EventListener {
self.inner.monitor_activity()
}
}
impl From<crate::Connection> for Connection {
fn from(conn: crate::Connection) -> Self {
Self { inner: conn }
}
}
#[cfg(test)]
mod tests {
use ntest::timeout;
use std::{os::unix::net::UnixStream, thread};
... | Rust | 0 |
position_value = position_size * current_price
cash = 0
hold_days = 1
total_trades += 1
df.loc[i, 'trade_action'] = f'SELL_BUY_{total_trades}'
trade_info = {
'trade_id': total_trades,
... | Python | 1 |
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api
from odoo.tools import formatLang
class AccountPayment(models.Model):
_inherit = "account.payment"
@api.depends('payment_method_line_id', 'currency_id', 'amount')
def _compute_check_amount_in_words(se... | Python | 1 |
Ref<'a>, _y: &'b u8) { }
fn lifetime_param_3<'a, 'b: 'a>(_x: Ref<'a>, _y: &'b u8) { } // no error, bounded lifetime
fn lifetime_param_4<'a, 'b>(_x: Ref<'a>, _y: &'b u8) where 'b: 'a { } // no error, bounded lifetime
struct Lt<'a, I: 'static> {
x: &'a I
}
fn fn_bound<'a, F, I>(_m: Lt<'a, I>, _f: F) -> Lt<'a, I>... | Rust | 0 |
# Copyright 2022 The BladeDISC 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 applicable law or ... | Python | 1 |
L_ZONE
savedId = db.getValue(sectionPath+'/cellZone')
cellZones = db.getCellZones(self._rname)
for czid, czname in cellZones:
if czname == 'All':
continue
radio = QRadioButton(czname)
if str(czid) == savedId:
... | Python | 1 |
and Pattern Recognition, 2019.
Retrieved from http://arxiv.org/abs/1812.07035
"""
return matrix[..., :2, :].clone().reshape(*matrix.size()[:-2], 6)
def axis_angle_to_rotation_6d(axis_angle):
"""
Convert rotations given as axis/angle to 6D rotation representation by Zhou
et al. [1].
Args:
... | Python | 1 |
import os, re, logging
import LangSegment
from classic_text_cleaner import *
logging.getLogger("markdown_it").setLevel(logging.ERROR)
logging.getLogger("urllib3").setLevel(logging.ERROR)
logging.getLogger("httpcore").setLevel(logging.ERROR)
logging.getLogger("httpx").setLevel(logging.ERROR)
logging.getLogger("asyncio"... | Python | 1 |
end = match time_events.binary_search_by(|t_e| {
let t = t_e.instant + t_e.duration;
t.cmp(&window_end)
}) {
Ok(e) => e + 1,
Err(e) => e,
};
// Now, we can very efficiently work with the only events that should be disp... | Rust | 0 |
ons to exponent
let ee = e1 + e2 + e3;
let ei = unsafe { ee.to_int_fast() };
// biased exponent of result:
let ej = ei + Vi64::<S>::from_bits(z.into_bits()) >> 52;
// add exponent by integer addition
let mut z = Vf64::<S>::from_bits((ei.into_bits() << 52) + z.into_bits(... | Rust | 0 |
,则添加为第二个速度
if isinstance(variables['speed'], list):
variables['speed'].append(value)
else:
variables['speed'] = [variables['speed'], value]
elif key == 'time' and 'time_a' in variables:
... | Python | 1 |
red_times)
.iter()
.all(|cnf| cnf == &0)
})
.cloned()
.collect()
}
})
.collect();
courses.sort_by_cached_key(|set| set.len());
if courses[0].len() == 0 {
Vec:... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.