text string | label_name string | labels int64 |
|---|---|---|
'''
533. Lonely Pixel II
URL := https://leetcode.com/problems/lonely-pixel-ii/description/
The inputs to this problem are sufficiently tiny
Leverage hashmaps
Decompose into two steps
(A) Get each row with a column having `target` black pixels ( need not be consecutive )
(B) For each row meeting cond A, map to unique ... | Python | 1 |
/ get min value from previous list
let min_inf_delta = diff_inf.iter().min_by(|a,b| a.partial_cmp(b).unwrap()).unwrap();
// select the cluster or clusters that achieve this value
let mut cluster_candidates:Vec<usize> = Vec::new();
for (id, cluster_score) in diff_inf.iter().enumerate(){... | Rust | 0 |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | Python | 1 |
}
};
},
LValueExpr::LocalVariableAssign(name) => {
let o_idx = local_var_map.get(name);
match o_idx {
None => { errors.push(Error::VariableNotRecognized(l_value.loc.clone(), name.clone())); },
Some(idx) => {
... | Rust | 0 |
by the network. Obviously you might have a completely different view on things.
#[serde(rename = "imei", skip_serializing_if = "Option::is_none")]
pub imei: Option<String>,
/// Tags are metadata for the device that you can set. These are just strings.
#[serde(rename = "tags", skip_serializing_if = "Opti... | Rust | 0 |
user may have changed their preference.
notification_recipient.messageid_sms = 'cancelled'
return
try:
message = view.sms_with_unsubscribe()
except NotImplementedError:
notification_recipient.messageid_sms = 'not-implemented'
return
notification_recipient.messageid_s... | Python | 1 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Description:
@Author: chenkeming
@Date: 2024-02-10 15:46:54
"""
from torchvision import transforms
# 视频训练集的数据增强,包括转换为张量和归一化
video_train = transforms.Compose(
[
transforms.ToTensor(), # 会将通道维度放在第一个维度
transforms.Normalize((0.3729, 0.2850, 0.2439), ... | Python | 1 |
</svg>
}
}
}
<filename>src/file.rs
use std::fs;
/// Try get pages file under a root path,
/// which enable approach to different pages easier.
pub fn try_under_root(root_path: &str, file_path: &str) -> Option<String> {
match fs::read_to_string(root_path.to_owned() + file_path) {
... | Rust | 0 |
length randomly using Binomial
// /// distribution with n - number of trials and p - probability of success
// #[wasm_bindgen(js_name = "newWithRandomBinomial")]
// pub fn new_with_random_binomial(row: usize, col: usize, n: u64, p: u64) -> IntegersMatrix {
// IntegersMatrix {
// ... | Rust | 0 |
if index == 0 {
links.insert((ad_id, campaign_id));
}
}
}
links.close();
let seed_worker: &[_] = &[1, 2, 3, index];
let mut rng_worker: StdRng = SeedableRng::from_seed(seed_worker);
let mut typed_things = Vec::new();
for _... | Rust | 0 |
ch item is padded to be a multiple of 8 bytes.
pub const ZBI_ALIGNMENT_BYTES: u32 = 0x8;
pub fn is_zbi_type_driver_metadata(zbi_type_raw: u32) -> bool {
(zbi_type_raw & 0xFF) == ZbiType::DriverMetadata as u32
}
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// Defines the types supported by the ... | Rust | 0 |
Ok(1);
/// let err_two: Result<usize, usize> = Err(2);
///
/// assert_eq!(beta(app!(unwrap_or(), 3.into_church(), ok_one.into_church()), NOR, 0), 1.into_church());
/// assert_eq!(beta(app!(unwrap_or(), 3.into_church(), err_two.into_church()), NOR, 0), 3.into_church());
/// ```
pub fn unwrap_or() -> Term {
abs!(2, ... | Rust | 0 |
y_loss(logits)
with self.profile("backward pass"):
self.fabric.backward(loss, retain_graph=True)
with self.profile("optimizer step"):
optimizer.step()
optimizer.zero_grad()
with self.profile("merging weights"):
... | Python | 1 |
void;
// Safe because we allocated fdt and converted name to a CString
let fdt_ret = unsafe {
fdt_property(
fdt.as_mut_ptr() as *mut c_void,
cstr_name.as_ptr(),
val_ptr,
val.len() as i32,
)
};
if fdt_ret != 0 {
return Err(Error::Fd... | Rust | 0 |
batch_size, n_heads, seq_len, scale,
DK=d_head_qk, DV=d_head_v, BK=BK, BV=BV,
num_warps=num_warps,
num_stages=num_stages,
USE_INITIAL_STATE=initial_state is not None
)
dq = dq.sum(0)
dk = dk.sum(0)
dv = dv.sum(0)
return dq, d... | Python | 1 |
words = MEDIUM_NODE_SIZE as u8
}
TxtNode::MarginKern(_) => {
r = get_node(MARGIN_KERN_NODE_SIZE);
words = MARGIN_KERN_NODE_SIZE as u8
}
TxtNode::Ligature(p) => {
r = get_node(SM... | Rust | 0 |
"""
Solution for "Binary Tree Zigzag Level Order Traversal" (Leetcode 103)
We need to traverse a binary tree level by level, but:
Odd levels (1st, 3rd, etc.) should be traversed left to right.
Even levels (2nd, 4th, etc.) should be traversed right to left.
Approach: BFS (Queue)
We will use Breadth-First Search (BFS) ... | Python | 1 |
= list()
for column in range(1, self.mTableClasses.columnCount()):
inames = list()
for row in range(self.mTableClasses.rowCount()):
size = self.relativeClassSizes[column - 1][row]
w: QTableWidgetItem = self.mTableClasses.item(row, column)
i... | Python | 1 |
= i + 1;
}
}
}
} else {
message = format!("{} subgoal(s) remaining:\n", fg.len());
let mut line = 3usize;
for goal in fg.into_iter() {
let (txt, mut cols, i) = goal_to_string(goal, line);
messag... | Rust | 0 |
from django.db import models
from django.contrib.auth.models import User
from django.forms import ValidationError
import re
from utils.validacpf import valida_cpf
class Perfil(models.Model):
class Meta:
verbose_name = 'Perfil'
verbose_name_plural = 'Perfis'
usuario = (models.OneToOneField(Use... | Python | 1 |
parts = token_data.split(':')
if len(parts) != 4:
return False
token_user_id, secret, timestamp, signature = parts
# 檢查使用者 ID
if token_user_id != user_id:
... | Python | 1 |
import os, sys, telebot
# 上传文件
def upload_file(tb, chat_id, file_dir):
doc = open(file_dir, 'rb')
tb.send_document(chat_id, doc)
# 上传文件夹内的文件
def upload_folder(tb, chat_id, folder_dir):
file_list = sorted(os.listdir(folder_dir))
for file in file_list:
path = os.path.join(folder_dir, file)
... | Python | 1 |
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Literal
class FileRepository(ABC):
@abstractmethod
async def add(self, name: str, size: int, updated_at: datetime, x: float, y: float) -> None:
raise NotImplementedError
@abstractmethod
async def update(self,... | Python | 1 |
let child_size = child.layout(child_id, proposed_child_size, cx, vger);
cx.layout.entry(child_id).or_default().offset =
[width_sum, (sz.height - child_size.height) / 2.0].into();
width_sum += child_size.width;
c += 1;
... | Rust | 0 |
# pma.py Scenarios
# 20 states, 16 transitions, 4 accepting states, 0 unsafe states, 4 finished and 0 deadend states
# actions here are just labels, but must be symbols with __name__ attribute
def Push(): pass
def Pop(): pass
# states, key of each state here is its number in graph etc. below
states = {
0 : {'Sce... | Python | 1 |
s::{create_dir, File};
use std::io::Read;
use std::{thread, time};
// When to give up on polling for a change and fail the test. DNS if less than 120 sec.
static GIVE_UP_POLLING_SECS: i64 = 120;
// The metadata contains a timestamp that needs to be zeroed for exact comparison.
static METADATA_KEY: &str = "metadata";
... | Rust | 0 |
, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}",
match self {
MetaCommunity::Community(c) => {c.to_string()}
MetaCommunity::ExtendedCommunity(c) => {c.to_string()}
MetaCommunity::LargeCommunity(c) => {c.to_string()}
}
... | Rust | 0 |
tput from template and uses the
`Handlebars Templating Language <http://handlebarsjs.com/>`_ for Python
via the ``pybars`` library. Please see the developer documentation on
:ref:`Output Handling <dev_output_handling>`.
**Note** This extension has an external dependency on ``pybars3``. You
must i... | Python | 1 |
import dash_cytoscape as cyto # <<< 1. استيراد المكتبة هنا
from app import app, server
from layout import layout
import callbacks
import app2
# <<< 2. إضافة السطر المهم لتحميل الإضافات
cyto.load_extra_layouts()
# تعيين الواجهة للتطبيق
app.layout = layout
# نقطة تشغيل التطبيق
if __name__ == '__main__':
app.run(de... | Python | 1 |
from airflow import DAG
from airflow.models import Variable
from airflow.providers.amazon.aws.operators.emr import EmrAddStepsOperator
from datetime import datetime
dag = DAG(
'submit_pyspark_streaming_job_to_emr',
start_date=datetime(2021, 1, 1),
catchup=False,
tags=['streaming'],
)
spark_packages ... | Python | 1 |
"""Test tablet responsive design workflow."""
page.set_default_timeout(10000)
# Set tablet viewport
page.set_viewport_size({"width": 768, "height": 1024})
mock_login(page, live_server)
# Test tablet functionality
posts_tab = page.locator('[data-tab="Posts"]')
expect(posts_tab).to_be_vis... | Python | 1 |
# -------------------------------------------------------------
#
# 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 unde... | Python | 1 |
stopped_in_range {
let mut step = target_step[0];
while step * y - step * (step - 1) / 2 >= YMIN {
let target_y = step * y - step * (step - 1) / 2;
if (target_y >= YMIN) && (target_y <= YMAX) {
touched = true;
... | Rust | 0 |
", "help", "Print this help menu");
// Parse options
let matches = unwrap_or_barf(opts.parse(&options), "Could not parse options");
// Print help message if we have to
if matches.opt_present("h") {
help(&prog_name, opts);
}
// Get start and end samples
let start_sample = matches
... | Rust | 0 |
let fake_block = bincode::deserialize::<FakeBlock>(&bytes1).unwrap();
let bytes2 = bincode::serialize(&fake_block).unwrap();
assert_eq!(bytes1, bytes2);
}
#[test]
fn test_fake_block() {
use std::convert::TryFrom;
let block = Block::new(
CryptoHashOf::from(CryptoHash(Vec::new())),
Pa... | Rust | 0 |
MutableBatch> {
self.tables.get(name)
}
/// Returns the number of tables within this write
pub fn table_count(&self) -> usize {
self.tables.len()
}
/// Returns the minimum timestamp in the write
pub fn min_timestamp(&self) -> i64 {
self.min_timestamp
}
/// Retu... | Rust | 0 |
from collections import Counter
true_list = ['T','R','U','E']
love_list = ['L','O','V','E']
heart_list = [true_list,love_list]
def LoveCalculator_v2(first_name, last_name):
love_numbers = []
first_name = first_name.upper()
last_name = last_name.upper()
name = first_name + last_name
print(na... | Python | 1 |
# model_utils.py
# Description: A brief description of what this file does.
# Author: Joshua Stiller
# Date: 15.11.24
import numpy as np
import torch
def split_array(array: np.ndarray | torch.Tensor, shape: tuple) -> np.ndarray | torch.Tensor:
"""
Splits an array into chunks of the specified shape, and stacks... | Python | 1 |
# -*- coding: utf-8 -*-
__author__ = "Marten4n6"
__license__ = "GPLv3"
from AppKit import NSPasteboard, NSStringPboardType
from time import time, sleep
from datetime import datetime
def run(options):
elapsed_time = 0
monitor_time = int(options["monitor_time"])
output_file = options["output_file"]
pr... | Python | 1 |
pub fn check(&self, old: &bool) -> Result<bool, Box<dyn Error>> {
let cache_file = self.cache_dir.join("cache");
let is_exist_cache = cache_file.exists();
let _hash = hash(&mut File::open(self.path)?, false)?;
let cache_file_path = self.cache_dir.join("cache_file");
let mut ... | Rust | 0 |
///
/// let m = c.module("MyModule");
///
/// let my_input = m.input("my_input", 80);
/// ```
pub fn input<S: Into<String>>(&'a self, name: S, bit_width: u32) -> &Signal<'a> {
let name = name.into();
// TODO: Error if name already exists in this context
if bit_width < MIN_S... | Rust | 0 |
(sheet_name, [inject_root_id(root_id, line) for line in lines])
for sheet_name, lines in input_dict.items()
]
),
**extra_kwargs
)
spreadsheet_input.read_sheets()
parser = SchemaParser(
root_schema_dict=create_schema(root_id) if use_schema else ... | Python | 1 |
import json
import logging
from datetime import datetime
from typing import Any, Optional
class AICouncilLogger:
"""Singleton logger for AI Council using standard Python logging."""
_instance = None
_initialized = False
def __new__(cls):
if cls._instance is None:
cls._ins... | Python | 1 |
:Xc @ s d Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d Z d Z e j
e d Z e j
d Z
d Z d Z d Z d
Z d Z d Z d
Z d Z d Z d Z d Z d S( sT
Tests for the bdist_wheel tag options (--python-tag, --universal, ... | Python | 1 |
# encoding: utf-8
from datetime import datetime
from utils.oracle_base import query_one
from utils.linux_base import LinuxBase
from utils.tools import mysql_exec,mysql_query,now
from utils.oracle_base import get_connection
parse_result = []
OracleKeyWordList=['ORA-','WARNING:','Starting ORACLE instance','Shutting dow... | Python | 1 |
&JsValue::from(val),
);
debug_assert!(
r.is_ok(),
"setting properties should never fail on our dictionary objects"
);
let _ = r;
self
}
}
<filename>src/world/map.rs
use bevy::{math::IVec2, prelude::Component};
use std::collections::HashMap;
use rltk:... | Rust | 0 |
from pynwb.ogen import OptogeneticSeries, OptogeneticStimulusSite
from pynwb.device import Device
from pynwb.testing import NWBH5IOMixin, AcquisitionH5IOMixin, TestCase
class TestOptogeneticStimulusSiteIO(NWBH5IOMixin, TestCase):
def setUpContainer(self):
""" Return the test OptogeneticStimulusSite to re... | Python | 1 |
torch.Tensor | None = None,
waves: torch.Tensor | None = None,
gsd: float | None = None,
) -> dict[str, torch.Tensor | float]:
datacube: dict[str, torch.Tensor | float] = {}
datacube["pixels"] = x
datacube["time"] = torch.zeros((x.shape[0], 4), device=x.device) if time is Non... | Python | 1 |
ut, x, y);
horiz.extend(points_right(input, x, y, width));
points.extend(horiz.iter());
for (x, y) in horiz {
let mut vert = points_up(input, x, y);
vert.extend(points_down(input, x, y, height));
for (x, y) in vert {
points.extend(points_left(input, x, y).iter());
... | Rust | 0 |
``fn unicode_text_to_u_t_f8((&::unicodetext::i18n::phonenumbers::UnicodeText, cpp_utils::AsBox)) -> cpp_utils::CppBox<::basic_string::std::cxx11::BasicStringCCharCharTraitsCCharRefAllocatorCCharRef>```<br>2) ```fn unicode_text_to_u_t_f8((&::unicodetext::i18n::phonenumbers::UnicodeText, cpp_utils::AsStruct)) -> ::basic_... | Rust | 0 |
from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth import get_user_model
class TestViews(TestCase):
def setUp(self):
self.client = Client()
self.user = get_user_model().objects.create_user(
username='testuser',
email='test@examp... | Python | 1 |
embed.add_field(name="ℹ️ Note", value=f"Using custom tax rate: {config[5]}x", inline=False)
embed.set_footer(text=f"Requested by {message.author.display_name}", icon_url=message.author.display_avatar.url)
await message.channel.send(embed=embed)
if config[2]:
... | Python | 1 |
put is None:
inputs_embeds = None
else:
inputs_embeds = self.get_input_embeddings_v0(
input_ids,
image_input=image_input,
video_input=video_input)
input_ids = None
hidden_states = self.langua... | Python | 1 |
"""
This is the implementation of HiddenMarkov,
which is accessible in https://github.com/FlameCharmander/MachineLearning,
accomplished by FlameCharmander,
and my csdn blog is https://blog.csdn.net/tudaodiaozhale,
contact me via 13030880@qq.com.
"""
#--*-- coding:utf-8
import numpy as np
class HiddenMarkov:
def fo... | Python | 1 |
True) as prof:
# with record_function("model_inference"):
# model(input_data['ego'])
# print("GPU time sorted operators:")
# print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=10))
# print("CPU time sorted operators:")
# ... | Python | 1 |
value):
ids_to_check = set(value) - set(self.user.openid_logins)
in_use = check_used_openids(ids_to_check, self.user)
if in_use:
count = len(in_use)
message = ngettext(u'The following %(count)d URL is already '
u'associated to a different u... | Python | 1 |
from cassandra.cqlengine import columns
from cassandra.cqlengine.models import Model
class PushTokens(Model):
__table_name__ = 'push_tokens'
username = columns.Text(partition_key=True)
domain = columns.Text(partition_key=True)
device_id = columns.Text(primary_key=True)
... | Python | 1 |
... | Python | 1 |
#!/usr/bin/env python
# Capstone Python bindings, by Nguyen Anh Quynnh <aquynh@gmail.com>
from __future__ import print_function
from capstone import *
from capstone.arm64 import *
from xprint import to_hex, to_x
ARM64_CODE = b"\x09\x00\x38\xd5\xbf\x40\x00\xd5\x0c\x05\x13\xd5\x20\x50\x02\x0e\x20\xe4\x3d\x0f\x00\x18\... | Python | 1 |
"""
[Problem]
https://leetcode.com/problems/valid-palindrome/description/
모든 대문자를 소문자로 변환하고 알파벳과 숫자가 아닌 문자들을 전부 제거한 이후에 앞에서 부터 읽으나 뒤에서 부터 읽으나 동일하게 읽힌다면, 그 문장은 회문입니다.
영숫자 문자들은 알파벳과 숫자들을 포함합니다.
[Brainstorming]
leftPosition과 rightPosition을 두고, 비교하면서 아닐 경우 false를 return한다. => O(s.length)
[Complexity]
N: s.length
Time: O... | Python | 1 |
"""
This test verifies that HTTPX request spans include request and response details:
'http.request.method' in span.attributes
'http.request.url' in span.attributes
'http.request.body' in span.attributes
'http.response.status_code' in span.attributes
'http.response.body' in span.attributes
"""
impo... | Python | 1 |
neckAx2 = gp_Ax2(neckLocation, neckAxis)
myNeckRadius = thickness / 4.0
myNeckHeight = height / 10.0
mkCylinder = BRepPrimAPI_MakeCylinder(neckAx2, myNeckRadius, myNeckHeight)
myBody_step2 = BRepAlgoAPI_Fuse(mkFillet.Shape(), mkCylinder.Shape())
# Our goal is to find the highest Z face and remove it
zMax = -1.0
# ... | Python | 1 |
NotFoundError as e:
db.rollback()
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
except Exception as e:
db.rollback()
logger.exception(f"Failed to update team member: {e}")
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detai... | Python | 1 |
# -*- coding: utf-8 -*-
from numpy import isnan
from pandas import DataFrame, Series
from atklip.controls.pandas_ta._typing import DictLike, Int, IntFloat
from atklip.controls.pandas_ta.ma import ma
from atklip.controls.pandas_ta.maps import Imports
from atklip.controls.pandas_ta.utils import (
tal_ma,
v_mamode... | Python | 1 |
count += 1;
state.total_deposit += deposit_amount;
let mut data_list: Vec<ExecuteData> = vec![];
let all_execute_data = if let Some(exec_msgs) = execute_msgs {
for msgs in exec_msgs {
let execute_data = ExecuteData {
order: msgs.order,
contract: deps.api.... | Rust | 0 |
def count_ways_to_construct(design, towel_patterns):
# Sort towel patterns by length in descending order to prioritize longer matches
sorted_patterns = sorted(towel_patterns, key=len, reverse=True)
# Create a DP array where dp[i] is the number of ways to construct the first i characters of the design
... | Python | 1 |
# -*- coding: utf-8 -*-
"""
author: Eastmount CSDN 2020-11-15
"""
import os
#评价指标 参数顺序
def classification_pj(pre, y_test):
# 正确率 Precision = 正确识别的个体总数 /识别出的个体总数
# 召回率 Recall = 正确识别的个体总数 / 测试集中存在的个体总数
# F值 F-measure = 正确率 * 召回率 * 2 / (正确率 + 召回率)
YC_A, YC_B = 0,0 #预测 bad good
ZQ_A, ZQ_B = 0,0 ... | Python | 1 |
# Copyright 2025 Snowflake Inc.
# SPDX-License-Identifier: Apache-2.0
#
# 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 app... | Python | 1 |
n=2)
plt.figure()
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=self.env.attack_types, normalize=True,
title='Normalized confusion matrix')
plt.savefig('results/confusion_matrix_A3C_{}.svg'.format(self.counter), format='svg', dpi=1000)
... | Python | 1 |
1.4929078, 1.4969554, 1.5010141, 1.5050838, 1.5091645, 1.5132562,
1.517359, 1.5214729, 1.5255982, 1.5297345, 1.533882, 1.5380408, 1.5422108, 1.5463922, 1.5505849,
1.554789, 1.5590044, 1.5632313, 1.5674696, 1.5717194, 1.5759809, 1.5802537, 1.5845382, 1.5888345,
1.5931423, 1.5974616, 1.6017927, 1... | Rust | 0 |
: &'a f64,
eth_price: &'a f64,
coingecko_link: &'a str,
) -> TokenInfo {
TokenInfo {
contract_address: contract_address.to_string(),
balance: *balance,
usd_price: *usd_price,
eth_price: *eth_price,
usd_balance: balance * usd_price,
... | Rust | 0 |
]
fn one_row() {
let pt = PascalsTriangle::new(1);
let expected: Vec<Vec<u32>> = vec![vec![1]];
assert_eq!(expected, pt.rows());
}
#[test]
#[ignore]
fn two_rows() {
let pt = PascalsTriangle::new(2);
let expected: Vec<Vec<u32>> = vec![vec![1], vec![1, 1]];
assert_eq!(expected, pt.rows());
}
#[t... | Rust | 0 |
*mut *mut u8, pcbpropertylistsize: *mut u32) -> u32;
#[doc = "*Required features: `\"Win32_Networking_Clustering\"`, `\"Win32_System_Registry\"`*"]
#[cfg(feature = "Win32_System_Registry")]
pub fn ResUtilGetPrivateProperties(hkeyclusterkey: super::super::System::Registry::HKEY, poutpropertylist: *mut ::cor... | Rust | 0 |
{
panic!("socket creation should have failed");
}
}
}
}
<reponame>interchainio/tendermint-rs<gh_stars>10-100
//! CanonicalProposal
use core::convert::{TryFrom, TryInto};
use tendermint_proto::{types::CanonicalProposal as RawCanonicalProposal, Protobuf};
use super::Type;
use c... | Rust | 0 |
#
# (C) Copyright Cloudlab URV 2021
#
# 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 in wr... | Python | 1 |
fetch(&id).await?;
tokio::task::spawn_blocking(move || {
database::get_global_connection().and_then(|conn| {
conn.execute_named(
include_str!("sql/youtube/add_video.sql"),
&[
(":vid", &id),
(":ts... | Rust | 0 |
let _ = c.print_info();
let zero = TenBitExpFP::zero();
let six = TenBitExpFP::from(6.0);
for i in 0..10000 {
let (_, n1) = generate_random_number(&mut rng);
let (s1, s2) = n1.share(&mut rng);
let res_should_be_fp = if n1 <= zero {
ze... | Rust | 0 |
# Copyright 2019 The Dreamer 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 applicabl... | Python | 1 |
#this file is the riddle of the pere fouras
import random
import json
import time
def load_riddles(file): #this loads the json file with the clues and riddles and it puts those in a dicctionary for us to use later
with open(file, "r") as f:
riddles = json.load(f)
return riddles
def pere_fouras_gate... | Python | 1 |
/// Position of light in world coordinates.
pub position: Vector3<f32>,
/// Distance at which light intensity decays to zero.
pub distance: f32,
/// Smoothstep left bound. It is ((hotspot_cone_angle + falloff_angle_delta) * 0.5).cos()
pub edge0: f32,
/// Smoothstep right bound. It is (hotspo... | Rust | 0 |
OsmNode,
Model,
};
use ::web_sys::{Element, HtmlAnchorElement};
use gloo_events::EventListener;
use js_sys::{Array, Function};
use leaflet::{
Circle, Control, LatLng, LatLngBounds, LayerGroup, Map, Marker, Polyline, Rectangle, TileLayer,
};
use seed::{prelude::*, window};
use serde::{Deserialize, Serialize};
#... | Rust | 0 |
Get the next handle. Since we don't recycle handles until all of
// them have been returned, there is a pathological case where a user
// may make a Very Large (usize::MAX) number of valid borrows and
// unborrows while always keeping at least one borrow outstanding, and
// we will run ... | Rust | 0 |
for immediate value at this time for eager immediate tagged messages");
let status = unsafe { (self.transport_interface_operations().ep_tag_eager_short)(self.ep(), self.tag_value.0, from_local_memory.as_ptr() as *const c_void, from_local_memory.len()) };
use self::Status::*;
match status.parse()
{
... | Rust | 0 |
, U10, Exp>;
pub type IFix64<Exp> = Fix<i64, U10, Exp>;
pub type IFixSize<Exp> = Fix<isize, U10, Exp>;
#[cfg(feature = "i128")]
pub type IFix128<Exp> = Fix<i128, U10, Exp>;
}
/// SI prefixes.
pub mod si {
use typenum::{N1, N2, N3, N6, N9, N12, N15, N18, N21, N24};
use typenum::{P1, P2, P3, P6,... | Rust | 0 |
attempts += 1
self._update_progress(0.9, "生成结果...")
result = SummaryResult(
original_text=text,
summary=summary,
style=config.style,
metrics=metrics
)
self._update_progress(1.0, "... | Python | 1 |
)
# vbox.addWidget(self.tableWidget, 0, 0, 1, 2)
vbox.addWidget(self.buttonAdd, 3, 0)
def add_row_table(self):
self.dict_perforation = self.data_well.dict_perforation
plast_all = self.tabWidget.currentWidget().labels_plast
self.dict_perforation_project = {}
... | Python | 1 |
bottom** left.
/// * A negative height indicates that the image origin is the **top** left.
pub height: i32,
/// Should be 1, 4, 8, 16, 24, or 32.
pub bits_per_pixel: u16,
/// The compression style of the image data.
pub compression: BmpCompression,
/// The number of bytes in the raw bitmap data.
///... | Rust | 0 |
e(item_path)
os.makedirs(series_folder, exist_ok=True)
logger.info(f"Created series folder: {series_folder}")
# Download DICOM instances
response = requests.get(f"{ORTHANC_URL}/series/{series_id}/instances", verify=False)
response.raise_for_status()
instances = response.json()
if... | Python | 1 |
('\u{fe31}', '\u{fe32}'), ('\u{fe58}', '\u{fe58}'), ('\u{fe63}',
'\u{fe63}'), ('\u{ff0d}', '\u{ff0d}')
];
pub const Pe_table: &'static [(char, char)] = &[
('\u{29}', '\u{29}'), ('\u{5d}', '\u{5d}'), ('\u{7d}', '\u{7d}'),
('\u{f3b}', '\u{f3b}'), ('\u{f3d}', '\u{f3d}'), ('\u{169c}',
... | Rust | 0 |
ype is not IgnoreRequest:
logger.error(
"Error downloading %(request)s: %(f_exception)s",
{"request": request, "f_exception": failure.value},
exc_info=failure_to_exc_info(failure),
extra={"spider": spider},
)
return failure
... | Python | 1 |
import numpy as np
import re
import matplotlib.pyplot as plt
from more_neurons_model_dsnn_config import decrease_rate,batch_size,learning_rate,weight_decay
from more_neurons_model_dsnn_config import L,r,decrease_over,K
from pathlib import Path
import pandas as pd
#this script compares performance of dsnn with differ... | Python | 1 |
not set).
///
/// Rounding is done according to the rounding\[3:0\] parameter, which can be one of:
/// (_MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC) // round to nearest, and suppress exceptions
/// (_MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC) // round down, and suppress exceptions
/// (_MM_FROUND_TO_POS_I... | Rust | 0 |
.select_best_match(&[FamilyName::Title(name)], &Properties::new())
.unwrap()
.load()
.unwrap()
}
fn u32_to_solid_source(x: u32) -> SolidSource {
let bytes = x.to_be_bytes();
SolidSource::from_unpremultiplied_argb(bytes[3], bytes[0], bytes[1], bytes[2])
}
pub static HEADER_CATAL... | Rust | 0 |
)\xc8\x0de\x9cM\xe1\xecV\
\x90\x1b\xca\xf8 \x85\xb3AAn(\xe3K\x14\xceR\
\x05\xb9\xa1\x8c\x9fQ8\xed\x0arC\x19\xff6\xd6(\
\x8c\x89\xc6\xff\x14d\x872^N\xe1\xecS\x90\x1b\xca\
\xd8A\xe1\xbc\xae 7\x94\xf1\x19\x0a\xa7KAn(\
\xe3\x0e\x0a\xe7f\x05\xb9\xa1\x8c\xbfP8\xad\x0arC\
9'S8\x07\x15\xe4\x862\xce\xa5p\xb6+\xc8\x0d\
e\x5cA\xe... | Python | 1 |
import requests
import random
def ask_LLM(prompt, host, api_key,backend = 'tabyapi',inst_beg = "[INST]",inst_end = "[/INST]",max_tokens = 1024,min_p = 0.9,top_k = 1,top_p = 0.9,temperature=0.8):
if backend == 'vllm':
payload = {
"prompt": prompt,
"model": "/workspace/text-generatio... | Python | 1 |
port),
tx,
rx,
stopped: Arc::new(AtomicBool::new(false)),
}
}
async fn handle_connection(
sender: Sender<Message>,
stream: TcpStream,
_addr: SocketAddr,
stopped: Arc<AtomicBool>,
) {
let mut ws = accept_async(stream)
... | Rust | 0 |
self.G_A.load_state_dict(weight_set['G_A'])
self.G_B.load_state_dict(weight_set['G_B'])
if self.training:
self.D_A.load_state_dict(weight_set['D_A'])
self.D_B.load_state_dict(weight_set['D_B'])
if __name__ == '__main__':
from utils.measure_model import measure_model
... | Python | 1 |
ackage(
"/Users/dinu/Desktop/reportlab",
Title="reportlab",
Version="1.10",
Description="ReportLab's Open Source PDF toolkit.",
DefaultLocation="/Applications/ReportLab",
Relocatable="YES")
######################################################################
# Command... | Python | 1 |
from flask import Flask, render_template, request, redirect, url_for, flash, send_from_directory
from pathlib import Path
from check_flag import verify_flag
import os
app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET", "dev-secret")
ROOT = Path(__file__).resolve().parents[1]
CHAL_DIR = ROOT / "chall... | Python | 1 |
Op::Sub => "-",
BinaryOp::Mul => "*",
BinaryOp::Div => "/",
};
paren(op_repr, [&e.lhs, &e.rhs])
}
Unary(e) => match e.op {
UnaryOp::Neg => paren("-", [&e.expr]),
},
Group(e) => lisp_printer(&e.expr),
Num(e) => e.... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.