text string | label_name string | labels int64 |
|---|---|---|
, 5, 6, 7, 8, 9][..]));
data.push(0..2);
assert_eq!(data.data_len(), 12);
assert_eq!(data.get(1), Some(&[0, 1][..]));
}
}
use crate::{decode, encode, handle, LexError, TokenStream};
use std::fmt::{self, Display};
use std::marker::PhantomData;
use std::panic::{self, PanicInfo};
use std::sync:... | Rust | 0 |
nwrap().tx.borrow().clone();
let transported = TransportedSender::<T, Codec> { port, data, codec: PhantomData };
transported.serialize(serializer)
}
}
impl<'de, T, Codec> Deserialize<'de> for Sender<T, Codec>
where
T: RemoteSend + Sync + Clone,
Codec: codec::Codec,
{
/// Deserializes th... | Rust | 0 |
e='dropout7')
net = slim.conv2d(net, num_classes, [1, 1],
activation_fn=None,
normalizer_fn=None,
biases_initializer=tf.zeros_initializer,
scope='fc8')
# Convert end_points_collection into a end_point d... | Python | 1 |
ource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(clippy::all)]
#![warn(clippy::cyclomatic_complexity)]
#![allow(unused)]
fn main() {
if true {
println!("a");
}
if true {
println!("a");
}
... | Rust | 0 |
_time = Some(input);
self
}
/// <p>The last time the resource was modified. The timestamp depends on the status of the job:</p>
/// <ul>
/// <li> <p> <code>CREATE_PENDING</code> - The <code>CreationTime</code>.</p> </li>
/// <li> <p> <code>CREATE_IN_PROGRESS</code> - ... | Rust | 0 |
}
IdEvent::Begin { at, .. } => { write!(f, "M {:?} ", at) }
IdEvent::End { close: true, .. } => { write!(f, "Z ") }
IdEvent::End { close: false, .. } => { Ok(()) }
}?;
}
write!(f, "}}")
}
}
/// A view on a [`PathCommands`](struct.PathComma... | Rust | 0 |
r.collider1,
context.pair.pair.collider2,
))
}
}
}
#[cfg(feature = "simd-is-enabled")]
#[inline]
pub fn generate_contacts_simd(
self,
mut context: ContactGenerationContextSimd,
events: &dyn EventHandler,
) {
let... | Rust | 0 |
e of linked list")
print("11. Exit")
while True:
display_menu()
choice = input("Enter your choice (1-11): ")
if choice == "1":
data = input("Enter the data to add at the beginning: ")
llist.insertAtBegin(data)
elif choice == "2":
data = input("Enter the data to add at the e... | Python | 1 |
_link_ptr: Ptr) -> Option<Ptr>;
fn max_key<'a>(&'a self) -> &'a K;
fn min_key<'a>(&'a self) -> &'a K;
fn keys<'a>(&'a self) ->&'a ~[K];
fn values<'a>(&'a self) -> &'a ~[V];
fn mut_keys<'a>(&'a mut self) ->&'a mut ~[K];
fn mut_values<'a>(&'a mut self) -> &'a mut ~[V];
fn is_root(&self) ->... | Rust | 0 |
eries.assign_thread_id("test123")
request_context.message = queries
request_context.connection_ready = True
handler = QueriesHandler()
responder = MockResponder()
await handler.handle(request_context, responder)
messages = responder.messages
assert len(messages) =... | Python | 1 |
from fastworkflow.build.class_analysis_structures import MethodInfo, PropertyInfo
from fastworkflow.build.pydantic_model_generator import generate_input_model_code, generate_output_model_code, generate_property_output_model_code
def test_generate_input_model_code_with_annotations():
method = MethodInfo('foo', [
... | Python | 1 |
if let Some(message) = tangle.get(&request.message_id.into()).await.map(|m| (*m).clone()) {
Sender::<MessagePacket>::send(
&peer_manager,
&metrics,
&peer_id,
MessagePacket::new(&message.pack_n... | Rust | 0 |
elf, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Coprocessor Access Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write... | Rust | 0 |
# Python in Excel
# Link to the challenge
# https://www.linkedin.com/posts/excelbi_challenge-powerquerychallenge-daxchallenge-activity-7232959812286771200-vPok/
# Read the data range
df = xl("A1:F10", headers=True)
# Perform data munging
dfs = []
for i in range(df.shape[1])[::2]:
dfi = df.iloc[:, i : i + 2].drop... | Python | 1 |
e sensors."""
encharge_aggregate = self.data.encharge_aggregate
assert encharge_aggregate is not None
return self.entity_description.value_fn(encharge_aggregate)
class EnvoyEnpowerEntity(EnvoySensorBaseEntity):
"""Envoy Enpower sensor entity."""
entity_description: EnvoyEnpowerSensorE... | Python | 1 |
)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rte_eth_burst_mode>())).info as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rte_eth_burst_mode),
"::",
stringify!(info)
)
);
}
#[doc = " An Eth... | Rust | 0 |
true),
)
.arg(
Arg::with_name("static-folder")
.long("static-folder")
.value_name("STATIC_FOLDER")
.env("STATIC_FOLDER")
.takes_value(true),
)
.get_matches();
let db_url = matches.value_of("db").unwrap_or("s... | Rust | 0 |
#!/usr/bin/env python
# coding:utf-8
from ctf import *
binary = './char'
context.arch = 'x86'
context.log_level= 'INFO'
mode = args['MODE'].lower()
os.environ['LD_LIBRARY_PATH'] = os.curdir
# os.environ['LD_PRELOAD'] = './nosleep.so'
elf = ELF(binary)
libc = [x for x in elf.libs.keys() if 'libc.so' in x]
libc = ELF(... | Python | 1 |
false() {
assert!(input::MODIFIER_NONE.is_control_only() == false);
assert!(input::MODIFIER_SHIFT.is_control_only() == false);
assert!(input::MODIFIER_CAPS_LOCK.is_control_only() == false);
assert!(input::MODIFIER_ALT.is_control_only() == false);
assert!(input::MODIFIER_SUPER.is_... | Rust | 0 |
from PyLTSpice import RawRead
from matplotlib import pyplot as plt
import numpy as np
def read_voltage_inv(N,RAW_FILE_PATH):
LTR = RawRead(RAW_FILE_PATH)
V=[]
for i in range(N):
node_read=i+1+N
V_="V(N" + str(node_read).zfill(3)+')'
#print(V_)
V_i = LTR.get_trace(V_)
... | Python | 1 |
>) -> T
where
T: Copy + Datum + num_traits::Signed + num_traits::Zero,
{
v.fold(T::zero(), |acc, &v| acc + v.abs())
}
fn l1u_t<'a, T>(v: ArrayViewD<'a, T>) -> T
where
T: Copy + Datum + num_traits::Unsigned + num_traits::Zero,
{
v.fold(T::zero(), |acc, &v| acc + v)
}
fn l2_t<'a, T>(v: ArrayViewD<'a, T>... | Rust | 0 |
k([x1, y1, x2, y2, classes.long()], dim=-1)
#bboxes = torch.stack([x1, y1, x2, y2, classes.long()], dim=-1).tolist()
transposed_img, transposed_bboxesd = self._Resize_for_batchmosaic(img, bboxes, xc, yc)
return transposed_img, transposed_bboxesd
def _Resize_for_batchmosaic(sel... | Python | 1 |
,
count: GLsizei,
transpose: GLboolean,
value: *const GLfloat,
),
>;
pub type PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC = ::std::option::Option<
unsafe extern "C" fn(
program: GLuint,
location: GLint,
count: GLsizei,
transpose: GLboolean,
value: *const GL... | Rust | 0 |
import torch
import torch.nn as nn
import numpy as np
from tqdm import tqdm
class AISModel(nn.Module):
def __init__(self, model, init_dist):
super().__init__()
self.model = model
self.init_dist = init_dist
def forward(self, x, beta):
logpx = self.model(x).squeeze()
log... | Python | 1 |
get_mut(&3);
assert_eq!(format!("{:?}", cache), "{3: 30, 6: 60, 2: 22}");
cache.set_capacity(2);
assert_eq!(format!("{:?}", cache), "{3: 30, 6: 60}");
}
#[test]
fn test_remove() {
let mut cache = LruCache::new(3);
cache.put(1, 10);
cache.put(2, 20);
cache.put(3, 30);
cache.put(4, 40);
... | Rust | 0 |
import tensorflow as tf
class MultiPosConLoss:
def __init__(self, tau=0.05):
"""NT-Xent a.k.a. Info-NCE loss. It can also works with more than one positive sample per
anchor i.e., it can implement the SupCon or MultiPosCon losses."""
self.tau = tau
@tf.function
def __call__(sel... | Python | 1 |
in parent:
parent[next_pos] = robot_pos # Set parent for backtracking
if done:
dynamic_obstacles = initial_dynamic_obstacles.copy()
print(f"Destination Reached in Episode {episode}!")
steps = len(parent)
if steps < best_steps:... | Python | 1 |
fn id(&self) -> WidgetId {
self.id
}
fn draw(
&self,
context: &GlContext,
_surface: &dyn Surface,
rect: Rect<i32>,
theme: &Theme,
_draw_2d: &mut Draw2d,
_cursor_pos: Option<Point2<i32>>,
_is_active: bool,
) {
theme.font.draw_st... | Rust | 0 |
from types import FunctionType
import threading
from Script.Core import cache_control, game_type, get_text, py_cmd
from Script.Design import constant, handle_instruct, ai_run
from Script.UI.Panel import see_character_info_panel, see_save_info_panel, achieve_panel
from Script.Config import normal_config
from Script.UI.M... | Python | 1 |
# -*- coding:utf-8 -*-
import re
from magic_doc.contrib.magic_html.utils import *
from magic_doc.contrib.magic_html.extractors.base_extractor import BaseExtractor
from magic_doc.contrib.magic_html.extractors.title_extractor import TitleExtractor
class CustomExtractor(BaseExtractor):
def __init__(self) -> None:
... | Python | 1 |
from the user’s terminal.
// Breaks the input into words and operators, obeying the quoting rules described in Quoting. These tokens are separated by metacharacters. Alias expansion is performed by this step (see Aliases).
// Parses the tokens into simple and compound commands (see Shell Commands).
// Perform... | Rust | 0 |
rd conversion traits
* use:
* let val = match serde_json::from_str(r#"["t","714109",1,"0.12900000","1.03377186",1504163835]"#) {
* serde_json::Array(vec) => vec,
* _ => Err(())
* };
* let records:: TradeRecord = TradeRecord::try_from(&val)
**/
impl<'a> TryFrom<&'a JsonValue> for TradeRecord {
typ... | Rust | 0 |
use glutin::{GlContext, HeadlessContext};
/// Initializes device and factory from a headless context.
/// This is useful for testing as it does not require a
/// X server, thus runs on CI.
///
/// # Example
///
/// ```rust
/// extern crate gfx_core;
/// extern crate gfx_window_glutin;
/// extern crate glutin;
///
///... | Rust | 0 |
P_Vpcomq_xmm_xmm_xmmm128_imm8
0x0008_8D8B,// XOP_Vpcomub_xmm_xmm_xmmm128_imm8
0x0008_8D8B,// XOP_Vpcomuw_xmm_xmm_xmmm128_imm8
0x0008_8D8B,// XOP_Vpcomud_xmm_xmm_xmmm128_imm8
0x0008_8D8B,// XOP_Vpcomuq_xmm_xmm_xmmm128_imm8
0x0000_0027,// XOP_Blcfill_r32_rm32
0x0000_004A,// XOP_Blcfill_r64_rm64
0x0000_0027,// XOP_... | Rust | 0 |
from tkinter import *
from tkinter import messagebox
from string import ascii_uppercase
import random
window = Tk()
window.title('H A N G M A N - Fruit Edition')
photos = [PhotoImage(file="images/hang5.png"),
PhotoImage(file="images/hang6.png"), PhotoImage(file="images/hang7.png"), PhotoImage(file="images/hang8.png"... | Python | 1 |
.map_err(|_| NodeError::ParsePk)?
.try_into()
.map_err(|_| NodeError::ParsePk)?
},
secret_key: {
hex::decode(secret_key)
.map_err(|_| NodeError::ParseSk)?
.try_into()
.ma... | Rust | 0 |
.lib.remove_focus(w);
self.lib.sync(false);
}
pub fn kill_window(&self, w: Window, clients: Vec<Window>) {
if w == self.lib.get_root() {
return;
}
if self.lib.kill_client(w) {
self.lib.update_net_client_list(clients);
}
info!("Top level w... | Rust | 0 |
#[cfg(any(feature = "mdns", feature = "relay"))]
let event = EitherOutput::First(event);
NetworkBehaviourAction::NotifyHandler {
peer_id: peer,
handler: NotifyHandler::One(connection),
event,
... | Rust | 0 |
!("\t{} {}, {}, {}, {}", inst, src1, src2, flags, cond);
let (reg1, id1, loc1) = self.prepare_reg(src1, inst.len() + 1);
let (reg2, id2, loc2) = self.prepare_reg(src2, inst.len() + 1 + reg1.len() + 1);
let asm = format!("{} {},{},#{},{}", inst, reg1, reg2, flags, cond);
self.add_asm_i... | Rust | 0 |
},
Command::Up(m) => AimPosition {
aim: aim - m,
..acc
},
Command::Down(m) => AimPosition {
aim: aim + m,
..acc
},
},
);
pos * depth
}
#![allow(dead_code)]
use std::fs::File;
use ... | Rust | 0 |
# ダメージ数表示を追加(敵の上部に素早くフェードイン・アウト)
try:
dval = float(dmg)
if dval <= 10.0:
color = WHITE
else:
t =... | Python | 1 |
"""
Eigenvalue solver using iterative methods.
Find k eigenvectors and eigenvalues of a matrix A using the
Arnoldi/Lanczos iterative methods from ARPACK [1]_,[2]_.
These methods are most useful for large sparse matrices.
- eigs(A,k)
- eigsh(A,k)
References
----------
.. [1] ARPACK Software, http://www.caam.rice... | Python | 1 |
Kind::Expr(inner) | StmtKind::Semi(inner),
..
},
],
expr: None,
rules: BlockCheckMode::DefaultBlock,
..
},
_,
) = expr.kind
{
expr = inner;
}
expr
}
/// Checks if the given expression... | Rust | 0 |
# master_gudang/consumers.py
import pika
from master_gudang.models import MasterGudang
def callback(ch, method, properties, body):
kode_barang_transaksi, quantity = map(int, body.decode().split(','))
try:
product = MasterGudang.objects.get(kode_barang=kode_barang_transaksi)
product.qty -= quant... | Python | 1 |
query += condQuery.replace("[DB]", conf.db)
field = condition.replace("[DB]", conf.db)
elif Backend.isDbms(DBMS.FIREBIRD):
query = rootQuery.blind.query % unsafeSQLIdentificatorNaming(tbl)
query += condQue... | Python | 1 |
process::exit(1);
};
let config = Config::new(env::args().skip(1)).unwrap_or_else(|err| bad(err, "Config Error:"));
if let Err(e) = run(config) {
bad(e, "Aplication Error");
}
}
mod integration_test;
#[cfg(test)]
mod get_root_tests {
use crate::integration_test::{api_url, random_u... | Rust | 0 |
ult': result
})
def analyze_mapping_performance(self) -> Dict:
"""Analyze mapping performance metrics"""
try:
total_mappings = len(self.mapping_history)
if total_mappings == 0:
return {}
confidence_scores = [
... | Python | 1 |
problem are conditional branches. There are basically two ways to handle them: Either,
only do the profiling if the branch is taken, which requires two jumps (one for the profiling
and one to get to the target pc). Or, always profile it as if the jump to the target pc was
taken, but then behind the conditi... | Rust | 0 |
,*c2)).unwrap().get(allele).unwrap().0.exp(),
// data.cluster_pair_allele_log_frequencies.get(&(*c1,*c2)).unwrap().get(allele).unwrap().0.exp(),
// match data.cells_to_alleles.get(cell).unwrap().get(&allele) { Some(_) => "allele present", None => "allele absent"}
// );
... | Rust | 0 |
dec, 'replace')))
if cdetype is not None:
update_exth_record((501, cdetype))
# Include remaining original EXTH fields
for id_ in sorted(self.original_exth_records):
recs.append((id_, self.original_exth_records[id_]))
recs = sorted(recs, key=lambda x:(x[0],x[0]))
... | Python | 1 |
ps_api_key}
if self.scrapeops_num_results is not None:
payload['num_results'] = self.scrapeops_num_results
response = requests.get(self.scrapeops_endpoint, params=urlencode(payload))
json_response = response.json()
self.headers_list = json_response.get('result', [])
def ... | Python | 1 |
or(exam.and(exam_clustering))
.or(save_history)
.or(list_history)
.or(static_history)
.or(static_files)
.or(favicon);
log::info!("www running");
let (_, run) = warp::serve(app).bind_with_graceful_shutdown(([0, 0, 0, 0], 3733), async move {
shutdown.await.ok();
... | Rust | 0 |
#!/usr/bin/python3 -i
#
# Copyright (c) 2022-2023 LunarG, Inc.
#
# 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, m... | Python | 1 |
= "TYPE_VARIABLE_CIRCLE"
assert thickness.thickness_circle_line == 0.1
def test_thickness_shape_orthotropy():
Model.clientModel.service.reset()
Model.clientModel.service.begin_modification()
Material(1, 'S275')
Thickness.ShapeOrthotropy(1, 'EFFECTIVE_THICKNESS', 1, ThicknessOrthotropyType.EFFECT... | Python | 1 |
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from domain.models.user import User
from domain.services.comment_service import CommentService
from infrastructure.database import get_db
from presentation.dto.comment_dto import CommentCreateDTO, CommentRes... | Python | 1 |
# -*- coding: utf-8 -*-
from openerp import models, api, fields
class MassMailing(models.Model):
_inherit = "mail.mass_mailing"
keep_archives = fields.Boolean('Keep Archives')
class MailComposeMessage(models.Model):
_inherit = "mail.compose.message"
@api.model
def get_mail_values(self, wizard,... | Python | 1 |
e::eyre::Result;
use env_logger::try_init;
use log::{debug, trace};
use crate::utils::{Range, LINE_ENDING};
pub mod utils;
fn app<'a, 'b>() -> App<'a, 'b> {
App::new("delete-line")
.version(crate_version!())
.arg(
Arg::with_name("file")
.takes_value(true)
... | Rust | 0 |
"""
This file contains various utility functions called by data_prep scripts.
"""
import requests
import os
import pandas as pd
import numpy as np
# Downloads given files from the url to the given downloads folder.
def download(url, download_to, files):
if(not os.path.isdir(download_to)):
os.mkdir(download_to)
r =... | Python | 1 |
SignedTransaction>>;
// To get the latest `Block` of finality, set `height` to `None`
fn get_block_by_height(&self, height: Option<u64>) -> ProtocolResult<Option<Block>>;
fn get_receipt_by_hash(&self, tx_hash: &Hash) -> ProtocolResult<Option<Receipt>>;
}
// Admission control will be called before enterin... | Rust | 0 |
import sys
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ._colorbar import ColorBar
from ._hoverlabel import Hoverlabel
from ._legendgrouptitle import Legendgrouptitle
from ._lighting import Lighting
from ._lightposition import Lightposition
from ._stream import Stream
from . impo... | Python | 1 |
b.is_ascii_digit() {
cx.i += 1;
for _ in 0..2 {
if !bs.get(cx.i)?.is_ascii_digit() {
err(cx, start, ErrorKind::InvalidStringLit);
}
cx.i += 1;
}
} else {
err(cx, start, ErrorKind::Invali... | Rust | 0 |
据总数'}
## 可用数据库架构
{schema_summary}
## 生成要求(仅返回JSON对象,不要其他文本)
- **保持简单**: 只生成满足用户需求的最简单SQL查询
- **单表优先**: 优先使用单张表,避免不必要的JOIN或复杂聚合
- **精确匹配需求**: 严格按照用户描述生成SQL,避免添加用户未明确要求的额外统计维度
- 必须使用上述真实存在的表名与列名
- **时间过滤统一规范**: 查询必须使用日期范围 dt >= {{start_date}} AND dt <= {{end_date}} 进行过滤
- **环比查询**: 对于环比查询,使用 {{prev_start_date}} 和 {{pre... | Python | 1 |
.clone(), Some(options.clone()));
"#
)
.into(),
});
ui::Window::new()
.child(ui::CodeSelect::new(code_for_language))
.into_node()
}
}
use std::{error::Error, f32::consts::PI};
use bevy::{prelude::*, tasks::AsyncComputeTaskPool};
use blackout::{
bevy_input_actionmap::InputMap,
bevy_openal::... | Rust | 0 |
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct GESClipAsset {
pub parent: GESAsset,
pub priv_: *mut GESClipAssetPrivate,
pub _ges_reserved: [gpointer; 4],
}
impl ::std::fmt::Debug for GESClipAsset {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
f.debug_struct(&format!(... | Rust | 0 |
import os
import signal
from functools import wraps
from visidata import BaseSheet, VisiData, vd
vd.option("debugger", "", "Activate the specified debugger")
SUPPORTED_DEBUGGERS = [
"remote-pdb", # dependency: remote-pdb, nice to have: pdbpp
"pudb", # dependency: pudb, nice to have: bpython
"web-pdb", ... | Python | 1 |
}
}
fn append_data_value(&mut self, value: DataValue, _format: &FormatSettings) -> Result<()> {
self.builder.append_data_value(value)
}
fn pop_data_value(&mut self) -> Result<DataValue> {
self.builder.pop_data_value()
}
fn finish_to_column(&mut self) -> ColumnRef {
sel... | Rust | 0 |
i]=(np.random.normal(mu, sigma, len(runTime[trl][i])))
maxForce[trl][i] = round(max(runForce[trl][i]).item(), 2)
self.fShow()
self.fShowAll()
nameSorted,forceSorted,colorSorted= self.fSort()
self.fRankShow(nameSorted,forceSorted,colorSorted... | Python | 1 |
ples
///
/// ```rust
/// use rocket::http::uri::Uri;
///
/// let uri = Uri::new("/Hello%2C%20world%21");
/// let decoded_path = Uri::percent_decode_lossy(uri.path().as_bytes());
/// assert_eq!(decoded_path, "/Hello, world!");
/// ```
pub fn percent_decode_lossy(string: &[u8]) -> Cow<... | Rust | 0 |
add_argument('--num_layers', type=int, default=5, help='Number of layers')
parser.add_argument('--hidden_size', type=int, default=28*28, help='Hidden size')
parser.add_argument('--lr', type=float, default=0.001, help='Learning rate')
args = parser.parse_args()
config = {
"num_epochs": args.... | Python | 1 |
epr(transparent)]
pub struct DevicePrivateDataCreateInfoEXTBuilder<'a>(DevicePrivateDataCreateInfoEXT, std::marker::PhantomData<&'a ()>);
impl<'a> DevicePrivateDataCreateInfoEXTBuilder<'a> {
#[inline]
pub fn new() -> DevicePrivateDataCreateInfoEXTBuilder<'a> {
DevicePrivateDataCreateInfoEXTBuilder(Defau... | Rust | 0 |
-")
sumando1 = int(input("Escriba el primer sumando . "))
sumando2 = int(input("Escriba el segundo sumando : "))
resultado = sumando1 + sumando2
print('El resultado de la sima es : ', str(resultado))
if resultado%2 == 0:
if resultado >= 1000:
print("El resultado de la suma es par y mayor o igual que 1000... | Python | 1 |
g are Hangul-splittable and throws a ValueError otherwise.
(default: True)
pad (str): Pad empty jamo positions (initial, medial, or final) with
`pad` character. This is useful for cases where fixed-length
strings are needed. (default: None)
Returns:
Hangul-split s... | Python | 1 |
from marshmallow import EXCLUDE, Schema, fields
from lib import ObjectIdField
class AccountsFilteredRequestSchema(Schema):
class Meta:
unknown = EXCLUDE
ordered = True
analytic_id = ObjectIdField(required=True, allow_none=False)
account_names = fields.List(fields.String, required=True, al... | Python | 1 |
|dataset| {
let buf = Vec::with_capacity(size as usize);
dataset.range(FSKey::extattr_range(ino))
.fold(buf, move |mut buf, (k, v)| {
match v {
FSValue::ExtAttr(xattr) => f(&mut buf, &xattr),
FSValue::Ex... | Rust | 0 |
left);
let right = File::open(right).expect("Right file can't be opened");
let right = BufReader::new(right);
let mut s1 = BTreeSet::new();
let mut s2 = BTreeSet::new();
for line in left.lines() {
s1.add_record_from_line(&line.unwrap())
}
for line in right.lines() {
s2.add... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2013 Kitware 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 cop... | Python | 1 |
(nonce+1), &encryption) {
Ok(d) => d,
Err(_) => return Err(Error::CryptoError)
};
Ok(data)
}
/// Send the output payload to the event manager, which will forward it to the handler connected to the `index` id
/// Blocking: we will wait for a response
fn send_t... | Rust | 0 |
else {
false
}
}
fn get_block_light(&self, x: i32, y: i32, z: i32) -> u8 {
self.block_light.get(((y << 8) | (z << 4) | x) as usize)
}
fn set_block_light(&mut self, x: i32, y: i32, z: i32, l: u8) {
self.block_light.set(((y << 8) | (z << 4) | x) as usize, l);
}
... | Rust | 0 |
import heapq
def a_star():
# Define the list of coins and their corresponding tax values
coins = [8, 13, 16, 4, 35, 2, 19, 2, 21, 26, 28, 12, 58, 28, 12, 35, 33, 4, 19, 27, 61, 30, 17, 20, 27, 25, 30, 31, 9, 15, 4, 13, 11, 29]
tax_values = {13: 1, 4: 1, 61: 2, 30: 19, 12: 4, 20: 16, 29: 10, 2: 2, 35: 17,... | Python | 1 |
l="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
trait TraitAddLifetimeBoundToAssociatedType<'a> {
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
type Associated: 'a;
fn method();
}
// Add default to associated type
#[cfg(cfail1)]
trait TraitAddD... | Rust | 0 |
# Notice that these two checksums are the same
// $ export ZERO_AR_DATE=1
// $ ar crus libfoo1.a foo.o && sleep 2 && touch foo.o && ar crus libfoo2.a foo.o
// $ md5sum libfoo*.a
//
// In any case if this doesn't end up getting read, it shouldn't... | Rust | 0 |
");
this.check_no_isolation("fstat")?;
let fd = this.read_scalar(fd_op)?.to_i32()?;
let metadata = match FileMetadata::from_fd(this, fd)? {
Some(metadata) => metadata,
None => return Ok(-1),
};
this.macos_stat_write_buf(metadata, buf_op)
}
fn li... | Rust | 0 |
_to_check =Vec::new();
for face in &self.faces{
//Verify incident_edge exist
if let Some(face_edge) = &face.borrow().outer_component {
polygons_to_check.push((face_edge.clone(),face));
}
for inner_edge in &face.borrow().inner_component{
polygons_to_check.push((inner_edge.clone(),face));
}
... | Rust | 0 |
all photos
min_date = min(ps[0].creation_date,ps[1].creation_date).date()
max_date = max(ps[0].creation_date,ps[1].creation_date).date()
for p in scan_ph:
p_date = p.creation_date.date()
if (len(ps) > 2) or (len(ps) == 2 and p_date >= min_date and p_date <= max_date):
# Photo belongs to the route period
... | Python | 1 |
Uint> = data.iter().map(|v| BigUint::from_slice(*v)).collect();
for (i, ni) in data.iter().enumerate() {
for (j0, nj) in data[i..].iter().enumerate() {
let j = j0 + i;
if i == j {
assert_eq!(ni.cmp(nj), Equal);
assert_eq!(nj.cmp(ni), Equal);
... | Rust | 0 |
(ErrorKind::BadBreakpadSym("unexpected module header").into());
}
self.state = IterState::Reading;
parse_module(record)
}
b"FILE" => {
self.state = IterState::Reading;
parse_file(record)
}
b"... | Rust | 0 |
rint("✅ dlib installed successfully!")
else:
print("❌ Precompiled dlib installation failed")
print("\nYou have two options:")
print("1. Install Visual Studio Build Tools and compile from source")
print("2. Try alternative installation methods")
choice = input("Choose... | Python | 1 |
//!
//! # Example
//! ```rust
//! use futures::{executor, future};
//! use futures_rate::{GateKeeper, Permit};
//! use std::future::Future;
//! use std::thread;
//! use std::time::Duration;
//!
//! fn main() {
//! let gatekeeper = GateKeeper::new(1);
//! let fut_values = async {
//! let fut_1 = build_f... | Rust | 0 |
t Contiguous<_0, _1> /* = */ (
pub _0,
pub _1,
);
pub
const
fn c_strlen (bytes: &[u8])
-> usize
{
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'\0' {
break;
}
i += 1;
}
i
}
p... | Rust | 0 |
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# Copyright (c) 2014 Mozilla Corporation
from lib.alerttask import AlertTask
from mozdef_util.qu... | Python | 1 |
docs.rs").is_some());
assert!(add_scheme_for_tld("nomnomnom.xyz").is_some());
assert!(add_scheme_for_tld("endless.horse").is_some());
assert!(add_scheme_for_tld("google.co.uk").is_some());
assert!(add_scheme_for_tld("notreal.co.uk/#banana").is_some());
assert!(add_scheme_for_tld(... | Rust | 0 |
) -> None:
if self._parsed_fn_signature is None:
dependency = unwrap_partial(self.dependency)
plugin = next(
(p for p in plugins.di if isinstance(p, DIPlugin) and p.has_typed_init(dependency)),
None,
)
if plugin:
s... | Python | 1 |
{
apply_map(dst, post_map);
}
Inst::Mov_R_R {
is64: _,
ref mut src,
ref mut dst,
} => {
apply_map(src, pre_map);
apply_map(dst, post_map);
}
Inst::MovZX_M_R {
extMode: _,
ref mut addr,... | Rust | 0 |
);
print(&a);
});
//Need to join other threads as main thread holds arrayfire context
handle.join().unwrap();
// ANCHOR_END: move_array_to_thread
}
#[test]
fn thread_borrow_array() {
set_device(0);
info();
let a = constant(1i32, dim4!(3, ... | Rust | 0 |
://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed 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 gover... | Rust | 0 |
#
# This file is part of the Chemical Data Processing Toolkit
#
# Copyright (C) Thomas Seidel <thomas.seidel@univie.ac.at>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# versi... | Python | 1 |
())
}
fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>) -> (K, V) {
let (empty, retkey, retval) = starting_bucket.take();
let mut gap = match empty.gap_peek() {
Some(b) => b,
None => return (retkey, retval)
};
while gap.full().distance() != 0 {
gap = match gap.shift()... | Rust | 0 |
# core/utils.py
import random
DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
USER_AGENTS = []
def load_user_agents(path="user_agents.txt"):
"""Loads user agents from a file, with a fallback."""
global USER_AGENTS
t... | Python | 1 |
n weight * reduction(params['lambda'].value * inf + damping * inf ** 2 / 2), inf
return Constraint(init_fn, loss_fn)
def combine(*args):
"""Combines multiple constraint tuples into a single constraint tuple.
Args:
*args: A series of constraint (init_fn, loss_fn) tuples.
Returns:
A s... | Python | 1 |
位三只乌鸦
# analysis_A_share(HighSanZhiWuYa) # 分析整个A股的高位三只乌鸦
# ChuShuiFuRong("000005.SZ", print_result=True, plot_examples=True) # 分析某只股票的出水芙蓉
# analysis_A_share(ChuShuiFuRong) # 分析整个A股的出水芙蓉
# DuanTouZhaDao("000007.SZ", print_result=True, plot_examples=True) # 分析某只股票的断头铡刀
# analysis_A_share(DuanTouZ... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.