text string | label_name string | labels int64 |
|---|---|---|
jectShape<Square, Horizontal, Vertical>,
}
}
/// What style of rendering for this object
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum ObjectRender {
/// Standard, non-affine rendering
Normal = 0,
/// Affine rendering
Affine = 1,
/// Object disabled (saves cycles for elsewhere!)
Disa... | Rust | 0 |
import pandas as pd
TrainFeature_best_score=pd.read_csv('train_27-29.csv')
TestFeature_best_score=pd.read_csv('test.csv')
print('加入4个时间特征')
TrainFeature_best_score['clickTime_day']=TrainFeature_best_score['clickTime'].apply(lambda x:str(x)[0]+str(x)[1])
TestFeature_best_score['clickTime_day']=TestFeature_best_s... | Python | 1 |
// The final dot forces this to be an FQDN, otherwise the search rules as specified
// in `ResolverOpts` will take effect. FQDN's are generally cheaper queries.
//let response = resolver.lookup_ip("example.com.").unwrap();
// This is a list of servers you can test the code against. Feel free to edit
... | Rust | 0 |
"""Logging facilities.
"""
from __future__ import print_function
import sys
def warn(msg, **kw):
to_log(msg)
_warn_nolog(msg, **kw)
def info(msg, **kw):
to_log(msg)
_info_nolog(msg, **kw)
def _warn_nolog(msg, **kw):
print(msg, file=sys.stderr)
def _info_nolog(msg, **kw):
print(msg)
d... | Python | 1 |
yle.0,
bMenu as i32,
dwExStyle.0,
)
},
)
}
/// [`DispatchMessage`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-dispatchmessagew)
/// function.
pub fn DispatchMessage(lpMsg: &MSG) -> isize {
unsafe { user32::DispatchMessageW(lpMsg as *const _ as *const _) }
}
/// ... | Rust | 0 |
= Result<Fragment, Error>> + Send + Sync;
/// Serves a request to retrieve blocks identified by the list of `ids`
/// Resloves to a stream of blocks to send to the remote client peer.
async fn get_fragments(&self, ids: FragmentIds) -> Result<Self::GetFragmentsStream, Error>;
/// The type of outbound ... | Rust | 0 |
: DWORD = 0x80000800;
pub const TAPE_DRIVE_ABSOLUTE_BLK: DWORD = 0x80001000;
pub const TAPE_DRIVE_ABS_BLK_IMMED: DWORD = 0x80002000;
pub const TAPE_DRIVE_LOGICAL_BLK: DWORD = 0x80004000;
pub const TAPE_DRIVE_LOG_BLK_IMMED: DWORD = 0x80008000;
pub const TAPE_DRIVE_END_OF_DATA: DWORD = 0x80010000;
pub const TAPE_DRIVE_RE... | Rust | 0 |
BOARD,
Anonymous: INPUT_0 { ki: kb_int_down }
},
INPUT {
r#type: INPUT_typeFlags::INPUT_KEYBOARD,
Anonymous: INPUT_0 { ki: kb_int_up }
}
]
}
/// Translates a string key representation to the virtual key code as Windows uses.
///
/// Not every possible one... | Rust | 0 |
entation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT H... | Rust | 0 |
ervice_environment_formset__complete__incorrect(repository):
form = ServiceEnvironmentsFormSet(
{**service_environments_form__set_data, "environments-0-dashboard_url": "-"}
)
assert not form.is_valid()
assert form.forms[0].errors == {"dashboard_url": ["Enter a valid URL."]}
def test_service_li... | Python | 1 |
import matplotlib.pyplot as plt
from ticker_fetch import get_nse_tickers
from data_fetcher import download_historical_data
# PLOTS in Same plot
def plot_data(symbols, x_axis, y_axis, start_date, end_date, timeframe="1d"):
plt.figure(figsize=(10, 6)) # Adjust figure size if needed
for symbol in symbols:... | Python | 1 |
import re
import numpy as np
class TextCleaner:
def __init__(self):
pass
def _remove_emoji(self, text: str) -> str:
# remove emojies
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300... | Python | 1 |
default="ยังไม่ดำเนินการ"
)
is_active: bool | None = None
updated_at: datetime| None = Field(
description="updated time",
default_factory=datetime.now
)
updated_by: str | None = Field(
description="updated by",
default="Admin"
)
# updated_at: datetime | N... | Python | 1 |
presacolocacionxmlgenerator.FrmPrincipal$21
empresacolocacionxmlgenerator.FrmPrincipal$43
empresacolocacionxmlgenerator.FrmPrincipal$8
empresacolocacionxmlgenerator.FrmPrincipal$40
empresacolocacionxmlgenerator.FrmPrincipal$9
empresacolocacionxmlgenerator.FrmPrincipal$41
empresacolocacionxmlgenerator.FrmPrincipal... | Rust | 0 |
port.as_bytes()),
(b"path", self.path.as_bytes()),
(b"registerProcedure", self.register_procedure.as_bytes()),
(b"protocol", self.protocol.as_bytes()),
];
element.extend_attributes(attrs.into_iter().cloned());
writer.write_event(Event::Empty(element))?;
... | Rust | 0 |
ore: ChannelCore::new(capacity),
slots: Slot::make_boxed_array(capacity),
recycle,
});
let tx = Sender {
inner: inner.clone(),
};
let rx = Receiver { inner };
(tx, rx)
}
/// Synchronously receives values from associated [`Sender`]s.
///
/// Instances of this struct are creat... | Rust | 0 |
import pytest
from gitlab import GitlabGetError
from gitlabform.gitlab.python_gitlab import PythonGitlab
from unittest.mock import MagicMock
class TestPythonGitlab:
def test_get_member_role_id_cached_gets_role_id_from_roles_in_group_on_saas(self):
group_name = "Test"
role_name = "custom_role"
... | Python | 1 |
r, 'a, 'tcx>,
code: &'tcx Self,
) -> bool {
self.parenthesized == code.parenthesized
&& self.args.attempt_match(state, &*code.args)
&& self.bindings.attempt_match(state, &*code.bindings)
}
}
impl Matchable for hir::GenericArg {
fn attempt_match<'r, 'a, 'tcx>(
... | Rust | 0 |
= T_ext[:3, :3]
t = T_ext[:3, 3]
fs.write('extrinsic_rotation', R)
fs.write('extrinsic_translation', t)
fs.write('timeshift_cam_imu', time_offset)
fs.release()
return True
def readExtFileOpencv(extrin_filepath):
fs = cv.FileStorage(extrin_filepath, cv.FileStorage_READ)
# rotation axis t... | Python | 1 |
p(self):
"""
This returns the group associated with a voms proxy on disk
"""
status, output, message = self.shell.cmd1(
'voms-proxy-info -file "%s" -vo' % self.location
)
if status != 0:
return None # No VO
vo_list = output.split(':')
... | Python | 1 |
execution of the fiber or start execution if it
/// hasn't already started.
///
/// # Return value
///
/// If `false` is returned then the fiber has reached a suspension
/// point. Fibers in this state can be resumed again.
///
/// If `true` is returned then the fiber has completely fin... | Rust | 0 |
"""
Write a python function to return the negative numbers in a list.
assert neg_nos([-1,4,5,-6]) == [-1,-6]
"""
def neg_nos(list):
return [x for x in list if x < 0]
print(neg_nos([-1,4,5,-6]))
/python_basics/python_basics_1.py
"""
Write a python function to return the sum of the numbers in a list.
assert sum_nos... | Python | 1 |
, 0x8, 0x80, 0, 0, 0, 0,
// arg name "abcdabcd" (no padding - already word-aligned)
0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64,
// arg value
0x9, 0, 0, 0, 0, 0, 0, 0,
];
("test_word_size_arg_name", record, expected_result)
}
fn test_no_args() -> TestCase {
let timestamp ... | Rust | 0 |
from abc import abstractmethod
from typing import Any
class Usecase:
"""
Usecase base class
"""
@abstractmethod
def execute(self, *args: Any):
"""
execute single usecase
"""
raise NotImplementedError("must override usecase execute") # pragma: no cover
| Python | 1 |
+ str(data[5])
+ ","
+ str(data[6])
+ ","
+ str(data[7])
+ ","
+ str(data[8])
) # パケットを作成
# print(str_data)
send_data = str_data.encode("utf-8") # バイナリに変換
sel... | 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 |
"]
#[inline(always)]
pub fn sptef(&self) -> SPTEF_R {
SPTEF_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - SPI Match Flag"]
#[inline(always)]
pub fn spmf(&self) -> SPMF_R {
SPMF_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - SPI Read Buffer Full Flag... | Rust | 0 |
"""Инициализируем callbacks"""
# Передаем инстансы с модуля dash_osv
#pylint: disable=wrong-import-position
from .. import dash_app
# , engine_cons
# import ics.dashapp1.pages.callbacks
import front_ex.dashapp1.pages.callbacks
| Python | 1 |
j: usize, AValue: *mut TRect);
pub fn LinkLabel_GetClientHeight(AObj: usize) -> i32;
pub fn LinkLabel_SetClientHeight(AObj: usize, AValue: i32);
pub fn LinkLabel_GetClientOrigin(AObj: usize, Result: *mut TPoint);
pub fn LinkLabel_GetClientRect(AObj: usize, Result: *mut TRect);
pub fn LinkLabel_GetClientWidth(... | Rust | 0 |
format!("{} ({} {})", env!("CARGO_PKG_VERSION"), build_params::version::get(), build_params::date::get());
let mut cli = App::new("Cargo Rune")
.bin_name("cargo rune")
.author(&*authors)
.version(env!("CARGO_PKG_VERSION"))
.long_version(&*version)
.about(env!("CARGO_PKG_DES... | Rust | 0 |
se:
if pair.count(i) == 1:
cl.append(dict['Pair'][dict['Pair'].index(i) + 1][0])
elif trip.count(i) == 1:
cl.append(dict['Trips'][dict['Trips'].index(i) + 1][0])
... | Python | 1 |
scope_visitor.visit_module(&module, &module);
let root_scope = scope_visitor.consume();
Ok(root_scope)
},
);
assert!(r.is_ok());
let scope_manager = r.unwrap();
let root_scope = scope_manager.get_root_scope();
assert_eq!(root_scope.kind, ScopeKind::Program);
asser... | Rust | 0 |
re calling
the wrapped function.
See :func:`check_onnx_install` for more info.
param min_version: The minimum version for onnx that it must be greater than
or equal to, if unset will require no minimum version
:type min_version: str
:param max_version: The maximum version for onnx that it m... | Python | 1 |
input::TextInput::new(
&mut self.input_state,
"Введите сюда текст...",
&self.input,
Message::InputChanged,
)
.size(20)
.padding(20);
let button = Button::new(
&mut self.button_state,
Text::new("Скопировать").horizon... | Rust | 0 |
import os
import grass.script as gs
from grass.pygrass.modules.shortcuts import raster as r
from grass.pygrass.modules.shortcuts import general as g
from landsat8_mtl import Landsat8_MTL
def cleanup():
"""
Clean up temporary maps
"""
gs.run_command(
"g.remove",
flags="f",
type=... | Python | 1 |
("Error: Unable to get reminders");
std::process::exit(1);
}
};
let reminders = reminders.trim_end();
if reminders == "" {
return vec![];
}
reminders.split(", ").map(String::from).collect()
}
fn main() {
azula_cli::run();
}
use std::collections::HashMap;
use crate... | Rust | 0 |
"""workshop_portal URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
... | Python | 1 |
# Copyright 2019-2021 Canaan Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | Python | 1 |
1 * e2
}
#[inline(always)]
fn gez(self) -> ClearModp {
let t = self.Trunc(ConstU64::<{ K - 1 }>, ConstBool::<true>);
ClearModp::from(1) + t.x
}
#[inline(always)]
fn eqz(self) -> ClearModp {
let cb: Slice<ClearModp> = BitDec_ClearModp(self.x, K);
let one = ClearMod... | Rust | 0 |
self.dispatch(protocol, transport, &name, ty, id)
}
}
}
}
#[macro_export]
macro_rules! service_processor_methods {
(methods = [$($iname:ident -> $oname:ident = $fname:ident.$mname:ident($($aname:ident: $aty:ty => $aid:expr,)*) -> $rty:ty => [$($ename:ident: $ety:ty => $eid:expr,)*],)*]) =... | Rust | 0 |
, "id_related_questions"))
self.assertEqual(len(select.all_selected_options), 2)
def test_inline_add_another_widgets(self):
from selenium.webdriver.common.by import By
def assertNoResults(row):
elem = row.find_element(By.CSS_SELECTOR, ".select2-selection")
with self... | Python | 1 |
# this files stores all constants needed for running the model (i.e. for
# particulate & environmental compartment objects & calcualting rate processes)
k_B_J_K = 1.38 * 10**-23 # Boltzmann constant k_B (in J/K)
g_m_s2 = 9.81 # gravitational acceleration on earth (in m/s2)
density_w_21C_kg_m3 = 998 # density of wa... | Python | 1 |
assert!(seg_midpoint(v1, v2).fuzzy_eq(Vector2::new(3.0, 3.0)));
/// ```
pub fn seg_midpoint<T>(v1: PlineVertex<T>, v2: PlineVertex<T>) -> Vector2<T>
where
T: Real,
{
if v1.bulge_is_zero() {
return midpoint(v1.pos(), v2.pos());
}
let (arc_radius, arc_center) = seg_arc_radius_and_center(v1, v2);... | Rust | 0 |
import unittest
from unittest import mock
from chirp.wxui import serialtrace
class TestSerialTrace(unittest.TestCase):
@mock.patch('serial.Serial.open')
def test_open(self, mock_open):
trace = serialtrace.SerialTrace()
self.assertIsNone(trace._SerialTrace__tracef)
trace.open()
... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
본인인증 버튼 클릭
"""
import asyncio
from playwright.async_api import async_playwright
from datetime import datetime
import os
async def click_auth_button():
"""본인인증 버튼 클릭"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
os.makedirs("logs/realtime", e... | Python | 1 |
point.1 - older_point.1;
let slope = delta_y / delta_x;
(older_point.1 + (x - older_point.0) * slope).max(0.0)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn time_chart_test_interpolation() {
let data = [(-3.0, 8.0), (-1.0, 6.0), (0.0, 5.0)];
assert_eq!(interpolate_point(&dat... | Rust | 0 |
"""Imports content from a given Reddit post"""
import requests
import logging
from sqlalchemy.exc import SQLAlchemyError
from db.setupdb import session
from db.models import Source, Download, Document, Chunk
# Logging set up to track the process in a console
logging.basicConfig(level=logging.INFO)
def fetch_reddit_po... | Python | 1 |
c_index].neighboring_labels.add(current_label)
else:
# this topic is not a core!
if current_label is None:
topic_clustering_results[topic_index].label = -1
else:
topic_clustering_results[topic_index].label = current_lab... | Python | 1 |
let mut cfg = ParserConfig::new().whitespace_to_characters(true);
cfg.ignore_end_of_stream = true;
let mut reader = cfg.create_reader(Buffer::with_capacity(4096));
reader.source_mut().write(initial_stream.as_bytes()).unwrap();
let _ = reader.next().unwrap();
let x = reader.next... | Rust | 0 |
else:
answers_ids = set(answers_ids)
n_answers = len(answers_ids)
gs_answer_ids = set(doc['answers_ids'])
n_gs_answers = len(gs_answer_ids)
if verbose:
# show the scores for correct answers
print([{e_index.look_up_by_id(_id)[0]... | Python | 1 |
}
#[test]
fn test_segment_circle_intersection() {
// Some very basic tests
let origo = Point2::new(0.0, 0.0);
let p1010 = Point2::new(10.0, 10.0);
let segment = LineSegment::new(origo, p1010);
let p010 = Point2::new(0.0, 10.0);
let pmid = Point2::new(5.0, 5... | Rust | 0 |
YsqHnltaMNJ00AENJUK8v5L8",
"<KEY>",
"///////<KEY>",
"<KEY>",
"<KEY>",
"PFmuXSFYBCv/bxanUtLSBW6M3DnnsiSE2lRI3S0exah/<KEY>",
"7ueqG601uT98WW0txBBoVYE2dMkaZ2aAwytE1bCUjZgsNAAAAMCgA3Q6OXDE4F5H1OX9ZthBP+V30l1HyN8oFzJ/rdr38UtxYNI581FcANSp+tT0VYw== obelis",
"<EMAIL>");
... | Rust | 0 |
r_list(ssl: *mut SSL_CTX, s: *const c_char) -> c_int;
pub fn SSL_CTX_new(method: *const SSL_METHOD) -> *mut SSL_CTX;
pub fn SSL_CTX_free(ctx: *mut SSL_CTX);
#[cfg(any(ossl110, libressl273))]
pub fn SSL_CTX_up_ref(x: *mut SSL_CTX) -> c_int;
pub fn SSL_CTX_get_cert_store(ctx: *const SSL_CTX) -> *mut X... | Rust | 0 |
XiuConfig().img:
msg = await pic_msg_format(msg, event)
pic = await get_msg_pic(msg)
await create_rift.finish(MessageSegment.image(pic))
else:
await create_rift.finish(msg, at_sender=True)
#探索秘境
@explore_rift.handle()
async def _(bot: Bot, event: GroupMessageEv... | Python | 1 |
.0.0")]
fn is_negative(self) -> bool;
/// Fused multiply-add. Computes `(self * a) + b` with only one rounding
/// error. This produces a more accurate result with better performance than
/// a separate multiplication operation followed by an add.
///
/// ```
/// # #![feature(std_misc)]
... | Rust | 0 |
if use_flash:
r += np.clip(
(delta_distance - 15) * cfg.REW_FLASH,
-5.0, 0.0, dtype=np.float32
)
# 4. 撞墙惩罚
if hit_wall:
r -= cfg.REW_HIT_WALL_PUNISH
# 5. 宝箱奖励
treasure_get = (self.curr_frame['obs']['score_info'][... | Python | 1 |
struct GPIO_FUNC118_IN_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> GPIO_FUNC118_IN_SEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x1f) | ((value as u32) & 0x1f);
self.w
}
}
impl R {
... | Rust | 0 |
}
}
let char = 'x'
let str = "hello, world"
let complex = "hello, char 'x' "
let newline = "hello, this is \
newline string";
pub fn foo() {
let realchar = 'F';
let decimal= 98_222; // 十进制表示的 98222
let hex = 0xff; //十六进制表示
let octal =0o77; // 八进制表示
let binary = 0b1111_0000; // 二进制表示 111100... | Rust | 0 |
impl LoadingError {
fn new<D: Debug>(d: D) -> Self {
LoadingError(format!("{:?}", d))
}
}
impl Display for LoadingError {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatError> {
write!(f, "Failed to load OsMesa dynamic library: {}", self.0)
}
}
impl Error for LoadingError {
... | Rust | 0 |
8 {
f64x8::new(value.re, value.im, value.re, value.im)
}
#[inline]
fn add_real(self, value: f64) -> f64x8 {
let increment = f64x8::splat(value);
self + increment
}
#[inline]
fn add_complex(self, value: Complex<f64>) -> f64x8 {
let increment = f64x8::new(
... | Rust | 0 |
{
error!(Error::ControlCharacterReference);
slf.machine_helper.character_reference_code = match x {
0x80 => 0x20AC, // EURO SIGN (€)
0x82 => 0x201A, // SINGLE LOW-9 QUOTATION MARK (‚)
0x83 => 0x019... | Rust | 0 |
, sign) = f32_decode(f);
if exponent < -126 {
Ok(Decimal::ZERO)
} else if exponent < 0 {
let numer = i128::from(sign) * i128::from(mantissa);
let denom = 1_i128 << ((-exponent) as usize);
let (coeff, n_frac_digits) = approx_rational(numer, denom);
... | Rust | 0 |
impl<R: Read> Iterator for BlockIterator<R> {
type Item = Block;
fn next(&mut self) -> Option<Self::Item> {
for tag in &mut self.mkv_iter {
let tag = tag.as_ref().unwrap();
if let Some(spec_tag) = &tag.spec_tag {
match spec_tag {
MatroskaSpec... | Rust | 0 |
sizeX= 3
sizeY=3
output = [[0, 2], [0, 1]]
input = [[0, 0], [1, 0]]
scan = [2, 0] | Python | 1 |
t() * 256.0f32;
let fractional = if fractional_f32 > 255.0 {
255
} else if fractional_f32 < 0.0 {
0
} else {
fractional_f32 as u8
};
Humidity::new(integer, fractional)
}
/// Convert this to the binary fixed-point representation expect... | Rust | 0 |
from typing import Optional
import hydra
import rootutils
from omegaconf import DictConfig
from tokan.utils import RankedLogger, extras, get_metric_value, train
log = RankedLogger(__name__, rank_zero_only=True)
rootutils.setup_root(__file__, indicator=".project-root", pythonpath=True)
@hydra.main(version_base="1.... | Python | 1 |
import vertexai
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk import trace as trace_sdk
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from vertexai.generative_models import GenerativeModel
from openinference.instrumentati... | Python | 1 |
e=100)
AddTimeSeriesLog(self.test_ws, Name="my_log", Time="2010-01-01T00:30:00", Value=15)
AddTimeSeriesLog(self.test_ws, Name="my_log", Time="2010-01-01T00:50:00", Value=100.2)
line = self.ax.plot(self.test_ws, **kwargs)[0]
output = generate_plot_command(line)
expected_command =... | Python | 1 |
}
let rel = if rel_opts.is_empty() {
"".to_owned()
} else {
format!("rel=\"{}\" ", rel_opts.join(" "))
};
format!("<a {}{}{}href=\"{}\">", rel, target, title, url)
}
}
impl Default for Markdown {
fn default() -> Markdown {
Markdown {
... | Rust | 0 |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | Python | 1 |
mapping_keys:
item["source"] = json_mapping_dict[source_mention_name]
if target_mention_name in mapping_keys:
item["target"] = json_mapping_dict[target_mention_name]
relation["links"] = relation_links
print('Write file path: {}'.format(alignment_relation_vizdata_file))
with open(alignment_relation_vizdata_... | Python | 1 |
lect(entry: &str, fields: &HashSet<&str>) -> String {
let mut s = String::new();
let mut lines = entry.split_inclusive('\n');
s.push_str(lines.next().unwrap()); // @article
for line in lines {
let field = line.split(" = ").next().unwrap().trim_start();
if fields.contains(field) {
... | Rust | 0 |
as.Unset] = schemas.unset,
name: typing.Union[MetaOapg.properties.name, str, schemas.Unset] = schemas.unset,
slug: typing.Union[MetaOapg.properties.slug, str, schemas.Unset] = schemas.unset,
storage_bytes: typing.Union[MetaOapg.properties.storage_bytes, str, schemas.Unset] = schemas.unset,
... | Python | 1 |
pub upper_hr_threshold: c_double,
pub decrement: c_double,
pub apply_max_decrement: hbool_t,
pub max_decrement: size_t,
pub epochs_before_eviction: c_int,
pub apply_empty_reserve: hbool_t,
pub empty_reserve: c_double,
#[cfg(not(feature = "1.10.0"))]
pub dirty_bytes_threshold: c_int,
... | Rust | 0 |
let token_defs = variants.iter().map(|v| {
let tok = snake_case(&v.syn.ident.to_string());
let tok = Ident::new(&tok, Span::call_site());
quote! {
wast::custom_keyword!(#tok);
}
});
let parses = variants.iter().map(|v| {
let tok = snake_case(&v.syn.ident.to_... | Rust | 0 |
# https://leetcode.com/problems/minimum-array-sum/
class Solution:
def minArraySum(self, nums: List[int], k: int, op1: int, op2: int) -> int:
dp = [[0] * (op2 + 1) for _ in range(op1 + 1)]
for x in nums:
newdp = [[x + y for y in row] for row in dp]
for i in range(op1 + 1):
... | Python | 1 |
import torch
import pytest
from onnx2pytorch.operations import Split
@pytest.fixture
def weight():
a = torch.rand(15)
a[[4, 7, 12]] = 0
return a
@pytest.mark.parametrize("enable_pruning", [True, False])
@pytest.mark.parametrize(
"split_size_or_sections, number_of_splits", [((5, 5, 5), None), (None,... | Python | 1 |
blic License for more details.
// You should have received a copy of the GNU General Public License
// along with Tetcoin. If not, see <http://www.gnu.org/licenses/>.
//! Collator for the adder test parachain.
use futures_timer::Delay;
use tetcoin_node_primitives::{Collation, CollatorFn};
use tetcoin_primitives::v1... | Rust | 0 |
);
assert_eq!(context.iter, true);
// Manually iterate over `iter` so as to not move it.
let mut count = 0;
while let Some(_) = iter.next() {
count += 1;
}
assert_eq!(count, 4);
// Check to see that when iterating, the context doesn't update counters... | Rust | 0 |
in 0..COUNT >> 2 {
Self::write((addr + (i << 2)) & 0xFFC, ((vec[i << 2] as u32) << 24) |
((vec[(i << 2) + 1] as u32) << 16) |
((vec[(i << 2) + 2] as u32) << 8) |
(vec[(i << 2) + 3] as u32));
}
}
// Over time we'll want to migrate to this one
... | Rust | 0 |
X O 5
4 . O X O O O X X . 4
3 . O X X X X X . O 3
2 . . O O O O O O . 2
1 . . . . . . . . . 1
A B C D E F G H I
Escreva uma intersecao ou 'P' para passar [O]:Branco (O) tem 62 pontos
Preto (X) tem 17 pontos
A B C D E F G H I
9 . . . . . . . . . 9
8 . . O O O O O O O 8
7 . . O X X X X X O 7
6 . O X... | Python | 1 |
"""
Write a function to put spaces between words starting with capital letters in a given string.
assert capital_words_spaces("Python") == 'Python'
"""
def capital_words_spaces(string):
return string
print(capital_words_spaces("Python"))
/python/codewars/7kyu/sum_of_digits_digital_root.py
"""
In this kata, you mu... | Python | 1 |
ic_deeplab_loss(
dataset.CITYSCAPES_PANOPTIC_INFORMATION)
global_step = tf.Variable(initial_value=0, dtype=tf.int64)
fake_datum = {
common.IMAGE:
tf.zeros([1, 1025, 2049, 3]),
common.RESIZED_IMAGE:
tf.zeros([1, 1025, 2049, 3]),
common.GT_SIZE_RAW:
... | Python | 1 |
from characters.models.core.background_block import Background, BackgroundRating
from characters.models.core.human import Human
from django import forms
from django.forms import BaseInlineFormSet, inlineformset_factory
class BackgroundRatingForm(forms.ModelForm):
class Meta:
model = BackgroundRating
... | Python | 1 |
: 0.15, # Relative to note size
'electrotype_present': True
},
'rbi_guidelines': """
The watermark should show a portrait of Mahatma Gandhi and an electrotype denomination numeral.
The portrait should be visible when held against light.
"""
},
'micro_letterin... | Python | 1 |
import os
import time
import json5
import torch
import pandas as pd
from transformers import AutoTokenizer
from utils import extract_prompts
from getHiddenStates import load_model, tokens_get_hidden_states
import numpy as np
def get_padding_length_and_prompt(task, tokenizer1, lang, device):
# 加载tokenizer
# to... | Python | 1 |
-> Celsius);
read_impl!(CpuSystemAgentTemperature = TEMP_CPU_SYSTEM_AGENT -> Celsius);
read_impl!(CpuCoreTemperature(u8) == TEMP_CPU_CORE -> Celsius);
read_impl!(GpuProximityTemperature = TEMP_GPU_PROXIMITY -> Celsius);
read_impl!(GpuDieTemperature = TEMP_GPU_DIE -> Celsius);
read_impl!(GetMemoryBankProximityTempera... | Rust | 0 |
from collections import deque
# Breadth-First Search (BFS)
def bfs(graph, start, goal):
visited = set() # To track visited nodes
queue = deque([start]) # Initialize the queue
path = [] # To store the traversal path
while queue:
node = queue.popleft() # Dequeue a n... | Python | 1 |
if scriptEfficiency == 100:
breaker = r("</script/>")
payloads = genGen(
fillings, eFillings, lFillings, eventHandlers, tags, functions, ends
)
for payload in payloads:
vectors[10].add(payload)
if c... | Python | 1 |
entree = input("Entrez des nombres séparés par des espaces : ")
liste = [int(x) for x in entree.split()]
n = len(liste)
for i in range(n):
for j in range(0, n - i - 1):
if liste[j] > liste[j + 1]:
liste[j], liste[j + 1] = liste[j + 1], liste[j]
print(f"Liste triée : {liste}") | Python | 1 |
"""
Key handling utilities for RSA keys (PKCS#1).
"""
from asn1crypto.keys import RSAPrivateKey, RSAPublicKey
from pkcs11.constants import Attribute, MechanismFlag, ObjectClass
from pkcs11.defaults import DEFAULT_KEY_CAPABILITIES
from pkcs11.mechanisms import KeyType
from pkcs11.util import biginteger
def decode_rs... | Python | 1 |
# What are docstrings in Python?
def addtwonumber():
"""
It is python program and take the input of user and then sum and
print a,b.
"""
print(addtwonumber.__doc__)
''' Here, (''' ''') and (""" """) are difrrent from each because
(''' ''') is multiple line commenets and (""" """) is docstring
and this print ... | Python | 1 |
"F16" => F16,
"F17" => F17,
"F18" => F18,
"F19" => F19,
"F2" => F2,
"F20" => F20,
"F21" => F21,
"F22" => F22,
"F23" => F23,
"F24" => F24,
"F3" => F3,
"F4" => F4,
"F5... | Rust | 0 |
ogger(logger_name).setLevel(logging.ERROR)
logging.getLogger(logger_name).propagate = False
# TensorFlow specific suppression
tf.get_logger().setLevel('ERROR')
tf.autograph.set_verbosity(0)
# Suppress warnings
warnings.filterwarnings('ignore', category=DeprecationWarning)
warnings.... | Python | 1 |
_options.foreground;
if log_to_file {
paths.log_file_path = cli_options.log_file_path.clone().or(paths.log_file_path);
} else {
paths.log_file_path = None;
};
return paths;
}
}
/// A dummy implementation of the Circuit Breaker pattern to demonstrate
/// capabilities of this library.
/// https://martinfo... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
# File names and corresponding imbalance ratios (IR)
files = ["solution_output_10.npy", "solution_output_50.npy", "solution_output_100.npy"]
labels = ["IR=10", "IR=50", "IR=100"]
# Create a figure with two subplots side by s... | Python | 1 |
.http2.min_time_between_pings_ms\0";
const OPT_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS: &[u8] =
b"grpc.http2.min_ping_interval_without_data_ms\0";
const OPT_HTTP2_MAX_PINGS_WITHOUT_DATA: &[u8] = b"grpc.http2.max_pings_without_data\0";
const OPT_HTTP2_MAX_PING_STRIKES: &[u8] = b"grpc.http2.max_ping_strikes\0";
... | Rust | 0 |
ESYS_TR_PASSWORD);
}
use brace_web::core::HttpResponse;
pub async fn get() -> HttpResponse {
HttpResponse::Ok().body("Hello world")
}
#[cfg(test)]
mod tests {
use brace_web::core::test::{call_service, init_service, TestRequest};
use brace_web::core::{web, App};
use super::get;
#[actix_rt::test]... | Rust | 0 |
class Settings:
"""Klasa przeznaczona do przechowywania wszystkich ustawień gry."""
def __init__(self):
"""Inicjalizacja danych statycznych gry."""
# Ustawienia dotyczące ekranu.
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
... | Python | 1 |
use ast::ast::Literal;
use span::Span;
named_attr!(
#[doc="
Recognize all kind of literals.
A literal is either a number or a string.
"],
pub literal<Span, Literal>,
alt!(
number
| string
)
);
#[cfg(test)]
mod tests {
use super::literal;
use ast::ast::{
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.