text string | label_name string | labels int64 |
|---|---|---|
/win32/controls/bumper-rebar-control-reference-messages)
/// (`u32`), convertible to [`WM`](crate::co::WM).
->
DELETEBAND, WM::USER.0 + 2
GETBARINFO, WM::USER.0 + 3
SETBARINFO, WM::USER.0 + 4
SETPARENT, WM::USER.0 + 7
HITTEST, WM::USER.0 + 8
GETRECT, WM::USER.0 + 9
INSERTBAND, WM::USER.0 + 10
SETBAN... | Rust | 0 |
k as rate = 0
self.assertEqual(len(g2), 2)
def test_shrink3(self):
g1 = np.array([[1.0]])
g2 = genome.Genome.shrink_mutate(g1, rate=1.0)
# should not shrink if already len 1
self.assertEqual(len(g2), 1)
def test_grow1(self):
g1 = np.array([[1.0], [2.0]])
... | Python | 1 |
"6")]
FaqAnswer(super::FaqAnswer),
}
}
/// Represents feedback the customer has about the quality & correctness of a
/// certain answer in a conversation.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct AnswerFeedback {
/// The correctness level of the specific answer.
#[prost(enumeration ... | Rust | 0 |
, state) => write!(f, "[Addr {:04X}] --> ReportState [{:?}]", address, state)?,
Message::RequestOperation(address, op) => write!(f, "[Addr {:04X}] <-- RequestOperation [{:?}]", address, op)?,
Message::AckOperation(address, op) => write!(f, "[Addr {:04X}] --> AckOperation [{:?}]", address, op)?,... | Rust | 0 |
list_trending_videos)),
)
.service(
web::scope("/api/a/creator")
.route("/follow", web::get().to(u::is_following))
.route("/follow", web::post().to(u::follow))
.route("/unfollow", web::post().to(u::unfollow))
.route("/profile", web::post().to(u::update_pro... | Rust | 0 |
weights_lut.iter()) {
(decode(weight))" "
}
</float_array>;
<technique_common>;
<accessor source=["#controller-weights-array"] count=[(weights_lut.len())]>;
<param name=["WEIGHT"] type=["float"]/>;
/accessor>;
... | Rust | 0 |
&*right_val,
::core::option::Option::None,
);
}
}
}
};
{
match (
&<String as crate::FromSource>::from_source(&mut source),
&Some(String::from("try")),
) {
(left_val, rig... | Rust | 0 |
NSET {}
#[doc = "Enable event routing"]
pub mod evtenset;
#[doc = "Disable event routing\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::... | Rust | 0 |
x_replace = x_rec.clone().detach()
elif self.fft_unmask_replace == 'mean':
x_replace = x.mean(dim=[2, 3], keepdim=True).expand(x.size())
elif self.fft_unmask_replace == 'mixed':
x_replace = 0.5 * x_rec.clone().detach() + 0.5 * x.c... | Python | 1 |
_eq!(
blocker_mask_rook(7.into()),
bitboard!(1, 2, 3, 4, 5, 6, 15, 23, 31, 39, 47, 55)
);
assert_eq!(
blocker_mask_rook(9.into()),
bitboard!(10, 11, 12, 13, 14, 17, 25, 33, 41, 49)
);
assert_eq!(
blocker_mask_rook(16.into()),
... | Rust | 0 |
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Medication(models.Model):
name = models.CharField(max_length=255)
times_per_day = (
models.PositiveIntegerField()
)
dose = models.CharField(max_length=255)
user = models.ForeignKey(Use... | Python | 1 |
,
pub command: Option<String>,
}
#[derive(Serialize, Deserialize)]
pub struct Storage {
pub projects: Vec<Project>,
}
impl Storage {
fn new() -> Self {
Self { projects: vec![] }
}
pub fn init() -> Result<Self, Error> {
Ok(match File::open(PathBuf::from(&*FILE_PATH)) {
... | Rust | 0 |
Option<Box<ListNode>>> for Solution {
fn solution(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut fake = Some(Box::new(ListNode::new(0)));
fake.as_mut().unwrap().next = head;
let mut cur = &mut fake;
while let Some(ref mut _cur) = cur {
match _cur.next.ta... | Rust | 0 |
ntrol Message Protocol (ICMP).
///
/// RFC 792.
pub const InternetControlMessageProtocol: u8 = 1;
/// Transmission Control Protocol (TCP).
///
/// RFC 793.
pub const TransmissionControlProtocol: u8 = 6;
/// User Datagram Protocol (UDP).
///
/// RFC 768.
pub const UserDatagramProtocol: u8 = 17;
}
//! Cros... | Rust | 0 |
ULayerConst for PtrOfELULayer {
#[inline] fn as_raw_ELULayer(&self) -> *const c_void { self.inner_as_raw() }
}
impl crate::dnn::ELULayer for PtrOfELULayer {
#[inline] fn as_raw_mut_ELULayer(&mut self) -> *mut c_void { self.inner_as_raw_mut() }
}
impl core::AlgorithmTraitConst for PtrOfELULayer {
#[inline]... | Rust | 0 |
def test_invalid_kafka_config_should_fail(mini_sentry, relay_with_processing):
options = {
"processing": {
"topics": {
"__unknown": "foobar",
"profiles": {
"name": "profiles",
"config": "does_not_exist",
},
... | Python | 1 |
ingは既に実行中です")
return
print(f"[HealthServer] セルフpingを開始: {interval_minutes}分間隔")
async def ping_loop():
while True:
try:
await asyncio.sleep(interval_minutes * 60) # 分を秒に変換
await self.self_ping()
... | Python | 1 |
ate::uri_ref!("")
};
}
/// Creates a `&'static RelRef` from a string literal.
///
/// Accepts only string constants and literals. The given string *MUST* be well-formed.
///
/// Example:
///
/// ```
/// # use async_coap_uri::prelude::*;
/// let x = rel_ref!("a/b/c?q=foobar#frag");
/// assert_eq!(x.raw_path(),"a/b/... | Rust | 0 |
'address group create '
+ '--description aaaa '
+ '--address 10.0.0.1 --address 2001::/16 '
+ name,
parse_output=True,
)
self.addCleanup(self.openstack, 'address group delete ' + newname)
self.assertEqual(name, cmd_output['name'])
self.ass... | Python | 1 |
.id == id)?;
let menu = gio::Menu::new();
for artist in song.artists.iter() {
menu.append(
Some(&format!("{} {}", *labels::MORE_FROM, artist.name)),
Some(&format!("song.view_artist_{}", artist.id)),
);
}
menu.append(Some(&*labels:... | Rust | 0 |
_unknown = input.read_u16().context("Can’t read mystery word")?;
let meta_size = input.read_u16().map(u32::from).context("Can’t read cast metadata size")?;
let info_size = input.read_u16().map(u32::from).context("Can’t read cast info size")?;
let kind = {
let value = input.read_u8()... | Rust | 0 |
::new(None),
destructor: None,
}
}
}
pub(crate) unsafe extern "C" fn resource_dispatcher<I: Interface>(
_implem: *const c_void,
resource: *mut c_void,
opcode: u32,
_msg: *const wl_message,
args: *const wl_argument,
) -> c_int
where
I: Interface + From<Resource<I>> + AsRe... | Rust | 0 |
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_sum = float('-inf')
running_sum, prefix_sum = 0, 0
for i in range(len(nums)):
running_sum += nums[i]
if prefix_sum < 0:
running_sum -= prefix_sum
prefix_sum = 0
... | Python | 1 |
# -*- coding: utf-8 -*-
import os
ACTIVE_LISTS = ('german', 'french', 'italian', 'english', 'spanish')
class StopWords(object):
def __init__(self):
self.stop_words_lists = {}
self.language = None
stop_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'st... | Python | 1 |
ommon/data/pairs/doubled-bytes/case73-73.txt"),
include_str!("common/data/pairs/doubled-bytes/case74-74.txt"),
include_str!("common/data/pairs/doubled-bytes/case75-75.txt"),
include_str!("common/data/pairs/doubled-bytes/case76-76.txt"),
include_str!("common/data/pairs/doubled-bytes/case77-77.txt"),
... | Rust | 0 |
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3 | Python | 1 |
#!/usr/bin/python3
def roman_to_int(roman_string):
if not roman_string or type(roman_string) != str:
return 0
roman_values = {
'I': 1, 'V': 5, 'X': 10, 'L': 50,
'C': 100, 'D': 500, 'M': 1000
}
number = 0
prev_value = 0
for char in reversed(roman_string):
... | Python | 1 |
True:
# Get user input
user_input = input("You: ")
# Exit the loop if the user types 'q'
if user_input.lower() == 'q':
print("Exiting conversation.")
break
# Check if the 'Esc' key is pressed to save the conversation
if user_input.lower() == 'atta... | Python | 1 |
s": f10EgMulticastBytes,
"f10EgMulticastBytesCount": f10EgMulticastBytesCount,
"f10EgMulticastPacketCount": f10EgMulticastPacketCount,
"f10EgMulticastGreenMin": f10EgMulticastGreenMin,
"f10EgMulticastGreenMax": f10EgMulticastGreenMax,
"f10EgMulticastGreenDrop": f10EgMulticastGreenDrop... | Python | 1 |
gual analysis section should provide a plausible and insightful hypothetical finding about cultural differences in concept representation.",
"The language acquisition application should propose a creative and practical use of the system for language learners.",
"The response should address ethic... | Python | 1 |
j] = T.float16(0)
C_warp[vii, vjj, vi, vj] = C_warp[vii, vjj, vi, vj] + A_shared_warp[vii, vkk, vi, vk] * B_shared_warp[vjj, vkk, vj, vk]
for ax0, ax1 in T.grid(16, 16):
with T.block("C_warp"):
v0 = T.axis.spatial(1, 0)
v1 = T.axis.... | Python | 1 |
<R> = data as *mut _;
let data: &mut ReadData<R> = &mut *data;
if data.triggered_error.is_some() {
(*size) = 0;
return data.buffer.as_ptr() as *const libc::c_char;
}
match data.reader.read(&... | Rust | 0 |
e.
*/
pub async fn get_course_material_service_info_by_exercise_type(
conn: &mut PgConnection,
exercise_type: &str,
) -> ModelResult<Option<CourseMaterialExerciseServiceInfo>> {
if let Ok(exercise_service) = get_exercise_service_by_exercise_type(conn, exercise_type).await {
let full_service_info = g... | Rust | 0 |
import os
slurmScript = """#!/bin/bash
#SBATCH -J jID_jName
##SBATCH -D wkPath
#SBATCH -n CoreNum
#SBATCH --nodes=1
#SBATCH -t 72:0:0
#SBATCH --mem=MEMFREEG
#SBATCH -o wkPath/jName.o.log
#SBATCH -e wkPath/jName.e.log
#- End embedded arguments
echo $SLURM_JOB_NODELIST
module load Anaconda3
conda activate CONDAENV
RUMC... | Python | 1 |
ng.as_ref().unwrap().driving_pos,
ParkingSpot::Lot(pl, _) => map.get_pl(pl).driving_pos,
}
}
pub fn spot_to_sidewalk_pos(&self, spot: ParkingSpot, map: &Map) -> Position {
match spot {
ParkingSpot::Onstreet(l, idx) => {
let lane = &self.onstreet_lanes[&l]... | Rust | 0 |
let (valid, rest) = self.bytes.split_at(err.valid_up_to());
self.bytes = rest;
Some(Ok(from_utf8(valid).unwrap()))
}
}
}
}
Iter { bytes }
}
#[cfg(feature = "std")]
#[cfg(test)]
mod tests {
use super::*;
use... | Rust | 0 |
o work you need to specify a single input image path")
continue
if args.test_mode:
n_fine_tuning_iters = 1
else:
n_fine_tuning_iters = 50
print("Fine tuning generator on single image, this might take a minute or two")
curren... | Python | 1 |
* x as f32) as u8;
let b = (0.3 * y as f32) as u8;
*pixel = image::Rgb([r, 0, b]);
}
// A redundant loop to demonstrate reading image data
for x in 0..imgx {
for y in 0..imgy {
let cx = y as f32 * scalex - 1.5;
let cy = x as f32 * scaley - 1.5;
... | Rust | 0 |
"""
This implementation is adapted from the Gymnasium API.
ref: https://github.com/Farama-Foundation/Gymnasium/blob/main/gymnasium/wrappers/utils.py
"""
import numpy as np
class RunningMeanStd:
"""Tracks the mean, variance and count of values."""
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_va... | Python | 1 |
an be invoked via [`Metadata::interpolate()`].
///
/// # Example
///
/// ```rust
/// use figment::Metadata;
///
/// let metadata = Metadata::named("environment variable(s)")
/// .interpolater(|profile, path| {
/// let keys: Vec<_> = path.iter()
/// .map(|k... | Rust | 0 |
ek;
use winrt::foundation::AsyncStatus;
#[test]
fn signed_enum() {
assert!(AsyncStatus::default() == 0.into());
assert!(AsyncStatus::Canceled == 2.into());
assert!(AsyncStatus::Completed == 1.into());
assert!(AsyncStatus::Error == 3.into());
assert!(AsyncStatus::Started == 0.into());
}
#[test]
fn ... | Rust | 0 |
x::new(size, 1, v);
Ok(&v / v.norm(Euclidean))
}
}
<gh_stars>0
use std::collections::HashMap;
use flexstr::SharedStr;
use minecrevy_io_str::{McRead, McWrite};
use minecrevy_key::Key;
use minecrevy_text::Text;
use crate::types::Slot;
#[derive(Clone, PartialEq, Debug, McRead, McWrite)]
pub struct Advancem... | Rust | 0 |
# mlapp/ml/evaluator.py
from sklearn.metrics import accuracy_score, confusion_matrix, ConfusionMatrixDisplay, precision_score, recall_score
# mlapp/ml/evaluator.py
import matplotlib.pyplot as plt
plt.switch_backend('Agg') # 백엔드 설정을 Agg로 변경
import io
import base64
import numpy as np
def evaluate_model(model, X_test,... | Python | 1 |
wards[0] if len(rewards) > 1 else 0
}
# 分析帕累托最优性
if self.cumulative_rewards:
# 检查最终联合策略是否实现帕累托最优
final_cumulative = {sid: self.cumulative_rewards[sid][-1]
for sid in self.service_ids if self.cumulative_rewards[sid]}
... | Python | 1 |
np.max(sample) < 200 or np.min(sample) < 0:
sample = (sample * 255).astype(np.uint8)
ax = plt.subplot(batch_size // 2, 2, j + 1)
plt.imshow(sample)
title = ""
label = batch_labels[j]
if isinstance(label, torch.Tensor):
label = label.numpy()
if la... | Python | 1 |
_add)?;
}
Instruction::F32Add => {
op2::<f32, f32, _>(rt, |a, b| value::canonicalize_f32_nan(a + b))?;
}
Instruction::I64Add => {
op2::<i64, i64, _>(rt, i64::wrapping_add)?;
}
Instruction::F64Add => {
op2::<f64, f64, _>(rt, |a, b| va... | Rust | 0 |
> {
# sibyl::block_on(async {
# let oracle = sibyl::env()?;
# let dbname = std::env::var("DBNAME").expect("database name");
# let dbuser = std::env::var("DBUSER").expect("user name");
# let dbpass = std::env::var("DBPASS").expect("password");
# let session = oracle.connect(&dbname, &dbuser, &dbp... | Rust | 0 |
np.array([('YRI','chr1',10114,4.3),('CEU','chr1',10116,5.2)], dtype=HapBlock)
>>> np.array([('CEU','chr1',10114,4.3),('YRI','chr1',10116,5.2)], dtype=HapBlock)
>>> ], 'HG00097': [
>>> np.array([('YRI','chr1',10114,4.3),('CEU','chr2',10116,5.2)], dtype=HapBlock)
>>> ... | Python | 1 |
ctory(&self, mux_tx: tokio::sync::mpsc::Sender<MuxCall> ) -> Box<dyn Router>;
fn logger(&self) -> fn(message: &str);
fn portal_request_handler(&self) -> Arc<dyn PortalAssignRequestHandler>;
}
#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct ClientIdent {
pub user: String,
pub portal_key: Option... | Rust | 0 |
size: (vertices.len() * std::mem::size_of::<Vertex>()) as wgpu::BufferAddress,
usage: wgpu::BufferUsage::VERTEX,
mapped_at_creation: true,
});
vertex_buffer
.slice(..)
.get_mapped_range_mut()
.copy_from_slice(bytemuck::cast_slice(&vertices)... | Rust | 0 |
a[0]/len(inp)
############### Main Script #################
n_epochs = args.epochs
print_every = args.log_interval
plot_every = 10
hidden_size = args.hidden_size
n_layers = args.n_layers
lr = args.lr
chunk_len = args.chunk_len
decoder = RNN(n_characters, hidden_size, n_characters, n_layers)
decoder_optimizer = to... | Python | 1 |
{
/// let pty: Pty = openpty(&term, width, height, width_px, height_px, &modes);
/// Ok(pty)
/// }.boxed()
/// });
/// struct Pty {
/// // ...
/// }
/// # fn openpty(_: &str, _: u32, _: u32, _: u32, _:u32, _:&[u8]) -> Pty {
/// # Pty {}
/// # }
//... | Rust | 0 |
g, t])
constESS = Equation(m, name="constESS", type="regular", domain=t)
balance = Equation(m, name="balance", type="regular", domain=t)
wind = Equation(m, name="wind", type="regular", domain=t)
costThermalcalc = Sum(t, VWC * PWC[t]) + Sum(
[t, g],
gendata[g, "a"] * gams_math.power(p[g,... | Python | 1 |
err)))
.unwrap()
.and_hms(0, 0, 0));
let duration = matches.value_of("duration")
.map(|duration| Duration::from_std(parse_duration::parse(duration)
.unwrap_or_else(|err| exiting_errf!("duration: {}", err))).unwrap());
let filter = matches.value_of("filter")
... | Rust | 0 |
fixed in py3.x (this adjustment is documented
# and/or debated in http://bugs.python.org/issue10789); so we'll just
# stick to the format that works in both (oddly the keyword argument
# works in py2.x but only with reentrant locks).
was_locked = lock.acquire(False)
try:
yield was_locked
... | Python | 1 |
n initial.split(".") if len(t.strip()) > 0
]
for i, (sent1, sent2) in enumerate(zip(sentences, sentences[1:])):
if sent1.endswith(alpha1 + ".") and sent2.startswith(alpha2 + "."):
# merge sentence i and i+1
sentences = (... | Python | 1 |
const PUBLIC_KEY_LENGTH: usize = ed25519::PUBLICKEYBYTES;
/// Number of bytes in a secret key.
pub const SECRET_KEY_LENGTH: usize = ed25519::SECRETKEYBYTES;
/// Number of bytes in a seed.
pub const SEED_LENGTH: usize = ed25519::SEEDBYTES;
/// Number of bytes in a signature.
pub const SIGNATURE_LENGTH: usize = ed255... | Rust | 0 |
er::stype::SType;
use super::stype_param::STypeParam;
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct SFunc {
pub t_dom: Vec<SType>,
pub t_range: SType,
pub tpe_params: Vec<STypeParam>,
}
<gh_stars>0
//! The `splits_io` module provides communication with
//! [Splits.io](https://Splits.io). The raw API is... | Rust | 0 |
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new() {
let c = Canvas::new(10, 20);
assert_eq!(c.get(0, 0), Color::new(0.0, 0.0, 0.0));
}
#[test]
fn test_fmt() {
let mut c = Canvas::new(2, 2);
c.set(0, 0, Color::new(1.0, 0.0, 0.0));
c.set(0, 1, ... | Rust | 0 |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Alfa Addon - Kodi Plugin
# https://github.com/alfa-addon/addon/blob/master/plugin.video.alfa/lib/aadecode.py
# ------------------------------------------------------------
# Modified by jsergio, gujal
import re
import six
def dec... | Python | 1 |
/// ln((β^α / Γ(α)) * x^(-α - 1) * e^(-β / x))
/// ```
///
/// where `α` is the shape, `β` is the rate, and `Γ` is the gamma function
fn ln_pdf(&self, x: f64) -> f64 {
self.pdf(x).ln()
}
}
#[rustfmt::skip]
#[cfg(test)]
mod test {
use std::f64;
use crate::statistics::*;
use cr... | Rust | 0 |
#!/usr/bin/python3
"""lass Student that defines a student"""
class Student:
"""
Represents a student.
Attributes:
first_name (str): The first name of the student.
last_name (str): The last name of the student.
age (int): The age of the student.
"""
def __init__(self, firs... | Python | 1 |
MASK: bool = true;
const OFFSET: u8 = 31;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[d... | Rust | 0 |
#Modified/simplified version of the node from: https://github.com/pamparamm/sd-perturbed-attention
#If you want the one with more options see the above repo.
#My modified one here is more basic but has less chances of breaking with ComfyUI updates.
import comfy.model_patcher
import comfy.samplers
class PerturbedAtte... | Python | 1 |
=> {}
}
let physx = physx_cfg
.define("PX_OUTPUT_LIB_DIR", &output_dir)
.define("PX_OUTPUT_BIN_DIR", &output_dir)
.define("PX_OUTPUT_ARCH", "x86")
.define("PX_BUILDSNIPPETS", "False")
.define("PX_BUILDSAMPLES", "False")
.define("PX_GENERATE_STATIC_LIBRARIES", "T... | Rust | 0 |
#creamos una lista con list[]
lista = list(["hola",56,18])
#cuenta el numero de elementos de una lista
resultado = len(lista)
#agregando elementos a una lista con append
lista.append("ajajjajaja")
#agregando un elemento a la lista en un indice especifico
lista.insert(2,"papaya")
#agregando varios elementos a la lista... | Python | 1 |
import os
import launch
from ament_index_python.packages import get_package_share_directory
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
def generate_launch_description():
# TODO: 驗證 drone_id <= num_drones
... | Python | 1 |
esult = parse(input);
assert_eq!(result, expected);
}
#[test]
fn error_unexpected_end() {
let input = "";
let expected = Err(Error::UnexpectedEnd);
let result = parse(input);
assert_eq!(result, expected);
}
}
<gh_stars>1-10
use std::{borrow::Cow, fmt};
#[derive(... | Rust | 0 |
2e-14,
7.79819451246194e-30,
-3.2138365634328507e-14,
-3.175994945548343e-14,
6.36770905528953e-14,
),
}
)
experiments = ExperimentList()
experiments.append(
Experiment(
beam=beam,
detector=d... | Python | 1 |
Vec<f32>>,
bones: Option<(BoneAttributes, u8)>,
) -> Vec<Vertex> {
let mut vertices = vec![];
for idx in 0..vertex_positions.len() / 3 {
let position = [
vertex_positions[idx * 3],
vertex_positions[idx * 3 + 1],
vertex_positions[idx * 3 + 2],
];
le... | Rust | 0 |
* 1.2, max_y)
fig = plt.figure(term, figsize=(6, 1.5), dpi=100)
ax = fig.add_subplot(111)
print(data[term_index])
ax.plot(data[term_index], color='b', linestyle='-', marker='x', label='Ground truth')
if smoothed_data is not None:
ax.plot(list(smoothed_data[term_inde... | Python | 1 |
import pandas as pd
import numpy as np
def fun1():
df1 = pd.read_csv("../weibo_keyword_crawl-main/weibo_keyword_crawl-main/data.csv",encoding='gb18030')
df2 = pd.DataFrame([df1['帖子内容'], df1['发布时间']]).T
df2.to_csv('data.csv')
#统一格式 保存字数大于100内容
def deal_bayi_weibo():
df1 = pd.read_csv("巴以冲突_weibo.csv")... | Python | 1 |
Iterator[dict]:
"""
For each path in the input, iterate over the jsonl files in that path.
Look in subdirectories recursively.
Use an iterator to conserve memory.
"""
if type(paths) == str:
paths = [paths]
def _iter():
for path in paths:
if bf.isdir(path):
... | Python | 1 |
dist_rs = np.linalg.norm(receiver_positions[:, np.newaxis, :] - sender_positions[np.newaxis, :, :], axis=2)
# 创建冲突矩阵
conflict_matrix = np.zeros((len(senders), len(senders)), dtype=int)
# 发送者和接收者重叠检查
overlap = (senders[:, np.newaxis] == senders[np.newaxis, :]) | (
receivers[:, np.n... | Python | 1 |
ion. A score of 5 indicates the response is empathetic and understanding, while a 1 suggests it lacks empathy and may come across as cold or indifferent.",
"Cultural Sensitivity": "Assess the response's cultural awareness and sensitivity, avoiding assumptions and generalizations while respecting diversity. A score ... | Python | 1 |
Box<Connection>>> {
let conn = Connection::new(scid, None, config, false)?;
if let Some(server_name) = server_name {
conn.handshake.lock().unwrap().set_host_name(server_name)?;
}
Ok(conn)
}
/// Writes a version negotiation packet.
///
/// The `scid` and `dcid` parameters are the source connec... | Rust | 0 |
livemetadata() {
let tmp_dir = ::tempdir::TempDir::new_in(".", "rocks").unwrap();
let db = DB::open(
Options::default().map_db_options(|db| db.create_if_missing(true)),
&tmp_dir,
)
.unwrap();
assert!(db.disable_file_deletions().is_ok());
let meta = db.get_live_files_metadata();... | Rust | 0 |
s3d[n] # (8, 3)
if cls is not None:
if isinstance(cls, np.ndarray):
# mlab.text3d(b[6, 0], b[6, 1], b[6, 2], '%.2f' % cls[n], scale=(0.3, 0.3, 0.3), color=color, figure=fig)
ax.text(b[6, 0], b[6, 1], '%.2f' % cls[n])
else:
... | Python | 1 |
urn value ranges from 1 to 12.
fn month(&self) -> UInt32Chunked;
/// Extract weekday from underlying NaiveDate representation.
/// Returns the weekday number where monday = 0 and sunday = 6
fn weekday(&self) -> UInt32Chunked;
/// Returns the ISO week number starting from 1.
/// The return valu... | Rust | 0 |
use crate::testutil::parse_ip_packet_in_ethernet_frame;
#[bench]
fn bench_parse(b: &mut Bencher) {
use crate::wire::testdata::tls_client_hello::*;
let bytes = parse_ip_packet_in_ethernet_frame::<Ipv4>(ETHERNET_FRAME_BYTES).unwrap().0;
b.iter(|| {
let mut buf = bytes;
... | Rust | 0 |
RCE_DWORD: D2D1_SVG_ASPECT_SCALING = 4294967295u32;
#[doc = "*Required features: 'Win32_Graphics_Direct2D'*"]
pub type D2D1_SVG_ATTRIBUTE_POD_TYPE = u32;
#[doc = "*Required features: 'Win32_Graphics_Direct2D'*"]
pub const D2D1_SVG_ATTRIBUTE_POD_TYPE_FLOAT: D2D1_SVG_ATTRIBUTE_POD_TYPE = 0u32;
#[doc = "*Required features... | Rust | 0 |
{308}\u{200d}\u{1f476}\u{1f3ff}",
&["\u{1f476}\u{1f3ff}\u{308}\u{200d}\u{1f476}\u{1f3ff}"]), ("\u{1f6d1}\u{200d}\u{1f6d1}",
&["\u{1f6d1}\u{200d}\u{1f6d1}"]), ("\u{61}\u{200d}\u{1f6d1}", &["\u{61}\u{200d}",
"\u{1f6d1}"]), ("\u{2701}\u{200d}\u{2701}", &["\u{2701}\u{200d}\u{2701}"]),
("\u{6... | Rust | 0 |
"""Litestar CLI integration for SQLSpec migrations."""
from contextlib import suppress
from typing import TYPE_CHECKING
import rich_click as click
from litestar.cli._utils import LitestarGroup
from sqlspec.cli import add_migration_commands
if TYPE_CHECKING:
from litestar import Litestar
from sqlspec.extens... | Python | 1 |
let current = current.clone();
// TODO: and this one too
let mut c = c.clone();
async move { Ok(c.current_url().await? != current) }
})
.await
}
}
/// Raw access to the WebDriver instance.
impl Client {
/// Issue an HTTP request to the given `url` with all ... | Rust | 0 |
#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: longofo
@file: __init__.py
@time: 2019/03/23
"""
import os
import random
import socket
import ssl
import threading
import time
from http.server import SimpleHTTPRequestHandler, HTTPServer
from pocsuite3.lib.utils import gen_cert
from pocsuite3.lib.core.common imp... | Python | 1 |
configurator.add_view(self.disable_content_share, route_name="delete_content_share")
# public download api
configurator.add_route(
"guest_download_info",
"/public/guest-download/{share_token}",
request_method="GET",
)
configurator.add_view(self... | Python | 1 |
ounter: u32,
/// Indicates whether a horizontal blank signal is being generated.
hblank_on: bool,
/// Indicates whether a horizontal sync signal is being generated.
hsync_on: bool,
/// Holds CPU ticks until we reach the end of a scanline.
wait_for_sync: bool,
/// Temporarily latches playfiel... | Rust | 0 |
r)
# num_perms x nsrc_ref
sisdrs = torch.stack(sisdrs, 0)
best_sisdr, idx = torch.max(sisdrs.sum(dim=-1, keepdim=True), dim=0)
if return_perm:
return sisdrs[idx[0]], permutations[idx[0]]
else:
return sisdrs[idx[0]]
def sparsity_loss(y, eps=1e-8):
"""Source sparsity loss for M... | Python | 1 |
import pandas as pd
from evidently.legacy.base_metric import GenericInputData
from evidently.legacy.base_metric import InputData
from evidently.legacy.base_metric import Metric
from evidently.legacy.calculation_engine.engine import metric_implementation
from evidently.legacy.calculation_engine.python_engine import Pyt... | Python | 1 |
// if (global_time >> 28) & 0x3 != pixel_bits as u64 {
// warn!("{} Checking bits should match!", output_prefix);
// }
// Subtract fast toa (ftoa count until the first clock edge, so less counts means later arrival of the hit)
l... | Rust | 0 |
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from api.models import TodoItem, Note, TodoList
from api.serializers import TodoItemSerializer, NoteSerializer, TodoListSerializer
# TodoList views
class TodoList... | Python | 1 |
serde_json::Value;
use std::path::PathBuf;
use taplo_common::{
schema::{associations::DEFAULT_CATALOGS, cache::DEFAULT_LRU_CACHE_EXPIRATION_TIME},
HashMap,
};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InitConfig {
pub cache_path: Option<PathBuf>,
#[s... | Rust | 0 |
# SPDX-License-Identifier: Apache-2.0
# Standard
from urllib.parse import parse_qs, urlparse
# First Party
from lmcache.logging import init_logger
from lmcache.v1.storage_backend.connector import (
ConnectorAdapter,
ConnectorContext,
)
from lmcache.v1.storage_backend.connector.base_connector import RemoteConne... | Python | 1 |
f:
existing = f.read()
for marker_tag in MARKER_TAGS:
if MARKER_IGNORE.format(tag=marker_tag) in existing:
msg.warn(
"Found ignore marker in existing file: skipping", output_file
)
return
... | Python | 1 |
"""Plotting helpers for sensor modeling."""
from __future__ import annotations
from typing import Dict
import logging
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
logger = logging.getLogger(__name__)
def plot_quantile_intervals(
actual_counts: np.ndarray,
quantile_info: Dict,
... | Python | 1 |
#!/usr/bin/env python
#####################################
# Installation module for FuzzBunch (on Wine)
#####################################
# AUTHOR OF MODULE NAME
AUTHOR="Mike Schladt (@mikeschladt). Tool by Miguel Diaz Lira (mdiazcl)"
# DESCRIPTION OF THE MODULE
DESCRIPTION="This module will install FuzzBunch o... | Python | 1 |
'*"]
pub const DISPID_MX_ATTRIBUTES_REMOVEATTRIBUTE: u32 = 1375u32;
#[doc = "*Required features: 'Win32_Data_Xml_MsXml'*"]
pub const DISPID_MX_ATTRIBUTES_SETATTRIBUTE: u32 = 1376u32;
#[doc = "*Required features: 'Win32_Data_Xml_MsXml'*"]
pub const DISPID_MX_ATTRIBUTES_SETATTRIBUTES: u32 = 1377u32;
#[doc = "*Required fe... | Rust | 0 |
= &slice[..list1.len()] {
return Comparison::Sublist;
}
slice = &slice[1..];
}
} else {
let mut slice = &list1[..];
while slice.len() >= list2.len() {
if list2 == &slice[..list2.len()] {
return Comparison::Superlist;
... | Rust | 0 |
>,</kbd> (thousands separator). For locales where the thousands
/// separator is a "." (e.g., Brazil), this key may generate a <kbd>.</kbd>.
NumpadComma,
/// <kbd>. Del</kbd>. For locales where the decimal separator is "," (e.g.,
/// Brazil), this key may generate a <kbd>,</kbd>.
NumpadDecimal,
/// <kbd>/</kbd>
... | Rust | 0 |
read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
Ok(OrgFreedesktopLogin1ManagerSessionRemoved {
arg0: i.read()?,
arg1: i.read()?,
})
}
}
impl dbus::message::SignalArgs for OrgFreedesktopLogin1ManagerSessionRemoved {
const NAME: &'static str = "SessionRe... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.