text string | label_name string | labels int64 |
|---|---|---|
>
// //
// // although it may also be generic over the output types T.
// pub fn deserialize<'de, D>(
// deserializer: D,
// ) -> Result<DateTime<Utc>, D::Error>
// where
// D: Deserializer<'de>,
// {
// let s = String::deserialize(deserializer)?;
// Utc.datetime_... | Rust | 0 |
#!/usr/bin/env python3
import asyncio
# Import async_generator from 0-async_generator module
async_generator = __import__('0-async_generator').async_generator
async def print_yielded_values():
"""Collects and prints all values generated by async_generator."""
result = []
async for i in async_generator():... | Python | 1 |
# coding:utf-8
import requests
from lib.core.common import url_handle,get_random_ua
from lib.core.poc import POCBase
# ...
import urllib3
urllib3.disable_warnings()
class POC(POCBase):
_info = {
"author" : "jijue", # POC作者
"version" : "1", # POC版本,默认是1
... | Python | 1 |
max_target_net = y.max(-1)[0]
# dim (batch_size, agents, number_actions)
network_prediction = self.q_network.forward(curr_state).view(
-1, self.agents, self.number_actions)
isNotOver = (torch.ones(*terminal.shape) - terminal)
# Bellman equation
batch_labels_te... | Python | 1 |
///
/// # Note:
/// Both the data-handle UDF or the state-handle UDF should be `Send`;
/// The user defined state should be `Send`;
///
/// # Examples:
/// ```rust
/// use pegasus::operator::Unary;
/// use pegasus::operator::IntoStream;
/// use pegasus::communication::Pipeline;
... | Rust | 0 |
from .communication import build_and_send_task
def list_accounts(sock, wildcard, use_wire_protocol):
"""
Retrieves a list of accounts from the server that match a specified wildcard pattern.
Args:
sock (socket.socket): The active socket connection to the server.
wildcard (str): A search pa... | Python | 1 |
# generator
# Функція, яка повертає ітератор генератора. Виглядає як звичайна функція, за вийнятком того, що вона містить вираз yield для створення серії значень,
# які можна використовувати в циклі for або які можливо получити по одному за допомогою функції next()
# Генераторні вирази
# Існує два схожих, але з різн... | Python | 1 |
# tcp_iterative/server_tcp_iterative_rpc.py
import socket
import sys
# Make sure to adjust this path if your structure is different
# This allows importing from a sibling directory like 'main_programs'
# when running as a module from the root.
from main_programs.rpc_logic import handle_rpc_request
HOST = '127.0.0.1'
... | Python | 1 |
ero(); window_size];
let mut output: Vec<f32> = vec![0.0; window_size];
let mut finders = [ExtremumFinder::new(); 256*2];
let mut was_below_baseline = [false; 256*2];
/* take each window from the microphone */
for window in receiver.iter() {
i += 1;
let mut input = get_windowed_sa... | Rust | 0 |
, C_null(T_opaque_box_ptr(cx))])
}
Some(&@ty::AutoAddEnv(ref r, ref s)) => {
cx.sess.span_bug(e.span, fmt!("unexpected static function: \
region %? sigil %?", *r, *s))
}
Some(&@ty::AutoDerefRef(ref adj)) => {
let mut ty =... | Rust | 0 |
import os.path
def initWrite(outputDir):
gamelist = open(os.path.join(outputDir, "gamelist.xml"), 'w', encoding="utf-8")
gamelist.write('<?xml version="1.0"?>\n')
gamelist.write("<gameList>\n")
return gamelist
def initRead(outputDir):
gamelist = open(os.path.join(outputDir, "gamelist.xml"), 'r',... | Python | 1 |
// `media-message = DQUOTE "MESSAGE" DQUOTE SP
/// DQUOTE "RFC822" DQUOTE`
///
/// Simplified:
///
/// `media-message = "\"MESSAGE\" \"RFC822\""`
///
/// Defined in [MIME-IMT]
///
/// "message" "rfc822" basic specific-for-message-rfc822 extension
pub fn media_message(input: &[u8]) -> IResult<&[u8], &[u... | Rust | 0 |
self.plant_x = self.width as f64 - 44.0;
}
self.last_update = SystemTime::now();
}
fn on_resize(&mut self, new_width: u32, new_height: u32) {
self.width = new_width;
self.height = new_height;
}
}
impl InputHandler for SpriteAnimationApp {
fn on_button_event(&mut s... | Rust | 0 |
arm.set_gpr(2, 0xA050_1122);
arm.run_immediately();
assert_eq!(arm.get_gpr(3), 0x0A05_4488);
}
#[test]
// sub r3, r1, r2
// r3 <- r1 - r2
fn sub_r3_r1_r2() {
setup();
let mut bus = MockBus::new();
&bus.set(0x0, 0xE041_3002);
let mut arm = ARMv4::new(R... | Rust | 0 |
(f'Unknown normalization {norm_type}.')
# Normalize losses by num_boxes.
losses = jax.tree_util.tree_map(lambda x: x / ntargets, losses)
if self.config.get('l2_decay_factor', 0) > 0:
l2_loss = model_utils.l2_regularization(model_params)
losses['l2_loss'] = 0.5 * self.config.l2_decay_factor * l... | Python | 1 |
lated signals directly,
# there is also the :func:`~.sim_modulated_signal` function.
#
# Instead of taking in pre-computed signals, this function takes in instructions
# for both the main and modulated signal, creates both and then returns the modulated signal.
#
#######################################################... | Python | 1 |
[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SafeKeeperState {
#[serde(with = "hex")]
pub tenant_id: ZTenantId,
/// Zenith timelineid
#[serde(with = "hex")]
pub timeline_id: ZTimelineId,
/// persistent acceptor state
pub acceptor_state: AcceptorState,
/// information about s... | Rust | 0 |
async fn one() -> usize { 1 }
/// async fn two() -> usize { 2 }
/// async fn three() -> usize { 3 }
///
/// # let _ = async {
/// let x = join!(one(), two(), three()).await;
/// assert_eq!(x, (1, 2, 3));
/// # };
/// ```
#[unstable(feature = "future_join", issue = "91642")]
pub macro join( $($fut:expr),+ $(,)? ) {
... | Rust | 0 |
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CFGCTRL;
#[doc = "`read()` method returns [cfgctrl::R](cfgctrl::R) reader structure"]
impl crate::Readable for CFGCTRL {}
#[doc = "`write(|w| ..)` method takes [cfgctrl::W](cfgctrl::W) writer structure"]
impl crate::Writable for CFGCTRL {}
#[doc = "USB VREG Configuratio... | Rust | 0 |
Masks tokens providing information on the type of tokens. This vector has the same length as token_ids.
pub masks: Vec<Mask>,
}
/// # Encoded sequence
/// Intermediate tokenization steps before addition of special tokens, after encoding
#[derive(Debug, Clone, PartialEq)]
pub struct TokenIdsWithOffsets {
/// V... | Rust | 0 |
Copy for CompressedCurvePoint<C>
where
C: WeierstrassCurve,
<<C as WeierstrassCurve>::CompressedPointSize as ArrayLength<u8>>::ArrayType: Copy,
{
}
impl<C: WeierstrassCurve> Clone for CompressedCurvePoint<C> {
fn clone(&self) -> Self {
Self::from_bytes(self.bytes.clone()).unwrap()
}
}
/// Unc... | Rust | 0 |
eturns:
Dictionary containing evaluation metrics, or None if no valid prediction could be made
"""
# Get available models in test data
available_models = {c['candidate_name'] for c in test_item['candidates']}
# Filter predictions to only include available models
valid_predictions = [p f... | Python | 1 |
trace!(
"WriteHandle::write_batch timeout={:?} new_upper={:?}",
timeout,
new_upper
);
let deadline = Instant::now() + timeout;
let lower = expected_upper;
let upper = new_upper;
let since = Antichain::from_elem(T::minimum());
let desc ... | Rust | 0 |
.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct AbstractLocation {
/// The address at which the location is valid.
pub addr: u64,
/// The call trace in which the location is valid.
pub trace: Vec<u64>,
/// The storage location.
pub storage: StorageLocation,
}
impl Abs... | Rust | 0 |
let _ = c.update_cmp(condition, s_result as u64, upper as u64);
}
// I<bit_size>::MIN
let lower = 0xffff_ffff_ffff_ffff << (bit_size - 1) as u64;
let condition = (s_result < lower as i64) as u32;
if c.check_match(cmpid | (4 << 28), context) {... | Rust | 0 |
__version__ = "1.5.1"
| Python | 1 |
# SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""Pin definitions for the SoPine."""
from adafruit_blinka.microcontroller.allwinner.a64 import pin
D2 = pin.PH3
D3 = pin.PH2
D4 = pin.PL10
D5 = pin.PH5
D6 = pin.PH6
D7 = pin.PH7
D8 = pin.PC3
D9 = pin.PC1
... | Python | 1 |
}
}
use std::collections::HashSet;
use std::collections::HashMap;
use std::ops::RangeInclusive;
use regex::Regex;
use aoc;
type Rule = (String, RangeInclusive<u64>, RangeInclusive<u64>);
type Ticket = Vec<u64>;
type TicketSpace = Vec<HashSet<String>>;
fn match_rule(v: u64, r: &Rule) -> bool {
r.1.contains(&v) ||... | Rust | 0 |
tions_service.get_role("Algorithm Member")).id,
)
editables.append(enriched_editable)
context = {"editables": editables, "show_no_results": len(search_results) == 0}
return templates.TemplateResponse(request, "organizations/parts/search_select_field.html.j2", cont... | Python | 1 |
plt.plot(x_smooth, y_smooth, '-', color='red')
plt.title('《{}》学习热度变化图'.format(course))
plt.xlabel('时间(天)')
plt.ylabel('热度')
plt.xticks(np.arange(6)*(400/5), ['0', '5', '10', '15', '20', '25'])
plt.yticks([])
plt.sav... | Python | 1 |
class Model:
def __init__(self, type, model_name, model_accuracy, model_gflops):
"""
初始化 Model 对象,表示一个机器学习模型。
:param type: 模型类型(可以是分类、回归等)
:param model_name: 模型名称
:param model_accuracy: 模型的准确率
:param model_gflops: 模型的算量
"""
self.type = type ... | Python | 1 |
new_with_backend_and_path")]
pub fn with_backend_and_path(
schema_id: &str,
backend: &impl IsA<SettingsBackend>,
path: &str,
) -> Settings {
unsafe {
from_glib_full(ffi::g_settings_new_with_backend_and_path(
schema_id.to_glib_none().0,
... | Rust | 0 |
import logging
from handlers import TODO_PATH, CDE_PATH, FIRS_PATH
from handlers.dummy import Dummy, DummyResponse
import devices
import config, features
_FIRST_CONTACT = '''
<?xml version="1.0" encoding="UTF-8"?>
<response>
<total_count>0</total_count>
<next_pull_time/>
<items>
<item action="UPLOAD" type... | Python | 1 |
mask):
return self.compute_location_loss(pred, targets, mask)
@staticmethod
def extract_index(start_logits, end_logits):
start_prob = nn.Softmax(dim=1)(start_logits)
end_prob = nn.Softmax(dim=1)(end_logits)
outer = torch.matmul(start_prob.unsqueeze(dim=2),
... | Python | 1 |
ild_id = guild_id)
old_attributes = channel._difference_update_attributes({
'name': new_name,
'type': channel_type.value,
})
vampytest.assert_eq(channel.name, new_name)
vampytest.assert_eq(
old_attributes,
{
'name': old_name,
},
)
... | Python | 1 |
from django.db import models
import datetime
#model.DateTimeField(auto_now=True, null=False) => updated_at
#model.DateTimeField(auto_now_add=True, null=False) => Default now()
# Create your models here.
class DateTimeModel(models.Model):
created_at = models.DateTimeField(default=datetime.datetime.now())
updat... | Python | 1 |
'''if get_refill['refill_way'] == "Form":
way_input = _("🥝 Способ пополнения: <code>По форме</code>", locale=lang)
elif get_refill['refill_way'] == "Nickname":
way_input = _("🥝 Способ пополнения: <code>По никнейму</code>", locale=lang)
elif get_refill['refill_w... | Python | 1 |
#!/usr/bin/env python2
import os
import sys
import re
import json
def main():
# Adapt manually.
duk = '/usr/local/bin/duk'
lzstring = '/home/duktape/duktape/lz-string/libs/lz-string.js'
duktape_repo = '/home/duktape/duktape'
duktape_testrunner_repo = '/home/duktape/duktape-testrunner'
duktape... | Python | 1 |
udio = np.concatenate((audio, white_noise), axis=-1)
aligned_len = audio.shape[-1]
return audio, aligned_len, stride_step
near_end_audio, _, _ = align_audio(near_end_audio, min_len)
far_end_audio, aligned_len, stride_step = align_audio(far_end_audio, min_len)
if SAMPLE_RATE != 16000 and not KEEP_ORIGINAL_SA... | Python | 1 |
ffixes=('', '_drop'))
df_merged = df_merged.drop(columns=['迄止日期_drop'] if '迄止日期_drop' in df_merged.columns else [])
df_merged['投注'] = df_merged['投注'].fillna('0')
df_merged['盈亏'] = df_merged['盈亏'].fillna('0')
... | Python | 1 |
self.y2, self.z2, self.x3, self.y3, self.z3,
)
};
let rotated_1 = rotate(base_tri);
let rotated_2 = rotate(rotated_1);
let same = tris_match(actual, base_tri)
|| tris_match(actual, rotated_1)
|| tris_match(actual, rotated_2);
if same {
... | Rust | 0 |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# this script shows how to create a few basic plots using seaborn and matplotlib.
# load the titanic dataset
df = pd.read_csv('titanic.csv')
# select relevant columns and drop rows with missing values for clean plotting
df = df[['Age', 'Fare', ... | Python | 1 |
import random
import numpy as np
import pytest
from pandas import DataFrame
from tests.utils import assert_dataframes_equals
from weaverbird.backends.pandas_executor.steps.rename import execute_rename
from weaverbird.pipeline.steps import RenameStep
@pytest.fixture
def sample_df():
return DataFrame({"NAME": ["f... | Python | 1 |
Some(Music { music: music_tmp })
}
}
/// Create a new music and load it from a stream (a struct implementing Read and Seek)
///
/// This function doesn't start playing the music (call [`play`] to do so).
/// Here is a complete list of all the supported audio formats:
/// ogg... | Rust | 0 |
_HEADER: Col = Some(1);
pub const COLUMN_BLOCK_BODY: Col = Some(2);
pub const COLUMN_BLOCK_UNCLE: Col = Some(3);
pub const COLUMN_META: Col = Some(4);
pub const COLUMN_TRANSACTION_ADDR: Col = Some(5);
pub const COLUMN_TRANSACTION_META: Col = Some(6);
pub const COLUMN_EXT: Col = Some(7);
pub const COLUMN_OUTPUT_ROOT: Co... | Rust | 0 |
ter(
label="Weather Bot",
message="How is the weather today?",
),
]
@cl.action_callback("action_button")
async def on_action_button(action: cl.Action):
"""Handle action button clicks."""
user = cl.user_session.get("user")
user_id = user.identifier if user else "anonymou... | Python | 1 |
'''
Tema: Mix avanzato di filter, map, reduce, lambda, any e comprehension
Obiettivo: Manipolare una lista di stringhe con più condizioni e operazioni
'''
# Esercizio Extra
# Titolo: "Analisi parole speciali"
'''
Traccia:
Scrivi una funzione analizza_parole(parole) che, data una lista di parole (stringhe), esegue i s... | Python | 1 |
import sys
import pygame
from game.interface.gui.constants import (
BOTTOM_COMPONENT_WIDTH_RATIO,
BOTTOM_COMPONENT_HEIGHT_RATIO,
TOP_COMPONENT_WIDTH_RATIO,
TOP_COMPONENT_HEIGHT_RATIO,
)
from .sprites.bottom import BottomComponentSprite
from .sprites.top import TopComponentSprite
class GraphicalInter... | Python | 1 |
oken_secret.clone())
}
}
/// Read keywords config into a vector of strings.
pub fn get_keywords() -> Vec<String> {
let keywords_path = Path::new(KEYWORDS_FILE);
let keywords_file = File::open(keywords_path).unwrap();
let keywords_json: Value = serde_json::from_reader(keywords_file).unwrap();
let k... | Rust | 0 |
#!/usr/bin/env python
# datetime:2020/6/3 11:36
from django.utils.translation import gettext_lazy as _
from dongtai_common.endpoint import R, UserEndPoint
from dongtai_common.models.deploy import IastDeployDesc
class AgentDeployInfo(UserEndPoint):
name = "api-v1-iast-deploy-info"
description = _("Agent deplo... | Python | 1 |
self, name: Symbol) -> UntypedPatternKind {
if self.is_constructor(&name) {
PatternKind::Constructor { arg: None, name }
} else {
PatternKind::Variable { name }
}
}
}
impl<E> Pass<UntypedCoreContext, E> for VarToConstructor {
type Target = UntypedCoreContext;
... | Rust | 0 |
# -*- coding:utf-8 -*-
# 作者:KKKC
import keras
from sklearn.preprocessing import Normalizer
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers... | Python | 1 |
hannel::Ch5),
5 => Ok(Channel::Ch6),
6 => Ok(Channel::Ch7),
7 => Ok(Channel::Ch8),
8 => Ok(Channel::Ch9),
9 => Ok(Channel::Ch10),
10 => Ok(Channel::Ch11),
11 => Ok(Channel::Ch12),
12 => Ok(Channel::Ch13),
13 => O... | Rust | 0 |
(board.pieces(None).count(), 32);
/// assert_eq!(board.pieces(Some(PieceColor::WHITE)).count(), 16);
/// assert_eq!(board.pieces(Some(PieceColor::BLACK)).count(), 16);
/// ```
pub fn new() -> Board {
let mut board = Board::new_clear();
board.pieces[Square::new(0, 0).to_index()] = Some(P... | Rust | 0 |
/////////
# END - EXAMPLE CUSTOM WIDGETS
# ///////////////////////////////////////////////////////////////
# RESIZE GRIPS AND CHANGE POSITION
# Resize or change position when window is resized
# ///////////////////////////////////////////////////////////////
def resize_grips(self):
... | Python | 1 |
ake(4usize)(inp)?; // 7 - 10
let mut s = String::new();
loop {
let (i, item) = not_line_ending(inp)?;
let item = std::str::from_utf8(item).unwrap();
s.push_str(item.trim_end());
let (i, _) = line_ending(i)?;
if peek(take(6usize))(i)?.1 != record_identifier {
r... | Rust | 0 |
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches
import matplotlib.cm as cm
import matplotlib.colors as mcolors
def generate_bar_chart(data, datasets, methods, title="Comparison of Settings Across Datasets",
colors=None, save_path=None):
"""
Gener... | Python | 1 |
import pytest
from jupyter_tikz import TexDocument, TexFragment
def test__str__() -> None:
# Arrange
code = "any code"
# Act
tex_template = TexFragment(code)
tex_document = TexDocument(code)
# Assert
assert str(tex_template) == code
assert str(tex_document) == code
@pytest.mark.pa... | Python | 1 |
fn can_set_current_pc() -> CoreResult<()> {
let ctx = test_codegen("* = $1234\nnop")?;
assert_eq!(ctx.current_segment().range(), 0x1234..0x1235);
assert_eq!(ctx.current_segment().range_data(), vec![0xea]);
Ok(())
}
#[test]
fn can_access_forward_declared_labels() -> CoreR... | Rust | 0 |
),
|h| h.update_gauge(value),
|| Handle::gauge(),
);
}
fn record_histogram(&self, key: Key, value: u64) {
self.inner.registry().op(
CompositeKey::new(MetricKind::Histogram, key),
|h| h.record_histogram(value),
|| Handle::histogram(),
... | Rust | 0 |
= 4;
pub const FUTEX_WAIT: u32 = 0;
pub const FUTEX_WAKE: u32 = 1;
pub const FUTEX_FD: u32 = 2;
pub const FUTEX_REQUEUE: u32 = 3;
pub const FUTEX_CMP_REQUEUE: u32 = 4;
pub const FUTEX_WAKE_OP: u32 = 5;
pub const FUTEX_LOCK_PI: u32 = 6;
pub const FUTEX_UNLOCK_PI: u32 = 7;
pub const FUTEX_TRYLOCK_PI: u32 = 8;
pub const F... | Rust | 0 |
, 1, 0) = s_1_3;
// 3 row: 2-right shift
let s_2_2 = at(state, 2, 2);
let s_2_3 = at(state, 2, 3);
*at_mut(state, 2, 3) = at(state, 2, 1);
*at_mut(state, 2, 2) = at(state, 2, 0);
*at_mut(state, 2, 0) = s_2_2;
*at_mut(state, 2, 1) = s_2_3;
// 4 row: 3-right shift <=> 1-left shift
let ... | Rust | 0 |
+ &type_annotation(¶meter.r#type, code_type))
.collect::<Vec<String>>()
.join(", ")
+ ")"
+ &type_annotation(&function_definition.return_type, code_type)
+ " => "
+ &lambda_body_to_string(&function_definition.statement_list, indent, code_type)
+ ";"
}... | Rust | 0 |
option::Option<unsafe extern "system" fn(pipeline: *mut WINBIO_PIPELINE, identity: *mut WINBIO_IDENTITY, subfactor: *mut u8, payloadblob: *mut *mut u8, payloadblobsize: *mut usize, hashvalue: *mut *mut u8, hashsize: *mut usize, rejectdetail: *mut u32) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: 'Win3... | Rust | 0 |
(x - mu) / sigma;
(1.0 + zeta * z).powf(-1.0 / zeta - 1.0) / sigma
}
}
impl UnivariateMoments for GeneralisedPareto {
fn mean(&self) -> f64 {
let (mu, sigma, zeta) = get_params!(self);
if zeta <= 1.0 {
undefined!("Mean is undefined for zeta <= 1.")
} else {
... | Rust | 0 |
CURLcode = 52;
pub const CURLE_SSL_ENGINE_NOTFOUND: CURLcode = 53;
pub const CURLE_SSL_ENGINE_SETFAILED: CURLcode = 54;
pub const CURLE_SEND_ERROR: CURLcode = 55;
pub const CURLE_RECV_ERROR: CURLcode = 56;
pub const CURLE_OBSOLETE57: CURLcode = 57;
pub const CURLE_SSL_CERTPROBLEM: CURLcode = 58;
pub const CURLE_SSL_CI... | Rust | 0 |
ples <= self.num_resolutions, f"we can only upsample {self.num_resolutions} times at most"
block_in = channels * channels_mult[self.num_resolutions - 1]
curr_res = (resolution // patch_size) // 2 ** (self.num_resolutions - 1)
self.z_shape = (1, z_channels, curr_res, curr_res)
# z to bl... | Python | 1 |
0x03, 0x00, # ██
0x07, 0x00, # ███
0x0E, 0x00, # ███
0x07, 0x00, # ███
0x03, 0x00, # ██
0x03, 0x00, # ██
0x03, 0x00, # ██
0x03, 0x00, # ██
0x03, 0xC0, # ████
0x01, 0xC0, # ███
0x00, 0x00, #
0x00, 0x00, #
0x00, 0x00, #
# @... | Python | 1 |
azyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT;
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<super::common::Point>>(
... | Rust | 0 |
data = {**config, **metrics}
data['name'] = exp_dir.name
data['only_vad'] = 'only_vad' in data['name']
all_models_data = append_data_dict(data, all_models_data)
except FileNotFoundError:
no_checkpoints.append(exp_dir)
models_data_df = create_dataf... | Python | 1 |
import os
import requests
from dotenv import load_dotenv
# Load FREEPIK_API_KEY as environment variable from .env file
load_dotenv()
API_URL = "https://api.freepik.com/v1/videos"
headers = {"x-freepik-api-key": os.getenv("FREEPIK_API_KEY"),}
common_params = {
"term": "city street portrait", # Required search ... | Python | 1 |
s['speech_path']:
alive.speak(json_args['speech_path'])
else:
return {"status": "Need speech_path!! 0.0", "receive args": json_args}, 200
elif json_args['type'] == "rhythm":
if json_args['music_path']:
alive.rhythm(j... | Python | 1 |
"""Use case for loading a schedule full days event."""
from jupiter.core.domain.concept.schedule.schedule_event_full_days import (
ScheduleEventFullDays,
)
from jupiter.core.domain.core.notes.note import Note
from jupiter.core.domain.core.time_events.time_event_full_days_block import (
TimeEventFullDaysBlock,
... | Python | 1 |
'+=============+==========+=====================+=====+==============+\n'
'| python| str| | 3891| 234936|\n'
'+-------------+----------+---------------------+-----+--------------+\n'
'|uncategorized| | 98312 bytes| 1... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | Python | 1 |
the backup modes to the CLI arguments is annotated on the
/// enum variants.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum BackupMode {
/// Argument 'none', 'off'
NoBackup,
/// Argument 'simple', 'never'
SimpleBackup,
/// Argument 'numbered', 't'
NumberedBackup,
/// Argument 'existi... | Rust | 0 |
: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Union) {
wrap_into_docblock(w, |w| {
wrap_item(w, "union", |w| {
render_attributes_in_pre(w, it, "");
render_union(w, it, Some(&s.generics), &s.fields, "", cx);
});
});
document(w, cx, it, None, Headin... | Rust | 0 |
# filename: backend/tests/test_integration_cors.py
def test_cors_configuration(logged_in_client):
response = logged_in_client.get("/", headers={"Origin": "http://localhost:3000"})
assert response.status_code == 200
assert response.headers["Access-Control-Allow-Origin"] == "http://localhost:3000"
asser... | Python | 1 |
import subprocess
import os
from app.utils import check_and_create_directory, load_json_file, save_json_file, log_event
from app.config import WHISPER_MODEL, STORAGE_PATH
def transcribe_audio(audio_file_path):
"""
Transcribe an audio file using the OpenAI Whisper model.
Parameters:
- audio_file_pa... | Python | 1 |
from operator import truediv
print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M or L: ")
pepperoni = input("Do you want pepperoni on your pizza? Y or N: ")
extra_cheese = input("Do you want extra cheese? Y or N: ")
# Base price
if size == "S":
price = 15
elif size == "M":... | Python | 1 |
cidx = int((item - color_offset) * color_ratio)
if cidx < 0:
cidx = 0
context.set_source_rgba(*palette.get(cidx))
context.rectangle(x, y, dx, dy)
if grid_width > 0:
fill()
... | Python | 1 |
arts[1])
if not _time_independent_equals(parts[2], signature):
logging.warning("Invalid cookie signature %r", value)
return None
timestamp = int(parts[1])
if timestamp < time.time() - max_age_days * 86400:
logging.warning("Expired cookie %r", value)
return None
if timesta... | Python | 1 |
address: sender.address.clone(),
value: 100.into(),
}])
.with_linear_fees(LinearFees {
constant: 10,
coefficient: 1,
certificate: 0,
})
.build();
let jormungandr_rest_address = config.get_node_address();
let _jormungan... | Rust | 0 |
import abc
from typing import TYPE_CHECKING, Optional
from pipenv.patched.pip._internal.metadata.base import BaseDistribution
from pipenv.patched.pip._internal.req import InstallRequirement
if TYPE_CHECKING:
from pipenv.patched.pip._internal.index.package_finder import PackageFinder
class AbstractDistribution(m... | Python | 1 |
ive(Clone, Debug, serde::Deserialize, PartialEq)]
#[serde(tag = "rpcStyle", content = "connection", rename_all = "camelCase")]
pub enum ChainConf {
/// Ethereum configuration
Ethereum(ethereum::Connection),
}
impl Default for ChainConf {
fn default() -> Self {
Self::Ethereum(Default::default())
... | Rust | 0 |
#Hierarchical Clustering
#Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the mall dataset
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:,[3, 4]].values
#Using the dendogram to find the optimal number of clusters
import scipy.cluster.hierarch... | Python | 1 |
os.makedirs(resdir)
shutil.copyfile(self.getInfoPlist(builddirs), os.path.join(resdir, "Info.plist"))
# make symbolic links
links = [
(["A"], ["Versions", "Current"]),
(["Versions", "Current", "Headers"], ["Headers"]),
(["Versions", "... | Python | 1 |
# https://leetcode.com/problems/number-of-operations-to-make-network-connected/
class Solution:
def makeConnected(self, n: int, connections: List[List[int]]) -> int:
adjList = {i:[] for i in range(n)}
visited = {i:False for i in range(n)}
for connect in connections:
ad... | Python | 1 |
Overflow check
}
fn job_id(&self) -> Uuid {
self.job_id
}
async fn run(&mut self, jobs: JobScheduler) {
(self.run)(self.job_id, jobs).await;
}
fn job_type(&self) -> &JobType {
&self.job_type
}
fn ran(&self) -> bool {
self.ran
}
fn set_ran(&mu... | Rust | 0 |
st_config_overrides(greeting, value, expected):
str_cfg = f"""
[project]
commands = {value}
[vars]
a = "world"
"""
overrides = {"vars.a": greeting}
assert "${vars.a}" in str_cfg
cfg = Config().from_str(str_cfg, overrides=overrides)
assert expected in str(cfg)
def test_warn_sin... | Python | 1 |
copt;
fn main() {
common::init();
// the docopt::Error::exit method automatically prints help (and version) as appropriate
let args: config::Args = Docopt::new(config::USAGE).and_then(|d|
d.help(true)
.version(Some(String::from(common::TO_UNI_VERSION)))
.deserialize()... | Rust | 0 |
let new_end = offset_end_point2(line, next, offset);
return Line2d::new(new_start, new_end);
}
pub(crate) fn offset_line(line: Line3d, prev: Option<Line3d>, next: Option<Line3d>, offset: f64) -> Line3d {
if prev.is_some() {
check_lines(prev.unwrap(), line)
}
if next.is_some() {
check_l... | Rust | 0 |
EFG', 'x') --> ABC DEF Gxxt fillvalue( t itert PY3t itt zip_longestt izip_longest( Rm t iterableR t argst output( ( s2 /home/ubuntu/Documents/Tello/Kalibracija/common.pyt grouper s
c C s| t | } t r! t | } n | j } t j | }... | Python | 1 |
#!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
# YOUR CODE HERE
if (number < 0):
number = number * -1
print(f"Last digit of -{number} is -{number % 10} and is less than 6 and not 0")
pass
elif ((number % 10) > 5):
print(f"Last digit of {number} is {number % 10} and is greater th... | Python | 1 |
KEY_RIGHT_SUPER = 347,
KEY_KB_MENU = 348,
KEY_LEFT_BRACKET = 91,
KEY_BACKSLASH = 92,
KEY_RIGHT_BRACKET = 93,
KEY_GRAVE = 96,
KEY_KP_0 = 320,
KEY_KP_1 = 321,
KEY_KP_2 = 322,
KEY_KP_3 = 323,
KEY_KP_4 = 324,
KEY_KP_5 = 325,
KEY_KP_6 = 326,
KEY_KP_7 = 327,
KEY_KP... | Rust | 0 |
nt('plotting ...')
# plt.figure(1, figsize=(12, 8))
# plt.clf()
# plt.subplot(2, 1, 1)
# plt.title('Multi Class Classification')
# plt.plot(x_plot, posterior_mean_sig, 'c', linewidth=1.)
# # plt.fill_between(x_plot, lb_sig, ub_sig, color='c', alpha=0.05, label='95% confidence')
# plt.plot(X, Y, 'k.', markersize=2, labe... | Python | 1 |
import json
from pathlib import Path
from asyncio import open_unix_connection
from typing import AsyncIterable
class SocketClient:
"""
A little facade to interact with SocketServer
"""
def __init__(self, file_descriptor_path: str):
self.__descriptor_path = Path(file_descriptor_path)
async... | Python | 1 |
import json
from copy import copy
from dataclasses import astuple
from typing import Dict
import numpy as np
from impl import types as t
from impl.buffers import make_uint_buffer
from impl.hashing import position_hash
from impl.meshes import box_geometry
from impl.repo import open_file
from impl.textures import (
... | Python | 1 |
_i8_0_16_513_15)
(i16: 0, 32, 513, 15, ri_i16_0_32_513_15)
(i32: 0, 32, 513, 15, ri_i32_0_32_513_15)
(i64: 0, 32, 513, 15, ri_i64_0_32_513_15)
}
macro_rules! range_from_into {
($(($t: ty: $mean: expr, $std_dev: expr, $length: expr, $name: ident))*) => ($(
#[test]
fn $name() {
let mut bin = Unimod... | Rust | 0 |
{}
pub struct Solution1{}
impl Solution {
pub fn pivot_index(nums: Vec<i32>) -> i32 {
if nums.len() < 3 {
return -1;
}
let mut low = 0;
let mut big = nums.len()-1;
let mut sum = 0;
while low < big {
if sum < 0 {
if ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.