text string | label_name string | labels int64 |
|---|---|---|
nto(),
).log(|m| debug!("Got new certificate: {:?}", m))
}
fn get_time_to_replace(&self) -> &Duration {
&self.replace_after
}
fn update_cache(&self, cache: &mut Cache) {
cache
.certificates
.insert(self.common_name.clone(), self.clone());
}
}
/// Th... | Rust | 0 |
ss, };
use std::fmt;
use std::io::Read;
use std::convert::TryFrom;
// SeiMessage
// SeiMessageKind
pub trait SeiMessage: fmt::Debug {
fn kind(&self) -> SeiMessageKind;
fn len(&self) -> usize;
fn as_bytes(&self) -> &[u8];
}
// SEI Payloads: Annex D ( Page 350 )
#[derive(Debug, Clone, Copy, PartialEq, Eq... | Rust | 0 |
"""Test functions for grid command."""
from easyviztest import *
class test_grid_basic(EasyvizTestCase):
def check_grid_on(self):
x,y,v,w = self.get_line_data()
plot(x,y)
grid('on')
title("plot(..);grid('on')")
n()
def check_grid_on_kwarg(self):
x,y,v,... | Python | 1 |
WUPE8_W { w: self }
}
#[doc = "Bits 2:3 - Wakeup Pin Enable For LLWU_P9"]
#[inline(always)]
pub fn wupe9(&mut self) -> WUPE9_W {
WUPE9_W { w: self }
}
#[doc = "Bits 4:5 - Wakeup Pin Enable For LLWU_P10"]
#[inline(always)]
pub fn wupe10(&mut self) -> WUPE10_W {
WUP... | Rust | 0 |
case("1 * 2", "mul(1, 2)"),
case("1 / 2", "div(1, 2)"),
case("1 ** 2", "exp(1, 2)"),
case("1 % 2", "mod(1, 2)"),
case("1 & 2", "and(1, 2)"),
case("1 | 2", "or(1, 2)"),
case("1 ^ 2", "xor(1, 2)"),
case("1 << 2", "shl(2, 1)"),
case("1 >> 2", "shr(2, 1)")
... | Rust | 0 |
(1 << 10),
file_format: file_format,
}
}
pub(crate) fn with_path<P: AsRef<Path>>(&self, path: P) -> ReaderResult<Reader<File>> {
Ok(Reader::new(self, File::open(path)?, self.file_format.clone()))
}
#[allow(dead_code)]
pub(crate) fn with_reader<R: io::Read>(&self, rdr: ... | Rust | 0 |
def calculate_price(
num_people: int,
is_agreement_client: bool = False,
student_ratio: float = 0.0,
senior_ratio: float = 0.0,
long_distance: bool = False,
hotel_package: bool = False,
employee: bool = False,
) -> int:
"""
根据七里扬帆三江口游线价格政策计算总价。
参数:
num_people : 游... | Python | 1 |
# Code generated by Lark OpenAPI.
import lark_oapi as lark
from lark_oapi.api.apaas.v1 import *
def main():
# 创建client
client = lark.Client.builder() \
.app_id(lark.APP_ID) \
.app_secret(lark.APP_SECRET) \
.log_level(lark.LogLevel.DEBUG) \
.build()
# 构造请求对象
request: A... | Python | 1 |
dbus_proxy(property)]
fn aam_enabled(&self) -> zbus::Result<bool>;
/// AamSupported property
#[dbus_proxy(property)]
fn aam_supported(&self) -> zbus::Result<bool>;
/// AamVendorRecommendedValue property
#[dbus_proxy(property)]
fn aam_vendor_recommended_value(&self) -> zbus::Result<i32>;
... | Rust | 0 |
"body": {"success": True}
}
}
]
}
integration_tests["api_endpoints"].append(test_scenario)
testing["unit_tests"] = unit_tests
testing["integration_tests"] = integration_tests
# Performance tests
... | Python | 1 |
.to_string());
}
result.into()
}
(Node::Value(ref set_path), _) => {
let ref_vec: Vec<&InnerData> = set_path.iter().collect();
let r = ctx.set_path(&ref_vec, array);
if r.is_err() {
return Data::check(r);
}
... | Rust | 0 |
if let Some(s) = sort {
url.query_pairs_mut().append_pair("sort", &s);
};
self.client.get(url.as_str()).send()?.json()
}
/// Full text search for matching concepts across the entire database.
pub fn search_concepts<'a>(&self,
search: &'a str,
... | Rust | 0 |
# MADE BY @MDEVIO ON GITHUB
from config import time, os, string, random
from config import Fore
from config import TiktokUsernameChecker
def username_generator():
"""
Generates usernames with a specified amount of characters
"""
while True:
try:
amount_of_usernames = int(input("\nHo... | Python | 1 |
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('blog.urls')),
path('api-auth/', include('rest_framework.urls')),
]
| Python | 1 |
t Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(type(e).__name__, str(e))
def DescribeEdgeClusterInstances(self, request):
"""查询边缘计算集群的节点信息
:param request: Request instance for Describ... | Python | 1 |
Internal function for converting from a channel to a port
*
* # Failure
*
* Fails if the port is detached or dead. Fails if the port
* is owned by a different task.
*/
fn as_raw_port<T: Send, U>(ch: comm::Chan<T>, f: fn(*rust_port) -> U) -> U {
struct PortRef {
p: *rust_port,
drop {
... | Rust | 0 |
from .views import ProductListAPIView, ProductRetrieveAPIView
__all__ = ["ProductListAPIView", "ProductRetrieveAPIView"]
| Python | 1 |
03 << 28)) | ((value as u32 & 0x03) << 28);
self.w
}
}
#[doc = "Field `CH1_LCTRL_MODE_U5` reader - This register is used to control the mode of channel1's low control signal for unit5. 2'd0:increase when control signal is low 2'd1: decrease when control signal is high others:forbidden"]
pub struct CH1_LCTRL... | Rust | 0 |
lazy_static! {
static ref RE: Regex = Regex::new(r"(?:[0-9a-fA-F]{3}){1,2}").unwrap();
}
RE.find(&val).and_then(|x| Some(x.as_str().to_string()))
}
fn in_range(num: u32) -> bool {
num < 256
}
fn hex_to_rgba(val: &str) -> Option<(u32, u32, u32)> {
// skip the first char if #
let mut p... | Rust | 0 |
# Code generated by Lark OpenAPI.
from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type
from lark_oapi.core.construct import init
class BatchDeleteEcoExamPaperRequestBody(object):
_types = {
"account_id": str,
"paper_id_list": List[str],
}
def __init__(self, d=None... | Python | 1 |
lif action == 2 and paddle1_y < 300:
correct_actions += 1
total_actions += 1
# Calculate accuracy, ensuring not to divide by zero
accuracy = correct_actions / total_actions if total_actions > 0 else 0
accuracies.append(accuracy)
avg_reward = total_r... | Python | 1 |
::new();
opts.set_wait(wait);
ffi_try!(crocksdb_flush_cf(self.inner, cf.inner, opts.inner));
Ok(())
}
}
/// Flushes multiple column families.
/// If atomic flush is not enabled, flush_cfs is equivalent to
/// calling flush_cf multiple times.
/// If atomic... | Rust | 0 |
MediaFoundation'*"]
pub const MF_MEDIA_ENGINE_USE_PMP_FOR_ALL_CONTENT: MF_MEDIA_ENGINE_PROTECTION_FLAGS = 2i32;
#[doc = "*Required features: 'Win32_Media_MediaFoundation'*"]
pub const MF_MEDIA_ENGINE_USE_UNPROTECTED_PMP: MF_MEDIA_ENGINE_PROTECTION_FLAGS = 4i32;
#[doc = "*Required features: 'Win32_Media_MediaFoundation'... | Rust | 0 |
() -> Self {
Self::new()
}
}
impl ProtocolRunnerService for ProtocolRunnerServiceDummy {
fn try_recv(&mut self) -> Result<ProtocolRunnerResponse, ResponseTryRecvError> {
Err(ResponseTryRecvError::Empty)
}
fn spawn_server(&mut self) {}
fn init_runtime(&mut self, _: TezosRuntimeConf... | Rust | 0 |
al
// A user is new in a channel and uses the rituals feature to send a message letting
// the chat know they are new.
// "<Sender> is new to <Channel>'s chat! Say hello!"
// msg-param-ritual-name - only valid value: "new_chatter"
"ritual" => UserNoticeEvent::... | Rust | 0 |
(CHECKSUM_TEMPLATE, checksum);
}
Ok(MaybeLock::Download {
url,
descriptor: pkg.to_string(),
})
}
pub(super) fn finish_download(
cache_path: &Filesystem,
config: &Config,
pkg: PackageId,
checksum: &str,
data: &[u8],
) -> CargoResult<File> {
// Verify what we just dow... | Rust | 0 |
t {
true => {
// forward
sender_vec.push(from);
packet_sender
.send((buf, size, remote_socket.clone()))
.unwrap();
}
false => {
// backward
if sender_vec.len() < 1 ... | Rust | 0 |
name, idx, len(js.keys()))
feat = [js[name]["output"][1]["tokenid"].split()]
nbest_hyps = model.translate(feat, args, train_args.char_list)
new_js[name] = add_results_to_json(
js[name], nbest_hyps, train_args.char_list
)
else:
... | Python | 1 |
t]
fn line_count_one_line() {
let w = 80_u16;
let styles = vec![PrintableStyle::All(true), PrintableStyle::Common(true)];
for s in styles {
assert_line_count!(RG_JSON_BEGIN, w, s, 1, &[]);
assert_line_count!(RG_JSON_MATCH, w, s, 1, &[1, 1]);
assert_line_co... | Rust | 0 |
```python
# Importing necessary libraries
import unittest
from src.testing import Testing
from tensorflow_data_validation.utils.testing import assert_anomalies_equal
from great_expectations.core import ExpectationSuiteValidationResult
from unittest.mock import patch, MagicMock
class TestTesting(unittest.TestCase):
... | Python | 1 |
inelist: *mut cavc_plinelist) {
if !plinelist.is_null() {
drop(Box::from_raw(plinelist))
}
}
/// Get the number of polylines inside a [cavc_plinelist].
///
/// `count` used as out parameter to hold the polyline count.
///
/// ## Specific Error Codes
/// * 1 = `plinelist` is null.
///
/// # Safety
///
/... | Rust | 0 |
INTO event (id, room_id, kind, set, label, data, occurred_at, created_by, created_at)
SELECT
id,
room_id,
kind,
set,
label,
data,
-- Monotonization
-- cutstarts and cutstops are left as is to avoid skew
(... | Rust | 0 |
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# 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 a... | Python | 1 |
"dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_18")))]
pub fn direction(&self) -> WebRTCRTPTransceiverDirection {
glib::ObjectExt::property(self, "direction")
}
#[cfg(any(feature = "v1_18", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_18")))]
pub fn ... | Rust | 0 |
.8, yaw_delta, commands, None)
agent.perform_py(intent)
chase_target = chaser.step_chase_py(agent, delta)
dynamics.update_agent_dynamics_py(agent, env, chase_target, delta)
just_pressed.clear()
collisions = world.collisions_py(agent.get_pos(), [0.5, 0.5, 0.3])
if... | Python | 1 |
aved_stdout = os.dup(1)
os.close(0)
os.close(1)
stdin = os.open('/dev/tty', os.O_RDONLY)
stdout = os.open('/dev/tty', os.O_RDWR)
return saved_stdin, saved_stdout
def restore_stdio((saved_stdin, saved_stdout)):
os.close(0)
os.close(1)
os.dup(saved_stdin)
os.dup(saved_stdout)
if __na... | Python | 1 |
pub async fn get_feedback_count_for_course(
conn: &mut PgConnection,
course_id: Uuid,
) -> ModelResult<FeedbackCount> {
let res = sqlx::query!(
"
SELECT COUNT(*) filter (
where marked_as_read
) AS read,
COUNT(*) filter (
where not(marked_as_read)
) AS unread
FROM feedback
WHERE course... | Rust | 0 |
compare_mode: Some($compare_mode)
});
};
}
macro_rules! test_definitions {
($name:ident {
path: $path:expr,
mode: $mode:expr,
suite: $suite:expr,
default: $default:expr,
host: $host:expr,
compare_mode: $compare_mode:expr
}) => {
#[derive(Debug... | Rust | 0 |
# agents.py
from mcp_client import MCPHealthcareClient, run_async
class DiagnosisAgent:
def __init__(self, mcp_client: MCPHealthcareClient):
self.mcp_client = mcp_client
async def run_async(self, symptoms: str) -> str:
return await self.mcp_client.call_tool("diagnose_symptoms", symptoms)
... | Python | 1 |
== "lang": Print some chars on stdout and stderr, and halt (fast).
program == "slow": Print some chars on stdout and stderr, and halt (slow).
program == "crasher": Print some chars but crash after a while.
program == "looper": Print things very slowly, forever.
program == "talker": Print things very fa... | Rust | 0 |
:impl Serialize) {
let text = serde_json::to_string(&message).unwrap();
self.when_stalled_send_text_message(text);
}
}
use rune_tests::*;
#[test]
fn test_hash_map_tile() {
let _: () = rune! {
pub fn main() {
use std::collections::HashMap;
enum Tile {
... | Rust | 0 |
== "text":
text = page.text
else:
return "⚠️ Invalid `content_type`. Use either 'summary' or 'text'."
return f"✅ **Wikipedia Page:** {title}\n\n**Content:** {text}\n\n🔗 **Read more:** {url}"
except Exception as e:
return f"Error fetching Wi... | Python | 1 |
nsmute(object));
}
#[inline]
unsafe fn reify(base: &'a Reified<Hold<'a> + 'a>) -> &'a (Hold<'a> + 'a) {
mem::transmute(base.reify())
}
}
use crate::Face;
use crate::buffer::Buffer;
use crate::plan::ShapePlan;
pub fn apply(plan: &ShapePlan, face: &Face, buffer: &mut Buffer) -> Option<()> {
... | Rust | 0 |
v, div25);
// multiply remainder by divisor so the remainder becomes an integer
let a = _mm256_mulhi_epu16(v_rem5, mul5);
let b = _mm256_mulhi_epu16(v_rem25, mul5);
let c = _mm256_mulhi_epu16(v, div25);
// interleave 8-bit chunks from 3 vectors
l... | Rust | 0 |
fn test_intersection_between_trees() {
let rectangles1 = create_random_rectangles(100, SEED_1);
let rectangles2 = create_random_rectangles(42, SEED_2);
let mut intersections_brute_force = Vec::new();
for rectangle1 in &rectangles1 {
for rectangle2 in &rectangles2 {
... | Rust | 0 |
class Solution:
def longestPalindrome(self, s: str) -> str:
res = ""
max_len = 0
for i in range(len(s)):
l, r = i, i
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r-l+1) > max_len:
res = s[l:r+1]
max_len = (... | Python | 1 |
lf._random_state = check_random_state(self.random_state)
def _new_learning_node(self, initial_stats=None, parent_node=None,
is_active=True):
"""Create a new learning node. The type of learning node depends on the tree
configuration."""
if initial_stats is None:
... | Python | 1 |
ier(YulIdentifier),
YulFunctionCall(YulFunctionCall),
#[serde(rename_all = "camelCase")]
UnhandledYulExpression {
node_type: String,
src: Option<String>,
id: Option<NodeID>,
},
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub s... | Rust | 0 |
buf.put_u64_le(self.index);
}
pub fn decode(buf: &mut &[u8]) -> Self {
let group = buf.get_u64_le();
let index = buf.get_u64_le();
Self { group, index }
}
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Mask {
pub group: u64,
pub index: u64,
}
impl Mask {
p... | Rust | 0 |
te bkground and black text
def printWhiteBlack_2(mess):
set_cmd_text_color(0xf0)
sys.stdout.write(mess)
resetColor()
#黄底蓝字
#white bkground and black text
def printYellowRed(mess):
set_cmd_text_color(BACKGROUND_YELLOW | FOREGROUND_RED)
sys.stdout.write(mess)
resetColor()
#####################... | Python | 1 |
}
fn reduce(&mut self, action: Self::Action) -> Changed {
match action {
Action::Increment => {
self.count += 1;
true
}
}
}
}
type AppDispatch = DispatchProps<ReducerStore<Counter>>;
struct App {
dispatch: AppDispatch,
}
impl Co... | Rust | 0 |
erface for the cube.
#[derive(UniformInterface)]
struct EnvironmentMappingShaderInterface {
#[uniform(unbound)]
projection: Uniform<[[f32; 4]; 4]>,
#[uniform(unbound)]
view: Uniform<[[f32; 4]; 4]>,
#[uniform(unbound)]
aspect_ratio: Uniform<f32>,
#[uniform(unbound)]
environment: Uniform<TextureBinding<Cu... | Rust | 0 |
while True:
print('forward')
a = input()
n = int(a)
if n == 8:
break
if n%2 == 0:
continue
print('fix') | Python | 1 |
tiiuae/falcon-40b-instruct",
# "Baichuan-7B": "baichuan-inc/Baichuan-7B",
# "Baichuan-13B": "baichuan-inc/Baichuan-13B-Base",
# "Baichuan-13B-Chat": "baichuan-inc/Baichuan-13B-Chat",
# "Baichuan2-7B": "baichuan-inc/Baichuan2-7B-Base",
# "Baichuan2-13B": "baichuan-inc/Baichuan2-13B-Base",
# "Baic... | Python | 1 |
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
import random
class HuDongSpiderSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defin... | Python | 1 |
LUSTER as u64)
}
fn write_zero_sector<H>(handle: &mut H) -> Result<(), Error>
where
H: io::Write,
{
handle.write_all(&[0; create::BYTES_PER_SECTOR as usize])?;
Ok(())
}
fn write_fat32_fat<H>(
handle: &mut H,
directory_hierarchy: &directory_hierarchy::DirectoryHierarchy,
) -> Result<(), Error>
wher... | Rust | 0 |
self.socket
.write_all(&self.send_buffer)
.context("Failed to send message")?;
Ok(())
}
}
// All of these structs are used to communicate with Criterion.rs. The benchmarks may be running
// any version of Criterion.rs that supports cargo-criterion, so backwards com... | Rust | 0 |
nteger + Ord,
{
let mut sparse_align_prob_mat = SparseProbMat::<T>::default();
for (i, align_probs) in align_prob_mat.iter().enumerate() {
let i = T::from_usize(i).unwrap();
for (j, &align_prob) in align_probs.iter().enumerate() {
if align_prob >= min_align_prob {
let j = T::from_usize(j).unwr... | Rust | 0 |
ors.ConnectionClose):
if hasattr(closable, "_close_connection"):
closable._close_connection() # pylint:disable=protected-access
elif isinstance(exception, errors.MessageHandlerError):
if hasattr(closable, "_close_handler"):
... | Python | 1 |
#! /usr/bin/env python
# Copyright (c) 2007, PediaPress GmbH
# See README.txt for additional licensing information.
from xml.sax.saxutils import escape as xmlescape
from mwlib.rendering.formatter import Formatter
from mwlib.writers.rl import pdfstyles
class RLFormatter(Formatter):
def __init__(self, font_switc... | Python | 1 |
e top)
{
// Triangle a-b-c
{
// Index 24 (a)
res.copy_within(v_range(5), x_start(24));
// Index 25 (b)
res.copy_within(v_range(1), x_start(25));
// Index 26 (c)
res.copy_within(v_range(11), x_start(26));
}
// ... | Rust | 0 |
)
current_tag_name = TAG_TABLE.get(tag.tag_id, str(tag.tag_id))
pts = tag.corners.astype(int)
last_box_pts = pts
box_lost_counter = BOX_PERSISTENCE
else:
current_tag_name = None
if box_lost_counter > 0:
... | Python | 1 |
from django.contrib import admin
from .models import Profile,Friendship
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
list_display = ['id','user','email','date_of_birth', 'city', 'get_phot... | Python | 1 |
#!/usr/bin/env python3
"""Configuration management for CourtListener MCP Server."""
from pydantic_settings import BaseSettings
class Config(BaseSettings):
"""Configuration for CourtListener MCP Server."""
# Server settings
host: str = "0.0.0.0"
mcp_port: int = 8785
# Logging
courtlistener_l... | Python | 1 |
uninitialized() };
let len = unsafe { ffi::xkb_keysym_get_name(keysym, buf.as_mut_ptr(), 64) };
if len < 0 {
failure::bail!("{} is not a valid keysym.", keysym)
}
let buf: [u8; 64] = unsafe { std::mem::transmute(buf) };
let s = std::str::from_utf8(&buf[..len as usize])?.to_string();
Ok(s... | Rust | 0 |
se_unchecked_animation)
p.drawEllipse(QPointF(xPos, barRect.center().y()),
self._pulse_radius, self._pulse_radius)
if self.isChecked():
p.setBrush(self._bar_checked_brush)
p.drawRoundedRect(barRect, rounding, rounding)
p.setBrush(self._h... | Python | 1 |
<16)+((source[4*x+1]as u32)<<8)+(source[4*x+0]as u32);
}
}
fn fe25519_sub (out:&mut[u32;8],basevalue:&[u32;8],valuetosubstract:&[u32;8]) {
let mut accu:i64;
accu = basevalue[7] as i64;
accu = accu - (valuetosubstract[7] as i64);
out[7]=(accu as u32)| 2147483648 ;
accu = (19 * (((accu >> 31) as i32) -... | Rust | 0 |
z { precision } => {
*precision = TimestampPrecision::from_typmod(typmod)?
}
Type::VarChar { max_length } => *max_length = CharLength::from_typmod(typmod)?,
_ if typmod != -1 => return Err("type does not support type modifiers".into()),... | Rust | 0 |
pr(C)]
pub struct CHANNEL {
#[doc = "0x00 - Load Count Register"]
pub load_count: self::channel::LOAD_COUNT,
#[doc = "0x04 - Current Value Register"]
pub current_value: self::channel::CURRENT_VALUE,
#[doc = "0x08 - Control Register"]
pub control: self::channel::CONTROL,
#[doc = "0x0c - Inter... | Rust | 0 |
&mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Font").finish()
}
}
use std::collections::BTreeSet;
use proc_macro2::TokenStream;
use quote::quote;
use syn::{punctuated::Punctuated, Expr, Token};
use yarte_dom::dom::{Document, Element, Expression, Node, VarId};
use crate::wasm::client::solver:... | Rust | 0 |
1 => Ok(reshaped.remove(0).into()),
_ => Ok(Value::Partitions(reshaped.into_iter().enumerate()
.map(|(idx, data)|
(IndexKey::from(idx as Integer), data.into()))
.collect::<IndexMap<IndexKey, Value>>()))
... | Rust | 0 |
(gen));
conf.compile_protos(&["service.proto"], &["../"]).unwrap();
}<reponame>cmaves/rustable
use async_std::channel::bounded;
use async_std::task::spawn;
use std::num::NonZeroU16;
use super::*;
use crate::properties::{PropError, Properties};
use async_rustbus::RpcConn;
/// A GATT service that is to be added to... | Rust | 0 |
#!/usr/bin/env python3
"""Investigate the intended behavior and documentation."""
import sys
sys.path.insert(0, '/root/hypothesis-llm/envs/troposphere_env/lib/python3.13/site-packages')
# Check the actual regex pattern and error message
import re
from troposphere import valid_names
print("Troposphere validation deta... | Python | 1 |
impl for<'a> FnMut() + 'static) -> Result<PinNotifySubscription<$pin>, EspError> {
PinNotifySubscription::subscribe(self, callback)
}
}
}
}
impl_input_pin_notify!(esp_idf_hal::gpio::Gpio0<Input>);
impl_input_pin_notify!(esp_idf_hal::gpio::Gpio1<Input>);
impl_input_pin_notify!(es... | Rust | 0 |
week from now.
let in_one_week = Utc::now().checked_add_signed(Duration::weeks(1)).unwrap();
if date > Utc::now().date().naive_utc() && date <= in_one_week.date().naive_utc() {
// We are in the future.
// Create an Airtable record.
let meeting = M... | Rust | 0 |
cc = dp.RCC.constrain();
let ccdr = rcc
.use_hse(25.mhz())
.sys_ck(400.mhz())
.pll2_strategy(rcc::PllConfigStrategy::FractionalNotLess)
.pll2_p_ck(12_288_000.hz())
.pll2_q_ck(6_144_000.hz())
.pll2_r_ck((48_000 * 63).hz())
// pll2_p / 2 --> mco2
.mco2_f... | Rust | 0 |
ovy);
matrix[r * 2 + 2] = -(zfar - znear) / (zfar - znear);
matrix[r * 2 + 3] = -1.0;
matrix[r * 3 + 2] = -(2.0 * zfar * znear) / (zfar - znear);
if flip_y {
matrix[r * 1 + 1] *= -1.0;
}
matrix
}
}
use super::{Material, Shape};
use crate::{Matrix4x4, Point, Vector};
use std::f64::const... | Rust | 0 |
-> usize {
self.length
}
}
#[cfg(test)]
mod tests {
use super::*;
#[macro_export]
macro_rules! assert_eq_f32 {
($left:expr, $right:expr $(,)?) => {{
assert!(($left - $right).abs() < f32::EPSILON);
}};
}
#[test]
fn basic() {
// Radiotap Header v... | Rust | 0 |
property('Priority', newrow.priority)
row.title = newrow.message
if (newrow.command == "a" or newrow.command == "A" or
newrow.command == "Artigo"):
row.set_property('Tags', "Artigo")
row.icon = "📰"
print("\033[92m" + f"Artigo: {... | Python | 1 |
R R% R( R) R* ( RZ t idxRT R ( ( sk /private/var/folders/vy/31wknkcs30l6xb2fzgwnrkh80000gn/T/pip-build-H4rTmN/pip/pip/_vendor/distlib/compat.pyR s ( R. R/ R] R R ( ( ( sk /private/var/folders/vy/31wknkcs30l6xb2fzgwnrkh80000gn/T/pip-build-H4r... | Python | 1 |
"""Add retest fields to Pattern model"""
import sqlite3
def upgrade():
"""Add new columns for retest functionality"""
conn = sqlite3.connect('instance/app.db')
cursor = conn.cursor()
# Add new columns
cursor.execute('ALTER TABLE pattern ADD COLUMN retest_status TEXT NOT NULL DEFAULT "none"')
... | Python | 1 |
must be a number.")
return
# Get channel info from all channels
all_channels = get_all_channels()
channel = None
for ch in all_channels:
if ch[0] == channel_id: # channel_id is first element
channel = (ch[1],) # channel_name is second element
break
... | Python | 1 |
//!
//! # Basic usage
//!
//! The quickest way to generate recommendations is by creating a [`Recommender`],
//! adding objects and tags and calling the by using the [`object_recommendations`]
//! method.
//!
//! ```
//! use pixie_rust::recommender::Recommender;
//!
//! let mut recommender: Recommender<String> = Recomm... | Rust | 0 |
let len = self.order.len() - 1;
&self.order[0..len]
}
pub(crate) fn order_last(&self) -> u32{ *self.order.last().unwrap() }
/// string data users can append in this item's filename.
pub fn tag(&self) -> Option<&str>{ self.tag.as_ref().map(|s| s.as_str()) }
/// calculate the filename from ... | Rust | 0 |
pend(
_VALUE.fields_by_name['struct_value'])
_VALUE.fields_by_name['struct_value'].containing_oneof = _VALUE.oneofs_by_name['kind']
_VALUE.oneofs_by_name['kind'].fields.append(
_VALUE.fields_by_name['list_value'])
_VALUE.fields_by_name['list_value'].containing_oneof = _VALUE.oneofs_by_name['kind']
_LISTVALUE.fields... | Python | 1 |
data: web::Data<AppData>, info: web::Json<LoginRequest>) -> HttpResponse {
let access_token = LoginService::try_login(&data.pool, &info.username, &info.password).await;
if let Ok(access_token) = access_token {
HttpResponse::Ok().json(LoginResponse { access_token })
} else {
HttpResponse::Fo... | Rust | 0 |
amBitmap>())).StreamSize as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(_TStreamBitmap),
"::",
stringify!(StreamSize)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_TStreamBitmap>())).BitmapSize as *cons... | Rust | 0 |
assert_eq!(msg.args(), "world");
assert_eq!(
msg.key_values(),
vec![("name".to_owned(), "\"chashu\"".to_owned())]
);
assert_eq!(logger.len(), 0);
}
use chrono::NaiveDateTime;
use crate::models::AlbumId;
use crate::schema::album_names;
pub type AlbumNameId = i32;
#[derive(Debug, Queryable... | Rust | 0 |
inline(always)]
#[deprecated = "You can just read the `IntegrationParams::dt` value directly"]
pub fn dt(&self) -> Real {
self.dt
}
/// The inverse of the time-stepping length, i.e. the steps per seconds (Hz).
///
/// This is zero if `self.dt` is zero.
#[inline(always)]
pub fn i... | Rust | 0 |
: parse_opt("transparency", &mut it, WithSid::parse)?,
index_of_refraction: parse_opt("index_of_refraction", &mut it, WithSid::parse)?,
})
}
}
impl XNodeWrite for Blinn {
fn write_to<W: Write>(&self, w: &mut XWriter<W>) -> Result<()> {
let e = Self::elem().start(w)?;
WithSid... | Rust | 0 |
sampler (i.e. MSAA ones do not). Optimally, we'd want to
/// encode this logic into the type system (TODO).
pub type TextureParam<R: Resources> = (handle::Texture<R>, Option<handle::Sampler<R>>);
/// An error type on either the parameter storage or the program side
#[derive(Clone, PartialEq, Debug)]
pub enum Paramete... | Rust | 0 |
@pytest.mark.parametrize('test_name, entry_point', tests)
def test_entry_point(test_name, entry_point):
print(f'Testing {entry_point}')
folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__))
) + '/tests_results'
os.makedirs(folder, exist_ok=True)
stdout_fd = open(os.path.join(folder... | Python | 1 |
e is not correct"
print " " + "For metadata record 1, ocpode is", opcode, "while expected value is" + color.END, stopZLMOpcode
sys.exit(1)
elif messageSize != 0:
print " " + color.RED + color.BOLD + "FAIL, message size is not correct"
print " " + "For metadata record 1, message size is", messag... | Python | 1 |
# Example file for Advanced Python: Language Features by Joe Marini
# strings and bytes are not directly interchangeable
# strings contain unicode, bytes are raw 8-bit values
# define some starting values
b = bytes([0x41, 0x42, 0x43, 0x44])
print(b)
s = "This is a string"
print(s)
# TODO: Try combining them.
# TODO... | Python | 1 |
let ret = unsafe{
getpeername(sockfd, addr as *mut sockaddr, addrlen as *mut socklen_t)
};
return Self::GetRet(ret as i64)
}
pub fn GetSockOpt(_taskId: u64, sockfd: i32, level: i32, optname: i32, optval: u64, optlen: u64) -> i64 {
let sockfd = match Self::GetOsfd(soc... | Rust | 0 |
import os
import threading
import time
import queue
import urllib.parse
from utils.shentools import *
class SymlinkChecker:
def __init__(
self, cloud_path, source_folder, target_folder, symlink_mode, num_threads=4
):
self.cloud_path = cloud_path
self.source_folder = source_folder
... | Python | 1 |
50;
/// SQUARE_D7 represents square 'd7' of a chess board
pub const SQUARE_D7: Square = 51;
/// SQUARE_E7 represents square 'e7' of a chess board
pub const SQUARE_E7: Square = 52;
/// SQUARE_F7 represents square 'f7' of a chess board
pub const SQUARE_F7: Square = 53;
/// SQUARE_G7 represents square 'g7' of a chess boa... | Rust | 0 |
# model_trainer.py
import random
import numpy as np
from collections import Counter
from ..GraphManager.graph_processor import GraphProcessor
import networkx as nx
from ..ModelGenerator.model_generator import ModelGenerator
from abc import ABC, abstractmethod
class ModelTrainer:
"""
所有训练器的基类。
负责绑定 AdaptoFl... | Python | 1 |
s to positions in P->x"]
#[doc = " @param P_new_n Number of new elements to be changed"]
#[doc = " @return output flag: 0: OK"]
#[doc = " 1: P_new_n > nnzP"]
#[doc = " <0: error in the update"]
pub fn osqp_update_P(
... | Rust | 0 |
resources.append(res)
return resources
class NativeSecurityGroupExceptions(object):
@staticmethod
def raise_invalid_property(msg):
raise exception.Invalid(msg)
@staticmethod
def raise_group_already_exists(msg):
raise exception.Invalid(msg)
@staticmethod
def ... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.