text string | label_name string | labels int64 |
|---|---|---|
=> srli_shift!(8),
9 => srli_shift!(9),
10 => srli_shift!(10),
11 => srli_shift!(11),
12 => srli_shift!(12),
13 => srli_shift!(13),
14 => srli_shift!(14),
15 => srli_shift!(15),
_ => srli_shift!(16),
}};
r.as_i64x2()
}
/// movapd
#[inline]
pub unsa... | Rust | 0 |
from flask import Blueprint
from flask_restful import Resource
from atp.utils.common import get_request_json, make_response, username_to_nickname
from atp.api.mysql_manager import UICasePageInfoManager,UICasePageObjectInfoManage
page = Blueprint('page_interface', __name__)
class Page(Resource):
def __init__(... | Python | 1 |
j = 88
elif taskToEval == 'alzheimerca':
Nsubj = 65
elif taskToEval == 'alzheimercf':
Nsubj = 52
elif taskToEval == 'alzheimeraf':
Nsubj = 59
elif taskToEval == 'parkinson':
Nsubj = 81
elif taskToEval == 'cognitive':
Nsu... | Python | 1 |
import logging
logger = logging.getLogger(__name__)
import sys
def list_h5(filename):
import tables
from PYME.IO import MetaDataHandler
from PYME.IO import tabular
from PYME.IO import unifiedIO
import json
with unifiedIO.local_or_temp_filename(filename) as fn:
with tables.open_file... | Python | 1 |
o.nng_aio());
}
}
pub fn reply(&mut self, msg: NngMsg, sender: oneshot::Sender<Result<()>>) {
if self.state != ReplyState::Wait {
panic!();
}
self.reply_sender = Some(sender);
unsafe {
let aio = self.aio.nng_aio();
self.state = Reply... | Rust | 0 |
from langchain_chroma import Chroma
from utils.eval_utils import get_langchain_chroma
import chromadb
import os
from dotenv import load_dotenv
from langchain_openai import OpenAIEmbeddings
from dotenv import load_dotenv
import ast
load_dotenv('../config/keys.env', override=True)
OPENAI_API_KEY = os.getenv('OPENAI_API_... | Python | 1 |
rel)
elif model.model_name in ["ukt"] and model.use_CL != 0:
loss,temp = model_forward(model, data)
else:
loss = model_forward(model, data)
opt.zero_grad()
loss.backward()#compute gradients
if model.model_name == "rkt":
... | Python | 1 |
(7, 0, 1), (8, 0, 1),
(9, 0, 1));
assert_match_groups!(r"a{3,}?", "aaaaaaa", (0, 0, 3));
assert_match_groups!(r"a{3,5}?", "aaa", (0, 0, 3));
assert_match_groups!(r"a{3,5}?", "aaaa", (0, 0, 3));
assert_match_groups!(r"a{3,5}?", "a... | Rust | 0 |
upil_pos[i] < left_pupil_target[i]:
left_pupil_pos[i] = min(left_pupil_pos[i] + pupil_speed, left_pupil_target[i])
elif left_pupil_pos[i] > left_pupil_target[i]:
left_pupil_pos[i] = max(left_pupil_pos[i] - pupil_speed, left_pupil_target[i])
if right_pupil_pos[i] ... | Python | 1 |
import pandas as pd
import pytest
from statsforecast import StatsForecast
from statsforecast.utils import AirPassengersDF as df
from statsforecast.models import (
AutoARIMA,
AutoETS,
AutoCES,
AutoTheta,
MSTL,
GARCH,
ARCH,
HistoricAverage,
Naive,
RandomWalkWithDrift,
Seasonal... | Python | 1 |
ling generated inputs in terse mode is a bit of a mess.
// First, we collect all inputs, expecting blank slots where we'll fill
// in the generated values.
let mut fields = input
.split(TERSE_IFS)
.map(|s| s.to_string())
.collect::<Vec<String>>();
if fields.len() != names.len() {... | Rust | 0 |
map_mask])
map_feature = map_feature.new_zeros(num_center_objects, num_polylines, map_feature_valid.shape[-1])
map_feature[map_mask] = map_feature_valid
# dense future prediction
obj_feature, pred_dense_future_trajs = self.apply_dense_future_prediction(
obj_feature=obj_featu... | Python | 1 |
::raw::c_void,
) -> hb_bool_t,
>;
#[doc = " hb_font_get_glyph_name_func_t:"]
#[doc = ""]
#[doc = " A virtual method for the #hb_font_funcs_t of an #hb_font_t object."]
#[doc = ""]
#[doc = " This method should retrieve the glyph name that corresponds to a"]
#[doc = " glyph ID. The name should be returned in a string... | Rust | 0 |
#!/usr/bin/env python3
"""
Test script to verify session management and duplicate prevention.
This script tests the session cleanup and duplicate prevention features.
"""
import asyncio
import sys
import os
import json
from datetime import datetime
# Add the current directory to the Python path
sys.path.append(os.pat... | Python | 1 |
let mut data = Vec::new();
self.input.read_to_end(&mut data)?;
Ok(Sound {
id,
format,
num_samples,
data,
})
}
pub fn read_sound_stream_head(&mut self) -> Result<SoundStreamHead> {
// TODO: Verify version requirements.
let p... | Rust | 0 |
} => &icons::SEARCH,
}
}
fn player_widget() -> impl Widget<Playback> {
Flex::row()
.with_child(
small_button_widget(&icons::SKIP_BACK)
.on_click(|ctx, _, _| ctx.submit_command(cmd::PLAY_PREVIOUS)),
)
.with_default_spacer()
.with_child(player_play_pau... | Rust | 0 |
"][1]
# pre-check latitude order and reverse if it is descending order
lat_start_data = get_latitude(ds)[0].values.item()
lat_end_data = get_latitude(ds)[-1].values.item()
if lat_start_data > lat_end_data:
ds = _reverse_lat(ds)
# proceed subset... | Python | 1 |
import sys
sys.path.append("build/")
from itertools import product
import _kernels
import pytest
import torch
def assert_close(a, b):
rtol, atol = {
torch.float16: (5e-3, 5e-3),
torch.bfloat16: (3e-2, 2e-2),
}[a.dtype]
torch.testing.assert_close(a, b, rtol=rtol, atol=atol)
def differe... | Python | 1 |
ize,
n_partition: usize,
) -> Result<(Vec<RangeProof>, Vec<RistrettoPoint>), RangeProofError> {
if value_vec_clipped.len() != blinding_vec.len() {
return Err(ProofError::WrongNumBlindingFactors.into());
}
// TODO mlei: checkbounds
if is_out_of_range(&value_vec_clipped, prove_range) {
... | Rust | 0 |
# =============================================================================
# Ural Classes Unit Tests
# =============================================================================
import pytest
from ural.classes import TrieDict
class TestTrieDict(object):
def test_basics(self):
trie = TrieDict()
... | Python | 1 |
ands
def provide_help(self):
print(
"\nHere are the available commands:\n\n"
"Use 'quit()' to exit the program\n"
"Use 'see_prompt()' to see the prompt that you've been building\n"
"Use 'submit_prompt()' to submit the prompt you've been building\n... | Python | 1 |
rn],1,100000)
# obj.passTransaction(obj.playerOrder[obj.currentTurn])
# obj.passTransaction(obj.playerOrder[obj.currentTurn])
# # obj.sell(obj.playerOrder[obj.currentTurn],1,4000)
# # obj.sell(obj.playerOrder[obj.currentTurn],1,2000)
# obj.passTransaction(obj.playerOrder[obj.currentTurn])
# obj.buy(obj.playerOrder[ob... | Python | 1 |
#!/usr/bin/env python
import sys
from xml.etree import ElementTree as ET
import json
import re
import datetime
class DestFileCreator:
nextTrip = 1
def __init__(self, firstTrip):
self.nextTrip = firstTrip
def next_dest(self, data_file):
newName = "Trip" + str(self.nextTrip).zfill(3) + "-"... | Python | 1 |
import os
import time
import pickle
import torch
import numpy as np
import sympy as sp
from pydantic import BaseModel, model_validator, field_validator, computed_field, ConfigDict
from typing import Dict, Optional, List, Tuple
class HomogeneousFDNConfig(BaseModel):
"""
Configuration class for the HomogeneousF... | Python | 1 |
::FileDownloadResult>>>,
uploads: HashMap<super::FiletransferHandle, oneshot::Sender<Result<super::FileUploadResult>>>,
}
impl From<super::Connection> for SyncConnection {
fn from(con: super::Connection) -> Self {
let (send, recv) = mpsc::channel(1);
Self {
con,
recv,
send,
commands: Default::defaul... | Rust | 0 |
n = int(input()) # The number for which we need to count digits
d = int(input()) # The digit whose occurrences we need to count
count = 0 # To keep track of occurrences
place = 1 # To track the current place (1s, 10s, 100s, etc.)
while n // place > 0:
higher = n // (place * 10)
current_digit = (n // place... | Python | 1 |
o_draw = cv2.resize(resized, (int(self.input_shape[0]*vidar), self.input_shape[1]))
# Use model to predict
inputs = [image.img_to_array(rgb)]
tmp_inp = np.array(inputs)
x = preprocess_input(tmp_inp)
y = self.model.predict(x)
... | Python | 1 |
from sys import stdin
for line in stdin:
line = line.split()
a = int(line[0])
b = int(line[1])
print(abs(a - b)) | Python | 1 |
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
"""Application settings."""
app_name: str = "User Management API"
secret_key: str = "YOUR_SECRET_KEY_HERE" # In production, set this securely
algorithm: str = "HS256"
access_token_expire_minutes: int = 30
class Conf... | Python | 1 |
DF_NAME};
use mnemonic::{self, gen_entropy, HDPath, Language, Mnemonic, ENTROPY_BYTE_LENGTH};
use rustc_serialize::json as rustc_json;
use serde_json;
use std::cell::RefCell;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use util;
fn to_chain_id(chain: &str, chain_id: Option<usize>, default_id: u16) -> u16 {
... | Rust | 0 |
(
(4. * log(6. / 5., b) + log(3. / 5., b)) / 5., relative_entropy(p, q, b))
q = Dist([1, 2, 2])
for b in np.arange(2.0, 4.0, 0.5):
self.assertAlmostEqual(log(2., b) / 5., relative_entropy(p, q, b))
p = Dist([1, 0, 0])
q = Dist([4, 1, 0])
for b in np.... | Python | 1 |
"context",
|m: &SplitRegionRequest| { &m.context },
|m: &mut SplitRegionRequest| { &mut m.context },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
"sp... | Rust | 0 |
point time is in the ISO8601 extended YYYY-MM-DD'T'HH:MM:SS'Z' format.</p>
pub tape_recovery_point_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The size, in bytes, of the virtual tapes to recover.</p>
pub tape_size_in_bytes: std::option::Option<i64>,
/// <p>The status of the virtual ta... | Rust | 0 |
# Docs: https://python.langchain.com/v0.1/docs/modules/tools/custom_tools/
# Import necessary libraries
import os
from typing import Type
from dotenv import load_dotenv
from langchain import hub
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain.pydantic_v1 import BaseModel, Field
fr... | Python | 1 |
\033[01;33m=============================================\033[00m""")
@classmethod
def installing(self):
print ("""\033[01;33m =============================================
\033[01;32m|________________ Installing _________________|
\033[01;33m=============================================\033[00m""")
@class... | Python | 1 |
torch.topk(prob, k_value, dim=1)
scores = topk_values
topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
labels = topk_indexes % out_logits.shape[2]
boxes = center_to_corners_format(out_bbox)
boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).re... | Python | 1 |
3, {cylcount} цил.\nТип - {mtype},\nVLK - {actual_vlk}")
label = tk.Label(root, text=root_title, justify="left", background='light grey')
label.pack(anchor="w")
root.minsize(420, 600)
# Создаем в нем фрейм для скроллинга
scrollable_frame = tk.Frame(root)
scrollable_frame.pack(fill="both", expan... | Python | 1 |
after the last decimal digit, and so on. This could overflow if done carelessly. We rely on
//! the parsing submodule to only hand out sufficiently small exponents, where "sufficient" means
//! "such that the exponent +/- the number of decimal digits fits into a 64 bit integer".
//! Larger exponents are accepted, but ... | Rust | 0 |
if key == ord("q"):
break
else:
writer.write(main_frame)
# Preview rendering on server
cv2.imshow("video", main_frame)
key = cv2.waitKey(1) & 0xFF
... | Python | 1 |
or.complaints.filter(status='in_progress').count(),
'resolved': doctor.complaints.filter(status='resolved').count(),
'closed': doctor.complaints.filter(status='closed').count(),
}
})
@api_view(['GET'])
@permission_classes([DoctorComplaintPermission])
def doctor_complaint_detail(req... | Python | 1 |
else {
bail!("{} does not have replicaCount", self.name);
}
for w in &self.workers {
if let Some(resources) = &w.container.resources {
base += resources.normalised()? * w.replicaCount;
}
// TODO: account for autoscaling in workers when it'... | Rust | 0 |
o #56288. Check that a supertrait projection (of
// `Output`) that references `Self` can be ok if it is referencing a projection (of
// `Self::Target`, in this case). Note that we still require the user to manually
// specify both `Target` and `Output` for now.
trait Base {
type Output;
}
trait Helper: Base<Outpu... | Rust | 0 |
nk_32.name());
assert_eq!("BANK", bank_32a.name());
}
#[test]
fn data_types_bank_views() {
let buffer = [66u8, 65, 78, 75, 1, 0, 1, 0, 100];
let bank_16 = BankView::B16(Bank16View::try_from_le_bytes(&buffer).unwrap());
let buffer = [66u8, 65, 78, 75, 4, 0, 0, 0, 4, 0, 0, 0, 100, 155, 200, 255];
le... | 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 u... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017-2020 The Project X-Ray Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
'''
Generate a primitive to place at ... | Python | 1 |
check whether the xArm movement is blocked, whether the payload exceeds the rated payload of xArm, and whether the acceleration value is too large. If it appears frequently, please contact technical support.",
},
"cn": {
"title": "电机位置偏差过大",
"desc": "请检查机械臂运动是否受阻,末端负载是否超过机械臂额定负载... | Python | 1 |
ompt")
col1, col2 = st.columns(2)
with col1:
test_prompt = st.text_area("Optimized Prompt", value="", height=200, key="test_prompt")
with col2:
test_question = st.text_area("Your Question", value="", height=200, key="test_question")
if st.button("Test Prompt"):... | Python | 1 |
most input and output formats expect an interleaved stream. This trait is used for those
/// conversions.
pub trait Interleave : super::Sample {
/// Interleaves all channels in `input` into output.
///
/// `out`'s contents must not require `drop`ping -- it is expected that the values there on entry
///... | Rust | 0 |
t pml4[pml4_index];
pml4_entry.ensure_present(&bitmap)?;
let pdpt_entry = &mut pml4_entry.as_mut_ref()[pdpt_index];
pdpt_entry.ensure_present(&bitmap)?;
let pd_entry = &mut pdpt_entry.as_mut_ref()[pd_index];
pd_entry.entry = join(
... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Adapters layer for holdings: builds a normalized snapshot used by Telegram commands
and smoke scripts. No network side-effects at import time.
"""
from __future__ import annotations
from typing import Any, Dict
try:
from core.holdings import get_wallet_snapshot # authoritative API
excep... | Python | 1 |
import pandas as pd
import numpy as np
import os
import pandas as pd
import numpy as np
import os
def generate_patient_csv(n_patients, delta, T, mu=12, std=5.0, folder=".", filename="patients.csv"):
"""
Generate patient CSV in the specified folder (default: current),
using normal distribution for number o... | Python | 1 |
# -*- coding: utf-8 -*-
import pandas as pd
import string
import time
import numpy as np
import scipy as sp
import gc
from scipy.stats import mode
import matplotlib.pyplot as plt
import math
usercost1=pd.read_csv(r'D:\360datamining\data\firstdata\data\consumption_recode.csv')
user=pd.read_csv(r'D:\360datamining\data\fi... | Python | 1 |
# MIT License
#
# Copyright The SCons Foundation
#
# 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 use, copy, modify, merge, ... | Python | 1 |
// an adapted RFC 2822 syntax from Section 3.3 and 4.3:
//
// date-time = [ day-of-week "," ] date 1*S time *S
// day-of-week = *S day-name *S
// day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun"
// date = day month year
// day = *S 1*2DIGIT *S
// month ... | Rust | 0 |
_base_ = '../higherhrnet/higherhrnet_w48_coco_640x640.py'
checkpoint_config = dict(interval=2)
evaluation = dict(interval=15, metric='mAP', key_indicator='AP')
log_config = dict(interval=50)
WITH_CENTER = 1
NUM_JOINTS = 17
channel_cfg = dict(
num_output_channels=NUM_JOINTS + WITH_CENTER,
dataset_joints=NUM_... | Python | 1 |
_queues:
q.put(args)
result = response_queue.get()
if isinstance(result, ModelFailure):
raise RuntimeError
img, metadata = result
return img, metadata
submit_btn.click(
on_submit,
[
cap1,
... | Python | 1 |
ples')
axes[1].set_ylabel('Expected Accuracy')
axes[1].set_title('Impact of Dataset Size on Performance')
axes[1].grid(True, alpha=0.3)
axes[1].legend()
# Add annotations
axes[1].annotate('You are here', xy=(95, 0.73), xytext=(150, 0.65),
arrowprops=dict(arrowstyle='->', color='red', lw=2))
axes[1].ann... | Python | 1 |
from fusil.file_tools import relativePath
from fusil.process.create import CreateProcess
class MangleProcess(CreateProcess):
def __init__(
self, project, arguments, mangle_pattern, use_relative_mangle=True, **kw
):
CreateProcess.__init__(self, project, arguments, **kw)
self.orig_cmdlin... | Python | 1 |
GHT,
lock.DOMAIN: TYPE_LOCK,
media_player.DOMAIN: TYPE_SETTOP,
scene.DOMAIN: TYPE_SCENE,
script.DOMAIN: TYPE_SCENE,
select.DOMAIN: TYPE_SENSOR,
sensor.DOMAIN: TYPE_SENSOR,
switch.DOMAIN: TYPE_SWITCH,
vacuum.DOMAIN: TYPE_VACUUM,
valve.DOMAIN: TYPE_VALVE,
water_heater.DOMAIN: TYPE_... | Python | 1 |
s,
"{} is not approximately equal to {}",
a.re,
b.re
);
assert!(
((a.im - b.im) as f64).abs() <= eps,
"{} is not approximately equal to {}",
a.im,
b.im
);
}};
}
pub struct CvtaDetails {
pub to: CvtaStateS... | Rust | 0 |
t mut last_name_cursor: usize = 0;
let last_name_id = gen_id.next();
let submit_id = gen_id.next();
let clear_id = gen_id.next();
let quit_id = gen_id.next();
let hide_db_id = gen_id.next();
let mut hide_db_state = false;
let mut database = Vec::<(String, String)>::new();
while !quit {... | Rust | 0 |
")]
#[test_case("v.1.2.3" => Err((ErrorKind::UnexpectedInput, Span::new(1, 2))); "v followed by dot")]
#[test_case("v-2.3.4" => Err((ErrorKind::UnexpectedInput, Span::new(1, 2))); "v followed by hyphen")]
#[test_case("v+3.4.5" => Err((ErrorKind::UnexpectedInput, Span::new(1, 2))); "v followed by plus")]
... | Rust | 0 |
sition = np.array(robot_state["joint_positions"])
gripper_position = np.array([robot_state["gripper_position"]])
# Save the images to disk so that they can be viewed live while the robot is running
# Create one combined image to make live viewing easy
if save_to_disk:
combined_image = np.concat... | Python | 1 |
rs::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> OutPointBuilder<'a, 'b> {
#[inline]
pub fn add_block_hash(&mut self, block_hash: &'b H256) {
self.fbb_.push_slot_always::<&H256>(OutPoint::VT_BLOCK_HASH, block_hash);
}
#[inline]
pub fn add_tx_hash(&mut self, tx_hash: &'b H256) {
self.fbb_.push_slot_... | Rust | 0 |
"""
Django rules for Refund
"""
import rules
from edx_rbac.utils import user_has_access_via_database
from ecommerce.core.constants import ORDER_MANAGER_ROLE
from ecommerce.core.models import EcommerceFeatureRoleAssignment
@rules.predicate
def request_user_has_refund_access(user):
"""
Check that if request ... | Python | 1 |
std::env::var("NETCDF_DIR") {
println!("cargo:rustc-link-search={}/lib", dir);
println!("cargo:rustc-link-lib=netcdf");
} else {
// Link to the system netcdf
println!("cargo:rustc-link-lib=netcdf");
}
}
}
use clap::arg_enum;
use mozlz4::{compress, dec... | Rust | 0 |
aphics::Mesh::new_line(
ctx,
&[
na::Point2::new(0.0, rect.h),
na::Point2::new(rect.w, rect.h),
],
1.5,
graphics::BLACK,
)?;
graphics::draw(ctx, &x_line, (rect.point(),))
}
fn draw_guide_line(
&s... | Rust | 0 |
assing,
"model__metric_list": None,
"model__predictor__activation": "relu",
"model__warmup_epochs": 2,
"model__predictor": MulticlassClassificationFFN,
"model__predictor__criterion": CrossEntropyLoss,
"model__predictor__criterion__task_weights": Tensor([1.0, 1.0, 1.0]),
"model__predictor__dr... | Python | 1 |
import torch
import torch.nn as nn
import numpy as np
import random
from tqdm import tqdm
import pickle
import time
import scipy
import scipy.io
import matplotlib.pyplot as plt
from utility import PINNs, get_data_2d, pf_func, init_weights
# PINNs
seed = 42
device = 'cuda:0'
# ----------------------------
# Configura... | Python | 1 |
score = 0
# Assign weights to each section
scoring_weights = {
"TODO: 广播粒子数据到所有进程": 10,
"TODO: 同步所有进程模拟的信息": 15,
"TODO: 归约所有进程计算的局部动量分量和能量(4次归约操作,到0号进程)": 15
}
# Reading the user's answers from my_mpi_comm.txt
user_answers = {}
current_todo = None
for line in user_c... | Python | 1 |
status if status >= 200 && status < 300 => {
let response = response
.text()
.await
.map_err(|err| RestHttpError::IoError(err))?;
nanoserde::DeJson::deserialize_json(&response)
.map_err(|json_err| RestHttpE... | Rust | 0 |
("Error returned is not the expected one: {}", err));
}
};
}
Ok(())
}
#[tokio::test]
async fn test_safeurl_validate_url_chars_with_control_characters() -> Result<()> {
let urls = vec![
// tests for
// https://en.wikipedia.org/wiki/... | Rust | 0 |
4 = Formatted code differs from existing code (write-mode diff only)"#;
println!("{}", exit_codes);
}
}
#[derive(Clone, Copy, Debug)]
enum Timer {
Initialized(Instant),
DoneParsing(Instant, Instant),
DoneFormatting(Instant, Instant, Instant),
}
impl Default for Timer {
fn default() ->... | Rust | 0 |
fault_cached_above_base_layer(tree_leafs, BINARY_ARITY),
);
let pp = public_params(
PaddedBytesAmount::from(porep_config),
usize::from(PoRepProofPartitions::from(porep_config)),
)?;
let offset_padded: PaddedBytesAmount = UnpaddedBytesAmount::from(offset).into();
let num_bytes_padded... | Rust | 0 |
define_distances,
dijkstra])
.attach(cors)
.launch();
}// This file is part of ucx. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/ucx/master/C... | Rust | 0 |
f.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u16) & 0x01) << 3);
self.w
}
}
#[doc = "4:4\\]
Regulator off\n\nValue on reset: 0"]
#[derive(Clone, Copy, De... | Rust | 0 |
(&[1, -1]));
assert_eq!(10, compute_test_result_task2(&[3, 3, 4, -2, -4]));
assert_eq!(5, compute_test_result_task2(&[-6, 3, 8, 5, -6]));
assert_eq!(14, compute_test_result_task2(&[7, 7, -2, -7, -4]));
}
}
//! Module for music related functions and constructs.
//!
//! See also [`sound`](supe... | Rust | 0 |
(bitmap: Self::PtrSize, nibble: u32) -> usize {
(bitmap >> ((256 >> 1) - nibble as u16 - 1) as usize).count_ones()
as usize
- 1
}
fn into_stride_size(bitmap: Self::PtrSize) -> Self {
// One bit needs to move into the self.0 u128,
// since the last bit of the *who... | Rust | 0 |
# actions = [self.action_tokenizer.decode_token_ids_to_actions(elem) for elem in action]
# print("action.shape:",action.shape)
# print("actions:",action)
action=action.reshape(-1)
return np.array(action)
if __name__ == "__main__":
inference_times = []
torch.cuda... | Python | 1 |
Addr::from_str("127.0.0.1:3456").unwrap(), Default::default());
//! ms1.start().unwrap();
//! ms2.join(SocketAddr::from_str("127.0.0.1:2345").unwrap()).unwrap();
//! std::thread::sleep(Duration::from_secs(ProtocolConfig::default().protocol_period * 2));
//! println!("{:?}", ms1.get_members().unwrap());
//! println!("{:... | Rust | 0 |
) as file:
writer = csv.DictWriter(file, fieldnames=header)
writer.writeheader()
for i in output_list:
writer.writerow(i)
def get_score(self, src_str: str, des_str: str):
# 评分标准为匹配度越高,得分越低
# 原因是为了与之前文件中写过的编辑距离的分数规则相同
# 根据两个输入字符长度判断... | Python | 1 |
batch_size = x.size(0)
batch = torch.zeros(batch_size, dtype=torch.long, device=x.device)
out = global_add_pool(out, batch)
return out
@pytest.fixture()
def hetero_model_native():
return NativeHeteroGNN
class HeteroConvModel(torch.nn.Module):
def __init__(self, metadata, mod... | Python | 1 |
# scraper/scrapers.py
import requests
from bs4 import BeautifulSoup
import datetime
import json
from .base_scraper import BaseScraper
class BaseScraper:
def scrape(self, **kwargs):
raise NotImplementedError
class TFCScraper(BaseScraper):
def scrape(self, base_url: str, max_pages: int = 1) -> list[dic... | Python | 1 |
"test"
path = "lib.rs"
"#;
#[derive(Builder, Default, Debug)]
#[builder(default, setter(into))]
pub struct TestRun {
update_snapshots: bool,
root_dir: PathBuf,
}
impl TestRun {
pub fn run(&self) -> Result<TestRunResult> {
let mut cmd = Command::new("cargo");
cmd.current_dir(&self.root_dir... | Rust | 0 |
;
fn recover(&self, _: E) -> Result<Self::Backoff, E> {
Ok(self.0.stream())
}
}
<reponame>RazrFalcon/svgdom
use std::fmt;
use log::warn;
use slab::Slab;
use crate::parser::parse_svg;
use crate::writer;
use crate::{
AttributeQName,
Attributes,
AttributeValue,
ElementId,
FilterSvg,... | Rust | 0 |
(Default: 0.0.0.0:0)"))
.get_matches()
}
}
<filename>src/main.rs
mod solutions;
mod util;
use solutions::*;
fn main() {
let args = std::env::args().collect::<Vec<String>>();
let problem = args.get(1).map(|s| s.as_str()).unwrap_or("None");
let start = std::time::Instant::now();
match... | Rust | 0 |
T1CTL,
}
#[doc = "Timer 0 Configuration\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::modify). See [API](https://docs.rs/svd2rust/#rea... | Rust | 0 |
#print(f"El profesor {profesor} no tiene un horario asignado para el día {dia_semana}.")
penaliza += 1
else:
#print(f"El profesor {profesor} no puede dar clase en ese horario.")
penaliza += 1
if penaliza >=1: return 1
else: return 0
############... | Python | 1 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
from PIL import Image
from torchvision.datasets import ImageFolder
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
print()
#Additional Info when using cuda... | Python | 1 |
from swesmith.bug_gen.procedural.base import ProceduralModifier
from swesmith.bug_gen.procedural.python.classes import (
ClassRemoveBasesModifier,
ClassRemoveFuncsModifier,
ClassShuffleMethodsModifier,
)
from swesmith.bug_gen.procedural.python.control_flow import (
ControlIfElseInvertModifier,
Cont... | Python | 1 |
!()
}
pub fn extractEulerAngleZXZ<N: Real>(M: &TMat4<N>) -> (N, N, N) {
unimplemented!()
}
pub fn extractEulerAngleZYX<N: Real>(M: &TMat4<N>) -> (N, N, N) {
unimplemented!()
}
pub fn extractEulerAngleZYZ<N: Real>(M: &TMat4<N>) -> (N, N, N) {
unimplemented!()
}
pub fn orientate2<N: Real>(angle: N) -> TMa... | Rust | 0 |
bits(0b01)
.extsel()
.bits(0b011) // T2C2
.align()
.clear_bit()
.dma()
.set_bit()
.dds()
.set_bit()
.cont()
.clear_bit()
.adon()
... | Rust | 0 |
name = "championId", skip_serializing_if = "Option::is_none")]
pub champion_id: Option<i32>,
#[serde(rename = "championPickIntent", skip_serializing_if = "Option::is_none")]
pub champion_pick_intent: Option<i32>,
#[serde(rename = "playerType", skip_serializing_if = "Option::is_none")]
pub player_typ... | Rust | 0 |
response = client.get("/api/v1/portfolio/portfolios/nonexistent")
# 驗證響應
assert response.status_code == 404
def test_update_portfolio_success(
self, client, mock_portfolio_service, sample_portfolio
):
"""測試成功更新投資組合"""
# 設定模擬
mock_portfolio_service.get_portfolio.... | Python | 1 |
import argparse
import os
import re
import sys
from datetime import date
import changelog
import tomlkit as toml
from semver import Version
with open("pyproject.toml", "r") as f:
pyproject = toml.load(f).unwrap()
old_version = Version.parse(pyproject["project"]["version"])
version = old_version
parser = argpar... | Python | 1 |
portunity'],
best_opportunity['market_condition'],
best_opportunity['market_data']
)
opportunities_sent = 1
if opportunities_sent == 0:
try:
print(f"✅ No new alerts sent (all in cooldown) at {datetime.now().strftime('... | Python | 1 |
riptor_sets(doc: &Spirv) -> TokenStream {
// TODO: not implemented correctly
// Finding all the descriptors.
let mut descriptors = Vec::new();
struct Descriptor {
set: u32,
binding: u32,
desc_ty: TokenStream,
array_count: u64,
readonly: bool,
}
// Loopin... | Rust | 0 |
': 'sami Skoltwara', 'yue': '斯科特薩米文', 'yue-Hans': '斯科特萨米文', 'yue-Hant': '斯科特薩米文', 'zh': '斯科特萨米语', 'zh-Hans': '斯科特萨米语', 'zh-Hant': '斯科特薩米文', 'zu': 'isi-Skolt Sami'},
'smt': {'en': 'Simte'},
'smu': {'en': 'Somray'},
'smv': {'en': 'Samvedi'},
'smw': {'en': 'Sumbawa'},
'smx': {'en': 'Samba'},
'smy':... | Python | 1 |
under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::arch::x86_64::*;
/// Returns true if this set contains the given value (u... | Rust | 0 |
ARN the feature `const_generics` is incomplete and may cause the compiler to crash
trait UnwrapItemsExt<'a, const C: usize> {
type Iter;
fn unwrap_items(self) -> Self::Iter;
}
struct MyStruct<const C: usize> {}
trait MyTrait<'a, const C: usize> {
type MyItem;
const MY_CONST: usize;
}
impl<'a, const ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.