text string | label_name string | labels int64 |
|---|---|---|
Mode,
) -> Result<Self, SynthesisError> {
let native = f()?;
let native = native.borrow();
let cs = cs.into();
let prover_iop_messages_by_round = Vec::<SuccinctRoundMessageVar<CF>>::new_variable(
cs.clone(),
|| Ok(native.prover_iop_messages_by_round.clone()),
... | Rust | 0 |
cfg(not(any(target_os = "freebsd", target_os = "netbsd", target_os = "openbsd")))]
d_ino,
#[cfg(any(target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))]
d_fileno,
#[cfg(not(target_os = "wasi"))]
d_reclen,
#[cfg(any(
target_os = "freebsd",
... | Rust | 0 |
method calls
/// If any of `binding_hir_ids` is used in any other way, then `clone_or_copy_needed` will be true
/// when `CloneOrCopyVisitor` is done visiting.
struct CloneOrCopyVisitor<'cx, 'tcx> {
cx: &'cx LateContext<'tcx>,
binding_hir_ids: Vec<HirId>,
clone_or_copy_needed: bool,
addr_of_exprs: Vec<... | Rust | 0 |
from airflow.decorators import task, dag
from airflow.providers.samba.hooks.samba import SambaHook
from airflow.hooks.base_hook import BaseHook
import pandas as pd
import datetime as dt
from sqlalchemy import create_engine
from airflow.providers.microsoft.mssql.hooks.mssql import MsSqlHook
import time
@dag(
descri... | Python | 1 |
;
assert_eq!(direction(3.0*FRAC_PI_4, -FRAC_PI_4), false);
assert_eq!(direction(3.0*FRAC_PI_4, -2.0*FRAC_PI_6), false);
assert_eq!(direction(3.0*FRAC_PI_4, -FRAC_PI_2), false);
assert_eq!(direction(3.0*FRAC_PI_4, -4.0*FRAC_PI_6), false);
assert_eq!(direction(3.0*FRAC_PI_4... | Rust | 0 |
tr, default=None,
help='Path to icon file for the filesystem')
parser.add_argument('--debug', action='store_true',
help='Enable debug logging')
parser.add_argument('--quiet', action='store_true',
help='Suppress all log messages except error... | Python | 1 |
"""
Copyright 2020 kivou.2000607@gmail.com
This file is part of yata.
yata 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 License, or
any later version.
yata is dist... | Python | 1 |
weights(lora_path, weight_name="pytorch_lora_weights.safetensors", adapter_name="test_1")
pipe.fuse_lora(lora_scale=1 / lora_rank,components = ["transformer"])
# 将lora和模型融合到一起然后保存到本地首先卸载lora
# pipeline.unload_lora_weights()
# save locally
# pipeline.save_pretrained("pat... | Python | 1 |
@jit(nopython=True)
def _numba_fast_moving_avg(values: np.ndarray,
m: int=20) -> np.ndarray:
"""
This is O(n) time and just-in-time compiled with numba
"""
# Initialize arrays to store data
moving_avg = np.empty(values.shape)
moving_avg[:m-1] = np.nan
# Exit early if m greater than le... | Python | 1 |
"""
加密和解密
对称加密 - 加密和解密是同一个密钥 - DES / AES
非对称加密 - 加密和解密是不同的密钥 - RSA
pip install pycrypto
"""
import base64
from hashlib import md5
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.PublicKey import RSA
# # AES加密的密钥(长度32个字节)
# key = md5(b'1qaz2wsx').hexdigest()
# # AES加密的初始向量(随机生成)
# iv = Random.new(... | Python | 1 |
("621", 2, "ng"), // Nigeria (Federal Republic of)
("622", 2, "td"), // Chad (Republic of)
("623", 2, "cf"), // Central African Republic
("624", 2, "cm"), // Cameroon (Republic of)
("625", 2, "cv"), // Cape Verde (Republic of)
("626", 2, "st"), // Sao Tome and P... | Rust | 0 |
m % S SK Jr S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SK r S SK
r
S SKrS SKJ
r
S SKJrJr S SKJrJrJrJrJrJrJr S SKJr S SKJr S SKrS SKrS SKrS SK rS SK!J"s J#r$ S SK%J&r& S S K'J(r( S S
K)J*r* S SK+J,r,J-r-... | Python | 1 |
} else {
log.add(
format!("Can't dequip {:?} because it's not an Equipment.", self),
colors::RED,
);
}
}
pub fn power(&self, game: &Game) -> i32 {
let base_power = self.fighter.map_or(0, |f| f.base_power);
let bonus_power: i32 = ... | Rust | 0 |
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 in writing, software
// distributed under the License is distributed on an "AS IS" B... | Rust | 0 |
y_with_x = 3_u32;
/// let matrix = Matrix2x2::from_shear_y(shear_y_with_x);
/// let vector = Vector2::new(1, 1);
/// let expected = Vector2::new(1, 1 + 3*1);
/// let result = matrix * vector;
///
/// assert_eq!(result, expected);
/// ```
#[rustfmt::skip]
#[inline]
pub fn from_she... | Rust | 0 |
ame,
"warning": billing_alarm_warning.name,
"critical": billing_alarm_critical.name
})
pulumi.export("finops_enterprise_status", {
"stack": stack_name,
"detection": "Hunter Lambda - Every 12h",
"prevention": "Guardian Lambda - Real-time",
"notification": "Multi-channel alerts (SNS/Discord/Slack... | Python | 1 |
pub consume_data:
Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_decompress_ptr) -> libc::c_int>,
pub start_output_pass:
Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_decompress_ptr) -> ()>,
pub decompress_data: Option<
unsafe extern "C" fn(
_: crate::jpeglib_h::j_de... | Rust | 0 |
write_bool(hash, entry.metadata().read_only(), 'r')?;
write_bool(hash, entry.metadata().hidden(), 'h')?;
write!(hash, "\t")?;
write_timestamp(hash, entry.metadata().created())?;
write_timestamp(hash, entry.metadata().modified())?;
write_timestamp(hash, entry.metadata().accessed())?;
write!(hash... | Rust | 0 |
::from(buf))
}
}
impl ops::Deref for PrivateKey {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<[u8; PRIVATE_KEY_BYTES]> for PrivateKey {
fn from(bytes: [u8; PRIVATE_KEY_BYTES]) -> Self {
PrivateKey(bytes)
}
}
impl From<SecretKey> for PrivateKey... | Rust | 0 |
();
// Align stack
sp = push(sp, 0);
// Save the (generator_wrapper) function on the stack.
sp = push(sp, f as usize);
#[naked]
unsafe extern "C" fn trampoline_1() {
asm!(
".cfi_def_cfa x29, 16",
".cfi_offset x30, -8",
".cfi_offset x29, -16",
... | Rust | 0 |
erive(Debug)]
pub struct ScancodeDecoder {
current_decoder: Decoder,
}
impl Default for ScancodeDecoder {
fn default() -> Self {
Self::new()
}
}
impl ScancodeDecoder {
/// Defaults to scancode set 2.
pub fn new() -> Self {
Self {
current_decoder: Decoder::Set2(KeyboardS... | Rust | 0 |
from confluent_kafka import Producer
from datetime import datetime
from random import randint, choice
from time import sleep
# Configuración del productor
producer_conf = {
'bootstrap.servers': 'localhost:9092'
}
producer = Producer(producer_conf)
# Función para enviar mensajes
def produce_messages(topic, num_mes... | Python | 1 |
# Copyright (C) 2023 Fujitsu
# 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 a... | Python | 1 |
u32) -> Result<ConcreteReplica> {
// bit ugly. Tries passed-in rpc first, then defaults to lookup by
// domain
let provider = self
.rpc
.as_ref()
.map(|rpc| Provider::<Http>::try_from(rpc.as_ref()))
.transpose()?
.unwrap_or_else(|| rpc... | Rust | 0 |
u8 = std::mem::transmute(op as u8);
let op = LLVMConstInt(LLVMInt8Type(), op_value as u64, 0);
let rd = self.section.emit_call_with_name(
"banshee_fp32_op_cvt_to_f",
[rs1, op, fpmode_src, fpmode_dst],
"fp32_op_cvt_to_f",
);
rd
}
/// emit fp32 ... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 23 13:12:46 2022
@author: Andrés Mejía
"""
# Caso b:
# 𝑌 ≡ 𝐷𝑃, 𝑋0 ≡ 1, 𝑋1 ≡ 𝑁𝑎𝑑𝑖𝑟, 𝑋2 ≡ df/dt, 𝑋3 ≡ 𝑉𝑒𝑛𝑑
## Importación de los datos
import pandas as pd
import numpy as np
import xlsxwriter
Data = pd.read_excel('DATOS.xlsx', sheet_name='Hoja1')
Data = r... | Python | 1 |
import os
import openpyxl
dst_filename = 'mgc_uart_reg.ralf'
workbook = openpyxl.load_workbook('REG.xlsx') # 返回一个workbook数据类型的值
file_obj = open(dst_filename,'w') # 打开目标文件
print(workbook.sheetnames) # 打印Excel表中的所有表
sheet = workbook['Sheet1'] # 获取某一个表
print(sheet.dimensions) # 获取表格的尺寸大小
row_num = sheet.max_row ... | Python | 1 |
import numpy as np
# Merge sort
def merge(left, right):
left_index = 0
right_index = 0
# Sorted population
sorted = []
# Compare fitnessess
while left_index < len(left) and right_index < len(right):
# Left fitness is higher or equal
if left[left_index][1] >= right[right_index]... | Python | 1 |
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
if 2 <= n <= 10 and all(-100 <= score <= 100 for score in arr):
highest = max(arr)
arr = [x for x in arr if x != highest]
runner_up = max(arr)
print(runner_up)
| Python | 1 |
rce_info.get_str("version-type") == "pony-age"
assert source_info.get_str("version") == "1234567"
assert source_info.get_str("version-guess", None) == "12"
extra_data = source_info.get_mapping("extra-data", None)
assert extra_data is not None
assert extra_data.get_str("pony", "green")
# Test what... | Python | 1 |
// 5min
5.0
} else {
// skip grids below 5min
continue;
};
marks.push(GridMark {
value: i as f64,
step_size,
});
}
marks
}
#[allow(clippy::unused_self... | Rust | 0 |
let leny = if trans == 'n' || trans == 'N' { m } else { n };
let noconj = trans == 't' || trans == 'T';
let mut kx = 0;
let mut ky = 0;
if incx < 0 {
kx = (-(lenx as isize) * incx) + incx
};
if incy < 0 {
ky = (-(leny as isize) * incy) + incy
};
if !beta.is_one() {... | Rust | 0 |
formatted_sum.to_string().as_str().parse::<f32>()?,
ticker,
formatted_basis.to_string().as_str().parse::<f32>()?,
home_currency,
lot.date_for_basis_purposes
)
} el... | Rust | 0 |
ub type R = crate::R<u32, super::TPR>;
#[doc = "Writer for register TPR"]
pub type W = crate::W<u32, super::TPR>;
#[doc = "Register TPR `reset()`'s with value 0"]
impl crate::ResetValue for super::TPR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of ... | Rust | 0 |
USD",
normalize_currency(&underlying[3..(underlying.len() - 3)], EXCHANGE_NAME),
);
assert_eq!(pair.as_str(), pair_expected);
let market_type = get_market_type(&market.symbol, EXCHANGE_NAME, None);
if market.symbol.starts_with("fi_") {
assert_eq!(market_type, M... | Rust | 0 |
import math
import numpy as np
def var_strat(level: int, T: float, M: int = None) -> float:
"""
Variance of Stratonovich signature of a one-dimensional continuous-time Brownian motion and its piecewise-linear approximation (Young/Lebesgue/Riemann integration).
"""
s2 = math.factorial(2*level) / (2**l... | Python | 1 |
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import savgol_filter
import networkx as nx
def plot_network(rec, prefix=""):
fg, ax = plt.subplots()
ax.matshow(rec.connections)
fg.savefig(f"{prefix}matrix.pdf")
fg.savefig(f"{prefix}matrix.png")
fg.savef... | Python | 1 |
bkey
def freeze_lookup_table(params: FreezeLookupTableParams) -> Instruction:
"""Constructs an instruction that freezes an address lookup table.
So that it can never be closed or extended again.
Empty lookup tables cannot be frozen.
Args:
params (FreezeLookupTableParams): The FreezeLookupTab... | Python | 1 |
Django tried these URL patterns, in this order:
</p>
<ol>
{% for pattern in urlpatterns %}
<li>{{ pattern }}</li>
{% endfor %}
</ol>
<p>The current URL, <code>{{ request_path|escape }}</code>, didn't match any of these.</p>
{% else %}
<p>{{ reason }}</p>
... | Python | 1 |
from flask import Flask, render_template, request, jsonify
import json
from maestro import Controller
import random
import time
import threading
import math
app = Flask(__name__)
x=Controller()
@app.route('/')
def index():
return render_template('index.html')
image_urls = [
"static/eyes.png",
"static/... | Python | 1 |
oint(&-&x, &A), &B)
);
assert_eq!(
g!(A + x * B),
op::point_add(&A, &op::scalar_mul_point(&x, &B))
);
assert_eq!(
g!(A - x * B),
op::point_sub(&A, &op::scalar_mul_point(&x, &B))
);
assert_eq!(g!(x * A + y * B), op::double_mul(&x, &A, &y, &B));
assert_eq!(g!(x ... | Rust | 0 |
11)
'_Atomic', # (C11)
'_BitInt', # (C23)
'_Bool', # (C99)
'_Complex', # (C99)
'_Decimal128', # (C23)
'_Decimal32', # (C23)
'_Decimal64', # (C23)
'_Generic', # (C11)
'_Imaginary', # (C99)
'_Noreturn', # (C11)
'_Static_assert', # (C11)
'_Thread_local', # (C11)
... | Python | 1 |
Secondly,
Minutely,
Hourly,
Daily,
Weekly,
Monthly,
Yearly,
}
impl fmt::Display for Frequency {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
Frequency::Secondly => "SECONDLY",
... | Rust | 0 |
id);
}
extern crate proc_macro;
use std::collections::HashMap;
use quote::ToTokens;
use crate::{ast::ToCode, ctxt::Ctx, input::QuoteInput, ret_type::parse_input_type};
mod ast;
mod builder;
mod ctxt;
mod input;
mod ret_type;
/// Don't invoke this macro directly, use the `quote!` macro from
/// `swc_ecma_quote` ins... | Rust | 0 |
encher: &mut Bencher) {
let data1: Array2<f64> = Array2::random((200, 50), Normal::new(1., 0.2));
let data2: Array2<f64> = Array2::random((50, 50), Normal::new(1., 0.2));
bencher.iter(|| {
data1.view().squared_euclidean_distance(data2.view());
})
}
extern crate rand;
/// This is a key value st... | Rust | 0 |
import os
from utils.topgg import update_topgg_count
from utils.status import status_refresh_interval
from dotenv import load_dotenv
from interactions import (
Intents,
AutoShardedClient,
listen,
Activity,
ActivityType,
Status,
)
from interactions.ext.debug_extension import DebugExtension
from c... | Python | 1 |
# Create python xml structures compatible with
# http://search.cpan.org/~grantm/XML-Simple-2.18/lib/XML/Simple.pm
from lxml import etree
from itertools import groupby
def xml2d(e):
"""Convert an etree into a dict structure
@type e: etree.Element
@param e: the root of the tree
@return: The dictionary... | Python | 1 |
im)) => Some(Complex { re, im }),
None => None
}
}
#[test]
fn test_parse_complex() {
assert_eq!(parse_complex("1.25,-0.0625"),
Some(Complex { re: 1.25, im: -0.0625 }));
assert_eq!(parse_complex(", -0.0625"), None);
}
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of thi... | Rust | 0 |
# 1507 4개의 직사각형 넓이
# matrix=[[0]*100 for i in range(100)]
# count=0
#
# for i in range(4):
# x1,y1,x2,y2=map(int,input().split()) # 4개 입력
#
# for x in range(x1,x2):
# for y in range(y1,y2):
# matrix[x][y]=1 # 해당 사각형 범위를 1로 채운다
#
# for i in range(0,100):
# for j in range(0,100):
# ... | Python | 1 |
(lc, rc) && eq_block(lt, rt) && eq_expr_opt(le, re),
(While(lc, lt, ll), While(rc, rt, rl)) => eq_label(ll, rl) && eq_expr(lc, rc) && eq_block(lt, rt),
(ForLoop(lp, li, lt, ll), ForLoop(rp, ri, rt, rl)) => {
eq_label(ll, rl) && eq_pat(lp, rp) && eq_expr(li, ri) && eq_block(lt, rt)
},... | Rust | 0 |
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import signals
from scrapy import log
from scrapy import log, signals
from core.spiders.GeneralSpider import GeneralSpider
from scrapy.utils.project import get_project_settings
import os
from scrapy.settings import Settings
def setup_c... | Python | 1 |
/css-grid-2/#typedef-track-breadth
#[derive(Debug, Clone, PartialEq)]
pub enum TrackBreadth {
Length(LengthPercentage),
Flex(f32),
MinContent,
MaxContent,
Auto
}
/// https://drafts.csswg.org/css-grid-2/#typedef-track-repeat
#[derive(Debug, Clone, PartialEq)]
pub struct TrackRepeat {
count: RepeatCount,
l... | Rust | 0 |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
# Make the twisted module executable with the default behaviour of
# running twist.
# This is not a docstring to avoid changing the string output of twist.
import sys
if __name__ == "__main__":
from twisted.application.twist._twist import T... | Python | 1 |
import matplotlib.pyplot as plt
import numpy as np
import cv2
import os
def img_show(img, time_interval=2, img_save=False):
plt.matshow(img)
plt.show(block=False)
plt.pause(time_interval)
plt.close()
def heatmap_show(img, width, height, time_interval=2, img_save=False):
heatmap = np.mean((img.da... | Python | 1 |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# File Name : preprocess.py
# Purpose :
# Creation Date : 10-12-2017
# Last Modified : Thu 18 Jan 2018 05:34:42 PM CST
# Created By : Jeasine Ma [jeasinema[at]gmail[dot]com]
import numpy as np
from config import cfg
data_dir = 'velodyne'
def process_pointcloud(point_clo... | Python | 1 |
from datetime import datetime, timedelta
import pytest
import unittest.mock
from test.integration.terrareg import TerraregIntegrationTest
from test import client, app_context, test_request_context
import terrareg.provider_model
import terrareg.provider_version_model
import terrareg.models
import terrareg.analytics
... | Python | 1 |
signals.forever() {
loop {
let pid = unsafe { libc::waitpid(-1, std::ptr::null_mut(), libc::WNOHANG) };
if pid <= 0 {
break;
}
}
}
});
}
<reponame>rustsack/rustsack-rs
trait Foo {
fn dummy(&self) { }
}
fn a(_x: ... | Rust | 0 |
index into the slice.
///
/// # Arguments
///
/// * `expiry_index` - Expiry series index.
/// * `product_index` - Index into the products slice. [0..NUM_PRODUCTS_PER_SERIES).
pub fn get_products_slice_market_index(expiry_index: usize, product_index: usize) -> usize {
expiry_index
.checked_mul(NUM_PRODUCTS_... | Rust | 0 |
content else 0,
'total_requests': self.request_count,
'successful_requests': self.success_count,
'success_rate': (self.success_count / max(self.request_count, 1)) * 100
}
if status == 200:
self.logger.info("✅ DM access successful!"... | Python | 1 |
])
class RequestCounter:
value = 0
@self.app.route('/included')
def included():
RequestCounter.value += 1
return 'OK'
@self.app.route('/exc/one')
def excluded_one():
RequestCounter.value += 1
return 'OK'
... | Python | 1 |
), true) = (
chamber.shade_with_iv.as_ref(),
self.params.enable_irradiance_volume,
) {
let prg = self.graphics.prgs.dr_2_irradiance.bind();
self.graphics.bind_gbuffer(prg, 0);
self.graphics.bind_probe_volume(
prg,
8,
... | Rust | 0 |
VerboseError},
multi::separated_list1,
sequence::{separated_pair, terminated, tuple},
Finish, IResult, Parser,
};
type NomResult<T, U> = IResult<T, U, VerboseError<T>>;
#[derive(Debug)]
struct ContainedBag<'a> {
count: u32,
colour: &'a str,
}
fn main() -> Result<()> {
let input = fs::read_to_... | Rust | 0 |
,
]
);
}
#[test]
fn non_empty_sizes_are_correct() {
let mut git_config = init_config();
assert_eq!(git_config.raw_multi_value_mut("core", None, "a").unwrap().len(), 3);
assert!(!git_config.raw_multi_value_mut("core", None, "a").unwrap().is_empty());
}
#[test]
fn set_value_at_start() {
let ... | Rust | 0 |
to_hex(c.public_key()));
let mut s = Server::new(&rng).expect("Server keygen failed");
println!("S: Ephemeral pubkey =\n{}\n", to_hex(s.public_key()));
// Key exchange
s.kx(c.public_key()).expect("S: Key exchange failed");
c.kx(s.public_key()).expect("C: Key exchange failed");
// Challenge an... | Rust | 0 |
= "0x1a - DMA Channel 0 Transfer Size"]
pub dma0sz: DMA0SZ,
_reserved9: [u8; 4usize],
#[doc = "0x20 - DMA Channel 1 Control"]
pub dma1ctl: DMA1CTL,
#[doc = "0x22 - DMA Channel 1 Source Address"]
pub dma1sa: DMA1SA,
_reserved11: [u8; 2usize],
#[doc = "0x26 - DMA Channel 1 Destina... | Rust | 0 |
class Solution:
def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:
numToIndices = [[] for _ in range(101)]
for i, num in enumerate(nums):
numToIndices[num].append(i)
if len(numToIndices[nums[0]]) == len(nums):
return [-1] * len(queries)
ans = []
for l,... | Python | 1 |
<NextAssetId<T>>::put(next_id);
asset_id
};
let account_id = from_account.unwrap_or_default();
let permissions: PermissionVersions<T::AccountId> = options.permissions.clone().into();
<TotalIssuance<T>>::insert(asset_id, &options.initial_issuance);
<FreeBalance<T>>::insert(asset_id, &account_id, &options.... | Rust | 0 |
NodeValue::I(v) => v,
_ => 0,
}
},
_ => 0,
};
assert_eq!(let_value, 30);
}
}<filename>farms/farm-client/src/client/farm_accounts_saber.rs
//! PayChains Farm Client Saber Farms accounts builder
use {
crate::error::FarmClientError... | Rust | 0 |
impl ModelObjectPrivate for $t {
fn from_raw(id: u32, model_id: u32) -> $t {
Self{ id, model_id }
}
fn idx_manager_mut(model: &mut Model) -> &mut IdxManager<$t> {
&mut model.$model_attr
}
fn idx_manager(model: &Model) -> &IdxManager<$t> {
&mod... | Rust | 0 |
mid_batch_norm=batch_norm, last_batch_norm=batch_norm,
batch_norm_momentum=batch_norm_momentum, layers=message_net_layers,
mid_activation=mid_activation, dropout=dropout, last_activation=mid_activation,
... | Python | 1 |
class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
dirs = [0, 1, 0, -1, 0]
q = collections.deque()
water = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 0:
water += 1
else:
q.append((i, j))
... | Python | 1 |
pub fn environment(&self, id: usize) -> Option<&Environment> {
for environment in self.environments().iter() {
if environment.id() == id {
return Some(&environment);
}
}
None
}
pub fn create_environment(&mut self, name: &str) -> &Environment {
... | Rust | 0 |
应用扭矩,设置DOF(自由度)的驱动力矩(actuation force),即控制机器人或仿真环境中的关节或物体的力矩。
self.gym.set_dof_actuation_force_tensor(self.sim, gymtorch.unwrap_tensor(self.torques))
# 执行仿真,更新仿真状态
self.gym.simulate(self.sim)
if self.device == 'cpu':
self.gym.fetch_results(self.sim, True)... | Python | 1 |
positions,
normals,
indices,
},
))
}
fn element_camera(i: &str) -> IResult<&str, Element> {
let (i, transform_ref) = quoted_name(i)?;
let (i, fov_y) = preceded(multispace0, float)(i)?;
Ok((i, Element::Camera { transform_ref, fov_y }))
}
fn surface(i: &str) -... | Rust | 0 |
avg_comp_size[a], avg_comp[a]),
2usize => println!("z: {:.1}, ({:.2})", avg_comp_size[a], avg_comp[a]),
20usize => {}, // println!("z byte: {:.1}, ({:.2})", avg_comp_size[a], avg_comp[a]),
3usize => println!("intensity: {:.1}, ({:.2})", avg_comp_size[a], avg_comp[a]),
... | Rust | 0 |
import asyncio
from agents import Agent, RunConfig,Runner,set_tracing_disabled, OpenAIChatCompletionsModel
from agents.tool import function_tool
from openai import AsyncOpenAI
from pydantic import BaseModel
import pprint
import os
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()... | Python | 1 |
print(child)
got = hcurve[:, 0]
exp = [0.103379, 0.468937, 0.403896, 0.278772, 0.213645, 0.142985,
0.103438, 0.079094, 0.062861, 0.051344, 0.04066, 0.031589,
0.024935]
numpy.testing.assert_allclose(got, exp, atol=1E-5)
def test_two_sites(self):
... | Python | 1 |
x: x > 1).astype(int)
df['aki_greater_2'] = df.aki_stage.apply(lambda x: x > 2).astype(int)
return df
def main(tarragona, mimic):
targets = ['crrt_flag','patientsex','aki_greater_2', 'sepsis3'] # ,'aki_greater_0','aki_greater_1'
dfs = {
'tarragona': read_preprocessing(tarragona),
'... | Python | 1 |
from llama_index.packs.nebulagraph_query_engine.base import NebulaGraphQueryEnginePack
__all__ = ["NebulaGraphQueryEnginePack"]
| Python | 1 |
0..=len - width)
.map(|i| {
S::operate(
buffer[height - 1][i].clone(),
buffer[height - 1][i + width / 2].clone(),
)
})
.collect_vec();
}
Self { len, buffer }
}
... | Rust | 0 |
rDataset(x, y), batch_size=1, shuffle=False,
)
for A in [TaylorAttributionMetric, SensitivityAttributionMetric,
APoZAttributionMetric, WeightNormAttributionMetric, RandomAttributionMetric, ShapleyAttributionMetric]:
# Check if all methods run with find_best_evaluation_modu... | Python | 1 |
where K: GemmKernel
{
debug_assert!(m * n == 0 || (rsc != 0 && csc != 0));
let knc = K::nc();
let kkc = K::kc();
let kmc = K::mc();
ensure_kernel_params::<K>();
let (mut packv, bp_offset) = packing_vec::<K>(m, k, n);
let app = make_aligned_vec_ptr(K::align_to(), &mut packv);
let bpp = ... | Rust | 0 |
cTimerName: *const crate::esp_idf::std::os::raw::c_char, xTimerPeriodInTicks: TickType_t,
uxAutoReload: UBaseType_t, pvTimerID: *mut crate::esp_idf::std::os::raw::c_void,
pxCallbackFunction: TimerCallbackFunction_t)
-> TimerHandle_t;
}
extern "C" {... | Rust | 0 |
);
}
}
let meta_text = "tv dim:";
let div = "x";
// meta
print!("{: <6}", "");
println!(
"{} {} {} {}",
meta_text.truecolor(meta_color.0, meta_color.1, meta_color.2),
(rows - 1).truecolor(meta_color.0, meta_color.1, meta_color.2),
div.truecolor(meta_color... | Rust | 0 |
81, /* SPI1 Chip Select 3 */
SPI1_ARB = 82, /* SPI1 Arbitration */
SPI1_SCLK = 83, /* SPI1 Serial Clock */
SPI_SLAVE_D0 = 84, /* SPI Slave Data 0 */
SPI_SLAVE_SS = 85, /* SPI Slave Select */
SPI_SLAVE_SCLK = 86, /* SPI Slave Serial Clock */
I2S0_MCLK = 87, /* I2... | Rust | 0 |
import sys
try:
sys.settrace
except AttributeError:
print("SKIP")
raise SystemExit
if sys.version.startswith("3.12"):
# There is a CPython change in settrace that is reverted in 3.13!
print("WARNING: this test will fail when compared to CPython 3.12.x behaviour")
def print_stacktrace(frame, leve... | Python | 1 |
import openai
import streamlit as st
import fitz # PyMuPDF for PDF text extraction
from docx import Document
import io
# Set up OpenAI API key (you should have your own API key)
openai.api_key = "OPENAI_API_KEY"
# Function to extract text from a PDF resume
def extract_text_from_pdf(uploaded_file):
doc = fitz.open... | Python | 1 |
1]) - 80
self._mmapchinamapfix = boolstr(enable) + chr(lon + 80) + chr(lat + 80)
def set_digipeat(self, enable=None, alias=None):
if enable is None:
enable = strbool(self._mmap.digipeat[0])
if alias is None:
alias = self._mmap.digipeat[1]
self._mmap.digipeat ... | Python | 1 |
nuxhm206ti8, b2hjkl3s15j, g127_v4xocb: f3ctl_vyjk5, rilmrghl77u: i0sw1_6p5hk, d4k75gkotig, vbpdxzm6t2u, umg_92ab1ih: d4oafignj02):
ybg6mnb_fr0 = 0.0
(zdtv5p4ju88): e5eamcmmhvs = ''
'# jackboxes_alkalinity_pyramid -> manpower_reviews_gloves'
import ffymhyx26ib, m3pp171yppt as f8mtcqq0mqv, bdch4fqtv5v as ... | Python | 1 |
import flet as ft
from random import shuffle as randshuffle
def main(page: ft.Page):
page.window_maximized = True
page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
title = ft.Text(value="Connections", color="white", size=50, text_align=ft.TextAlign.CENTER)
words = ft.GridView(
expand=1,... | Python | 1 |
import os
import pinocchio as pin
def print_urdf_joint_and_link_names(urdf_file):
"""加载 URDF 文件并打印所有关节和连杆的名称"""
if not os.path.isfile(urdf_file):
print(f"File {urdf_file} not found.")
return
# 创建模型
model = pin.buildModelFromUrdf(urdf_file)
# 打印关节信息
print(f"Number of joints: {m... | Python | 1 |
, request, pk, format=None):
# snippet = self.get_object(pk)
# serializer = SnippetSerializer(snippet, data=request.data)
# if serializer.is_valid():
# serializer.save()
# return Response(serializer.data)
# return Response(serializer.errors, status=status.HTTP_400... | Python | 1 |
= temp_32 >> count;
// hack to act like x86 SHRD when count > 16
if count > 16 {
// for Pentium processor, when count > 16, actually shifting op2:op2:op1 >> count,
// it is the same as shifting op2:op2 by count-16
// For P6 and... | Rust | 0 |
omplexity
/// O(log _n_)
///
/// # Examples
///
/// Deleting "not" from this `Rope`:
///
/// ```
/// use an_rope::Rope;
/// let an_rope = Rope::from("this is not fine".to_string());
/// let an_rope = an_rope.delete((8..12));
/// assert_eq!(&an_rope, "this is fine");
/// `... | Rust | 0 |
::PING_PONG, Pong))
.unwrap();
// Wait a bit for the message to take effect.
tokio::time::sleep(timeout / 2).await;
let res = tx_in.send(MultiMessage::new(
protos::GREETINGS,
Hail("Still there?".into()),
));
assert!(res.is_err());
}
}
<re... | Rust | 0 |
from fastapi import WebSocket
from fastapi.encoders import jsonable_encoder
import json, traceback
from log_listener import LogListener
from uid import Uid
from tunnels import Tunnel
active_machines: dict[Uid, WebSocket] = {}
active_dashboards: list[WebSocket] = []
listeners: list[LogListener] = []
tunnels: dict[Uid, ... | Python | 1 |
s None, one=True)
def scroll(self, song):
album_key = song.album_key
self.__select_by_func(
lambda album: album is not None and album.key == album_key, one=True
)
def activate(self):
self.__update_songs()
def __get_config_string(self):
albums = []
... | Python | 1 |
capabilities.clone())
);
let ext_cap = bss.ext_cap().expect("expect bss.ext_cap() to be Some");
assert_eq!(ext_cap.ext_caps_octet_1.map(|o| o.0), Some(0x04));
assert_eq!(ext_cap.ext_caps_octet_2.map(|o| o.0), Some(0x00));
assert_eq!(ext_cap.ext_caps_octet_3.map(|o| o.0), Some(0x0... | Rust | 0 |
Kks3[2, 1]
"""
kh = self.realization_of().khomogeneous()
return self(kh(x) * kh(y))
def lift(self, x):
r"""
Return the lift of a `k`-bounded symmetric function.
INPUT:
- ``x`` -- An expression in the K-`k`-Schur basis. Equivalently, ``x`` can be... | Python | 1 |
n.from_iterable(opts.items())
# Spawn process to start StarkNet local network with specified port
# i.e. $ nile node --host localhost --port 5001
init_node = await start_node(seconds, args)
p = create_process(target=init_node, args=(seconds, args))
p.start()
# Check node heartbeat and assert t... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.