text string | label_name string | labels int64 |
|---|---|---|
1 => ::std::option::Option::Some(CloakState::Cloaked),
2 => ::std::option::Option::Some(CloakState::CloakedDetected),
3 => ::std::option::Option::Some(CloakState::NotCloaked),
4 => ::std::option::Option::Some(CloakState::CloakedAllied),
_ => ::std::option::Opti... | Rust | 0 |
"configurationReference", default, skip_serializing_if = "Option::is_none")]
pub configuration_reference: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ApplicationProfile {
#[serde(rename = "galleryApplications", default, skip_serializing_if = "Vec::is_empty")]
pub... | Rust | 0 |
.is_empty() {
return Err(unclean.into());
}
let mut revwalk = repo.revwalk()?;
revwalk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::REVERSE);
revwalk.push(series.id())?;
revwalk.hide(base.id())?;
let commits: Vec<Commit> = revwalk.map(|c| {
let id = c?;
let mut comm... | Rust | 0 |
ermissions and
//! limitations under the License.
// This file is generated by rust-protobuf 2.0.6. Do not edit
// @generated
// https://github.com/Manishearth/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clippy)]
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(box_pointers)]
#![allow(dead_code)]
#![allow(... | Rust | 0 |
from OPERATIONS import add_book, add_member, issue_book, return_book, view_books, view_members
def menu():
while True:
print("\n===== Library Management System =====")
print("1. Add Book")
print("2. View All Books")
print("3. Register Member")
print("4. View All Members")
... | Python | 1 |
te {
key: "width".into(),
value: vec!["100vw".into()].into(),
}]
.into(),
}),
ScopeContent::Block(Block {
condition: vec![vec![".inner".into()].into()].into(),
style_attributes: vec![StyleAttr... | Rust | 0 |
# Prompt: open ycombinator.com startup directory and filter for Spring 2025 batch
# Outcome: fail
import webbrowser
import subprocess
import time
def open_ycombinator_and_filter(spring_year):
# Open the Y Combinator startup directory
url = "https://www.ycombinator.com/companies"
webbrowser.open(url)
... | Python | 1 |
unspent) in self.unspents.iter().enumerate() {
let txin = TxIn {
previous_output: OutPoint {
txid: bitcoin::hash_types::Txid::from_hex(&unspent.txhash)?,
vout: unspent.vout as u32,
},
script_sig: lock_script_ver.get(ind... | Rust | 0 |
import pandas as pd
def Chaikin_Oscillator(close: pd.Series, high: pd.Series, low: pd.Series, volume: pd.Series, adjust: bool = True) -> pd.Series:
"""
Calculates the Chaikin Oscillator from the given price and volume data.
The Chaikin Oscillator is a momentum indicator that combines price and volume data... | Python | 1 |
"iter: {iter}",
"{meters}",
"lr: {lr:.6f}",
"max mem: {memory:.0f}",
]
).format(
eta=eta_string,
iter=iteration,
meters=str(meters),
... | Python | 1 |
n update_move_fluid(
&mut self,
context: &UpdateContext,
container_one: &mut impl PneumaticContainer,
container_two: &mut impl PneumaticContainer,
) {
if !self.is_powered_for_manual_control && !self.is_powered_for_automatic_control {
self.set_open_amount_from_pres... | Rust | 0 |
dt = datetime.date(y, M, d)
self.assertEqual(nntplib._unparse_datetime(dt),
(date_str, time_str))
self.assertEqual(nntplib._unparse_datetime(dt, False),
(date_str, time_str))
gives(1999, 6, 23, "19990623", "000000")
... | Python | 1 |
#!/usr/bin/env python3
# python has builtin regex lib called re
import re
import sys
def main():
"""
main functions: search, match, fullmatch
to use:
search(pattern, string, flags)
where pattern is the regex to search for
string is the string to search in
flags is an optional set of... | Python | 1 |
ion of each component to the metric, as given by the AtP algorithm.
"""
# model = LanguageModel(model_name, device_map="cpu", dispatch=True)
attn_cache, mlp_cache = get_atp_caches(
model_name,
clean_tokens,
corrupted_tokens,
off_distribution_tokens,
answer_token_indi... | Python | 1 |
unix::io::AsRawFd;
#[cfg(not(linux))]
fn get_mode(fd: &FileDesc) -> io::Result<libc::mode_t> {
unsafe {
let mut stat: libc::stat = mem::zeroed();
cvt_r(|| libc::fstat(fd.as_raw_fd(), &mut stat)).map(|_| stat.st_mode)
}
}
#[cfg(lin... | Rust | 0 |
ck_storage_ids = post_child_location(
barcodes=rack.barcodes,
names=rack.names,
parent_storage_id=top_parent_storage_id,
location_schema=parameters.rack_schema,
benchling_client=benchling_client
)
# Create drawers within racks/canes
if storage... | Python | 1 |
PROVISIONED</code> for predictable workloads. <code>PROVISIONED</code> sets the billing mode to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadWriteCapacityMode.html#HowItWorks.ProvisionedThroughput.Manual">Provisioned Mode</a>.</p>
/// </li>
/// <li>
/// <p>
//... | Rust | 0 |
standard_length_ext);
lengths
};
for _ in 0..64 {
let (i, s) = run_round(&mut list, ind, skip, &part_2_lengths);
ind = i;
skip = s;
}
let dense = reduce_hash(&list);
println!("Knot hash is {}", hexadecimal(&dense));
}
// returns (index, skip)
fn run_round(lis... | Rust | 0 |
# search/forms.py
from django import forms
class SearchForm(forms.Form):
query = forms.CharField(label='Search', max_length=255, required=True)
| Python | 1 |
"ZeroDiv"
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
// check for instances of 0.0/0.0
if_chain! {
if let ExprKind::Binary(ref op, ref left, ref right) = expr.node;
if let BinOpKi... | Rust | 0 |
ation_status(platform_blob, enclave_trusted, update_info) }
}
//! A generic array indexed by `Color`
use std::ops::{Index, IndexMut};
use types::color::*;
// This is an array of size 2 indexable by Color to obtain an attribute that is color dependant
// such as castling squares or castling moves
#[derive(Clone)]
pub... | Rust | 0 |
# Time Complexity: O(nlogn)
# Space Complexity: O(1)
def heapify(arr, n, i):
"""
Helper function to maintain the heap property of a subtree rooted at index i.
:param arr: List of elements
:param n: Size of the heap
:param i: Root index of the subtree
"""
largest = i # Initialize largest as... | Python | 1 |
if recipe_builder.is_valid(coord) {
if i == N * N - 1 { // We have successfully placed all bricks.
squares.push(recipe_builder.get_recipe().clone());
} else {
i += 1; // Go to next coord.
continue;
... | Rust | 0 |
# Copyright (C) 2024 Habana Labs, Ltd. an Intel Company.
# coding=utf-8
# The following code has been taken from https://github.com/NVIDIA/NeMo/blob/ \
# 782b4e1652aaa43c8be390d9db0dc89544afa080/nemo/collections/nlp/modules/ \
# common/megatron/rotary_pos_embedding.py
import importlib.util
import torch
from torch im... | Python | 1 |
puConfig.html
pub fn imu<D>(i2c: I2C,
delay: &mut D,
config: &mut MpuConfig<Imu>)
-> Result<Self, Error<E>>
where D: DelayMs<u8>
{
let dev = I2cDevice::new(i2c);
Mpu9250::new_imu(dev, delay, config)
... | Rust | 0 |
blasoxide<filename>src/kernels/mod.rs<gh_stars>1-10
#[cfg(all(
any(target_arch = "x86_64", target_arch = "x86"),
target_feature = "avx"
))]
mod avx;
#[cfg(all(
any(target_arch = "x86_64", target_arch = "x86"),
target_feature = "avx"
))]
pub use avx::{l1d::*, l1s::*};
#[cfg(all(
any(target_arch = "... | Rust | 0 |
import unittest
from api import get_bank_holidays
class TestUKBankHolidaysAPI(unittest.TestCase):
def test_get_bank_holidays_default(self):
# Test the default call to get_bank_holidays
response = get_bank_holidays()
self.assertIn('title', response)
self.assertIn('events', response... | Python | 1 |
() }.mLastAccess
}
}
/// Safely deallocable hdfsFileInfo pointer
struct HdfsFileInfoPtr {
pub ptr: *const hdfsFileInfo,
pub len: i32,
}
/// for safe deallocation
impl<'a> Drop for HdfsFileInfoPtr {
fn drop(&mut self) {
unsafe { hdfsFreeFileInfo(self.ptr as *mut hdfsFileInfo, self.len) };
}... | Rust | 0 |
desired_template_changes = dict()
# complete the template with specific ansible parameters
if self.is_parameter('labels'):
desired_template_changes['LABELS'] = self.get_parameter('labels')
if self.requires_template_update(host.TEMPLATE, desired_template_chang... | Python | 1 |
4_0 = C::gpr_to_imm8_gpr(ctx, expr2_0);
let expr5_0 = constructor_x64_rotr(ctx, pattern3_0, expr3_0, &expr4_0)?;
let expr6_0 = constructor_output_gpr(ctx, expr5_0)?;
return Some(expr6_0);
}
... | Rust | 0 |
ake PID values negative
imxy_debiased = max(imxy_debiased, imx, imy)
else:
imxy_debiased = imxy
## ORIGINAL VERSION
# debias_factor = imxy_debiased / imxy
## NEW VERSION
## Add if-else to avoid errors when imxy == 0
if imxy > 0:
debias_factor = imxy_debiased / imxy
e... | Python | 1 |
other words: upwind from the
/// center of the world.
fn gen_spawn_location(wind: &Wind, bounds: &WorldBounds) -> Vector3<f32> {
let mut rng = thread_rng();
if Self::wind_towards_direction(wind.wind, Vector2::new(1.0, 0.0)) {
Vector3::new(
bounds.left,
... | Rust | 0 |
import sys
from file_utils import read_file
from yaml_utils import process_yaml_content, convert_to_json
def scan_file(file):
file_contents = read_file(file)
file_contents = file_contents.split("\n")
processed_file = []
for line in file_contents:
if "TemplateURL:" in line:
try:
... | Python | 1 |
ser.id, uid, fits)
await callback_query.edit_message_reply_markup(reply_markup=InlineKeyboardMarkup(buttons))
@handler.callback_query(pattern=r"^gcsim_page\|", block=False)
async def gcsim_page(self, update: "Update", _: "ContextTypes.DEFAULT_TYPE") -> None:
callback_query = update.callback_que... | Python | 1 |
import math
from faster_whisper import WhisperModel
import torch
def generate_subtitles(date_str):
# Followed this guide: https://www.digitalocean.com/community/tutorials/how-to-generate-and-add-subtitles-to-videos-using-python-openai-whisper-and-ffmpeg
# Used this to get faster whisper working: https://stackover... | Python | 1 |
for cookie in cookies:
browser.add_cookie(cookie)
browser.get(link2)
# Основные действия с таблицей
rows = len(browser.find_elements(By.XPATH, f"//tbody/tr[{student}]/td[@data-nb]"))
def dangers1():
nonlocal dolv2_local
arr1 = browser.find_element... | Python | 1 |
y: &[u8]) -> bool {
if x.len() != y.len() {
return false;
}
// If we don't have enough bytes to do 4-byte at a time loads, then
// fall back to the naive slow version.
//
// TODO: We could do a copy_nonoverlapping combined with a mask instead
// of a loop. Benchmark it.
if x.len... | Rust | 0 |
nal_report(
prompt= combined_query,
learnings= learnings,
visited_urls= visited_urls
)
async with aiofiles.open("report.md", "w", encoding="utf-8") as f:
await f.write(report)
if console:
console.print(Panel.fit(Text("Final Report:", st... | Python | 1 |
ray TypeId { ns_id: 1, id: 0 }; 8) {
// unsafe { TODO: call ffi:graphene_box_get_vertices() }
//}
pub fn get_width(&self) -> f32 {
unsafe { ffi::graphene_box_get_width(self.to_glib_none().0) }
}
pub fn init(&mut self, min: Option<&Point3D>, max: Option<&Point3D>) {
unsafe {
... | Rust | 0 |
lways)]
pub fn inputpull(self) -> &'a mut W { self.variant(MODE1_A::INPUTPULL) }
#[doc = "Input enabled with filter. DOUT determines pull direction"]
#[inline(always)]
pub fn inputpullfilter(self) -> &'a mut W { self.variant(MODE1_A::INPUTPULLFILTER) }
#[doc = "Push-pull output"]
#[inline(always... | Rust | 0 |
as
/// a field in the `bitfield::bitfield` macro.
///
/// The type must implement `core::clone::Clone` and `core::marker::Copy`.
///
/// The following methods are generated:
///
/// ```ignore
/// /// Returns true if the enumeration is represented by a signed primitive type.
/// const fn is_signed() -> bool;
/// ```
//... | Rust | 0 |
metadata to the job information."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
impl UpdateJobParameters {
pub fn new() -> Self {
Self::default()
}
}
<filename>src/test/ui/static/static-mut-requires-unsafe.rs
static mut a: isize = 3;
fn main... | Rust | 0 |
from fastapi import Depends, HTTPException
from fastapi.params import Header
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
from typing import Annotated
from starlette.datastructures import Headers
from starlette.websockets import WebSo... | Python | 1 |
modelSpace.newLoadPattern(name= '5')
lp5.newNodalLoad(n2.tag,xc.Vector([0,0,0,0,0,F])) # Positive moment about z axis
# We add the load case to domain.
modelSpace.addLoadCaseToDomain("5")
# Solution 5 T
analysis= predefined_solutions.simple_static_linear(feProblem)
result= analysis.analyze(1)
RF= beam3d.getResisting... | Python | 1 |
start_array();
for item_743 in var_741 {
{
let mut object_744 = array_742.value().start_object();
crate::json_ser::serialize_structure_crate_model_data_source_to_index_field_mapping(&mut object_744, item_743)?;
object_744.finish();
}
... | Rust | 0 |
color:
Color = DB.Color(*color)
self._revit_object.SetProjectionFillColor(Color)
if pattern:
fill_pattern = FillPatternElement.by_name_or_element_ref(pattern)
self._revit_object.SetProjectionFillPatternId(fill_pattern.Id)
if visible is not None:
... | Python | 1 |
# Extracts the most important sentences with the selected criterion.
extracted_sentences = _extract_most_important_sentences(sentences, ratio, words)
# Sorts the extracted sentences by apparition order in the original text.
extracted_sentences.sort(key=lambda s: s.index)
return _format_results(extract... | Python | 1 |
ag = 42034;
pub const ExifTag_EXIF_TAG_LENS_MAKE: ExifTag = 42035;
pub const ExifTag_EXIF_TAG_LENS_MODEL: ExifTag = 42036;
pub const ExifTag_EXIF_TAG_LENS_SERIAL_NUMBER: ExifTag = 42037;
pub const ExifTag_EXIF_TAG_COMPOSITE_IMAGE: ExifTag = 42080;
pub const ExifTag_EXIF_TAG_SOURCE_IMAGE_NUMBER_OF_COMPOSITE_IMAGE: ExifT... | Rust | 0 |
import os
import unittest
import pytest
from torch_tb_profiler.profiler.data import RunProfileData
from torch_tb_profiler.profiler.diffrun import (compare_op_tree, diff_summary,
print_node, print_ops)
from torch_tb_profiler.utils import timing
def load_profile(worker, ... | Python | 1 |
mentwise_affine {
(
Some(vs.ones("weight", &normalized_shape)),
Some(vs.zeros("bias", &normalized_shape)),
)
} else {
(None, None)
};
LayerNorm {
eps,
elementwise_affine,
normalized_shape,
... | Rust | 0 |
*ppDevice);
COMMETHOD(
[],
HRESULT,
"GetDevice",
(["in"], LPCWSTR, "pwstrId"),
(["out"], POINTER(POINTER(IMMDevice)), "ppDevice"),
),
# HRESULT RegisterEndpointNotificationCallback(
# [in] IMMNotificationClient *pClient);
... | Python | 1 |
Layout(name="header", size=3),
Layout(ratio=1, name="main"),
Layout(size=10, name="footer"),
)
layout["main"].split_row(Layout(name="side"), Layout(name="body", ratio=2))
layout["body"].split_row(Layout(name="content", ratio=2), Layout(name="s2"))
layout["s2"].split_column(
L... | Python | 1 |
register name for the high byte of that register and the `l` modifier will emit the register name for the low byte. The asm code will therefore be expanded as `mov ah, al` which copies the low byte of the value into the high byte.
If you use a smaller data type (e.g. `u16`) with an operand and forget the use template... | Rust | 0 |
i32)
};
match status {
-1 => Err(I2cError::TransferAbort),
x if x >= 0 => match received_string.len() == x as usize {
true => Ok(()),
false => Err(I2cError::InvalidReceiveString),
},
_ => Err(I2cError::IOError),
}
... | Rust | 0 |
play_all_logs(maybes: &HashMap<String, Arc<Mutex<Vec<Maybe<ResponseResult>>>>>) -> Vec<Entry> {
let mut view: Vec<Entry> = Vec::new();
let vec = vec![
"anchor_redeem_and_repay_stable",
"anchor_borrow_and_deposit_stable",
"anchor_governance_claim_and_stake",
];
for key in vec {
... | Rust | 0 |
_rows,
pretty_input,
pretty_results,
}
}
}
/// Create a test parquet file with varioud data types
async fn make_test_file(scenario: Scenario) -> NamedTempFile {
let output_file = tempfile::Builder::new()
.prefix("parquet_pruning")
.suffix(".parquet")
.tem... | Rust | 0 |
import cv2
import numpy as np
import os
# ====================================================
# 設定パラメータ(魚眼カメラ用)
# ====================================================
CONFIG = {
"camera_index": 0, # カメラのデバイスID(必要に応じて変更)
"checkerboard_dims": (9, 6), # チェスボードの内部角点数 (横, 縦)
"subpix_w... | Python | 1 |
# --------------------------------------------------
# File Name : P1_02_RLE.py
# Problem : Part-I RLE
# Author : Worralop Srichainont
# Date : 2025-06-16
# --------------------------------------------------
# Input command
cmd = input().strip()
# Initialize result variable
result = ""
# Convert string to ... | Python | 1 |
).await?;
info!("Peer {:?} is now {:?}", peer_info, status);
}
Ok(PeerFoldParameters((peer_info, vec)))
}
_ => Ok(PeerFoldParameters((peer_info, vec))),
}
}
//! Build-in filters
use std::fmt;
use std::ptr;
use super::{Buffer, Render, RenderError};
/// Helpe... | Rust | 0 |
].$c,
$d[idx.0[13] as usize].$c,
$d[idx.0[14] as usize].$c,
$d[idx.0[15] as usize].$c,
]),
])
};
}
let fr = gather!(&ctx.factors, r);
let fg = gather!(&ctx.factors, g);
let fb = gather!(&ctx.factors, b);
... | Rust | 0 |
import numpy as np
import pandas as pd
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score,f1_score
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
datasets=load_wine()
x= datasets.dat... | Python | 1 |
None)?;
/// # write_worksheet(&mut worksheet)?; // write worksheet contents
/// # let mut chart = workbook.add_chart(ChartType::Column);
/// let mut series1 = chart.add_series(None, Some("=Sheet1!$A$2:$A$6"));
/// let mut series2 = chart.add_series(None, Some("=Sheet1!$B$2:$B$6"));
/// let mut ... | Rust | 0 |
Cow::Borrowed(entry.get_value()))?,
))
})
.collect::<Result<Vec<(u64, V)>, Error>>()?;
Ok(ListProof::from_raw_parts(proof, entries, pb.get_length()))
}
}
}
// Copyright 2019 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 ... | Rust | 0 |
import os
import re
import yaml
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
with open('config.yml', 'r', encoding='utf-8') as file:
config = yaml.safe_load(file)
work_directory = config['work_directory']
file_patterns = config['file_patterns']
replac... | Python | 1 |
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
#
# Complete the 'icecreamParlor' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
# 1. INTEGER m
# 2. INTEGER_ARRAY arr
#
def icecreamParlor(m... | Python | 1 |
, 4, 5, 6, 7],
vec![0, 1, 2, 3],
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
)
);
}
}
<reponame>conradludgate/hashes-rs
//! An implementation of the [GOST R 34.11-94][1] cryptographic hash algorithm.
//!
//! # Usage
//! ```rust
//! use gost94::{Gost... | Rust | 0 |
"""Common settings for the app."""
import logging
import os
L = logging.getLogger()
L.setLevel(logging.DEBUG)
ALLOWED_ORIGIN = os.getenv('ALLOWED_ORIGIN', 'http://localhost:8080')
ALLOWED_IP = os.getenv('ALLOWED_IP', '')
| Python | 1 |
#coding=utf-8
import sys
import logging
import time
import math
import cv2
import pywt
import numpy as np
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
class BlindWatermark():
@staticmethod
def _gene_signature(wm,size,key):
'''
提取特征,用来比对是否包含水... | Python | 1 |
},
/// sigev_signo: TIMER_SIG,
/// sigev_notify: nc::SIGEV_SIGNAL,
/// sigev_un: nc::sigev_un_t::default(),
/// };
/// let mut timer_id = nc::timer_t::default();
/// let ret = nc::timer_create(nc::CLOCK_MONOTONIC, Some(&mut ev), &mut timer_id);
/// assert!(ret.is_ok());
//... | Rust | 0 |
rror_for_status()?
.json()?)
}
}
pub(crate) fn edit_team(
&self,
team: &Team,
name: &str,
description: &str,
privacy: TeamPrivacy,
) -> Result<(), Error> {
#[derive(serde::Serialize)]
struct Req<'a> {
name: &'a str,... | Rust | 0 |
num_timesteps: int, total_timesteps: int
) -> None:
"""
Compute current progress remaining (starts from 1 and ends to 0)
:param num_timesteps: current number of timesteps
:param total_timesteps:
"""
self._current_progress_remaining = 1.0 - float(num_timesteps) / floa... | Python | 1 |
);
fn set_property_text(&self, text: Option<&str>);
}
impl<O: IsA<CompletionItem> + IsA<glib::object::Object>> CompletionItemExt for O {
//#[cfg(feature = "v3_24")]
//fn set_gicon<'a, P: IsA</*Ignored*/gio::Icon> + 'a, Q: Into<Option<&'a P>>>(&self, gicon: Q) {
// unsafe { TODO: call ffi::gtk_sourc... | Rust | 0 |
ror should be above");
if let Some(ref mut stdin) = pyg_proc.stdin {
write!(stdin, "{}", &input).unwrap();
}
let pyg_output = pyg_proc.wait_with_output()
.expect("pygmentize wait failed?");
String::from_utf8(pyg_output.stdout).expect("could not read pygmentize ... | Rust | 0 |
let my_paginate = MyPaginate{page: 1};
/// my_paginate.set_page(2);
/// my_paginate.set_perpage(100);
/// my_paginate.set_skip_page(12);
/// ```
pub fn trait_inherit(){
trait Page{
fn set_page(&self, p: i32){
println!("Page Default: 1");
}
}
trait PerPage{
fn set_perpage... | Rust | 0 |
MIT, which is original license at the time of copying.
//! Original test authors have copyright for their work.
#![deny(warnings)]
#![allow(clippy::needless_update)]
use std::path::PathBuf;
use swc_css_ast::Stylesheet;
use swc_css_codegen::{
writer::basic::{BasicCssWriter, BasicCssWriterConfig},
CodegenConfi... | Rust | 0 |
+1}/{len(inputs)}")
except Exception as e:
self.logger.error(f"Error procesando input {i+1}: {str(e)}")
results.append(f"Error: {str(e)}")
return results
def multi_model_consensus(self, prompt: str, tasks: List[str], **kwargs) -> Dict[str, str]:
... | Python | 1 |
MaterialTarget::Texture(Wrapper::new(TextureOptions::default()), texture_type)
}
_ => MaterialTarget::None,
}
}
}
//! Provides a few convenience extras for logging.
//! - FnGuard allow tracing entering and leaving functions
//! - ThreadLocalDrain adds a thread id to th... | Rust | 0 |
if opts.no_default_features {
args.extend_from_slice(&["--no-default-features"]);
}
for features in &opts.features {
args.extend_from_slice(&["--features", features]);
}
let target_dir = target_directory(true);
let target_dir_str = target_dir.to_string_lossy();
if !opts.no_instru... | Rust | 0 |
ializing_if = "Option::is_none")]
pub last_modified_date_time: Option<String>,
#[serde(rename = "locale")]
#[serde(skip_serializing_if = "Option::is_none")]
pub locale: Option<String>,
#[serde(rename = "subject")]
#[serde(skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,... | Rust | 0 |
import json
import urllib.error
import urllib.request
class response_wrapper:
def __init__(self, wrapped_req, stream_mode):
self.stream_mode = stream_mode
try:
wrapped_resp = urllib.request.urlopen(wrapped_req)
self.status_code = wrapped_resp.status
... | Python | 1 |
count.fetch_add(1, Ordering::SeqCst);
wait_table.add_waiter(dummy_waiter(1.into(), lock.ts, lock.hash));
assert_eq!(waiter_count.load(Ordering::SeqCst), 1);
// Remove the waiter.
wait_table.remove_waiter(lock, 1.into()).unwrap();
assert_eq!(waiter_count.load(Ordering::SeqCst), 0)... | Rust | 0 |
n on_fields<TField: Into<String>>(
first: TField,
rest: impl IntoIterator<Item = TField>,
reason: impl Into<String>,
) -> Self {
let mut r = Self {
fields: SmallVec::from_const([first.into()]),
reason: reason.into(),
};
r.fields.extend(rest.int... | Rust | 0 |
ack, Player::process_callback, &mut *local as *mut _ as *mut _) != 0 {
return Self::error("jack_set_process_callback().");
}
if (lib.activate)(jack) != 0 {
return Self::error("jack_activate().");
}
Ok(Player {
lib: lib,
... | Rust | 0 |
import openai
import os
# This class instantiate the API, used to communicate with GPT
class ChatGPT:
def __init__(self, method, sysprompt, example):
self.id = 0
self.chat_history = [
{"role": "system", "content": sysprompt}
]
if example:
self.prompt = syspro... | Python | 1 |
sub $t3, $t1, $t0
and $t4, $t0, $t1
or $t5, $t0, $t1
xor $t6, $t0, $t1
sll $t7, $t0, 2
srl $t8, $t1, 2
sllv $t8, $t1, $t8
srlv $t3, $t8, $t5
"""
@pytest.mark.parametrize("arch", ["mips32", "mipsel32"])
def test_mips32_binary_operations(qemu_assembly_run, arch):
qemu_assembly_run(MIPS_BINARY_OPERATIONS, arch)
... | Python | 1 |
single row
# input as a string, to a dictionary object consumable by BigQuery.
# It refers to a function we have written. This function will
# be run in parallel on different workers using input from the
# previous stage of the pipeline.
| 'String To BigQuery Row' >>
beam.Map(lambda s: da... | Python | 1 |
ntln!("Number of lantern fishes after {} days: {}", number_of_days, number_of_fishes);
}
const REPRODUCTION_RATE : i64 = 7;
const INITIAL_REPRODUCTION_RATE : i64 = 9;
fn num_of_fish(available_days : i64, first_reproduction : i64) -> i64 {
let mut available_days = available_days - first_reproduction;
if availa... | Rust | 0 |
and global_step % args.
validation_steps == 0):
log_validation(args, unet=unet, accelerator=
accelerator, weight_dtype=weight_dtype, epoch=epoch
)
logs = {'loss': loss.detach().item(), 'raw_model_loss':
... | Python | 1 |
xt::DiscordContext;
use crate::gateway::{
CompressionType, GatewayConfig, GatewayContext, GatewayError, GatewayHandler, GatewayResponse,
};
use crate::ws::*;
use crate::ws::Response::*;
use crossbeam_channel::{self, Receiver, Sender};
use minnie_model::event::*;
use minnie_model::gateway::*;
use minnie_model::types... | Rust | 0 |
erval range defined by interv and the sign depends on sc and the source sign.
/// The mantissa is normalized to the interval specified by interv, which can take the following values:
/// _MM_MANT_NORM_1_2 // interval [1, 2)
/// _MM_MANT_NORM_p5_2 // interval [0.5, 2)
/// _MM_MANT_NORM_p5_1 // interva... | Rust | 0 |
from typing import Tuple
from interfaces import ExtendedResult
def generate_report_for_address(extended_data: ExtendedResult) -> Tuple[str, str]:
# Logging the report generation process
print(
f"Generating transaction report for Bitcoin address ({extended_data.address}) "
f"from {extended_data.... | Python | 1 |
color::Fg(my_normal_gray), name, style::Reset);
print!("{}{}{}", color::Fg(my_green), observation_text, style::Reset);
print!("{}{}{}", color::Fg(my_normal_gray), obs, style::Reset);
let name_pad_len = BLOCK_LEN - PAD1_LEN - PAD2_LEN - (2 * R_SIDE_TEXT_LEN ) - NAME_LEN - NAME_LEN;
let add_space = &r... | Rust | 0 |
f64(transmute(a), transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vcagtq_f64() {
let a: f64x2 = f64x2::new(-1.2, 0.0);
let b: f64x2 = f64x2::new(-1.1, 0.0);
let e: u64x2 = u64x2::new(!0, 0);
let r: u64x2 = transmute(vcagtq_f64(transmu... | Rust | 0 |
from playsound3 import playsound
def morse_sonido(texto):
"""
La funcion reproduce el codigo morse que se recibe como parametro
Parametros:
codigo: string
"""
# Diccionario donde la clave es el caracter y el valor es el sonido en codigo morse
dic_sonido_morse = {
'a': 'sonidos\\le... | Python | 1 |
Err(e) => fail!("Unable to load file {}: {}", input_file.display(), e),
};
match parse::route_config(&contents) {
Ok(config) => config.1,
result => {
eprintln!("Unable to parse route config file {}:", input_file.dis... | Rust | 0 |
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.document_loaders import PyPDFLoader, DirectoryLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import FAISS
DATA_PATH = "data/"
DB_FAISS_PATH = "vectorstores/db_faiss"
def create_vector_db():
... | Python | 1 |
}
}
fn layer_fill_circle(layer: &mut Layer, cx: i32, cy: i32, r: i32, value: f64) {
assert!(r > 0);
let x0 = clampi(cx - r, 0, (WIDTH - 1) as i32);
let y0 = clampi(cy - r, 0, (HEIGHT - 1) as i32);
let x1 = clampi(cx + r, 0, (WIDTH - 1) as i32);
let y1 = clampi(cy + r, 0, (HEIGHT - 1) as i32);
... | Rust | 0 |
recommend,
opinion)
_, _ = module.db_module.update_mz_result_survey(mz_request_id, mz_result_id, 1)
return result, message
except Exception as ex:
print(ex)
return 400, {"error": ... | Python | 1 |
5, 4, 7], blue),
Triangle::new([5, 7, 6], blue),
Triangle::new([1, 5, 6], yellow),
Triangle::new([1, 6, 2], yellow),
Triangle::new([4, 5, 1], purple),
Triangle::new([4, 1, 0], purple),
Triangle::new([2, 6, 7], cyan),
Triangle::new([2, 7, 3], cyan),
];
let... | Rust | 0 |
",
application_id, token
)
}
// ██████╗ █████╗ ███████╗███████╗██╗███╗ ██╗ ██████╗
// ██╔══██╗██╔══██╗██╔════╝██╔════╝██║████╗ ██║██╔════╝
// ██████╔╝███████║███████╗███████╗██║██╔██╗ ██║██║ ███╗
// ██╔═══╝ ██╔══██║╚════██║╚════██║██║██║╚██╗██║██║ ██║
// ██║ ██║ ██║███████║███████║██║██║ ╚█... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.