text string | label_name string | labels int64 |
|---|---|---|
from rest_framework import serializers
from .models import Course, Module, Material, UserProgress, Signup, Video
class CourseSerializer(serializers.ModelSerializer):
class Meta:
model = Course
fields = '__all__'
class ModuleSerializer(serializers.ModelSerializer):
class Meta:
model = M... | Python | 1 |
"""Tests for :mod:`peagen.core.keys_core`.
These exercises the plugin resolution path used by ``create_keypair``.
"""
from __future__ import annotations
from pathlib import Path
from peagen.core import keys_core
class DummyRef:
"""Simple container mimicking a key reference returned by a provider."""
mate... | Python | 1 |
ls/checkpoint_{episode}.pth')
# Save final model
agent.save_model('models/final_model.pth')
plt.figure(figsize=(8,4))
plt.plot(agent.value_trace, label='Value (pred)')
plt.plot(agent.return_trace, label='Return (target)')
plt.title('Critic Prediction vs. Empirical Return')
plt.xlabel(... | Python | 1 |
(Long, 2), LCONST_1, DIV(Long), STORE(Long, 2),
LOAD(Long, 2), LCONST_1, REM(Long), STORE(Long, 2),
LOAD(Long, 2), NEG(Long), STORE(Long, 2),
LOAD(Long, 2), BIPUSH(1), SHL(Long), STORE(Long, 2),
LOAD(Long, 2), BIPUSH(1), SHR... | Rust | 0 |
match value.write_to_buffer_with_ctx( Endianness::NATIVE, slice ) {
Ok( _ ) => {},
Err( error ) => {
match get_error_kind( &error ) {
ErrorKind::OutputBufferIsTooSmall { expected_size, .. } => {
static_assert!( *expected_size == 6 );
}... | Rust | 0 |
from pprint import pprint
import yaml
with open('../DATA/mongo.yaml') as mongo_in:
mongo_data = yaml.load(mongo_in, Loader=yaml.BaseLoader)
pprint(mongo_data)
| Python | 1 |
(false, BearerKind::Tcp) => PeerMode::AsNode,
#[cfg(target_family = "unix")]
(false, BearerKind::Unix) => PeerMode::AsClient,
};
let output: Option<String> = match args.is_present("output") {
#[cfg(feature = "logs")]
true => Some(args.value_of_t("output")?),
_ => None,
... | Rust | 0 |
for i in range(self.accountListWidget.count()):
item = self.accountListWidget.item(i)
widget = self.accountListWidget.itemWidget(item)
if widget and widget.account_name == account_name:
# 从test_list中移除对应的测试功能
if widget.test_cookie in self.test_list:
... | Python | 1 |
if func_type != "i64 (i64)*" {
return Err(LlvmError(format!("Run function has wrong type: {}", func_type)));
}
Ok(())
}
/// Optimize an LLVM module using a given LLVM optimization level.
unsafe fn optimize_module(module: LLVMModuleRef, optimization_level: u32)
-> Result<(), LlvmError> {
let... | Rust | 0 |
ler(rng)
},
);
}
fn observe(
&mut self,
z: &VectorN<f64, ZD>,
h: impl Fn(&VectorN<f64, D>) -> VectorN<f64, ZD>,
_h_normalize: impl Fn(&mut VectorN<f64, ZD>, &VectorN<f64, ZD>),
_hx: &MatrixMN<f64, ZD, D>,
noise: &CorrelatedNoise<f64, ZD>,
... | Rust | 0 |
chor/Vanchor-common responses -------- */
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
pub struct EdgeInfoResponse {
pub src_chain_id: u64,
pub root: [u8; 32],
pub latest_leaf_index: u32,
pub target: [u8; 32],
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq... | Rust | 0 |
#!/usr/bin/env python3
"""
Test script for the lesson-specific video validation system
"""
import sys
import os
import json
# Add the current directory to Python path so we can import the main scraper
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_lesson_validation_functions():
"""Test a... | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | Python | 1 |
ransceiver")
}
offer, err := opc.CreateOffer(nil)
if err != nil {
t.Errorf("Plan B CreateOffer failed: %s", err)
}
mdNames := getMdNames(offer.parsed)
assert.ObjectsAreEqual(mdNames, []string{"video", "audio", "data"})
apc, err := NewPeerConnection(... | Rust | 0 |
:new(width.into(), height.into()).to_logical(mon.get_hidpi_factor()),
).with_fullscreen(Some(mon));
let ctx = glutin::ContextBuilder::new()
.with_vsync(false)
.with_multisampling(4)
.with_double_buffer(Some(true))
.with_srgb(true);
let win = Gl... | Rust | 0 |
key.into().raw();
unsafe {
let val = AnyObject::from_raw(ruby::rb_hash_aref(self.raw(), key));
if val.is_nil() {
None
} else {
Some(V::cast_unchecked(val))
}
}
}
/// Returns the number of key-value pairs in `self`.... | Rust | 0 |
u16,
pub sounds: Vec<Sound>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Sound {
pub id: Hash40,
pub unk1: u16,
pub prob: u16,
pub unk2: i16,
pub unk3: i16,
pub unk4: u32,
}
pub fn from_stream<C: Read + Seek>(reader: &mut C) -> Result<SequenceBank, Error> {... | Rust | 0 |
*"]
pub fn value(this: &SvgAngle) -> f32;
# [wasm_bindgen (structural , method , setter , js_class = "SVGAngle" , js_name = value)]
#[doc = "Setter for the `value` field of this object."]
#[doc = ""]
#[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/SVGAngle/value)"]
... | Rust | 0 |
# imports
import cv2
from cvzone.PoseModule import PoseDetector
from gpiozero import Motor
from time import sleep
detector = PoseDetector()
# Create a VideoCapture object
cap = cv2.VideoCapture(0)
# Define the stepper motor
motor = Motor(forward=33, backward=35)
def move_stepper_motor(direction):
if direction ... | Python | 1 |
) }
}
pub mod graph;
pub mod segmentation;
use std::fs;
use anyhow::{Context, Result};
fn main() -> Result<()> {
let path = "not_exists_file.txt";
fs::read(path)
.context(format!("Failed to read instrs from {}", path))?;
// fs::read(path)
// .with_context(|| format!("Failed to read instrs ... | Rust | 0 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# NO CHECKED-IN PROTOBUF GENCODE
# source: flights.proto
# Protobuf Python Version: 6.30.2
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descri... | Python | 1 |
e pickle is a bytes object,
it's wrapped in a BytesIO object, and the latter's tell() result is
used. Else (the pickle doesn't have a tell(), and it's not obvious how
to query its current position) pos is None.
)r8 )r r r r r s r c C s d}d}t }i... | Python | 1 |
deadc0de {
//! panic!("Unknown frame-format!");
//! }
//! // We know the size of the now following data
//! let mut buf = vec![0; size];
//! r.read_exact(&mut buf).and(Ok(buf))
//! }
//!
//! /// Write the given data as a new frame to the given writer.
//! pub fn w... | Rust | 0 |
}
};
let find_arg = |arg: &Arg| -> Result<(u32, Option<usize>, OpArg), String> {
// Returns the length, the id (for variables) and the OpArg.
Ok(match arg {
Arg::Const(Value::Bit(b)) => (1, None, OpArg::Cst(vec!(*b))),
Arg::Const(Value::BitArray(a)) => (a.len() as u3... | Rust | 0 |
request!(
self,
BuffersFromPixmapRequest {
pixmap,
..Default::default()
}
)
}
#[inline]
pub fn buffers_from_pixmap_immediate(
&mut self,
pixmap: Pixmap,
) -> crate::Result<BuffersFromPixmapReply> {
let b... | Rust | 0 |
# -*- coding: UTF-8 -*-
# vim: set expandtab sw=4 ts=4 sts=4:
#
# phpMyAdmin web site
#
# Copyright (C) 2008 - 2016 Michal Cihar <michal@cihar.com>
#
# This program 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 Foundati... | Python | 1 |
C)]
#[derive(Debug, Copy, Clone)]
pub struct Tcl_HashKeyType {
pub version: ::std::os::raw::c_int,
pub flags: ::std::os::raw::c_int,
pub hashKeyProc: Tcl_HashKeyProc,
pub compareKeysProc: Tcl_CompareHashKeysProc,
pub allocEntryProc: Tcl_AllocHashEntryProc,
pub freeEntryProc: Tcl_FreeHashEntryPro... | Rust | 0 |
users may execute transformations on.
pub fn source<S>(self, builder: SourceBuilder<S>) -> Stream<S::Item>
where
S: Source,
{
self.source_to_stream(SourceBuilderType::Single(builder))
}
fn source_to_stream<S, B>(self, builder_type: SourceBuilderType<S, B>) -> Stream<S::Item>
wh... | Rust | 0 |
, p = result.x
s = 1.0-p
print("Computed parallel fraction of p={:5.5f}".format(p))
print("Test ID is {:s}".format(testid))
n = linspace(1,nps.max())
speed = T1/times
times_model = execution_time(T1, p, s, n)
speed_model = T1/times_model
speed_ideal = n
fig = plt.figure(figsize=(8,6))
ax = plt.gca()
ax.plot(nps, spe... | Python | 1 |
# Generated by Django 3.2.6 on 2021-08-29 19:36
import cloudinary.models
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('product', '0001_initial'),
('order', '0001... | Python | 1 |
# Copyright (c) DP Technology.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function
import logging
import copy
import os
import pandas as pd
import numpy as np
import csv
from typing... | Python | 1 |
f torch.cuda.is_available() else "cpu")
print("device is set to: ", device, '\n')
prm = Mistral_PRM(prm_base_model)
prm.load_state_dict(torch.load(state_dict_file))
prm.to(device)
prm.eval()
return prm_tokenizer, prm
# local value model: str->digit in [low, high]
def get_local_value(prompt_ans... | Python | 1 |
ecomposed as follows:
/// ```text
/// R(roll, yaw, pitch) == R_x(roll) * R_y(yaw) * R_z(pitch)
/// ```
/// The corresponding rotation matrices are
/// ```text
/// | 1 0 0 |
/// R_x(roll) := | 0 cos(roll) -sin(roll) |
/// | 0 sin(rol... | Rust | 0 |
= batch_sizes
def compiled_sampler_for_task(self, task: sinter.Task) -> sinter.CompiledSampler:
return self
def sample(self, suggested_shots: int) -> sinter.AnonTaskStats:
self.batch_sizes.append(suggested_shots)
return sinter.AnonTaskStats(
shots=suggested_shots,
... | Python | 1 |
l_pinger_system
.stop_notify(&small_pinger)
.wait_timeout(STOP_COMPONENT_TIMEOUT)
.expect("Pinger never stopped!");
ponger_system
.kill_notify(ponger)
.wait_timeout(STOP_COMPONENT_TIMEOUT)
.expect("Ponger never died!");
small_pinger.on_definition(|c| {
as... | Rust | 0 |
an:
// use std::cmp::Ordering;
// use std::io;
// Do this:
// use std::{cmp::Ordering, io};
// There's also a glob operator:
// use std::collections::*;
// To bring in code from src/foo.rs:
// mod foo;
fn chapter07() {
// Paths in the module tree:
// Relative path:
parent::child_one::foo();
... | Rust | 0 |
*get_values(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING),
]
or model_class.__name__ == "LevitForImageClassificationWithTeacher"
):
continue
for problem_type in problem_types:
with self.subTest(msg=f"Testing {model_class} with {... | Python | 1 |
ash_map::{Entry, HashMap},
hash::Hash,
marker::PhantomData,
},
};
/// Descriptors layout for `SparseDescriptors`.
#[derive(Debug)]
pub struct SparseDescriptorsLayout<T> {
raw: DescriptorSetLayout,
cap: u32,
marker: PhantomData<fn() -> T>,
}
impl<T> DescriptorsLayout for SparseDescripto... | Rust | 0 |
# Copyright (C) 2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from os import walk, path
from utils.helpers import CfgError
from pathlib import Path
# WA to keep CI job working until we add requirements
try:
import yaml
except:
import subprocess
import sys
p = subprocess.Popen('{} -m pip... | Python | 1 |
InitResponse {
messages: ctx.messages,
attributes: ctx.attributes,
})
}
}
}
impl<T> From<Context<T>> for HandleResponse<T>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
fn from(ctx: Context<T>) -> Self {
HandleResponse {
mess... | Rust | 0 |
failed to connect to the AP")
tp = get_camera_connection_guided(camera_password)
if format_sd:
tp.format_sd_card()
tp.get_sdcard_info() # This is not necessary but is part of the tapo app process so have kept it
if camera_alias:
tp.set_device_alias(camera_alias)
tp.set_third_use... | Python | 1 |
$ctxarg.op_arg_load_term_at($arg_pos, $procarg.get_heap_mut());
};
// Take a term from IP, and assert it is a CP or a NIL
(
$vmarg:ident, $ctxarg:ident, $procarg:ident, $arg_pos:expr,
cp_or_nil($arg_ident:ident)
) => {
let $arg_ident = $ctxarg.op_arg_read_term_at($arg_pos);
debug_assert!($arg_... | Rust | 0 |
atingPoint> {
let (v_raw, i_raw) = raw.split_at(v_fmt.digits);
let voltage = v_fmt.parse(v_raw)?;
let current = i_fmt.parse(i_raw)?;
Ok(OperatingPoint { voltage, current })
}
}
impl Index<PresetIndex> for Presets {
type Output = OperatingPoint;
fn index(&self, i: PresetInd... | Rust | 0 |
to_ref)]
::std::mem::transmute::<_, &::std::ffi::CStr>(
&[#(#bytes),*] as *const [u8] as *const ::std::ffi::CStr
)
}
})
}
Err(Error(span, msg)) => {
let span = span.into();
quote_spanned!(... | Rust | 0 |
display')
m = phyDispRE.search(out)
if m:
for prop in ['width', 'height']:
displayInfo[prop] = int(m.group(prop))
for prop in ['density']:
# In mPhysicalDisplayInfo density is already a factor, no need to calculate
displayInfo[prop... | Python | 1 |
3, Rn: 31, Rd: 31, }.encode().decode(),
Instruction::SQNEG_asimdmisc_R { Q: 1, size: 3, Rn: 31, Rd: 31, })
}
#[test]
fn roundtrip_CMGE_asimdmisc_Z() {
assert_eq!(Instruction::CMGE_asimdmisc_Z { Q: 1, size: 3, Rn: 31, Rd: 31, }.encode().decode(),
Instruction::CMGE_asimdmisc_Z { Q: 1... | Rust | 0 |
# Generated by Django 4.0.8 on 2024-12-27 18:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('quiz', '0006_rename_choice_text_es_choice_choice_text_kk_and_more'),
]
operations = [
migrations.RemoveField(
model_name='choice',
... | Python | 1 |
ount the given [`ir::ItemImpl`].
///
/// # Details
///
/// Given
/// - the callable's identifier `i`
/// - the optionally set callable's selector `s`
/// - the impl blocks trait path in case it implements a trait, `P`
/// - the impl blocks optional user provided namespace `S`
///
/// Then the selector is composed in th... | Rust | 0 |
();
unsafe {
Widget::from_glib_none(ffi::gtk_image_menu_item_new_with_label(label.to_glib_none().0)).downcast_unchecked()
}
}
#[cfg_attr(feature = "v3_10", deprecated)]
pub fn new_with_mnemonic(label: &str) -> ImageMenuItem {
assert_initialized_main_thread!();
un... | Rust | 0 |
16;
SerializableFileAttr {
size: stat.st_size as u64,
blocks: stat.st_blocks as u64,
atime: SerializableTimespec {
sec: stat.st_atime as i64,
nsec: stat.st_atime_nsec as i32,
},
mtime: SerializableTimespec {
sec: stat.st_mtime as i64,
... | Rust | 0 |
akingContract::get_key_staking_contract(),
Account::Staking(staking_contract),
);
Ok(())
}
}
<reponame>cssivision/slings
use std::io;
use std::ops::Sub;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Instant;
use crate::driver::{self, Action};
pub mod delay;
pub mod... | Rust | 0 |
hello HTTP/1.1\r\nHost: localhost\r\n\r\n\r\n";
let message = http::HttpMessage {
header: http::HttpHeader::Method(
http::HttpVersion::V11,
http::HttpMethod::Get("/hello".to_string()),
),
headers: [("Host".to_string(), "localhost".to_string())]
.iter()
... | Rust | 0 |
test_simple_object() {
let string = r#"{"asd":"sdf", "dfg":"fgh"}"#;
let value = Value::parse(string).unwrap();
let expected_value = Value::Object(vec![
("asd".into(), Value::String("sdf".into())),
("dfg".into(), Value::String("fgh".into())),
]);
assert_eq!(value, expected_value);... | Rust | 0 |
e time;
pub struct GameHandler<G,R,RenderData,Exit>
where G: Game<(),RenderData,Exit>,
R: Renderer;
impl<G,R,RenderData,Exit> GameHandlerTrait<G,R,RenderData,Exit> for GameHandler<G,R,RenderData,Exit>
where G: Game<(),RenderData,Exit>,
R: Renderer
{
fn run(&self,renderer: R,game: &mut G) -> Exit{
/... | Rust | 0 |
# Copyright (c) OpenMMLab. All rights reserved.
from .angle_coder import CSLCoder
from .delta_midpointoffset_rbbox_coder import MidpointOffsetCoder
from .delta_xywha_hbbox_coder import DeltaXYWHAHBBoxCoder
from .delta_xywha_rbbox_coder import DeltaXYWHAOBBoxCoder
from .distance_angle_point_coder import DistanceAnglePoi... | Python | 1 |
"""
Infrastructure层 - 任务队列基础设施
提供Celery等任务队列的技术实现
"""
__version__ = "1.0.0"
__all__ = [] | Python | 1 |
es (so 0 is the first frame)
# update/draw components on each frame
# *pump* updates
if t >= 0.0 and pump.status == NOT_STARTED:
# keep track of start time/frame for later
pump.tStart = t # not accounting for scr refresh
pump.frameNStart = frameN # exact frame index
win.tim... | Python | 1 |
rlandırma) veya "remove" (silme) seçenekleri.
"""
Q1 = dataframe[col].quantile(0.25)
Q3 = dataframe[col].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
outliers = dataframe[(dataframe[col] < lower_bound) | (dataframe[col] > upper_bound)]
num_outli... | Python | 1 |
axis=1)
prob.to_csv(os.path.join(self.fold_path, f'{self.taskid}_{self.classifier}_{count}_prob.csv'))
return y_pred
def one_feature_train(self, X_train, y_train, X_test, y_test):
if self.optimization is not None:
self.logger.info(f'Select the best params...............')
... | Python | 1 |
std::{
fs::File,
io::{Cursor, Read},
path::{Path, PathBuf},
};
use rodio::{Decoder, OutputStream, OutputStreamHandle, Source};
use rtools::data_manager::LoadFromPath;
pub struct Sound {
_path: PathBuf,
_stream: OutputStream,
stream_handle: OutputStreamHandle,
data: ... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 17-9-30 下午4:01
# @Author : Luo Yao
# @Site : http://github.com/TJCVRS
# @File : establish_char_dict.py
# @IDE: PyCharm Community Edition
"""
Establish the char dictionary in order to contain chinese character
"""
import json
import os.path as ops
import ... | Python | 1 |
= now();
assert_eq!(ts2 - ts1, Duration::from_millis(333));
clock.adjust_by(Duration::from_millis(111));
let ts3 = now();
assert_eq!(ts3 - ts1, Duration::from_millis(444));
clock.set_time(ts1);
assert_eq!(ts1, now());
// Switch back to the original clock
... | Rust | 0 |
let paramaters: Vec<&str> = command.split_whitespace().collect();
for word in paramaters.iter().skip(1) {
result.push(word);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_search_parameters() {
let empty_vec: Vec<&str> = Vec::new();
assert_eq!(em... | Rust | 0 |
<u16>() {
Ok(count) => count,
Err(_) => return Err(format!("Cannot parse digital out port count: \"{}\"", ports[1]))
};
let analog_in = match ports[2].parse::<u16>() {
Ok(count) => count,
Err(_) => return Err(format!("Cannot parse ... | Rust | 0 |
til
// we're sure the subsystem has done pruning.
async fn wait_for_pruning(&self) {
Delay::new(self.pruning_config.pruning_interval * 2).await
}
}
impl Default for TestState {
fn default() -> Self {
let persisted_validation_data = PersistedValidationData {
parent_head: HeadData(vec![7, 8, 9]),
block_num... | Rust | 0 |
ioner_from_conditioning_config(conditioning_config)
cross_attention_ids = diffusion_config.get('cross_attention_cond_ids', [])
add_cond_ids = diffusion_config.get('add_cond_ids', [])
global_cond_ids = diffusion_config.get('global_cond_ids', [])
input_concat_ids = diffusion_config.get('input_concat_ids'... | Python | 1 |
import asyncio
import json
import aiohttp
SCHOOL_URL_FMT = 'http://educacao.dadosabertosbr.com/api/escola/{}'
SEARCH_SCHOOL_URL = (
'http://educacao.dadosabertosbr.com/api/escolas/buscaavancada?'
'situacaoFuncionamento=1&energiaInexistente=on&aguaInexistente=on&'
'esgotoInexistente=on'
)
@asyncio.corou... | Python | 1 |
# -*- coding: utf-8 -*-
# basic colors
BLACK = "\033[30m"
RED ="\033[31m"
GREEN ="\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
# bright colors
BRIGHT_BLACK = "\033[90m"
BRIGHT_RED = "\033[91m"
BRIGHT_GREEN = "\033[92m"
BRIGHT_YELLOW = "\033[93m"
BRIGHT_BLUE ... | Python | 1 |
None);
}
use crate::config::VitStartParameters;
use crate::scenario::controller::VitController;
use crate::scenario::controller::VitControllerBuilder;
use crate::{config::Initials, Result};
use assert_fs::fixture::{ChildPath, PathChild};
use chain_crypto::SecretKey;
use chain_impl_mockchain::testing::scenario::templat... | Rust | 0 |
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('api/v1/timetable/', consumers.TimetableConsumer.as_asgi()),
] | Python | 1 |
pub const ARATAKI_ITTO_SKILL: AratakiIttoSkillType = AratakiIttoSkillType {
normal_dmg1: [0.7923, 0.8568, 0.9213, 1.0134, 1.0779, 1.1516, 1.253, 1.3543, 1.4557, 1.5662, 1.6929, 1.8419, 1.9908, 2.1398, 2.3023],
normal_dmg2: [0.7637, 0.8258, 0.888, 0.9768, 1.039, 1.11, 1.2077, 1.3054, 1.403, 1.5096, 1.6317, 1.77... | Rust | 0 |
[]
yy = []
minx = 0.0
for a in range(tot_timestep):
minx = ti.min(agent.traj[a, 0, 0], minx)
xx.append(a)
yy.append(agent.traj[a, 0, 0])
print("min traj x:", minx)
plt.clf()
plt.plot(xx, yy)
... | Python | 1 |
# SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""Atmel SAMA5 pin names"""
from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
PD23 = Pin(119)
AD4 = PD23
PD21 = Pin(117)
AD2 = PD21
PD20 = Pin(116)
AD1 = PD20
PD24 = Pin(120)
AD5 = ... | Python | 1 |
class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
def dijakstras(start, graph):
dist = [float('inf')] * (n+1)
minheap = [(0, start)]
dist[start] = 0
while minheap:
old_dist , node = heapq.heappop(minhe... | Python | 1 |
def chain_of_thought_prompt(user_input):
prompt = (
"Think about the following question one step at a time:\n"
f"{user_input}\n"
"“Break down your reasoning and provide an answer."
)
return prompt | Python | 1 |
esult<Option<K>>,
// MF: Fn(MI, KF) -> Result<MT>,
// MI: std::iter::Iterator<Item = (usize, &'a Meta)>,
// {
// let mut metas: Vec<(_, &'a _)> = Vec::new();
// let mut lits = Vec::new();
// for (i, nmeta) in self.iter().enumerate() {
// match nmeta {
// ... | Rust | 0 |
if domain is None:
continue
v_cookies = {}
for c in v['request']['cookies']:
v_cookies[c['name']] = c['value']
if len(v_cookies) > 0:
CookiesConfig.cookies[domain] = v_cookies
new_cook... | Python | 1 |
number = int(input("enter a number"))
count = 0
for each in range(1,number+1):
if (each % 2):
print() | Python | 1 |
# The MIT License (MIT)
# Copyright © 2023 Yuma Rao
# Copyright © 2023 const
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the “Software”), to deal in the Software without restriction, including without limitation
# the rights to u... | Python | 1 |
, mem: &[u8]) -> bool{
let mut pixel_turned_off = false;
for (byte_number, block) in mem.iter().enumerate(){
let y = (sy as usize + bit_number) % HEIGHT;
for but_number in 0..8 {
let x = (sx as usize + bit_number) % WIDTH;
let current_pixel = self.... | Rust | 0 |
::get_revs(&repo, start_oid_excluded, end_oid_included).unwrap();
let summaries: Vec<String> = rev_walk.map(|oid| repo.find_commit(oid.unwrap()).unwrap().summary().unwrap().to_string()).collect();
assert_eq!(summaries.len(), 2);
assert_eq!(summaries.first().unwrap(), "four, five, six, and seven... | Rust | 0 |
new_df[col_name] = single_value
else:
raise ValueError(
f"Column '{col_name}' must have either 'col_id' or 'single_value'."
)
# Special case handling
if col_name == "diagnosis":
new_df[col_name] = new_df[col_name].fillna("nan")
#... | Python | 1 |
: *const ::std::os::raw::c_char);
}
extern "C" {
pub fn Rf_doIdle(dd: pDevDesc);
}
extern "C" {
pub fn Rf_doesIdle(dd: pDevDesc) -> Rboolean;
}
extern "C" {
pub static mut R_interrupts_suspended: Rboolean;
}
extern "C" {
pub static mut R_interrupts_pending: ::std::os::raw::c_int;
}
extern "C" {
pub ... | Rust | 0 |
RE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TC1MCI0_RE`"]
pub type TC1MCI0_RE_R = crate::R<bool, TC1MCI0_RE_A>;
impl TC1MCI0_RE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TC1MCI0_RE_A {
match self.bits {
false... | Rust | 0 |
8 = ints_3[b_6 as usize];
masks[i_5] = i_8;
let mut i_9 = 0;
let mut i_10 = 0;
let mut i_11 = 0;
let mut i_12_1 = 0;
if i_8 & i_7 != 0 {
i_9 = ints_3[(b_6 - 1) as usize];
} else {
... | Rust | 0 |
for iev, ev in enumerate(ev_run):
status = cl.command_execution_status.to_string(
ev.command_execution_status)
if _DEBUG > 20:
print("ctx status {0} {1}".format(iev, status))
if slicedRWArgs is not Non... | Python | 1 |
rocess_apple_health_file(
file_path=sample_xml_file,
start_date=start_date,
end_date=end_date
)
# Should have predictions for filtered period
assert len(result.daily_predictions) <= 14
assert result.records_processed > 0
# Check that dates ar... | Python | 1 |
"""add severity range
Revision ID: 5f1d2027ec67
Revises: e4c1903496cb
Create Date: 2025-05-13 15:45:25.683218+00:00
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5f1d2027ec67'
down_revision = 'e4c1903496cb'
branch_labels = None
depends_on = None
def upgrad... | Python | 1 |
#Napisz program rozwiązujący (tzn. obliczający miejsca zerowe) trójmianu kwadratowego, np. 3x^2+5x-20
print("Program obliczy x1 i x2 trójmianu kwadratowego.")
a = float(input("Podaj współczynnik a: "))
b = float(input("Podaj współczynnik b: "))
c = float(input("Podaj współczynnik c: "))
delta = b**2 - 4 * a * c
pi... | Python | 1 |
ly(ply_path, xyz, SH2RGB(shs) * 255)
# try:
# pcd = fetchPly(ply_path)
# except:
# pcd = None
# scene_info = SceneInfo(point_cloud=pcd,
# train_cameras=train_cam_infos,
# test_cameras=test_cam_infos,
# nerf_nor... | Python | 1 |
SimpleTimeline <NodeVarying<Physics>, Physics::Steward>>,
}
#[derive (Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
pub enum NodeVarying<Physics: TreeContinuumPhysics> {
#[serde(deserialize_with = "::serde::Deserialize::deserialize")]
Branch (BranchVarying <Physics>),
#[serde(deserialize_with = "::serde::... | Rust | 0 |
"""
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 under the Apache License, Version 2.0 (the
"License"); you may not use this ... | Python | 1 |
'''
Names: nick nojiri & ariel winkler
Date: 1/30/2025
Description: Three card monte
'''
import check_input
import random
def three_card_monte( bank ):
"""the main game, asks you how much you want to bet and to choose a card. bank is how much money you have. we return bank acting as our balance."""
p... | Python | 1 |
_body.code_mut(), total_func) > 0 {
need_grow_counter = true;
}
}
}
},
&mut elements::Section::Export(ref mut export_section) => {
for ref mut export in export_section.entries_mut() {
if let &mut elements::Internal::Function(ref mut func_index) = export.internal_mut() {
if *fu... | Rust | 0 |
.hidden_state, sorted_indices)
#
#
# self.check_forward_args(x, self.hidden_state, batch_sizes)
# #if batch_sizes is None:
# result =[]#gru(x, self.hidden_state, self._flat_weights, self.use_bias, self.num_layers,
# self.dropout_rate, self.training, self.bidirectional, s... | Python | 1 |
def even(x):
return x % 2 == 0
c = [3, 7, 1, 18, 9, 12, 5, 2, 22, 10]
n = len(c)
h = []
for i in range(0, n):
for j in range(0, n - i - 1):
if c[j] > c[j + 1]:
c[j], c[j + 1] = c[j + 1], c[j]
for i in range(0, n - 1):
h = filter(even, c)
ans = list(h)
print(ans)
| Python | 1 |
import pyLCIO
import numpy as np
import uproot
reader = pyLCIO.IOIMPL.LCFactory.getInstance().createLCReader()
reader.open("/local/d1/mu+mu-/sim/1000_10_sim.slcio")
for ievt, event in enumerate(reader):
print("Event", ievt)
mcpCollection = event.getCollection("MCParticle")
for mcp in mcpCollection:
... | Python | 1 |
ive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
enum SensorType {
Bool,
Numeric,
String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
struct Asset {
id: String,
#[serde(skip_serializing_if = "Option::is_none")]
is_plant: Option<bo... | Rust | 0 |
.write_u8(name_bytes[i])?;
}
match self.joined {
false => writer.write_u8(0)?,
true => writer.write_u8(1)?,
}
writer.write_u64(self.seqno)?;
Ok(())
}
}
// the Readable implmentation for deserializing ServerInfo
impl Readable for ServerInfo {
fn read<R: Reader>(reader: &mut R) -> Result<Self, Error... | Rust | 0 |
from flask import jsonify, request
from flask_jwt_extended import jwt_required
from api import api_bp
from dataBase.querys import obtenerAlumnos, registrarAlumno, editarAlumno, eliminarAlumno
@api_bp.route('/alumnos', methods=['GET'])
@jwt_required()
def getAlumnos():
alumnos=obtenerAlumnos()
return jsonif... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.