text string | label_name string | labels int64 |
|---|---|---|
put.
let x = z;
let x_sq = x.square(cs.namespace(|| "x_sq"))?;
let x_cu = x_sq.mul(cs.namespace(|| "x_cu"), &x)?;
let y = AllocatedNum::alloc(cs.namespace(|| "y"), || {
Ok(x_cu.get_value().unwrap() + x.get_value().unwrap() + F::from(5u64))
})?;
cs.enforce(
|| "y = x^... | Rust | 0 |
method(#method)
.path(#path)
})
}
}
pub fn dispatch_fn(&self) -> TokenStream {
TyTree::new(self.args())
.extract_args()
}
pub fn dispatch(&self) -> TokenStream {
// Because the arguments *might* be closed over into a trait object that... | Rust | 0 |
352195);
}
#[test]
fn test_iterate_days_less_allocation() {
let input = parse_str::<u8>(COMMANDS);
assert_eq!(less_allocation_iterate(18, &input).len(), 26);
// assert_eq!(less_allocation_iterate(80, &input).len(), 5934);
// assert_eq!(less_allocation_iterate(256, &input).l... | Rust | 0 |
l_gal_bin_{}_{}.txt'.format(i, j))
ell = open_dat(save_dir + 'measured_3x2pt_bps/galaxy_bp/ell.txt')
bp_measured = open_dat(save_dir + 'measured_3x2pt_bps/galaxy_bp/bin_{}_{}.txt'.format(i, j))
bp_err = open_dat(save_dir + 'measured_3x2pt_bps/galaxy_bp/bin_{}_{}_err.txt'.format(i, j... | Python | 1 |
ctor_3d(p, num_knn + 1)
indices.append(idx[1:]) # Skip the first index since it's the point itself
sq_dists.append(dist[1:])
return torch.tensor(sq_dists, dtype=pts_tensor.dtype, device=pts_tensor.device), torch.tensor(indices, dtype=torch.long, device=pts_tensor.device)
def params2cpu(params, i... | Python | 1 |
#!/usr/bin/env python3
##############################################################################bl
# MIT License
#
# Copyright (c) 2025 Advanced Micro Devices, Inc. All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation... | Python | 1 |
# shortcuts
def offA(self):
'''
Set status to 'off'
Input:
None
Output:
None
'''
self.set_statusA(False)
def onA(self):
'''
Set status to 'on'
Input:
None
Output:
None
... | Python | 1 |
from django.contrib import admin
from .models import Message, Thread, UserSetting
# Register your models here.
admin.site.register(UserSetting)
class MessageInline(admin.StackedInline):
model = Message
fields = ('sender', 'text', 'isread')
readonly_fields = ('sender', 'text', 'isread')
class ThreadAdmin... | Python | 1 |
import enum
import json
from sqlalchemy.orm import declarative_base
from sqlalchemy import TypeDecorator, VARCHAR, Integer, Column, Text, ForeignKey, Boolean
from sqlalchemy.types import Enum
Base = declarative_base()
class ListType(TypeDecorator):
impl = VARCHAR
def process_bind_param(self, value, dialect)... | Python | 1 |
pt) {
true => Some((y, (yt, ypt))),
false => None
}).collect(); // every person tested positive and their interval
let mut zp: Vec<(i32, Edge)> = edges.par_iter()
.filter(|e| matches!(e.label,Label::meets))
.map(|e| (e.dst, e.clone())).collect... | Rust | 0 |
]
fn should_support_redactions_changing_length() {
let redact = &vec![s!(r"(?:123)"), s!(r"(?:def)")];
let p = LineRules::new(&[], &[], redact).unwrap();
redact_match!(p, "Hello INFO not redacted", "Hello INFO not redacted");
redact_match!(
p,
"count def 123 h... | Rust | 0 |
import datetime
from openlibrary.plugins.worksearch.code import execute_solr_query
from openlibrary.plugins.worksearch.search import get_solr
def fetch_works_trending_scores(current_day: int):
resp = execute_solr_query(
'/export',
{
"q": f'trending_score_hourly_sum:[1 TO *] OR trendin... | Python | 1 |
er_a = EventListener { ret: None };
let listener_b = EventListener { ret: None };
dispatcher.add(Box::new(listener_a));
dispatcher.add(Box::new(listener_b));
let mut uses = 0;
dispatcher.dispatch(&(), &mut uses);
assert_eq!(uses, 2);
}
/// Tests that a listener will not be called after it has requested to stop l... | Rust | 0 |
ent = tangent.into();
verticies[chunk[0] as usize].bitangent = bitangent.into();
verticies[chunk[1] as usize].bitangent = bitangent.into();
verticies[chunk[2] as usize].bitangent = bitangent.into();
}
let vertex_buffer = device.create_buffer_init... | Rust | 0 |
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
text=True)
package_location = package_location.stdout.strip()
os.environ["AS_DAEMON_PATH"] = package_location + "/dashinfer/allspa... | Python | 1 |
"""
Extensions to the Open Spherical Camera API specific to the Gear 360 camera (2017).
Usage:
At the top of your Python script, use
from osc.gear360_2017 import Gear360_2017
After you import the library, you can use the commands like this:
gear360 = Gear360_2017()
gear360.state()
gear360.info()
# Captur... | Python | 1 |
,
PAGE_EXECUTE_READWRITE,
TOKEN_ALL_ACCESS,
HANDLE,
LUID,
TOKEN_PRIVILEGES,
LUID_AND_ATTRIBUTES,
SE_PRIVILEGE_ENABLED,
SECURITY_DESCRIPTOR
},
processthreadsapi::{
OpenProcess,
CreateRe... | Rust | 0 |
")
mapper_path = os.path.join(this_directory, "mapper.yaml")
sparse_opt_path = os.path.join(this_directory, "sparse_opt_output.yaml")
#sparse_opt_path = os.path.join(this_directory, "..", "multiSCNN","single_core_optimization", "yaml_gen", "sparse_opt_output.yaml")
ert_path = os.path.join(this_direc... | Python | 1 |
a\xf9o\xea\
\xa2\xb7\xa0\x98;\x1b\x80^\x99\xb6\xd9\xd5\xff\x9f\xcd\xdc\
\xb5\xda\x0c;\xa8\xf3\xd5\xffO;?\x04D6\xff\x17\
a\xff\xbf\x04\xb3\x91%\xa5,U<\xc6\xc1!xq\
\xf3\xce\xe5\x8d\xce\x13^v\x1d^D\xfdh\xe7\xe2x\
\x97\xacASx\xf0\x82\x9d\xccK\xbb<z6C\x97\
Vm\x14P \x10)\x9fy\xe7\xe6-{P\xa4\xc2\
a\x19<\xc6\xf1L\x90\x86\xb2\x... | Python | 1 |
cense <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//
#[macro_use]
extern crate clap;
extern crate futures;
extern crate hyper;
extern crate ipfs_api;
use command::CliCommand;
use ipfs_api::IpfsClient;... | Rust | 0 |
},
ser::SerializeMap,
Deserialize, Deserializer, Serialize, Serializer,
};
use zeroize::Zeroize;
use super::error::Error;
use super::wql;
pub type ProfileId = i64;
pub type Expiry = chrono::DateTime<chrono::Utc>;
pub(crate) fn sorted_tags(tags: &Vec<EntryTag>) -> Option<Vec<&EntryTag>> {
if tags.len() >... | Rust | 0 |
from m2cgen.assemblers import get_assembler_cls
from m2cgen.interpreters import FSharpInterpreter
from tests import utils
from tests.e2e.executors.base import BaseExecutor
EXECUTOR_CODE_TPL = """
{model_code}
[<EntryPoint>]
let main args =
let res = score (List.ofSeq (Seq.map double args))
{print_code}
0... | Python | 1 |
rt
... names = ' '.join(sorted(n.name for n in node.tips()))
... print(f"Tips: {names}, support: {support_value}")
Tips: F I, support: 9.0
Tips: D H J, support: 6.0
Tips: C D H J, support: 6.0
Tips: C D F G H I J, support: 6.0
Tips: C D E F G H I J, support: 9.0
Tips: B C D E F G... | Python | 1 |
from solution import *
from solution import custom_dencrypt, main
# Test custom_dencrypt function
def test_custom_dencrypt():
assert custom_dencrypt("Hello, World!", 13) == "Uryyb, Jbeyq!"
assert custom_dencrypt("Uryyb, Jbeyq!", 13) == "Hello, World!"
assert custom_dencrypt("abc", 3) == "def"
assert c... | Python | 1 |
-13");
}
#[test]
fn test_and_then() {
let mut mock = tokio_mock_task::MockTask::new();
let mut svc = Foo.then(|res| future::ok(format!("Ok-{:?}", res.unwrap())));
let mut fut = svc.call(14);
let res = assert_ready!(mock.enter(|| fut.poll()));
assert_eq!(res, "Ok-14")... | Rust | 0 |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#### Extrapolation ####
# Importing necessary libraries
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
# Create data frame for data in text
age = pd.DataFrame([6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,... | Python | 1 |
nt': None, 'test_file': test_file,
'reuse_master': reuse_master, 'clear': clear }
# add in the tests
testNames = []
for test in config.tests:
# #1989: find test first to make sure it exists and is executable
err_msg = None
try:
rp = rospkg.RosPack()... | Python | 1 |
/// # Arguments
///
/// * `name` - Name of file descriptor.
/// * `fd` - File descriptor sent by client.
pub fn set_fd(name: String, fd: RawFd) {
Self::inner().fds.write().unwrap().insert(name, fd);
}
/// Get extern file descriptor restored in `QMP_CHANNEL`.
///
/// # Argum... | Rust | 0 |
, FONT_CHARACTER_WIDTH, FONT_CHARINFO_DEPTH, FONT_CHARINFO_HEIGHT,
FONT_CHARINFO_ITALCORR, FONT_CHARINFO_WIDTH,
};
/* ***************************************************************************\
Part of the XeTeX typesetting system
Copyright (c) 1994-2008 by SIL International
Copyright (c) 2009 by <NAME>
SIL ... | Rust | 0 |
3GetJointState(
self.handle,
status_handle,
joint_index as i32,
&mut sensor_state,
) {
return Ok(sensor_state.into());
}
}
Err(Error::new("getJointState failed (2)."))
}
/// get_joint_states i... | Rust | 0 |
"--BN", action="store", default=None)
parser.add_argument("--U_ROUTING", action="store", default=None)
parser.add_argument("--ROUTING", action="store", required=True)
parser.add_argument("--ENV", action="store", required=True)
args = parser.parse_args()
DDPG_config = vars(args)
return DDPG_co... | Python | 1 |
::VBank => 0x40,
Interrupt::LCDState => 0x48,
Interrupt::TimerOverflow => 0x50,
Interrupt::SerialIOComplete => 0x58,
Interrupt::JoyPad => 0x60,
}
}
}
bitflags!(
pub struct InterruptType: u8 {
const VBLANK = 1 << 0;
const LCDSTAT = 1 << 1;
const TIMER_OVERFLOW = 1 << 2;
c... | Rust | 0 |
ize_divisor, w // size_divisor)
text_region = self.generate_text_region_mask(
level_img_size, lv_text_polys[ind], lv_text_polys_idx[ind])[None]
current_level_maps.append(text_region)
center_region = self.generate_center_region_mask(
le... | Python | 1 |
# Copyright 2020 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 agreed to in writing, s... | Python | 1 |
for PipelineInfoKHR {
fn default() -> Self { Self::new() }
}
#[repr(C)]
#[derive(Clone, Debug)]
pub struct SubpassDescription2 {
s_type : i32,
pub p_next : *const c_void,
pub flags : SubpassDescriptionFlags,
pub pipeline_bind_point : PipelineBindPoint,
pub view_mask : u32,
pub input_attachment_count : u32,
pub... | Rust | 0 |
gl::$n);
DEBUG!("Disabled GL::{}", stringify!($n));
*state &= !1u64;
}
}
pub fn Save() {
debug_assert!({
let v = overflow_map().entry(gl::$n).or_insert(0);
*v = 64.min(*v + 1);
true
});
let state = Self::state();
*state = (*state & 1u64) | (*state << 1);
}
pub... | Rust | 0 |
:
if os.path.exists(self.feedback_file):
with open(self.feedback_file, 'r', encoding='utf-8') as f:
content = f.read()
if content.strip(): # 检查文件是否为空
feedbacks = json.loads(content)
e... | Python | 1 |
quotes:
continue
for keyword in keywords:
last_token = converted_text[-len(keyword) :]
if last_token == keyword:
converted_text = converted_text[: len(converted_text) - len(keyword)] + keyword.lower()
return converted_text
clas... | Python | 1 |
: PathBuf) -> Result<()> {
let mut target = dir;
target.extend([".perseus", "dist", "static"]);
// We'll only delete the directory if it exists, otherwise we're fine
if target.exists() {
if let Err(err) = fs::remove_dir_all(&target) {
bail!(ErrorKind::RemoveArtifactsFailed(
... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Whisper weight initialization utility for OmniAudioEncoder
"""
import torch
from transformers import WhisperModel
def load_whisper_weights(encoder, whisper_model_name="openai/whisper-small", verbose=False, is_acoustic=False):
"""
Load pretrained Whisper enco... | Python | 1 |
ialize(self, params):
self._JobId = params.get("JobId")
self._RunType = params.get("RunType")
if params.get("SuccessResource") is not None:
self._SuccessResource = []
for item in params.get("SuccessResource"):
obj = AsyncResourceVO()
obj._d... | Python | 1 |
"""
Module for string manipulation operations.
"""
def reverse_string(text: str) -> str:
"""
Returns the reversed string
Args:
text (str): The string to be reversed
Returns:
str: The reversed string
Time Complexity:
O(n) where n is the length of the string
Space Com... | Python | 1 |
import bpy
# For some reason this only works when executing multiple times
obj = bpy.context.active_object
if obj is not None:
bbox = obj.bound_box
min_x = bbox[0][0]
max_x = bbox[6][0]
min_y = bbox[0][1]
max_y = bbox[6][1]
dim_x = max_x - min_x
dim_y = max_y - min_y
ma... | Python | 1 |
# Generated by Django 4.2.16 on 2025-05-26 17:01
from django.apps.registry import Apps
from django.db import migrations, models
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
def fix_inactive_visible_nodes(
apps: Apps, _schema_editor: BaseDatabaseSchemaEditor
) -> None:
LanguageTreeNode ... | Python | 1 |
40, 80, 160]:
print('...for n =', n)
a = 0.0
b = 2*np.pi
v, h = np.linspace(a, b, n, endpoint=False, retstep=True)
x, y = np.meshgrid(v, v, indexing='ij')
xo = np.random.rand(*x.shape)*10
yo = np.random.rand(*x.shape)*10
def test_function(x, y): return np.exp(np.sin(x))*np.cos(y)
f ... | Python | 1 |
std::os::raw::c_uint,
pub __writers: ::std::os::raw::c_uint,
pub __wrphase_futex: ::std::os::raw::c_uint,
pub __writers_futex: ::std::os::raw::c_uint,
pub __pad3: ::std::os::raw::c_uint,
pub __pad4: ::std::os::raw::c_uint,
pub __cur_writer: ::std::os::raw::c_int,
pub __shared: ::std::os::raw::c_int,
pub... | Rust | 0 |
c1 == c2
def test_compare_unordered_different_order(self):
# https://github.com/pandas-dev/pandas/issues/16603#issuecomment-
# 349290078
a = Categorical(["a"], categories=["a", "b"])
b = Categorical(["b"], categories=["b", "a"])
assert not a.equals(b)
def test_numeri... | Python | 1 |
# %%
import json
import os
import sys
import time
from dataclasses import dataclass, field
from typing import List
# %%
@dataclass
class Alfred_Item:
title: str
subtitle: str
valid: bool = True
match: str = None
arg: str = None
icon: str = None
quicklookurl: str = None
def __post_i... | Python | 1 |
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
WORKER = 'worker'
MANAGER = 'manager'
ADMIN = 'admin'
ROLE_CHOICES = [
(WORKER, 'Работник'),
(MANAGER, 'Менеджер'),
(ADMIN, 'Админ'),
]
role = models.CharField(max... | Python | 1 |
if ion is renamed.
let last_sa = &env::args().last().unwrap();
if last_sa.ends_with("ion") {
println!("stdio");
} else {
println!("{}", last_sa);
}
}
Status::TRUE
}
}
}
<reponam... | Rust | 0 |
mut self) {
// For input like "Mr. Johnson", we'll generally have the correct title (Mr.) but the first
// will be Johnson and last is empty.
if !self.title.is_empty() && !self.first.is_empty() && self.last.is_empty() {
self.last = self.first.to_string();
self.first.clear... | Rust | 0 |
rig_ret_0_0, mut orig_ret_0_1) = o; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_1.0 }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::channelmanager::PaymentSendFailure::native_... | Rust | 0 |
: {type(dance_video_url)}")
print(f"✅ 参数验证通过,dance_video_url: {dance_video_url}")
handler = WanXiangAPIHandler()
task_data = {
"model": "animate-anyone-template-gen2",
"input": {
"video_url": dance_video_url
}
}
print(f"📤 模板生成请求数据: {task_data}")
# 🔥 修复:使... | Python | 1 |
,
init: Some(e),
}
}
fn if_zero_empty() -> Part {
ProgramPart::Stmt(Stmt::If(if_stmt(number_lit_expr("0"), Stmt::Empty, None)))
}
fn if_zero_empty_else() -> Part {
ProgramPart::Stmt(Stmt::If(if_stmt(
number_lit_expr("0"),
Stmt::Empty,
Some(Stmt::Empty),
)))
}
fn if_stm... | Rust | 0 |
min_val: i64,
dest: &mut Vec<i64>,
) -> Result<usize, NormalError> {
let sz = dest.len();
let query = format!(
"SELECT {} FROM {} WHERE {}={} AND {} > {} ORDER BY {} LIMIT {}",
self.right_column_name,
self.table_name,
self.left_column_na... | Rust | 0 |
}
}
fn emit_list<N>(&mut self, nodes: &[N], format: ListFormat) -> Result
where
Self: Emit<N>,
N: Spanned,
{
for (idx, node) in nodes.iter().enumerate() {
if idx != 0 {
self.write_delim(format)?;
if format & ListFormat::LinesMask == L... | Rust | 0 |
}
#[inline(always)]
#[allow(unsafe_code)]
pub(crate) fn comb_filter_const_inplace(
y: &mut [f32],
y_offset: usize,
t: usize,
n: usize,
g10: f32,
g11: f32,
g12: f32,
) {
unsafe {
let g10v = _mm_load1_ps(&g10 as *const f32);
let g11v = _mm_load1_ps(&g11 as *const f32);
... | Rust | 0 |
let mut vector = Vec::new();
for x in 0..3 {
let mut bar = BTreeMap::new();
bar.insert(String::from("time"), Value::from(123456 + (x as i32)));
bar.insert(String::from("ratio"), Value::from(3.14159 + (x as f32)));
bar.insert(String::from("size"), Value::from(... | Rust | 0 |
umerate(getFeaturesFromQgsIterable(to_points))]
feat = QgsFeature()
fields = QgsFields()
orig_id_field_data_type = getFieldDatatype(from_points, from_id_field)
dest_id_field_data_type = getFieldDatatype(to_points, to_id_field)
fields.append(QgsField('origin_id', orig_id_... | Python | 1 |
be displayed only.")
args.save_dir = None
else:
plt.rcParams.update({
"text.usetex": True,
"pgf.rcfonts": False,
"pgf.texsystem": "pdflatex",
"font.size": 8,
})
print("Starting quantum Monte Carlo simulation... | Python | 1 |
StreamingResponse(self._messages.batches)
class AsyncMessagesWithStreamingResponse:
def __init__(self, messages: AsyncMessages) -> None:
self._messages = messages
self.create = async_to_streamed_response_wrapper(
messages.create,
)
self.count_tokens = async_to_streamed... | Python | 1 |
// An element with position: absolute; is positioned relative to the nearest
// positioned ancestor (instead of positioned relative to the viewport, like fixed).
//
// A "positioned" element is one whose position is anything except static.
if let Some(LayoutPosition::Static) = aren... | Rust | 0 |
erate() {
if el.coords.x > self.nodes[result_ind].coords.x {
result_ind = ind;
}
}
self.nodes[result_ind].coords.x
}
pub fn find_biggest_y(&self) -> f64 {
let mut result_ind = 0;
for (ind, el) in self.nodes.iter().enumerate() {
... | Rust | 0 |
der<i8>) {
let tcp_listener = TcpListener::bind(format!("0.0.0.0:{}", params.proxy_port))
.await
.expect("运行http监听失败");
loop {
let (socks_client, _) = tcp_listener.accept().await.unwrap();
//读取进来的流量
let (mut ir, mut iw) = socks_client.into_split();
// 通知outside发... | Rust | 0 |
from .threaded import Threaded
from .utils import is_hexstring
class Ir(Threaded):
# TODO: auto parse available protocols from >: ir help
PROTOCOLS = ["NEC", "NEC42", "NEC42ext", "Samsung32",
"RC6", "RC5", "RC5X", "SIRC", "SIRC15", "SIRC20"]
def __init__(self, serial_wrapper) -> None:
... | Python | 1 |
pull_image(*image, f).map_err(|e| e.chained_message()));
let results: Vec<Result<_, String>> = join_all(futures).await;
let errors = results
.into_iter()
.filter(|r| r.is_err())
.map(|e| e.unwrap_err())
.collect::<Vec<String>>();
if !errors.is_empty() {
error!("Error ... | Rust | 0 |
nto());
/// hashes.insert("foo/Position".try_into()?, "678".into());
///
/// assert_eq!(
/// FieldInfo::new("int16", "foo", FieldCase::Unit)?.md5_string("foo", &hashes)?,
/// "int16 foo",
/// );
/// assert_eq!(
/// FieldInfo::new("float64", "foo", FieldCase::Vector)?.md5_stri... | Rust | 0 |
ds_itr = _repeat_iter(self.ds.get_data)
with self._guard:
while True:
dps = []
for k in range(self.nr_proc):
dps.append(copy.copy(next(ds_itr)))
to_map = [x[self.index] for x in dps]
res = self._pool.map_asy... | Python | 1 |
from __future__ import annotations
import numpy as np
import pandas as pd
import pytest
import datashader as ds
import datashader.transfer_functions as tf
df = pd.DataFrame({'x': np.array(([0.] * 10 + [1] * 10)),
'y': np.array(([0.] * 5 + [1] * 5 + [0] * 5 + [1] * 5)),
'f64': np.... | Python | 1 |
# Copyright 2012-2017 Camptocamp SA
# Copyright 2017 Okia SPRL (https://okia.be)
# Copyright 2020 Tecnativa - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class Mail(models.Model):
_inherit = "mail.mail"
def _update_control_line_status(self):
fo... | Python | 1 |
}
IrOp::Return(op) => op.generate(ir, output, annotated, instruction_count),
IrOp::Call(op) => op.generate(ir, output, annotated, instruction_count),
IrOp::Let(op) => op.generate(ir, output, annotated, instruction_count),
}
}
}
<reponame>Eric-Arellano/rust
macro_... | Rust | 0 |
!(), err),
// }
// }
// #[test]
// fn art_paint_contributions_box() {
// if !gtk::is_initialized() {
// if let Err(err) = gtk::init() {
// panic!("File: {:?} Line: {:?}: {:?}", file!(), line!(), err)
// };
// }
/... | Rust | 0 |
from typing import List, Optional
import re
class ParagraphChunker:
"""
A text splitter that respects paragraph boundaries and combines paragraphs until
reaching a maximum size without breaking any paragraph.
"""
def __init__(self,
max_chunk_size: int = 512,
... | Python | 1 |
ist >0.02) and (reachDist > 0.02)
# Object on the ground, far away from the goal, and from the gripper
# Can tweak the margin limits
def orig_pickReward():
hScale = 100
if self.pickCompleted and not(objDropped()):
return hScale*(heightTarget - sel... | Python | 1 |
def detect_compute_compatibility(CUDA_HOME, so_file):
try:
cuobjdump = os.path.join(CUDA_HOME, 'bin', 'cuobjdump')
if os.path.isfile(cuobjdump):
output = subprocess.check_output("'{}' --list-elf '{}'".format(
cuobjdump, so_file), shell=True)
output = output.de... | Python | 1 |
(message, &signature).is_ok();
//!
//! let encoded_public_key: Vec<u8> = serialize(&public_key).unwrap();
//! let encoded_signature: Vec<u8> = serialize(&signature).unwrap();
//! # }
//! # #[cfg(not(feature = "serde"))]
//! # fn main() {}
//! ```
//!
//! After sending the `encoded_public_key` and `encoded_signature`, t... | Rust | 0 |
= run_bootstrap_node(opts.address).await?;
log::info!("bootstrap node address: {}", addr);
task.await.map_err(|e| e.into())
} else {
listen(opts).await
}
}
<filename>rand_lcg/src/lib.rs<gh_stars>0
//
// lib.rs
// Copyright (C) 2019 <NAME> <<EMAIL>>
// Distributed under terms of the MIT ... | Rust | 0 |
posture.0 = formation.pos(&enemy.formation_index);
let ang = ANGLE * ONE / 128;
posture.1 -= clamp(posture.1, -ang, ang);
}
OwlState::TrajAttack => {
let (subworld1, mut subworld2) = world.split::<(&Enemy, &Troops)>();
let (enemy, troops_opt)... | Rust | 0 |
20analy\
sis\x20on\x20groups\x20that\x20are\x20clusters.\n\n\x0c\n\x05\x04\0\x02\
\x04\x05\x12\x03J\x02\x06\n\x0c\n\x05\x04\0\x02\x04\x01\x12\x03J\x07\x11\
\n\x0c\n\x05\x04\0\x02\x04\x03\x12\x03J\x14\x15b\x06proto3\
";
static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDe... | Rust | 0 |
import logging
import os.path
import re
import secrets
from typing import Optional
RED = "\033[1;31m"
RST = "\033[0;0m"
logger = logging.getLogger("uvicorn.app.konoha.data.resource")
class Resource:
NBYTES = 6
KONOHA_DIR = "/tmp/konoha"
def __init__(self, path: Optional[str]) -> None:
if path ... | Python | 1 |
(Some(self.current), name);
self.current_node_mut().children.push(key);
self.hash_maps.insert(key, node);
self.current = key;
}
}
pub fn pop_env(&mut self) {
self.current = self.current_node().parent.unwrap();
}
pub fn get(&self, name: &str) -> Opt... | Rust | 0 |
r = std::env::current_dir().expect("Valid current directory path");
Self::new("127.0.0.1".to_owned(), 8001, dir, "index.html".to_owned())
}
}
<reponame>3cL1p5e7/ic
//! The EMPTY_WASM is a legal wasm module that can be installed as a canister on
//! the IC, but that does not do anything.
use hex_literal::he... | Rust | 0 |
e
def get_events(self) -> str:
if self.parent.status not in ["running", "completed"]:
event_list = [event["DisplayMessage"] for event in self.events]
return "\n".join(event_list)
return ""
JobToAllocDict = dict[str, list[NomadAllocation]]
def _get_allocations(
nomad_... | Python | 1 |
impl ops::Sub for Amount {
type Output = Self;
fn sub(self, other: Self) -> Self {
Amount(self.0 - other.0)
}
}
<reponame>sorpaas/solana
//! This account contains the clock slot, epoch, and leader_schedule_epoch
//!
pub use crate::clock::Clock;
use crate::{
account::Account,
clock::{Epoc... | Rust | 0 |
Destination Connection ID (0..160) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SCID Len (8) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source Connection ID (0..160) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-... | Rust | 0 |
import os
from celery import Celery
from celery.schedules import crontab
# Set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings")
app = Celery("core")
## Get the base REDIS URL, default to redis' default
BASE_REDIS_URL = os.environ.get("REDI... | Python | 1 |
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 Intel Corporation
#
# 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 app... | Python | 1 |
ted!()
}
/// pmuludq
///
/// Not yet implemented.
#[inline]
pub fn _mm_mul_su32(a: __m64, b: __m64) -> __m64 {
unimplemented!()
}
/// Not yet implemented.
#[inline]
pub fn _mm_set_epi64(e1: __m64, e0: __m64) -> __m128i {
unimplemented!()
}
/// Not yet impl... | Rust | 0 |
0, 0x06, 0x93, 0x68, 0x00, 0xA4, 0x01,
0xA4, 0x00,
];
let mut aml = Vec::new();
Method::new(
"TEST".into(),
1,
false,
vec![
&If::new(&Equal::new(&Arg(0), &ZERO), vec![&Return::new(&ONE)]),
&Return::new(&... | Rust | 0 |
", r"foo./.\bar");
tp!(r"foo\.", "bar", r"foo\.\bar");
tp!(r"foo.\.", "bar", r"foo.\.\bar");
tp!("foo", "", "foo\\");
tp!("foo", ".", r"foo\.");
tp!("foo", "..", r"foo\..");
tp!("foo", "/", "/");
tp!("foo", r"\", r"\");
tp!("/foo/bar", "/", "/");
t... | Rust | 0 |
command);
}
#[test]
fn test_segment_deleted() {
let segment = String::from("segment-1");
let segment_deleted = WireCommands::Replies(Replies::SegmentDeleted(SegmentDeletedCommand {
request_id: 1,
segment,
}));
test_command(segment_deleted);
}
#[test]
fn test_delete_table_segment() {
... | Rust | 0 |
s_works() {
let hex_lits = Selector::from([0xC0, 0xDE, 0xCA, 0xFE]).hex_lits();
assert_eq!(
hex_lits,
[
syn::parse_quote! { 0xC0_u8 },
syn::parse_quote! { 0xDE_u8 },
syn::parse_quote! { 0xCA_u8 },
syn::parse_quote! {... | Rust | 0 |
f i == len(val_p) -1:
break
for i, d in enumerate(hold_out_p):
request = {}
request["messages"] = [
{"role":"user", "content": synth_sys_prompt+ d["description"]},
{"role":"assistant", "content": "P"}
]
hold_out_data.append(request)
for i, d in enumerate(hold_out_u):
reques... | Python | 1 |
or::Dir3, t: f64, front_face: bool, material: &material::Material) -> HitRecord {
HitRecord {
p: p,
normal: if front_face {outward_normal} else {-outward_normal},
t: t,
front_face: front_face,
material : material,
}
}
pub fn position(&... | Rust | 0 |
if global_angular_velocity_data is not None:
output_dict["body_ang_vel"] = global_angular_velocity_data
output_dict["root_ang_vel"] = global_angular_velocity_data[:, 0, :]
# Extended Rigid Body (rg_pos_t, etc.) data
g_trans_ext_data = raw_motion_arrays.get("... | Python | 1 |
MAGE_PATCH_TOKEN * image_token_len}{DEFAULT_IM_END_TOKEN}\n{qs}"
else:
qs = f"{DEFAULT_IMAGE_TOKEN}\n{qs}"
# 配置对话模板
conv_mode = "mpt"
conv = conv_templates[conv_mode].copy()
conv.append_message(conv.roles[0], qs)
conv.append_message(conv.roles[1], None)
prompt = conv.get_prompt()
... | Python | 1 |
would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest::default();
///
/// // Y... | Rust | 0 |
(SystemTime::UNIX_EPOCH).ok());
match timestamp {
Some(y) => Some((x, y)),
_ => None
}
})
.for_each(|(x_path, x_created)| match &newest {
None => {
newest = Some((x_path, x_created));
}
Some((_, y... | Rust | 0 |
lit.push(lit_dir);
fs::create_dir(p_lit).unwrap_or_panic(&format!("failed to create {}", lit_dir));
})
}
enum Target { Root, Src, Lit }
impl Target {
fn path_buf(&self, filename: &str) -> PathBuf {
CURRENT_DIR_PREFIX.with(|p| {
let p = p.borrow_mut();
let mut p = p.clon... | Rust | 0 |
TA.split(",").flat_map(|x| x.parse::<i32>()).collect()
}
<gh_stars>10-100
use crate::{error::Error,
event::BuilderEvent,
kafka::{KafkaConfig,
KafkaConsumer,
KafkaPublisher}};
use async_trait::async_trait;
use habitat_core::util;
use serde::{Deserialize,
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.