text string | label_name string | labels int64 |
|---|---|---|
estando a Pilha
if __name__ == "__main__":
pilha = Stack()
# Empilhando elementos
pilha.push("Cebola")
pilha.push("Salada")
pilha.push("Melancia")
# Espiando o topo
pilha.peek()
# Desempilhando elementos
pilha.pop()
pilha.pop()
# Verificando se está vazia
print("... | Python | 1 |
# coding=utf-8
# Copyright (c) 2019 Alibaba PAI team.
#
# 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 ... | Python | 1 |
import os
import signal
from typing import cast
import docker
import psutil
from docker.errors import NotFound
from docker.models.containers import Container
from bridge.console import log_task
from bridge.utils.filesystem import resolve_dot_bridge
def stop():
with log_task("Stopping bridge services...", "All b... | Python | 1 |
_address + size_of::<u32>();
let slice = &mut self.memory[start_address..end_address];
let pointer = slice.as_mut_ptr();
unsafe {
*pointer = value
}
}
pub fn write_half_word(&mut self, address: u32, value: u16) {
let start_address = address as usize;
... | Rust | 0 |
#
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# 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 u... | Python | 1 |
cSettings::default()).await?;
log::info!("Successfully logged in to Matrix homeserver");
client
.register_event_handler({
let tx = tx.clone();
let watched_rooms = args.matrix_rooms.clone();
move |event: SyncMessageEvent<MessageEventContent>, room: Room| {
... | Rust | 0 |
self, prelude::*, BufReader, Read, Write},
time::Duration,
},
};
const BUF_SIZE: usize = 52428800;
impl Read for File {
fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> {
match self.state {
State::Flush => {
self.state = State::Sleep;
retu... | Rust | 0 |
[doc = "0x10 - LPO Clock Select Register"]
pub lpoclks: LPOCLKS,
_reserved3: [u8; 4usize],
#[doc = "0x18 - ADC Options Register"]
pub adcopt: ADCOPT,
#[doc = "0x1c - FTM Option Register 1"]
pub ftmopt1: FTMOPT1,
#[doc = "0x20 - Miscellaneous control register 0"]
pub misctrl0: MISCTRL0,
... | Rust | 0 |
.disable_mesh()
.x_label_formatter(&|v| format!("{:.0}", v))
.y_label_formatter(&|v| format!("{:.0}", v))
.label_style(("sans-serif", 20))
.draw()
.unwrap();
let polynom4 = |x| 4f32 + x * (-28f32 + x * (12f32 - x)) / 16f32;
chart
.draw_series(LineSeries::... | Rust | 0 |
with shape :math:`(N, P, O*)`.
Returns:
torch.Tensor: Calculated mean scalar value of KL divergence
(float).
"""
with torch.no_grad():
old_dist = self._old_policy(obs)[0]
new_dist = self.policy(obs)[0]
kl_constraint = torc... | Python | 1 |
io,
os::unix::io::{AsRawFd, RawFd},
};
use sys::{IORING_SETUP_IOPOLL, IORING_SETUP_SQPOLL};
/// Create a new io_uring instance with given `entries` entries and default
/// configuration values. On success, [`Sq`], [`Cq`] and [`Registrar`] will be
/// returned.
///
/// `entries` denote the number of sqes and i... | Rust | 0 |
#[bitfield::bitfield(8)]
#[derive(Display)]
struct BitField(Flags);
// No flags set.
let field = BitField::new();
assert_print_eq!(field, "{}", 1, "-");
}
// Test bit field features.
#[test]
fn debug_named_field() {
#[bitfield::bitfield(8)]
... | Rust | 0 |
mask: u32,
) -> Result<impl Iterator<Item = &percore::CoreId>> {
// FIXME: currently we only support the 'Flat Model' logical mode
// (so we just ignore the destination format register). See 10.6.2.2
// of Volume 3A of the Intel software developer's manual
Ok(self.config.cpu... | Rust | 0 |
/// A node which stores values written to it on a stack. When the node is read from it will pop the
/// top value off of the stack and return it.
#[derive(Debug)]
pub struct StackMemoryNode {
stack: Vec<isize>,
read_index: Option<usize>,
}
impl StackMemoryNode {
/// Construct a new, empty `StackMemoryNode`... | Rust | 0 |
uest_remote(device_key, "127.0.0.1", 9190, timeout=10000)
remote.upload(tmp.relpath(filename))
rlib = remote.load_module(filename)
# upload parameters to device
dev = remote.device(str(target), 0)
module = runtime.GraphModule(rlib["default"](dev))
data_tvm = tvm.nd.array... | Python | 1 |
ebb2, &[]);
cur.ins().trap(TrapCode::User(0));
cur.insert_ebb(ebb1);
let v1 = cur.ins().iconst(I32, 1);
let v2 = cur.ins().iadd(v0, v1);
cur.ins().jump(ebb0, &[v2]);
cur.insert_ebb(ebb2);
cur.ins().return_(&[v0]);
let cfg = ControlFlowGraph::with_funct... | Rust | 0 |
12IFG10),
34 => Val(ADC12IV_A::ADC12IFG11),
36 => Val(ADC12IV_A::ADC12IFG12),
38 => Val(ADC12IV_A::ADC12IFG13),
40 => Val(ADC12IV_A::ADC12IFG14),
42 => Val(ADC12IV_A::ADC12IFG15),
44 => Val(ADC12IV_A::ADC12IFG16),
46 => Val(ADC12IV_A::A... | Rust | 0 |
channel, b'1', b'2')],
)?;
Ok(value as f32)
}
fn get_temperature(&mut self, channel: usize) -> Result<f32> {
let value = self.get(
CommandGet::Temperature,
[b'M', match_channel_to!(channel, b'1', b'2')],
)?;
Ok(value as f32)
}
}
#[derive(Clon... | Rust | 0 |
nt
regular_html = format_tool_use_content(regular_tool)
todowrite_html = format_tool_use_content(todowrite_tool)
# Regular tool should use standard formatting
assert 'class="collapsible-details"' in regular_html
assert "<summary>" in regular_html
# Tool name/ID no longe... | Python | 1 |
.cpu().numpy() # (B, H, W, 3), val:[-1,1]
pred_imgs = pred_drv_imgs.permute(0, 1, 3, 4, 2).cpu().numpy() # (B, T, 256, 256, 3), val:[-1,1]
gt_imgs = drv_imgs.permute(0, 1, 3, 4, 2).cpu().numpy() # (B, T, 256, 256, 3), val:[-1,1]
... | Python | 1 |
from pathlib import Path
def analyze_unknown_problems():
report_dir = Path("reports/")
total_files = 0
unknown_count = 0
# Durchsuche alle TXT-Reports
for report_path in report_dir.glob("*.txt"):
total_files += 1
try:
with open(report_path, "r", encoding="utf-8") as f:
... | Python | 1 |
c.add_assign(encryption_key.P_2.mul(r.into_repr()));
proof.c = c.into_affine();
let proof = Proof {
proof,
v_eta_gamma_inv: pk.pk.vk.eta_gamma_inv_g1.mul(v).into_affine(),
};
Ok(proof)
}
pub fn verify_proof<E: PairingEngine>(
pvk: &PreparedV... | Rust | 0 |
from queues import Queue
studentQueue = Queue() #instance self.queue = []
while True:
choice = input("Press any key to continue and ENTER to STOP: ")
if choice == "":
print("Program ends")
break
else:
while True:
userInput = int(input("Press 1. Enqueue\n2. Dequeue\n3. P... | Python | 1 |
ets";
pub const HFUNC_DEPOSIT: ScHname = ScHname(0xbdc9102d);
pub const HFUNC_WITHDRAW: ScHname = ScHname(0x9dcc0f41);
pub const HVIEW_ACCOUNTS: ScHname = ScHname(0x3c4b5e02);
pub const HVIEW_BALANCE: ScHname = ScHname(0x84168cb4);
pub const HVIEW_TOTAL_ASSETS: ScHname = ScHname(0xfab0f8d2);
// @for... | Rust | 0 |
r):
clf = FakeClassifier()
scores = bootstrap_point632_score(
clf,
X[:100],
y[:100],
scoring_func=roc_auc_score,
predict_proba=True,
random_seed=123,
)
if "TRAVIS" in os.environ or os.environ.get("TRAVIS") == "true":
T... | Python | 1 |
app_id=cls.one_month_app.id,
activity_level=ActivityLevel.ONE_MONTH
)
cls.cred2 = UserCredential(
domain=cls.domain,
user_id=1,
username='user1',
app_id=cls.three_month_app.id,
activity_level=ActivityLevel.THREE_MONTHS
)
... | Python | 1 |
"""
The various HTTP responses for use in returning proper HTTP codes.
"""
from django.http import HttpResponse
class HttpCreated(HttpResponse):
status_code = 201
def __init__(self, *args, **kwargs):
location = kwargs.pop('location', '')
super(HttpCreated, self).__init__(*args, **kwargs)
... | Python | 1 |
tr(value)
return list(map(encode_src_dict, value))
else:
assert isinstance(value, dict), str(value)
return encode_src_dict(value)
elif parameter.parameter_type == "gx_data_collection":
assert isinstance(value, dict), str(value)
... | Python | 1 |
open(debug_file, "a", encoding='utf-8') as f:
if missing_fields:
f.write(f"Missing fields: {', '.join(missing_fields)}\n")
else:
f.write("All required fields present\n")
# 准备投资辩论状态
investment_debate_state = sta... | Python | 1 |
line())
.append("end")
}
/// Same as expr, expect it wraps seq, let, etc in begin end
///
fn wrap_expr(expression: TypedExpr, env: &mut Env) -> Document {
match &expression {
Expr::Seq { .. } => begin_end(expr(expression, env)),
Expr::Let { .. } => begin_end(expr(expression, env)),
... | Rust | 0 |
k.Mock()
self._fake_coroutine(start_mock, unittest.mock.Mock(status=200))
connector = aiohttp.ProxyConnector(
'http://proxy.example.com', loop=loop_mock)
tr, proto = unittest.mock.Mock(), unittest.mock.Mock()
self._fake_coroutine(loop_mock.create_connection, (tr, proto))
... | Python | 1 |
["Σκευᾶς", "Skeuâs | skyoo-as'", "left-handed; Scevas (i.e. Scævus), an Israelite"],
"G4631":["σκευή", "skeuḗ | skyoo-ay'", "furniture, i.e. spare tackle"],
"G4632":["σκεῦος", "skeûos | skyoo'-os", "a vessel, implement, equipment or apparatus (literally or figuratively [specially, a wife as contributing to the usefulne... | Python | 1 |
zar ({str(e)[:30]}...)\n\n"
# ✅ GENERAR PREDICCIONES ENSEMBLE PARA REPORTE
try:
print("🔍 Generando predicciones ENSEMBLE para reporte Discord...")
all_predictions = await self.tcn_predictor.predict_all_symbols_v3()
if not all_predictions:
... | Python | 1 |
import requests
import time
from datetime import datetime, timedelta
API_KEY = "ur api key"
def get_option_price_history(ticker):
"""Fetches the number of days of historical data available for an option."""
print(f"[DEBUG] Fetching price history for {ticker}...")
start_date = (datetime.today() - timedelt... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Timesheets/attendances reporting",
'description': """
Module linking the attendance module to the timesheet app.
""",
'category': 'Hidden',
'version': '1.0',
'depends': ['hr_timesh... | Python | 1 |
from django import forms
class FormularioContacto(forms.Form):
nombre=forms.CharField(label="Nombre", required=True)
email=forms.CharField(label="Email", required=True)
contenido=forms.CharField(label="Contenido", widget=forms.Textarea)
| Python | 1 |
import os
import matplotlib.pyplot as plt
import pandas as pd
def make_charts(df: pd.DataFrame, x_names: list[str], y_name: str, folder: str) -> None:
folder_path = f"charts/{folder}"
os.makedirs(folder_path, exist_ok=True)
for feature in x_names:
img = df[[feature, y_name]].plot.scatter(x=featu... | Python | 1 |
import os
import tempfile
import click
from werkzeug.serving import run_simple
def make_app():
from shorty.application import Shorty
filename = os.path.join(tempfile.gettempdir(), "shorty.db")
return Shorty(f"sqlite:///{filename}")
def make_shell():
from shorty import models, utils
application... | Python | 1 |
(),
})
.collect()
})
.collect()
}
#[aoc(day3, part1)]
pub fn part1(input: &[Vec<bool>]) -> usize {
// Make table dimensions explicit
let height = input.len();
let width = input[0].len();
// For every column
let gamma: usize = (0..width)
.map(... | Rust | 0 |
use crate::protocol::BitswapConfig;
use fnv::FnvHashSet;
use futures::task::Context;
use futures::task::Poll;
use libp2p::core::connection::ConnectionId;
use libp2p::core::{Multiaddr, PeerId};
use libp2p::swarm::protocols_handler::OneShotHandler;
use libp2p::swarm::{
DialPeerCondition, NetworkBehaviour, NetworkBeh... | Rust | 0 |
import random
# all_obj_en = ['Mug', 'Banana', 'Toothpaste', 'Bread', 'Softdrink', 'Yogurt', 'ADMilk', 'VacuumCup', 'BottledDrink', 'PencilVase',
# 'Teacup', 'Caddy', 'Dictionary', 'Cake', 'Date', 'Stapler', 'LunchBox', 'Bracelet', 'MilkDrink', 'CocountWater', 'Walnut', 'HamSausage',
# 'Glu... | Python | 1 |
_reloc: binemit::Reloc,
_constant_offset: ir::ConstantOffset,
) {
// Do nothing for now: cranelift emits constant data after the function code and also emits
// function code with correct relative offsets to the constant data.
}
fn reloc_jt(
&mut self,
_offse... | Rust | 0 |
range(7):
output[i].append(tokens_A[i].clone().tolist()[0])
output[7].append(token_T.clone().tolist()[0])
input_pos = input_pos.add_(1)
return output
@torch.inference_mode()
def generate_ASR(
model: GPT,
audio_features: torch.Tensor,
input_ids: list,
leng,
task,
... | Python | 1 |
import requests
# Set base URL and attacker server URL
BASE_URL = "http://127.0.0.1"
# Replace with your actual server
ATTACKER_SERVER = "https://your_attacker_server.com"
# Step 1: Make a GET request to search endpoint
search_response = requests.get(f"{BASE_URL}/search?search=test")
print("Search Response Status Cod... | Python | 1 |
elf.ring_pg,
)
if type(out) == tuple:
context_layer, _, _ = out
else:
context_layer = out
# (bs, seq_len, head_cnt/N, head_size) -> (bs, seq_len/N, head_cnt, head_size)
# scatter 1, gather 2
context_layer = (
... | Python | 1 |
It then responds to these events by performing actions on the Cosmos chain if required
use crate::get_with_retry::get_block_number_with_retry;
use crate::get_with_retry::get_chain_id_with_retry;
use crate::metrics;
use cosmos_gravity::build;
use cosmos_gravity::query::get_last_event_nonce;
use deep_space::private_key:... | Rust | 0 |
print(" *** Welcome To The iContacts ***")
myContacts = {}
# creating function, which will check the key value and returns the corressponding value of the searched key value
def keyVal(dict, key):
if key in dict.keys():
print(f"Phone number of {key} is : {dict[key]}.\n")
else:
print("Not present!")
# if we re... | Python | 1 |
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
# Copyright 2015 and onwards Google, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/license... | Python | 1 |
_in.r - 74 * v_in.g + 112 * v_in.b + 128) >> 8) + 128, 0, 255);
yuv_v.s2 = clamp(((112 * v_in.r - 94 * v_in.g - 18 * v_in.b + 128) >> 8) + 128, 0, 255);
uint3 yuv_p;
if (type == 0) {
// YUV420P
yuv_p.s0 = y * width + x;
yuv_p.s1 = y / 2 * width / 2 + x / 2 + width * height;
... | Rust | 0 |
ry<(
Entity,
&mut Transform,
&mut AsepriteAnimation,
&CrabMoveWalker,
)>,
zapped_query: Query<Entity, With<BeingZapped>>,
mut map_query: MapQuery,
tile_query: Query<&Tile>,
grab_state: ResMut<MouseGrabState>,
) {
if !grab_state.shall_grab {
return;
}
... | Rust | 0 |
"""Google Gemini provider implementation for gpt.py."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Iterator, Optional
from .common import (
DEFAULT_GOOGLE_MAX_TOKENS,
APIError,
InvalidAPIKeyError,
check_dependency,
parse_messages,
validate_api_key,
)
# Third-pa... | Python | 1 |
dead_code)]
pub(crate) enum OptionsProps {
AddLeadingZeroToHexNumbers,
AlwaysShowScale,
AlwaysShowSegmentRegister,
BinaryDigitGroupSize,
BinaryPrefix,
BinarySuffix,
BranchLeadingZeroes,
DecimalDigitGroupSize,
DecimalPrefix,
DecimalSuffix,
DigitSeparator,
DisplacementLeadingZeroes,
FirstOperandCharIndex,
G... | Rust | 0 |
from typing import List
from pydantic import BaseModel, Field
"""
Just some Input models for FastApi
"""
class InputModel(BaseModel):
prev_tx_hash:str
output_index:int
address:str
index:int
signature:str
class OutputModel(BaseModel):
amount:int
address:str
index:int
input_hash:st... | Python | 1 |
parse_data[0] = len(parse_data) - 1
if node.get("component", {}).get("code", "") == "remote_plugin":
cur_step_detail["plugin_code"] = (
node.get("component", {}).get("data", {}).get("plugin_code", {}).get("value")
)
el... | Python | 1 |
::from_repr(BigInteger768([
0xeed5a0a2eeed0d6e,
0xd10e0f23a0015544,
0xa9cd701b711a8cd6,
0xe9ff46772ea6b4dd,
0x43627948f5f3db53,
0x60a618188f984bcd,
0x93b59b8613f58256,
0x80029a27200b574a,
... | Rust | 0 |
B12 = geomath::sin_cos_series(true, ssig2, csig2, &self._C1a);
}
AB1 = (1.0 + self._A1m1) * (B12 - self._B11);
}
let sbet2 = self._calp0 * ssig2;
let mut cbet2 = self._salp0.hypot(self._calp0 * csig2);
if cbet2 == 0.0 {
cbet2 = self.ti... | Rust | 0 |
from numpy._core.strings import __all__, __doc__
from numpy._core.strings import *
| Python | 1 |
1] # (batch, 1, 1)
x = x + stoch_layer_coeff * self.dropout(
self.merge_proj(w1 * x1 + w2 * x2))
elif self.merge_method == "fixed_ave":
x = x + stoch_layer_coeff * self.dropout(
self.merge_proj((1.0 - self.cgmlp... | Python | 1 |
ERENCE) {
1
} else if matches.is_present(options::dereference::NO_DEREFERENCE) {
0
} else {
-1
};
let mut bit_flag = if matches.is_present(options::traverse::TRAVERSE) {
FTS_COMFOLLOW | FTS_PHYSICAL
} else if matches.is_present(options::traverse::EVERY) {
FTS... | Rust | 0 |
) -> isize {
//! *(self.0 + 1) as isize
//! }
//! }
//!
//! impl From<Address> for IntegerObject {
//! fn from(address: Address) -> Self {
//! IntegerObject(address)
//! }
//! }
//!
//! impl Into<Address> for IntegerObject {
//! fn into(self) -> Address {
//! self.0
//! }
//!... | Rust | 0 |
from __future__ import print_function
from __future__ import absolute_import
import torch
import torch.nn as nn
import torch.nn.functional as F
from .wordsequence import WordSequence
from .crf import CRF
class SeqModel(nn.Module):
def __init__(self, data):
super(SeqModel, self).__init__()
self.use_... | Python | 1 |
CTL_SPEC>`"]
pub type FLCTL_READ_TIMCTL = crate::Reg<flctl_read_timctl::FLCTL_READ_TIMCTL_SPEC>;
#[doc = "Read Timing Control Register"]
pub mod flctl_read_timctl;
#[doc = "FLCTL_READMARGIN_TIMCTL register accessor: an alias for `Reg<FLCTL_READMARGIN_TIMCTL_SPEC>`"]
pub type FLCTL_READMARGIN_TIMCTL =
crate::Reg<flc... | Rust | 0 |
ks': 'فلسطینی علاقٕہ', 'ks-Arab': 'فلسطینی علاقٕہ', 'ksb': 'Ukingo wa Maghalibi na Ukanda wa Gaza wa Palestina', 'ksf': 'zǝ palɛstínǝ', 'ksh': 'Palästina', 'ku': 'Herêmên Filîstînî', 'kxv': 'palesṭiati handi', 'kxv-Latn': 'palesṭiati handi', 'ky': 'Палестина аймактары', 'lag': 'Mweemberera wa kʉmweeri wa Gáaza', 'lb': ... | Python | 1 |
n(rows) - 1)]) and any(
[columns[i] != columns[i + 1] for i in range(len(columns) - 1)]
):
raise InvalidShipCoordinateException(
"Neither the rows or columns have constant value."
)
# Check if there's a duplicate tuple in the c... | Python | 1 |
path.into(),
container_name.into(),
use_system,
)?));
}
log::info!("cgroup manager V2 will be used");
Ok(Box::new(v2::manager::Manager::new(
DEFAULT_CGROUP_ROOT.into(),
cgroup_path.into(),
... | Rust | 0 |
{}
ty::GenericParamDefKind::Type {
has_default,
ref object_lifetime_default,
ref synthetic,
} => {
has_default.hash_stable(hcx, hasher);
object_lifetime_default.hash_stable(hcx, hasher);
synthetic.ha... | Rust | 0 |
ign s2_beacon with s1_beacon and check whether alignment is correct
let offset = s2_beacon - s1_beacon; // offset + x1 = x2 (if correct)
let mut aligned_beacons: Vec<Vector3<i32>> =
s1_beacons.clone().into_iter().map(|v| offset + v).collect();
aligned_beacons.sort_by(... | Rust | 0 |
ut,
token_usage_output,
token_usage_total,
)
return text, token_usage_input, token_usage_output, token_usage_total
except google_exceptions.Unauthenticated as e:
logging.error(f"Gemini API authentication error: {e}")
rai... | Python | 1 |
le_path)?
} else {
let dir_path = file_path.parent().unwrap();
fs::create_dir_all(&dir_path)?;
WhisperBuilder::default()
.add_retentions(&config.retentions)
.x_files_factor(config.x_files_factor)
.aggregation_method(config.aggregation_method)
... | Rust | 0 |
/tari<gh_stars>0
// Copyright 2019 The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the ... | Rust | 0 |
== suggestion_id:
return s
raise HTTPException(status_code=404, detail="Suggestion not found")
except Exception as e:
logger.exception("Error accepting suggestion=%s blog_id=%s", suggestion_id, blog_id)
raise HTTPException(status_code=500, detail=str(e))
@router.pos... | Python | 1 |
=tf.int64)
for ac in ac_spectrum:
with summary_writer.as_default():
with tf.contrib.summary.always_record_summaries():
tf.contrib.summary.scalar("Autocorrelation", ac, step=plot_step)
plot_step.assign(plot_step + n_steps)
if HAS_MATPLOTLIB:
# Choose a single chain and plot ... | Python | 1 |
if __name__ == '__main__':
string = input().strip()
# Check for any alphanumeric characters
has_alnum = any(char.isalnum() for char in string)
print(has_alnum)
# Check for any alphabetical characters
has_alpha = any(char.isalpha() for char in string)
print(has_alpha)
# Che... | Python | 1 |
import torch.nn as nn
from utils import *
from torch.nn import Module
import scipy.sparse as sp
class GCN_Layer(Module):
def __init__(self, inF, outF):
super(GCN_Layer, self).__init__()
self.W1 = torch.nn.Linear(in_features=inF, out_features=outF)
self.W2 = torch.nn.Linear(in_features=inF, ... | Python | 1 |
|\
grep -Eo "define.*?(KEY_|BTN_)+[a-zA-Z0-9_]*\s+(0x[0-9a-f]*|[0-9]+)+" |\
awk '{ printf "%s %s\n", tolower($3), tolower($2) }' |\
sed "s/key_//" |\
awk '{ printf "%s => \"%s\",\n", $1, $2 }' > /tmp/code_to_name
*/
#[allow(unreachable_patterns)]
pub fn code_to_name(x: u16) -> &'static str {
match x {
... | Rust | 0 |
QUARE_C2,
Square::D2 => bitboard::SQUARE_D2,
Square::E2 => bitboard::SQUARE_E2,
Square::F2 => bitboard::SQUARE_F2,
Square::G2 => bitboard::SQUARE_G2,
Square::H2 => bitboard::SQUARE_H2,
Square::A3 => bitboard::SQUARE_A3,
Square::B3 => bi... | Rust | 0 |
import sys
from collections import defaultdict
# Read input
n = int(sys.stdin.readline())
graph = defaultdict(list)
for _ in range(n-1):
u, v = map(int, sys.stdin.readline().split())
graph[u].append(v)
# Function to find the centroid (average) of all cities
def calculate_centroid(cities):
total_x = sum(x ... | Python | 1 |
loc_C65B'),
(0x00007350, 'loc_C65B'),
(0x0000734F, 'loc_C65B'),
(-1, 'loc_C663'),
)
def _loc_C65B(): pass
label('loc_C65B')
SetScenaFlags(ScenaFlag(0x01D5, 0, 0xEA8))
Jump('loc_C663')
def _loc_C663(): pass
label('loc_C663')
Call(ScriptId.Map, 'EV_DoJump_QS_... | Python | 1 |
import copy
from autogluon.features.generators import (
AutoMLInterpretablePipelineFeatureGenerator,
AutoMLPipelineFeatureGenerator,
IdentityFeatureGenerator,
)
def get_default_feature_generator(feature_generator, feature_metadata=None, init_kwargs=None):
if init_kwargs is None:
init_kwargs =... | Python | 1 |
''' Implement quick sort
'''
from random import randint
def quick_sort(pass_in_seq):
quick_sort_helper(pass_in_seq,0,len(pass_in_seq)-1)
''' p | <p | >p | unpartitioned
i j
step1 3 8 2 5 1 4 7 6
i
j
step2 3 8 2 5 1 4 7 6
i j
3 2... | Python | 1 |
cell::VolatileCell<u32>,
}
#[doc = "Receive buffer is filled up"]
pub mod events_endrx;
#[doc = "Data sent from TXD"]
pub struct EVENTS_TXDRDY {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Data sent from TXD"]
pub mod events_txdrdy;
#[doc = "Last TX byte transmitted"]
pub struct EVENTS_ENDTX {
register: ::... | Rust | 0 |
#!/usr/bin/python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | Python | 1 |
# core/ai_plugin_base.py
from core.prompt_engine import build_prompt
class AIPluginBase:
"""
Base interface for every AI engine.
Each plugin (OpenAI, Claude, Manual, etc.) may implement the desired methods.
"""
async def handle_incoming_message(self, bot, message, prompt):
"""Process a me... | Python | 1 |
#!/usr/bin/env python3
"""External Captive Portal Web Server."""
from flask import Flask, redirect, render_template, request
from waitress import serve
# Module Variables
base_grant_url = ""
user_continue_url = ""
success_url = ""
app = Flask(__name__, static_url_path='/5004/static')
# Flask micro-webservice URI ... | Python | 1 |
= fastrand::Rng::new();
/// base1.seed(0x4d595df4d0f33173);
/// base1.bool(); // Use the generator once.
///
/// let base2 = fastrand::Rng::new();
/// base2.seed(0x4d595df4d0f33173);
/// base2.bool(); // Use the generator once.
///
/// let rng1 = base1.clone();
/// let rng2 = base2.... | Rust | 0 |
;
#[cfg(not(debug_assertions))]*/
let display = Display::with_debug(gl_window, DebugCallbackBehavior::Ignore)?;
let device_pixel_ratio = display.gl_window().get_hidpi_factor();
// pre-caching shaders means to compile all shaders on startup
// this can take significant time and ... | Rust | 0 |
ctions(temperature))
.collect()
}
fn m(&self) -> Cow<Array1<f64>> {
match self.molecule_shape() {
MoleculeShape::Spherical(n) => Cow::Owned(Array1::ones(n)),
MoleculeShape::NonSpherical(m) => Cow::Borrowed(m),
MoleculeShape::Heterosegmented(component_inde... | Rust | 0 |
from .depictionresources import add_unit_meshes
__all__ = [
"add_unit_meshes",
] | Python | 1 |
max value)^2)`
Concave,
/// 2: The SoundFont modulator controller moves in a convex fashion from the minimum to the maximum value in the direction and with the polarity specified by the ‘D’ and ‘P’ bits. The convex curve is the same curve as the concave curve, except the start and end points are reversed.
Convex,... | Rust | 0 |
angle = inv_angle_start + ig*dangle;
if sort_normalized:
arr1 = arr1
arr2 = arr2/np.max( np.abs(arr2) )*np.max( np.abs(arr1) )
arr3 = arr3/np.max( np.abs(arr3) )*np.max( np.abs(arr1) )
arr3 = arr3/np.max(... | Python | 1 |
field = Model._meta.get_field(field_name)
# Handle M2M relations
if field.remote_field and isinstance(
field.remote_field, models.ManyToManyRel
):
try:
values = base.deserialize_m2m_values(
field, field_valu... | Python | 1 |
# Copyright (C) 2024 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AnalyticAccount(models.Model):
_inherit = "account.analytic.account"
trip_id = fields.One2many("tms.order", "analytic_account_id", copy=False)
route_id = fiel... | Python | 1 |
attention_mask=text_input['attention_mask'],
cand_vis=cand_embeds,
hist_vis=hist_vis_input,
)
loss, hidden_states = output.loss, output.hidden_states
fuse_logits = torch.zeros((fuse_embeds.shape[0], fuse_embeds.shape[1])).to(
fuse_embeds.device).to(s... | Python | 1 |
}
}
pub fn set_quant_params(&mut self, params: &QParams) -> TractResult<()> {
let q = self.as_quant_mut().ok_or("try to zero_point on a float mat mul")?;
unsafe {
if let Some(t) = params.zero_point_a.as_ref() {
if t.rank() == 0 {
q.set_zero_point_... | Rust | 0 |
"""Helper module to handle time related stuff"""
from time import sleep as original_sleep
from datetime import datetime
from random import gauss
from random import uniform
# Amount of variance to be introduced
# i.e. random time will be in the range: TIME +/- STDEV %
STDEV = 0.5
sleep_percentage = 1
sleep_percentage =... | Python | 1 |
(
position().skip(ident("fragment")),
name::<'a, T>(),
ident("on").with(name::<'a, T>()).map(TypeCondition::On),
parser(directives),
parser(selection_set)
).map(|(position, name, type_condition, directives, selection_set)| {
FragmentDefinition {
position, ... | Rust | 0 |
ty = seasonality.groupby(level=(0,2)).apply(
lambda s: s.reset_index(level=(0,2),drop=True).reindex(years).fillna(method="ffill")
)
seasonality = seasonality.swaplevel("birth_month","birth_year").sort_index()
seasonality.index.rename(["state","year","month"],inplace=True)
## Then use it to distribute bi... | Python | 1 |
0x001a96a6, 0x0d1526ab, 0x63315c21, 0x5e0a72ec,
0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,
0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e,
0xcfcbd12f, 0xc1de8417, 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3,
0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x1... | Rust | 0 |
#Python program to check the score from a student ,print grades as A+ if score >= 90,A if 80 or above, B+ if 70 or above and so on...
#print failed if the score is below 50, if score > 100 print invalid
r1=int(input("enter physics score :"))
r2=int(input("enter maths score :"))
r3=int(input("enter science score :"))
... | Python | 1 |
config_path: file_path }
}
pub fn run(&mut self, archive: &mut PackageArchive, auth_token: &str) -> bool {
if !self.config_path.exists() {
debug!("no post processing config - skipping");
return true;
}
debug!("starting post processing");
let mut cfg = m... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.