text string | label_name string | labels int64 |
|---|---|---|
import streamlit as st
import pandas as pd
import plotly.express as px
import urllib.request
from urllib.error import HTTPError
# Function to download CSV files from URLs with error handling
def download_csv(url):
try:
print(f"Downloading data from: {url}")
response = urllib.request.urlopen(url)
... | Python | 1 |
ity, comp: u64) -> Option<&'a T> {
let value = unsafe { ecs_get_id(self.world, entity.raw(), comp) };
if value.is_null() {
return None;
}
Some(unsafe { (value as *const T).as_ref().unwrap() })
}
pub fn add<T: Component>(&self, entity: Entity) {
// flecs_static_assert(is_flecs_constructible<T>::val... | Rust | 0 |
s, "
"could be related to finished_requests_ids")
@pytest.mark.parametrize("model", [SSM_MODELS[0], HYBRID_MODELS[0]])
@pytest.mark.parametrize("max_tokens", [64])
def test_multistep_correctness(
vllm_runner,
example_prompts,
model: str,
max_tokens: int,
) -> None:
with vllm_ru... | Python | 1 |
'''
Diamond Pattern
Problem Description:
You are given an integer n. Your task is to return a diamond pattern of '*' with n rows for the upper part (the widest row will have 2n - 1 stars), and the lower part is the mirrored version of the upper part. Each row should be centered with appropriate spaces.
Input:
A single... | Python | 1 |
Bytes,
// The number of chunks currently allocated.
num_allocated_chunks: u64,
// A linked list of unallocated chunks.
free_list_head: Address,
memory: M,
}
#[repr(packed)]
struct AllocatorHeader {
magic: [u8; 3],
version: u8,
// Empty space to memory-align the following fields.
... | Rust | 0 |
?;
{
let parameters = foreign_types_shared::ForeignType::as_ptr(¶meters);
crate::ex_data::set(parameters, private_key)?;
openssl2::openssl_returns_1(openssl_sys2::RSA_set_method(
parameters,
super::rsa::pkcs11_rsa_method(),
))?;
}
let openssl_key = openssl::pkey::PKey... | Rust | 0 |
16(cmd_read_temp, 0, 6) & 0x00ff
cmd_read_temp.append(hi_c)
cmd_read_temp.append(lo_c)
while (1):
try:
ser.write(cmd_read_temp)
print("Read Temp:", cmd_read_temp)
time.sleep(0.2) # wait 0.5s
response = ser.read(32)
# print("read byte data... | Python | 1 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression
netflix_df=pd.read_csv("netflix.csv")
prime_df=pd.read_csv("prime.csv")
hotstar_df=pd.read_csv("hotstar.csv")
title_hotstar = hotstar_df['year'].value_counts().sort_index()
title_hotstar_df = titl... | Python | 1 |
\n🎬 Production:")
print(f" Articles processed: {status['total_articles_processed']}")
print(f" Reels created: {status['total_reels_created']}")
print(f" Total cost: ${status['total_cost']:.6f}")
print(f"\n📂 Categories: {', '.join(status['categories_tr... | Python | 1 |
gDeliveryStreamInputOperationOutputAlias = crate::operation::UntagDeliveryStream;
#[doc(hidden)]
pub type UntagDeliveryStreamInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl UntagDeliveryStreamInput {
/// Consumes the builder and constructs an Operation<[`UntagDeliveryStream`](crate::operation:... | Rust | 0 |
[
V::Mask::default(),
V::Mask::default(),
V::Mask::default(),
V::Mask::default(),
// The all-ones stream.
!V::Mask::default()
];
// Additional `+ 1` allows for antidiagonal handling at start of row.
... | Rust | 0 |
/// Processes the next item yielded by the stream.
///
/// This is somewhat akin to
/// [`Handler::handle`][crate::Handler::handle],
/// except that it must only return unit (`()`).
///
/// While a [`Handler`][crate::Handler] forwards any values
/// it produces to the caller which takes ... | Rust | 0 |
e_height).floor() as usize;
if line == self.mouse_down {
let palette = Arc::make_mut(&mut data.palette);
palette.index = line;
data.select(ctx);
}
ctx.set_handled();
}
_ => (),
... | Rust | 0 |
rcam():
# test that the code skips processing for a NIR instrument
# size of integration
ngroups = 5
xsize = 2048
ysize = 2048
# create the data and groupdq arrays
csize = (1, ngroups, ysize, xsize)
data = np.full(csize, 1.0)
groupdq = np.zeros(csize, dtype=int)
# create a JWS... | Python | 1 |
let biased = graph.add_node(Add(mat_mul_out, bias, 0));
// Grab VarIndex for biased's output
let biased_out = biased.get(&graph).outputs[0];
(biased_out, weights, bias)
}
pub fn dense_biased_manual(graph: &mut Graph,
input: VarIndex,
weights: VarIn... | Rust | 0 |
import h5py
from src.general.figure import set_figure
from src.general import *
from src.general import *
from src.general import *
def the_figure(ax, fig):
set_figure.set_label_and_title(ax, title=f'Stability of Measurement System', xlabel='Measurement Sequence', ylabel='Wavelength(nm)', mode='3d', zlabel_rotati... | Python | 1 |
int(sub_path) >= 2**31:
# https://bitcoin.stackexchange.com/a/92057
return False
return True
def ltrim_path(bip32_path, depth):
"""
Left trim off a path by a given depth
"""
if not is_valid_bip32_path(bip32_path):
raise ValueError(f"Invalid bip32 path: {bip32_path... | Python | 1 |
type Error = crate::Error;
fn try_from(from: String) -> Result<Self, Self::Error> {
use std::convert::TryInto;
from.as_str().try_into()
}
}
impl std::convert::TryFrom<&str> for Port {
type Error = crate::Error;
fn try_from(from: &str) -> Result<Self, Self::Error> {
Ok(fro... | Rust | 0 |
untracked.double(PTCUTTEMPLATE),
runControl = cms.untracked.bool(RUNCONTROLTEMPLATE),
runControlNumber = cms.untracked.vuint32(int(runboundary)),
TkFilterParameters = FilteringParams,
... | Python | 1 |
continue
print("scattering_type:", label)
assert len(six_term_fits.all[label]) == 1
assert six_term_fits.all[label][0].n_terms() == 6
fit_group.append(six_term_fits.all[label][0])
reset_max_error(itvc_tab.entries[label], fit_group[-1])
trimmed_fit_group =[]
prev_fit = None
for fit in fit... | Python | 1 |
(tracked via a thread-local variable) without referencing a
//! handle. It is expected that all executors will set a value for the default
//! executor. This value will often be set to the executor itself, but it is
//! possible that the default executor might be set to a different executor.
//!
//! For example, a sin... | Rust | 0 |
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Widgets Demo")
widgets = [
tk.Label,
tk.Checkbutton,
ttk.Combobox,
tk.Entry,
tk.Button,
tk.Radiobutton,
tk.Scale,
tk.Spinbox,
]
for widget in widgets:
try:
widget = widget(root, text=widget.__name__)
... | Python | 1 |
class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
total_time = 0
last_index_m = last_index_p = last_index_g = -1
n = len(garbage)
for i in range(n):
total_time += len(garbage[i])
if 'M' in garbage[i]:
... | Python | 1 |
use std::cmp::Ordering;
pub fn p1(s: &str) -> usize {
let [lo, hi] = parse(s);
(lo..=hi).filter(|&n| is_valid_p1(n)).count()
}
pub fn p2(s: &str) -> usize {
let [lo, hi] = parse(s);
(lo..=hi).filter(|&n| is_valid_p2(n)).count()
}
fn is_valid_p1(n: u32) -> bool {
if !(100_000..1_000_000).contains(&n) {
... | Rust | 0 |
# Mostrar recetas existentes
recetas = cargar_datos(RECETAS_FILE)
tk.Label(ventana, text="Seleccione una Receta:").pack()
combo_recetas = ttk.Combobox(ventana, values=[r["nombre"] for r in recetas])
combo_recetas.pack()
# Mostrar gastos semanales y mensuales
gastos = c... | Python | 1 |
} else {
Ok(())
}
}
// Obtain the EcPoint, which is an (x,y) coordinate. Each coordinate is 32 bytes.
// These are preceded by an 04 byte meaning "uncompressed point."
// The returned vector will therefore have len=65.
fn get_ec_point(
ctx: &Ctx,
session_handle: CK_SESSION_HANDLE,
object_hand... | Rust | 0 |
USB_PORT_STATUS_HIGH_SPEED: u32 = 1024u32;
#[doc = "*Required features: 'Win32_Devices_Usb'*"]
pub const USB_PORT_STATUS_LOW_SPEED: u32 = 512u32;
#[doc = "*Required features: 'Win32_Devices_Usb'*"]
pub const USB_PORT_STATUS_OVER_CURRENT: u32 = 8u32;
#[doc = "*Required features: 'Win32_Devices_Usb'*"]
pub const USB_POR... | Rust | 0 |
Err(err) => {
error = Err(err);
EntityVisitResult::Break
}
}
});
error?;
while let Some(_entity) = breadcrumbs.pop() {
create_end_xml_event_from_entry(&mut writer)?;
}
Ok(())
}
pub fn process_astxml(
source_file_path: String,
out... | Rust | 0 |
= (n & 0b10_0000) != 0;
let home = (n & 0b01_0000) != 0;
let copyrighted = (n & 0b00_1000) != 0;
let copyright_id_start = (n & 0b00_0100) != 0;
track_assert!(!originality, ErrorKind::Unsupported);
track_assert!(!home, ErrorKind::Unsupported);
track_assert!(!copyrighted, ... | Rust | 0 |
gaData),
RMC(RmcData),
GSV(GsvData),
GSA(GsaData),
VTG(VtgData),
GLL(GllData),
Unsupported(SentenceType),
}
/// parse nmea 0183 sentence and extract data from it
pub fn parse(xs: &[u8]) -> Result<ParseResult, String> {
let nmea_sentence = parse_nmea_sentence(xs)?;
if nmea_sentence.chec... | Rust | 0 |
import torch
import torch.nn as nn
__all__ = ["CrossEntropyLoss", "SoftEntropyLoss"]
class CrossEntropyLoss(nn.Module):
"""Cross entropy loss with label smoothing regularizer.
Reference:
Szegedy et al. Rethinking the Inception Architecture for Computer Vision. CVPR 2016.
Equation: y = (1 - epsilon) *... | Python | 1 |
,
}
/// 8 bit registers
#[derive(Debug, PartialEq, Clone, Copy, Display)]
pub enum Reg8 {
A,
F,
B,
C,
D,
E,
H,
L,
/// A'
AP,
/// F'
FP,
/// B'
BP,
/// C'
CP,
/// D'
DP,
/// E'
EP,
/// H'
HP,
/// L'
LP,
}
/// 16-bit registe... | Rust | 0 |
ned()));
}
let mut input_props = Vec::with_capacity(info.input_file_count());
let mut output_props = Vec::with_capacity(info.output_file_count());
let iter = info.Block_properties().into_iter();
for (file, properties) in iter {
let ucp = UserCollectedPropertiesDecoder... | Rust | 0 |
numbers = [1,3,5]
def solution(numbers, num1, num2):
return numbers[num1:num2+1]
a = solution(numbers, 1, 3)
print(a)
| Python | 1 |
expected_output = {
'capture': {
1: {
'time': '0.000000',
'scr_mac_address': 'f4:db:e6:5b:97:04',
'dst_mac_address': '01:80:c2:00:00:00',
'protocol': 'STP',
'packet_size': 60,
'data': 'RST. Root = 32768/805/6c:b2:ae:49:6a:40 Cost = 0 Port = 0x8185'
},
2: {
'time': '2.000739',
'scr_mac_a... | Python | 1 |
inux::clipboard::get_clipboard(bufname.as_ptr(), fmtname.as_ptr()) }
}
#[cfg(target_os = "linux")]
pub fn set(_ctx: &mut Context, data: &str) {
use std::ffi::CString;
let bufname = CString::new("CLIPBOARD").unwrap();
unsafe { sapp_linux::clipboard::claim_clipboard_ownership(bufname.as_ptr(), data.to_owne... | Rust | 0 |
20 minutes
if 'DYNO' in environ:
ON_HEROKU = True
else:
ON_HEROKU = False
URL = environ.get("URL", "")
# Rename Info : If True Then Bot Rename File Else Not
RENAME_MODE = bool(environ.get('RENAME_MODE', True)) # Set True or False
# Auto Approve Info : If True Then Bot Approve New Upcoming Join Request Else N... | Python | 1 |
from collections import OrderedDict
import pytest
from lumo.core.meter import ReduceItem, Meter
def test_meter():
m = Meter()
m['loss'] = 0.5
m['accuracy'] = 0.8
# test __getitem__ method
assert m['loss'] == 0.5
# test __setitem__ method
m['loss'] = 0.2
assert m['loss'] == 0.2
... | Python | 1 |
ibd(y_true_valid, y_proba_valid, y_proba, t)
threshold_metrics[t_rounded] = {
'Precision': precision_rounded,
'Precision 95% CI': [round(metric_ci['precision'][0], 2), round(metric_ci['precision'][1], 2)],
'Recall': recall_rounded,
... | Python | 1 |
# -*- coding: UTF-8 -*-
import numpy as np
import math
from scipy.special import psi, gammaln
N = 2
It = 50
xn = np.random.normal(5, 1, N)
m = 0.
beta = 0.0001
a = 0.001
b = 0.001
a_gamma = np.random.gamma(1, 1, 1)[0]
b_gamma = np.random.gamma(1, 1, 1)[0]
m_mu = np.random.normal(m, (beta) ** (-1.), 1)[0]
beta_mu = n... | Python | 1 |
lclose(self.ssm_posterior.smoothed_means, self.joint_means)
assert allclose(self.ssm_posterior.smoothed_covariances, self.joint_covs)
assert allclose(self.ssm_posterior_diag.smoothed_means, self.joint_means)
assert allclose(self.ssm_posterior_diag.smoothed_covariances, self.joint_covs)
... | Python | 1 |
ect, but I guess
* that some clients like auctex would not like it very much. we cannot use
* "<<13" instead of "/SYNCTEX_UNIT_FACTOR" because the integers are signed and we do not
* want the sign bit to be propagated. The origin of the coordinates is at
* the top left corner of the page. For pdf mode, it is... | Rust | 0 |
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.v1.endpoints import pdf
app = FastAPI(
title="HTML to PDF Service",
description="A service to convert HTML to PDF using Selenium",
version="1.0.0"
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
... | Python | 1 |
mark=none, cViolet, thick, dashed, dash pattern=on 1pt off 1pt] table[x=pos, y=mif_50, col sep=comma] {{data.csv}};
\addplot+[mark=none, cYellow, thick, dashed, dash pattern=on 1pt off 1pt] table[x=pos, y=mil_50, col sep=comma] {{data.csv}};
\addplot+[mark=none, thick, cRed] table[x=pos, y=random_50, col sep=co... | Python | 1 |
| coroutine_manager_index << Self::CoroutineManagerIndexBitShift
| user_bits_unshifted << Self::UserBitsBitShift
| generation_unshifted << Self::GenerationBitShift
| index_unshifted << Self::IndexBitShift
)
}
/// Is not for a coroutine?
#[inline(always)]
pub const fn is_not_for_a_coroutine(user_data:... | Rust | 0 |
A3FA264B9C475098FDCF6E00D7C996E1B8B7EB");
test_rfc6979_sig(&mut p256, "sample", Type::Sha224,
"3045022053B2FFF5D1752B2C689DF257C04C40A587FABABB3F6FC2702F1343AF7CA9AA3F022100B9AFB64FDC03DC1A131C7D2386D11E349F070AA432A4ACC918BEA988BF75C74C");
test_rfc6979_sig(&mut p256, "sample", Type::Sha256,
"30460221... | Rust | 0 |
, args);
started_graphs.into_iter()
.map(|(g, dnodes)| {
let g_explore = args.graph_explorer_builder.build(&g);
let remained_terminals = dnodes.into_iter().collect::<IHashSet<String>>();
let graph_discovery = singularity.replace_current_state(remained_terminals, g_explor... | Rust | 0 |
"""
Union Find Disjoint Set Complexity analysis
Time complexity:
Find operation:
It keeps going up the parent until we reach the root node, which has parent equal to itself.
In the worst case, when it is a straight line, it could be O(n)
However with path compression optimisation, where wh... | Python | 1 |
lafcn = Function('lafcn', [tau], [La])
Da[j-1] = lafcn(tau_root[0])
xA_plt = np.resize(np.array([],dtype=MX),(nalg,(deg+1)*nicp*(nk)+1))
offset4=0
offset5=0
for k in range(nk):
for i in range(nicp):
for j in range(deg+1):
if j!=0:
xA_plt[:,offset5] = xA_opt[:,offset4]
... | Python | 1 |
return Ok(self);
}
}
let c = c.unwrap();
// Let's see if any of the outbound links are a candidate.
match self.children.binary_search_by_key(&c, |p| p.0.clone()) {
// No candidate link, so make one.
Err(i) => {
let new_child... | Rust | 0 |
n\nFor information about available fields see [sm3_instr](sm3_instr) module"]
pub type SM3_INSTR = crate::Reg<u32, _SM3_INSTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SM3_INSTR;
#[doc = "`read()` method returns [sm3_instr::R](sm3_instr::R) reader structure"]
impl crate::Readable for SM3_INSTR {}
#[doc = "`wr... | Rust | 0 |
_json::Value::Null, std::convert::identity),
op_msg=op_msg,
data=data_file,
rules=rules_file,
rule=info.rule,
msg=info.message.replace("\n", ";"),
))
}
fn binary_error_message(
rules_file: &str,
data_file: &str,
op_msg: &str,
info: &NameInfo<'_>,
) -> crate::... | Rust | 0 |
b=MyBuddyCallback())
buddy.subscribe()
pending_pres = None
pending_uri = None
else:
print "No pending request"
elif input == "R":
if pending_pres:
acc.pres_notify(pending_pres, pj.SubscriptionState.TERMINATE... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
import pywt
import mne
import argparse
def process_eeg_signal(
edf_file, channel_name, wavelet="cmor1.5-1.0", scales=np.arange(1, 128)
):
# Load the EDF file
raw = mne.io.read_raw_edf(edf_file, preload=True)
# Select the channel of interest
if ch... | Python | 1 |
self
}
/// When the pool is created this is a multiplier for the amount of sub
/// pools to be created.
///
/// Other values will be adjusted if the multiplier is > 1:
///
/// * `reservation_limit`: Stays zero if zero, otherwise (`reservation_limit`/multiplier) +1
/// * `desire... | Rust | 0 |
/// CPUID.(EAX=07H, ECX=0H):ECX.AVX512_VNNI\[bit 11\]
AVX512_VNNI = 24,
/// CPUID.(EAX=07H, ECX=0H):EDX.AVX512_VP2INTERSECT\[bit 08\]
AVX512_VP2INTERSECT = 25,
/// CPUID.(EAX=07H, ECX=0H):ECX.AVX512_VPOPCNTDQ\[bit 14\]
AVX512_VPOPCNTDQ = 26,
/// CPUID.(EAX=07H, ECX=0H):EBX.AVX512BW\[bit 30\]
AVX512BW = 27,
///... | Rust | 0 |
_dir = left_knee_local_dir / torch.norm(left_knee_local_dir)
left_knee_local_dir_tile = torch.tile(left_knee_local_dir.unsqueeze(0), [left_knee_rot.shape[0], 1])
left_knee_local_dir0 = quat_rotate(left_knee_rot, left_knee_local_dir_tile)
left_knee_local_dir1 = quat_rotate(left_knee_q, left_knee_local_dir_ti... | Python | 1 |
_base_ = [
'../_base_/models/mask_rcnn_r50_fpn.py',
'../_base_/datasets/coco_instance.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
optimizer = dict(
_delete_=True,
type='AdamW',
lr=0.0001,
weight_decay=0.1,
paramwise_cfg=dict(norm_decay_mult=0., bypass_dup... | Python | 1 |
f result.init(init) {
Some(result)
} else {
None
}
}
///Decrements self, returning immediately if it was signaled.
///
///Otherwise awaits for signal.
pub fn wait(&self) {
let result = unsafe {
semaphore_wait(self.handle.load(Ordering::Acq... | Rust | 0 |
help builder.
htmlhelp_basename = 'pyGeoPressuredoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10... | Python | 1 |
# -*- coding: utf-8 -*-
"""yolo.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1LuOSSC5VsITuS54MktXZIzL2B0bhp1xh
"""
!pip install torch torchvision torchaudio pillow opencv-python numpy ultralytics
import torch
from PIL import Image, ImageFilter
import... | Python | 1 |
international.com/phpBB3/index.php", 0x2bed3602,
fnv1a_32_test_176: u32, b"http://www.travelquesttours.com/index.htm", 0xb26249e0,
fnv1a_32_test_177: u32, b"http://www.wunderground.com/global/stations/89606.html", 0x2c9b86a4,
fnv1a_32_test_178: u32, &repeat(b"21701", 10), 0xe415e2bb,
fnv1a_32_test_179: u32, &re... | Rust | 0 |
#[derive(Debug, FromProtobuf)]
pub struct Score {
#[Get]
score_type: Score_ScoreType,
#[Get]
score: i32,
score_details: ScoreDetails,
}
#[derive(Debug, FromProtobuf)]
pub struct CategoryScoreDetails {
#[Get]
pub none: f32,
#[Get]
pub army: f32,
#[Get]
pub economy: f32,
... | Rust | 0 |
params=params)
response.raise_for_status()
data = response.json()
results = []
if 'data' in data:
for media in data['data']:
try:
results.append({
'id': media['id'],
... | Python | 1 |
import pytest
import types
#useful for debugging tests
def pretty(*things, **named_things):
import pprint
for t in things:
pprint.PrettyPrinter(indent=2, width=200).pprint(t)
for k,v in named_things.items():
print(str(k) + ":")
pprint.PrettyPrinter(indent=2, width=200).pprint(v)
fr... | Python | 1 |
32f1xx_hal::{
delay::Delay,
pac,
prelude::*,
spi::{Mode, Phase, Polarity, Spi},
};
use embedded_hal::digital::v2::OutputPin;
use dw3000::{Config, hl, time::Instant};
use nb::block;
#[entry]
fn main() -> ! {
rtt_init_print!();
rprintln!("Coucou copain !");
/******************************************************... | Rust | 0 |
import re
from typing import Callable
punctuation = set(['!', '?', '…', ',', '.', '-'," "])
METHODS = dict()
def get_method(name:str)->Callable:
method = METHODS.get(name, None)
if method is None:
raise ValueError(f"Method {name} not found")
return method
def get_method_names()->list:
ret... | Python | 1 |
XConnection>> {
match *self {
EventsLoop::Wayland(_) => None,
EventsLoop::X(ref ev) => Some(ev.x_connection()),
}
}
}
impl EventsLoopProxy {
pub fn wakeup(&self) -> Result<(), EventsLoopClosed> {
match *self {
EventsLoopProxy::Wayland(ref proxy) => pr... | Rust | 0 |
nfig.vlog(&format!("Read {}b from file", read_size));
if read_size == 0 { // if nothing read then it is end of the file
self.file_read = true;
break;
}
let part = Part {
content: Vec::from(&buffer[..read_size]),
last_tra... | Rust | 0 |
stored in the same directory as the present notebook. Now we can run the Python script, as shown below.
#
# First we show a run with one party only. However, this time the code runs outside the Jupyter notebook, using its own Python interpreter. Once the run is completed, the screen output is displayed in the output... | Python | 1 |
"), Some(&1.5.into()));
///
/// // "Steal" ownership of a value. Can replace with any valid Value.
/// let old_x = value.pointer_mut("/x").map(|x| mem::replace(x, Value::Null)).unwrap();
/// assert_eq!(old_x, 1.5);
/// assert_eq!(value.pointer("/x").unwrap(), &Value::Null);
/// }... | Rust | 0 |
import os
import numpy as np
from pathlib import Path
from pylib import schism_grid # from ZG's pylib: pip install pylibs-ocean
def gen_mask(gd:schism_grid, area_file='puertori'):
xyz = np.loadtxt(area_file)
out_mask_name = f'{Path(area_file).stem}_mask.txt'
xyz[xyz[:, 0]>180, 0] -= 360
ie, ip, aco... | Python | 1 |
, 3]);
assert!(ob.downcast::<PyArray2<i32>>().is_err());
})
}
<filename>lib_gbemulation/src/apu/channel/square_channel.rs
use crate::apu::channel::frame_sequencer::FrameSequencer;
use crate::apu::channel::frequency_sweep::{FrequencySweep, FrequencySweepResult};
use crate::apu::channel::length_counter::{Len... | Rust | 0 |
Option<&'a Cancellable>>>(&self, data: u16, cancellable: P) -> Result<(), Error>;
fn put_uint32<'a, P: Into<Option<&'a Cancellable>>>(&self, data: u32, cancellable: P) -> Result<(), Error>;
fn put_uint64<'a, P: Into<Option<&'a Cancellable>>>(&self, data: u64, cancellable: P) -> Result<(), Error>;
fn set_... | Rust | 0 |
from typing import Optional
from datetime import datetime, UTC
from pydantic import BaseModel, field_validator, EmailStr
from enum import Enum
class UserRole(str, Enum):
ADMIN = "admin"
USER = "user"
class User(BaseModel):
"""User domain model"""
id: str
fullname: str
email: str # Now requi... | Python | 1 |
the listen address to the
/// public internet or other unauthorized parties.
#[clap(
long,
hide = true,
value_name = "HOST:PORT",
env = "MZ_THIRD_PARTY_METRICS_ADDR"
)]
third_party_metrics_listen_addr: Option<SocketAddr>,
/// Enable persistent user tables. Has to be... | Rust | 0 |
ySym = 0xff94;
pub const XK_KP_Home: KeySym = 0xff95;
pub const XK_KP_Left: KeySym = 0xff96;
pub const XK_KP_Up: KeySym = 0xff97;
pub const XK_KP_Right: KeySym = 0xff98;
pub const XK_KP_Down: KeySym = 0xff99;
pub const XK_KP_Prior: KeySym = 0xff9a;
pub const XK_KP_Page_Up: KeySym = 0xff9a;
pub const XK_KP_Next: KeySym ... | Rust | 0 |
ret.append(get_opcodes()[item.upper()][0])
elif item[:4] == "PUSH":
ret.append(PUSH_OFFSET + int(item[4:]))
elif item[:3] == "DUP":
ret.append(DUP_OFFSET + int(item[3:]))
elif item[:4] == "SWAP":
ret.append(SWAP_OFFSET + int(item[4:]))
elif i... | Python | 1 |
.dictionary(&doc2);
if dict1.is_empty() || dict2.is_empty() {
return Err("empty dictionary");
}
let dict = dict1.join(&dict2);
if dict.len() <= 1 {
return Ok(1.0);
}
let doc_bow1 = match dict.bow_normalized(&doc1) {
Some(bow) => bow,... | Rust | 0 |
0 as libc::c_int;
}
}
/* Update the comps[].factor member of the output image with the one */
/* of m_reduce */
it_comp = 0 as libc::c_int as OPJ_UINT32;
while it_comp < (*p_image).numcomps {
(*(*p_image).comps.offset(it_comp as isize)).factor =
(*p_j2k).m_cp.m_specific_param.m_dec.m_reduce;
... | Rust | 0 |
rate) mod simplify_outer_joins;
<reponame>uigctaw/botel<filename>botel_tokenizer/src/lib.rs
use regex::Regex;
use lazy_static::lazy_static;
#[derive(Debug)]
#[derive(PartialEq)]
pub enum Token {
Whitespace(String),
Equals(String),
Integer(String),
Name(String),
Plus(String),
}
lazy_stati... | Rust | 0 |
eError:
invalid_itsvar_counts.append(itsvar_count)
valid_itsvar_percent = (len(valid_itsvar_counts) / output_df.shape[0])*100
invalid_itsvar_percent = (len(invalid_itsvar_counts) / output_df.shape[0])*100
invalid_itsvar_counts_fmt = '\n '.join(invalid_itsvar_counts)
print(f'Out of the {output_df.shape[0]... | Python | 1 |
from __future__ import annotations
from cmath import sqrt
def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]:
"""
Given the numerical coefficients a, b and c,
calculates the roots for any quadratic equation of the form ax^2 + bx + c
>>> quadratic_roots(a=1, b=3, c=-4)
(1.0, -... | Python | 1 |
from typing import List
def triplet_sum_smaller(nums: List[int], target: int)->int:
n = len(nums)
count = 0
nums = sorted(nums) # Keep original nums outside of the function
print('Sorted nums: ', nums)
for i in range(n-2):
left = i + 1
right = n-1
while left < right:
... | Python | 1 |
tains() {
let sector = Sector::new(Point::zero(), 10, 0.0.deg(), 90.0.deg());
let contained_points = Rectangle::new(Point::new(-10, -10), Size::new(30, 30))
.points()
.filter(|p| sector.contains(*p));
assert!(contained_points.eq(sector.points()));
}
#[test]
... | Rust | 0 |
__version__ = "v1.0.0"
| Python | 1 |
lude exception '{}'",
net.cidr,
except
);
}
}
}
Ok(())
}
}
<reponame>saruman9/rust-analyzer
//! Helper functions for binary operator type inference.
use hir_def::expr::{ArithOp, BinaryOp, CmpOp};
use su... | Rust | 0 |
"white",
},
{
"key": "light_brightness",
"integer_value": math.ceil(
brightness_to_value(self.brightness_range, brightness)
),
},
)
... | Python | 1 |
_id,
revisions: d
.revisions
.iter()
.map(ClientPurchaseOrderRevision::from)
.collect(),
}
}
}
impl From<PurchaseOrderVersion> for ClientPurchaseOrderVersion {
fn from(d: PurchaseOrderVersion) -> Self {
Self {
... | Rust | 0 |
more_detail=False
def choose_country():
st.session_state.country=True
st.session_state.area=False
st.session_state.more_detail=False
def choose_area():
st.session_state.area=True
st.session_state.more_detail=False
def more_detail():
st.session_state.more_detail=True
def travel():
st.titl... | Python | 1 |
lr=0.1)
print(f"Initial State: {initial_state[:,:,:]}")
true_trajectory = sample[:, args.start_time:args.end_time].to(device) # Shape: [bs, steps, body_num, feature_dim]
nonzero_mask = true_trajectory[...,0:1] != 0
for i in range(100):
optimizer.zero_grad()
pre... | Python | 1 |
MA4 {}
#[doc = "`write(|w| ..)` method takes [otg_hs_diepdma4::W](otg_hs_diepdma4::W) writer structure"]
impl crate::Writable for OTG_HS_DIEPDMA4 {}
#[doc = "OTG_HS device endpoint-4 DMA address register"]
pub mod otg_hs_diepdma4;
#[doc = "OTG_HS device endpoint-5 DMA address register\n\nThis register you can [`read`](... | Rust | 0 |
from tunacode.core.state import StateManager
def test_session_persistence_and_reset():
"""
Characterization: Session persists within StateManager instance, reset_session replaces it.
"""
sm = StateManager()
sm.session.user_config["foo"] = "bar"
# Session persists changes
assert sm.session.... | Python | 1 |
#!python3
"""
Demonstration of the fractional-budgeting algorithm maximizing the product of utilities.
AUTHOR: Erel Segal-Halevi
SINCE: 2019-11
"""
import cvxpy
TOTAL_BUDGET=4000
budget_for_greens = cvxpy.Variable()
budget_for_reds = cvxpy.Variable()
budget_for_yellows = cvxpy.Variable()
budget_for_blues = ... | Python | 1 |
word = "spider"
thousand = "1000"
ten = 10
first_half = 'full'
second_half = 'moon'
complete = (first_half + ' ' + second_half)
print(complete) | Python | 1 |
from moviepy.editor import VideoFileClip, clips_array
def main():
# Path to the input video
# [REMOVED PATH] input_video_path = '/home/jasvir/Music/Movie work/Split screen/1.mp4'
# Load the video
video = VideoFileClip(input_video_path)
# Get the duration of the video and calculate the duration o... | Python | 1 |
.iter()
.map(|fpr| [&fpr[..], &[0; 6][..]].concat().try_into().unwrap())
.collect::<Vec<_>>()
.try_into()
.unwrap();
let last_ip = {
let mut last_ip = fpu.fpu.fiseg.into();
last_ip |= u64::from(fpu.fpu.fioff) << u32::BITS;
last_ip
};
let last_dp = {
let mut last_dp = fpu.fpu.foseg.into()... | Rust | 0 |
/ 60_f32 / 60_f32;
return Ok(format!("{:.0} часа назад", h.ceil()));
}
x if x <= 20 * 60 * 60 => {
let h = x as f32 / 60_f32 / 60_f32;
return Ok(format!("{:.0} часов назад", h.ceil()));
}
x if x ... | Rust | 0 |
from tkinter import *
from tkinter.ttk import *
from tkinter.messagebox import *
from subprocess import *
from math import log, tan, e, pi, hypot
import json
import os
try:
from sys import _MEIPASS
except:
_MEIPASS = '.'
geo_ori = json.load(open(os.path.join(_MEIPASS, 'geo.json')))
geo = {}
for station in geo... | Python | 1 |
.v })
}
pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
let node = self.map.get_mut(KeyRef::new(k))?;
Some(unsafe { &mut node.as_mut().v })
}
pub fn move_to_front<Q: ?Sized>(&mut self, k: &Q) -> bool
where
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.