text string | label_name string | labels int64 |
|---|---|---|
def middle_letter(input_string):
"""
Returns the middle letter(s) of the input string.
"""
length = len(input_string)
middle_index = length // 2
if length % 2 == 0:
return input_string[middle_index - 1:middle_index + 1]
else:
return input_string[middle_index]
input_str1 = "... | Python | 1 |
core), test_metric.append(test_score)
print(f'Epoch {epoch:03d} | Validation score: {val_score:.4f} | Test score: {test_score:.4f}', end='')
if val_score > best_score:
best_score = val_score
final_test_score = test_score
print(' <<< BEST VALIDATION EPOCH')
# print('learned score:... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import Command
from odoo import models, _
class SaleOrder(models.Model):
_inherit = 'sale.order'
def _cart_find_product_line(
self, product_id=None, line_id=None,
event_booth_pending_... | Python | 1 |
/<uuid:pk>/update/",
EvaluationGroundTruthUpdate.as_view(),
name="ground-truth-update",
),
path(
"<slug:slug>/leaderboard/",
LeaderboardDetail.as_view(),
name="leaderboard",
),
path("<slug:slug>/methods/", MethodList.as_view(), name="method-list"),
path(
... | Python | 1 |
"""
robots.txtパーサーモジュール
Webサイトのrobots.txtファイルを解析し、アクセス可能かどうかを判断するクラスを提供します。
"""
from __future__ import annotations
import logging
import time
import urllib.robotparser
from urllib.parse import urlparse
# ロガーの設定
logger = logging.getLogger(__name__)
class RobotsChecker:
"""robots.txtチェッカークラス"""
def __init_... | Python | 1 |
ame = \"apple\"\n\n [[fruit.variety]]\n name = \"red delicious\"\n\n [fruit.physical]\n color = \"red\"\n shape = \"round\"\n\n # INVALID: This array of tables conflicts with the previous table\n [[fruit.physical]]\n color = \"green\"\n" ;
let p = crate::parser::parse(&src);
assert!(!p.errors.is... | Rust | 0 |
mit);
/// }));
/// }
///
/// for handle in join_handles {
/// handle.await;
/// }
/// }
/// ```
///
/// [`Rc`]: std::sync::Rc
/// [`AcquireError`]: crate::sync::AcquireError
/// [`OwnedSemaphorePermit`]: crate::sync::OwnedSemaphorePermit
pu... | Rust | 0 |
rate {
Decimal::one().try_div(conversion_rate).unwrap()
} else {
conversion_rate
}
}
}
// Creates a range of reasonable collateral exchange rates
prop_compose! {
fn collateral_exchange_rate_range()(percent in 1..=500u64) -> C... | Rust | 0 |
](https://docs.rs/passive) traits.
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use synstructure::{AddBounds, Structure};
macro_rules! derive_traits {
($($proc_name:ident: $trait_name:ident,)*) => {$(
fn $proc_name(s: Structure) -> TokenStream {
d... | Rust | 0 |
51, 95, 77, 97, 100, 110, 101, 115, 115, 71, 97, 109, 101, 95, 85, 76, 84, 73, 77, 65, 84, 69, 46, 115, 119, 102, 47, 97, 114, 101, 110, 97, 77, 97, 100, 110, 101, 115, 115, 71, 97, 109, 101, 50, 46, 115, 111, 108].as_slice(), ErrorKind::Eof))]
}
use std::iter::FromIterator;
///Container for all the compiler flags pa... | Rust | 0 |
[doc = "Checks if the value of the field is `CONST_1110`"]
#[inline(always)]
pub fn is_const_1110(&self) -> bool {
**self == HIBIO0SEL_A::CONST_1110
}
#[doc = "Checks if the value of the field is `CONST_1111`"]
#[inline(always)]
pub fn is_const_1111(&self) -> bool {
**self == HIB... | Rust | 0 |
~= right) ± `{:?}`
left: `{:?}`
right: `{:?}`"#,
0.001, x, ans
)
}
}
#[test]
fn dense_solver_err() {
// should fail because b is not a single row
let a = mat![0., -1., 5.; 0., 1., -3.; 0., 4., 1.];
let b = mat![10., 1.; -2., 0.; 1., 18.];... | Rust | 0 |
"""JumpAround"""
def main() :
"""JumpAround"""
x = int(input())
x2 = x + 5
x3 = x - 17
x4 = x * 32
x5 = 5*(x**2) + (10)*(5*x) + 3
print(x)
print(x2)
print(x3)
print(x4)
print(x5)
main()
| Python | 1 |
#!/usr/bin/env python3
"""Print info f nginx logs """
from pymongo import MongoClient
if __name__ == "__main__":
""" check for all elements in a collection """
client = MongoClient('mongodb://127.0.0.1:27017')
collection = client.logs.nginx
print(f"{collection.estimated_document_count()} logs")
p... | Python | 1 |
use fuchsia_component::client as fclient;
// use fidl_fuchsia_component as fcomponent;
// use fidl_fuchsia_component_decl as fdecl;
// use fidl_fuchsia_io as fio;
// use fidl::endpoints;
//
// let realm_proxy = fclient::realm()?;
// let (exposed_directory, server_end) = endpoints::create_pr... | Rust | 0 |
pytrec_eval to use this function, eg. `pip install pytrec_eval`")
ndcg = {}
_map = {}
recall = {}
precision = {}
for k in k_values:
ndcg[f"NDCG@{k}"] = 0.0
_map[f"MAP@{k}"] = 0.0
recall[f"Recall@{k}"] = 0.0
precision[f"P@{k}"] = 0.0
map_string = "map_cut." + ",... | Python | 1 |
> + 'static>(
c: &mut Criterion,
desc: String,
inp: &Vec<SizeVec<T>>,
) {
eprintln!("Generating for {} (1/3)", desc);
struct Wrap<S, T>(SizeVec<S>, Box<T>);
impl<S, T> Debug for Wrap<S, T> {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
... | Rust | 0 |
class Solution:
def countNumbers(self, n: int) -> int:
# Generate primes up to sqrt(n)
limit = int(math.isqrt(n)) + 1
is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False
primes = []
for i in range(2, limit + 1):
if is_prime[i]:
... | Python | 1 |
import random
import string
# TR
# Rüzgar Batu Kurt tarafından yazılmıştır.
# Bu kod, bir mesajı şifrelemek ve çözmek için bir anahtar kullanır.
# Kullanıcıdan alınan mesaj, belirli bir karakter kümesi kullanılarak şifrelenir ve daha sonra çözülür.
# Anahtar, karakter kümesinin karıştırılmasıyla oluşturulur.
# Kullanıc... | Python | 1 |
#[inline]
fn zero() -> Self {
AtomicUsize::new(0)
}
#[inline]
fn into_inner(self) -> Self::Inner {
self.into_inner()
}
}
impl Idx for u32 {
type Atomic = AtomicU32;
#[inline]
fn new(idx: usize) -> Self {
assert!(idx <= u32::MAX as usize);
idx as u32
... | Rust | 0 |
# 1️⃣ insert() - Insert an item at a specific position
materials = ["Concrete", "Steel", "Glass"]
materials.insert(1, "Wood") # Insert "Wood" at index 1
print("After insert:", materials) # ['Concrete', 'Wood', 'Steel', 'Glass']
# 2️⃣ pop() - Remove item at a specific index
removed_item = materials.pop(2) # Remove i... | Python | 1 |
velope>(8);
let (task, context) =
make_dispatcher(8, 10, lanes(vec!["lane"]), ReceiverStream::new(envelope_rx));
let addr = RoutingAddr::remote(1);
let link = Envelope::link().node_uri("/node").lane_uri("other").done();
let assertion_task = async move {
assert!(envelope_tx.send(Tagge... | Rust | 0 |
timelapse")
timelapse_remaining = pycam.timelapse_rates[pycam.timelapse_rate]
timelapse_timestamp = time.time() + timelapse_remaining + 1
# dont let the camera take over auto-settings
saved_settings = pycam.get_camera_autosettings()
# prin... | Python | 1 |
skip,
)
} else {
(mode_decision.tx_size, mode_decision.tx_type)
};
cdef_coded = encode_block_pre_cdef(
&fi.sequence,
ts,
cw,
if cdef_coded { w_post_cdef } else { w_pre_cdef },
bsize,
tile_bo,
skip,
);
encode_block_post_cdef(
fi,
ts,
cw,
if cdef_coded { w_p... | Rust | 0 |
# Generated by Django 3.0.2 on 2021-11-02 05:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0008_user_profile_power_like_count'),
]
operations = [
migrations.AlterField(
model_name='user_profile',
nam... | Python | 1 |
"Unsupported synchronous exception @ {:#x}: ESR = {:#x} (EC {:#08b}, ISS {:#x})",
tf.elr,
esr.get(),
esr.read(ESR_EL1::EC),
esr.read(ESR_EL1::ISS),
);
}
}
}
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this ... | Rust | 0 |
x;
if cx.unreachable.get() {
let ty = val_ty(pointer_val);
let eltty = if ty.kind() == llvm::Array {
ty.element_type()
} else {
ccx.int_type
};
return llvm::LLVMGetUndef(eltty.to_ref());
}
B(cx).load(poin... | Rust | 0 |
self, year: DateYear) {
unsafe {
ffi::g_date_set_year(self.to_glib_none_mut().0, year);
}
}
pub fn subtract_days(&mut self, n_days: u32) {
unsafe {
ffi::g_date_subtract_days(self.to_glib_none_mut().0, n_days);
}
}
pub fn subtract_months(&mut self... | Rust | 0 |
so we transform the token into a
// `FalseEnd` one
Some(MultiStr(MultiStringToken::CandidateEnd(s))) => {
token = Some(MultiStr(MultiStringToken::Literal(s)))
}
// Early report errors for now. This could change in the future
Some(Normal(Normal... | Rust | 0 |
engine_file.with_suffix('.py.original')
try:
# 备份原文件
if engine_file.exists() and not backup_file.exists():
import shutil
shutil.copy2(engine_file, backup_file)
print(f"✅ 备份原引擎文件: {backup_file}")
# 读取现有内容
with open(engine_file, 'r', e... | Python | 1 |
fn change(&mut self, _: Self::Properties) -> yew::prelude::ShouldRender
{
false
}
fn view(&self) -> yew::prelude::Html
{
yew::prelude::html! {
<svg
class=self.props.class.unwrap_or("")
width=self.props.size.unwrap_or(24).to_string()
... | Rust | 0 |
데이트
for j in range(num_uavs):
if j != i:
global_action_mask[j, chosen_action] = True
else:
logits_i = action_logits[i] / temperature - dist_matrix[i] / temperature
logits_i = logits_i - logits_i.max() # 로짓 안정화
probs_i = F.softm... | Python | 1 |
schedule::{DynamicScheduler, Scheduler, StaticScheduler},
Circuit, Root, Stream,
},
monitor::TraceMonitor,
operator::{DelayedFeedback, Generator},
trace::{
ord::{OrdIndexedZSet, OrdZSet},
BatchReader,
},
zset,
};
#[test]
fn... | Rust | 0 |
he model to training mode
total_loss = 0
total_dice = 0
total_dice_binary = 0
for images, masks in train_loader:
# Reset optimizer gradient to zero
optimizer.zero_grad()
images = images.to(device) # Move images to the configured device
masks = masks.to(device)
... | Python | 1 |
xer = Lexer::<DefaultContext>::new_from_file(&file, source, if_cache, opt);
let context = Context::default();
let mut parser = UnitParser { lexer, context };
match parser.parse() {
Ok(unit) => {
unit.dump_me();
}
Err(e) => {
eprintln!("{:?}", e);
}
... | Rust | 0 |
fn last_os_error() -> ~str;
fn rust_set_exit_status(code: libc::intptr_t);
}
fn env() -> ~[(~str,~str)] {
let mut pairs = ~[];
for vec::each(rustrt::rust_env_pairs()) |p| {
let vs = str::splitn_char(p, '=', 1u);
assert vec::len(vs) == 2u;
vec::push(pairs, (vs[0], vs[1]));
}
... | Rust | 0 |
import re
import pytest
from marker.converters.pdf import PdfConverter
from marker.renderers.markdown import MarkdownOutput
from marker.schema import BlockTypes
from marker.schema.document import Document
from marker.util import classes_to_strings
@pytest.mark.filename("arxiv_test.pdf")
@pytest.mark.output_format("... | Python | 1 |
::OutputError, parameter::Parameter, parameter_kind::ParameterKind,
parser::Parser, platform::Platform, position::Position, positional::Positional, recipe::Recipe,
recipe_context::RecipeContext, recipe_resolver::RecipeResolver, runtime_error::RuntimeError,
scope::Scope, search::Search, search_config::SearchConfig... | Rust | 0 |
import pandas as pd
import numpy as np
from ogb.nodeproppred import DglNodePropPredDataset
from ogb.utils.url import download_url
def read_data(filename):
df = pd.read_csv(filename)
return df
def chaoshen():
# load dgl dataset
dataset = DglNodePropPredDataset('ogbn-arxiv', root='data/ogb/')
g, l... | Python | 1 |
"""API asynchronous job running mechanisms can use to get a fresh OIDC token."""
import logging
from fastapi import Query
from fastapi.responses import PlainTextResponse
from galaxy import (
exceptions,
util,
)
from galaxy.authnz.util import provider_name_to_backend
from galaxy.managers.context import Provid... | Python | 1 |
endingCatchUp::None;
},
state => debug!(target: "afg",
"Noted processed catch up message when state was: {:?}",
state,
),
}
}
fn handle_catch_up_request(
&mut self,
who: &PeerId,
request: CatchUpRequestMessage,
set_state: &environment::SharedVoterSetState<Block>,
) -> (Option<GossipMessag... | Rust | 0 |
+nconsts: c_int) -> FcBool;
fn FcNameUnregisterConstants(++consts: *FcConstant, ++nconsts: c_int) -> FcBool;
fn FcNameGetConstant(++string: *FcChar8) -> *FcConstant;
fn FcNameConstant(++string: *FcChar8, ++result: *c_int) -> FcBool;
fn FcNameParse(++name: *FcChar8) -> *FcPattern;
fn FcNameUnparse(++pat: *FcPattern... | Rust | 0 |
("RESH_CONFIG").unwrap_or_else(|_| "/etc/resh.toml".to_string());
let config: Config = read_config(&config_file).unwrap_or_else(|e| {
die!("Failed to read {}: {}", config_file, e);
});
let full_command = match config.commands.get(&command_alias) {
Some(cmd) => cmd,
None => die!("Un... | Rust | 0 |
work.touch()
work.work()
work.endtime = time.time()
work.server.doneWork(work)
except InvalidInProgWorkId, e: # the work was canceled
pass # Nothing to do, the server already knows
except Exception, e:
# Tell the server that the work unit failed
work.exci... | Python | 1 |
plement _pad_or_backfill
# Simulate a 3rd-party EA that has not yet updated to include a "copy"
# keyword in its fillna method.
# error: Signature of "fillna" incompatible with supertype "ExtensionArray"
def fillna( # type: ignore[override]
self,
value=None,
method=None,
... | Python | 1 |
}
Example {
centered: true,
AvatarList {
Avatar {
shape: Shape::RoundedCircle,
size: Size::Sm,
image_url: "/img/avatars/000m.jpg",
}
Avata... | Rust | 0 |
from tkinter import *
import math
import numpy as np
import matplotlib.pyplot as plt
# Função para calcular a expressão
def calcular():
try:
resultado = eval(entrada.get())
entrada.delete(0, END)
entrada.insert(END, str(resultado))
except Exception as e:
entrada.delete(0, END)
... | Python | 1 |
#def BFSReadTxt():
# filename = "input_txts/BFS_adjMatrix.txt"
# adjMatrix = []
# with open(filename, 'r') as file:
# lines = file.readlines()
# n = int(lines[0])
# for i in range(1, n+1):
# adjMatrix.append(lines[i].split())
# weights = lines[n+1].split()
# for i in r... | Python | 1 |
deposit is returned.
///
/// The dispatch origin for this call must be _Signed_.
///
/// Parameters:
/// - `delegate`: The account that previously announced the call.
/// - `call_hash`: The hash of the call to be made.
///
/// # <weight>
/// Weight is a function of:
/// - A: the number of announcem... | Rust | 0 |
Init.into(),
ordering: ChannelOrder::Unordered.into(),
counterparty: Some(ChannelCounterparty {
port_id: chain.config.port_id.to_string(),
channel_id: "".to_string(),
}),
connection_hops: vec![solo_machine_connection_id.to_string()],
... | Rust | 0 |
// // Not emitting: Bridge method - type erasure
// /// [compareTo](https://developer.android.com/reference/java/time/OffsetTime.html#compareTo(java.lang.Object))
// ///
// /// Required features: "java-lang-Object"
// #[cfg(any(feature = "all", all(feature = "java-lang-Object")))... | Rust | 0 |
from django.conf import settings
from django.conf.urls import url, patterns
from . import views as mkv
from feeds import MemberActivityFeed
mksurlpatterns = patterns('mks.views',
url(r'^parties-members/$', mkv.PartiesMembersRedirctView.as_view(), name='parties-members-index'),
url(r'^parties-members/(?P<pk>\d+... | Python | 1 |
.parse::<i32>().ok()).filter(|&byr| byr >= 2020 && byr <= 2030).is_some()
&& pp.get("hgt").and_then(|raw| parse_height(raw)).filter(|(h, u)| if u == "cm" { *h >= 150 && *h <= 193 } else if u == "in" { *h >= 59 && *h <= 76 } else { false }).is_some()
&& pp.get("hcl").filter(|raw| is_hair_color(raw)).is_s... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from lib.poc.dummy import *
'''
http://blog.nsfocus.net/weblogic-ns-2019-0015/ vuln env: docker pull ismaleiva90/weblogic12
'''
poc_raw = '''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:wsa="http://www.w3.org/2005/08/addressing"xml... | Python | 1 |
f"Username: {username}\n"
f"Created at: {item['tweet'].created_at.isoformat()}\n"
f"Tweet: {item['tweet'].text}\n\n"
)
tweet_text = self.clean_text(tweet_text)
if info["group"] == "influenc... | Python | 1 |
output_sentence = ' '.join(output_words)
print('<', output_sentence)
if __name__ == "__main__":
# """
hidden_size = 256
encoder1 = EncoderRNN(input_lang.n_words, hidden_size).to(device)
attn_decoder1 = AttnDecoderRNN(hidden_size, output_lang.n_words, dropout_p=0.1).to(device)
trai... | Python | 1 |
"""Constants for the siren component."""
from enum import IntFlag
from functools import partial
from typing import Final
from homeassistant.helpers.deprecation import (
DeprecatedConstantEnum,
all_with_deprecated_constants,
check_if_deprecated_constant,
dir_with_deprecated_constants,
)
DOMAIN: Final ... | Python | 1 |
ive` to implement `init()`.
///
/// It returns `Error` in the following cases:
/// - Environment variable is not present
/// - Parsing failed
pub fn load_var<T: FromStr>(
var_name: &'static str,
hashmap: Option<&HashMap<String, String>>,
) -> Result<T, Error> {
match hashmap {
None => env::var(var_n... | Rust | 0 |
let wff = WorkflowFunction::new(signal_sender);
let mut wfm = ManagedWFFunc::new(t, wff, vec![]);
wfm.get_next_activation().await.unwrap();
let cmds = wfm.get_server_commands().commands;
assert_eq!(cmds.len(), 1);
assert_eq!(
cmds[0].command_type(),
Co... | Rust | 0 |
from .giveaways import Giveaways
async def setup(bot):
await bot.add_cog(Giveaways(bot))
| Python | 1 |
red(trial_wrapper, all_args)
for i, result in enumerate(results_iterator):
No, (win, hps) = result
A, B, S, C, HP = all_args[No][1]
csvwriter.writerow({"No": No, "A": A, "B": B, "S": S, "C": C, "HP": HP, "Win": win, **hps})
... | Python | 1 |
lone(),
Some(Box::new(future).boxed())))),
time); //为定时器设置定时异步任务
return Ok(());
}
Err(Error::new(ErrorKind::Other, format!("Spawn timing task failed, task_id: {:?}, reason: timer n... | Rust | 0 |
",
"W_cs_C_oz_U_ap",
"W_csz_C_o_U_ap",
"W_cz_C_aops",
"W_cz_U_aops",
"W_psz_C_co_U_a",
"W_psz_U_aco",
"W_sz_C_co_U_ap",
"W_z",
"W_z_C_acops",
"W_z_C_co_U_aps",
"W_z_U_acops",
];
#[cfg(feature = "instr_info")]
impl fmt::Debug for RflagsInfo {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Resul... | Rust | 0 |
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import js_to_json
class OnionStudiosIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?onionstudios\.com/(?:video(?:s/[^/]+-|/)|embed\?.*\bid=)(?P<id>\d+)(?!-)'
_EMBED_REGEX = [r'(?s)<(?:iframe|bulbs-video)[^>]+?src=(["\'])(?P<ur... | Python | 1 |
quare,
Ok(Some("sine")) => monotron_synth::Waveform::Sine,
Ok(Some("sawtooth")) => monotron_synth::Waveform::Sawtooth,
Ok(Some("noise")) => monotron_synth::Waveform::Noise,
e => {
println!("Unknown wave argument {:?}", e);
return;
}
};
println!(
... | Rust | 0 |
import re
import pytest
from scrapli_community.huawei.smartax.huawei_smartax import DEFAULT_PRIVILEGE_LEVELS
@pytest.mark.parametrize(
"priv_pattern",
[
("exec", "SCRAPLI-MA5800-X7>"),
("privilege_exec", "SCRAPLI_HUAWEI-SMARTAX_TEST_OLT1#"),
("configuration", "SCRAPLI_HUAWEI-SMARTAX_... | Python | 1 |
qrt(1 + 4.76190476190476 / S1_stoich)
+ 4.76190476190476 / S1_stoich
)
P49: float = math.log(math.sqrt(1 + 40000.0 / S1_stoich**2) + 200.0 / S1_stoich)
S1_conc: float = S1 / C
J0: float = 1
return {
"P1": P1,
"P2": P2,
"P3": P3,
"P4": P4,
"P5": P5,
... | Python | 1 |
原文本
st.write("🔍 **SQL提取调试**:未找到明确的SQL格式,尝试直接清理原文本")
cleaned = clean_sql_content(response_text)
# 如果清理后的文本包含SELECT,则返回
if 'SELECT' in cleaned.upper():
st.write(f"🔍 **SQL提取调试**:清理后的文本包含SELECT = {cleaned[:200]}...")
return cleaned
# 最后尝试从整个响应中提取SQL... | Python | 1 |
from django.db import connection
from django.db.models import Value
from django.db.models.functions import Length, LPad, RPad
from django.test import TestCase
from ..models import Author
class PadTests(TestCase):
def test_pad(self):
Author.objects.create(name="John", alias="j")
none_value = (
... | Python | 1 |
" @param need_expand perform realpath() if this variable is true and filename is not NULL"]
#[doc = " @return true if variables has been set"]
pub fn ucl_parser_set_filevars(
parser: *mut ucl_parser,
filename: *const ::std::os::raw::c_char,
need_expand: bool,
) -> bool;
}
#[doc = " S... | Rust | 0 |
import json
import os
# 모듈 불러오기
from fastapi import FastAPI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import BaseModel
# JSON 페이로드의 예상 구조를 정의하는 Pydantic 모델
class Query(BaseModel):
prompt: str
stroke: str
distan... | Python | 1 |
mod igrepper;
const PARAMETER_ERROR: &str = "Data can only be passed by STDIN if no file parameter is specified";
const DEFAULT_EDITOR_COMMAND: [&str; 3] = ["vim", "-R", "-"];
fn main() {
let matches = App::new("igrepper")
.version("1.3.1")
.about("The interactive grepper")
.arg(
... | Rust | 0 |
# This code is part of a Qiskit project.
#
# (C) Copyright IBM 2018, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications ... | Python | 1 |
import os
from PIL import Image, ImageChops
from .image_config import image_config
from AXUI.logger import LOGGER
def image_compare(image1, image2, diff_image_name="diff.bmp"):
'''compare two images, return difference percentage
#code from http://rosettacode.org/wiki/Percentage_difference_between_images#Pyt... | Python | 1 |
0x68ee463b, <KEY>, 0x42e5e368, 0x5def6f90, 0xf7659a20, 0x3441de33, 0x7fb94831,
0xcbeae9b2,
],
iv: [0x9c4a9254, 0xc485236c, 0xf838de7e],
pt: &hex!("73731054514f3fb0102c7a1df809f212"),
aad: &hex!("d55820e7acbb27d23c7df32938cf7d42"),
ct: &hex!("13b7823cac37f40eb811e3c966... | Rust | 0 |
260019,
7260219, 7260233, 7260327, 7260548, 7260806, 7260966, 7261029, 7261268, 7261291, 7261476,
7261553, 7261759, 7262349, 7262428, 7262518, 7262622, 7262761, 7262790, 7266440, 7268049,
7274677, 7279570, 7279571, 7279595, 7279597, 7279599, 7279600, 7279734, 7279735, 7279739,
7279741, 7279742, 7279746,... | Rust | 0 |
e += len;
if device_path.device_type == DeviceType::End {
break;
}
unsafe {
let next = byte_ptr.add(len) as *const DevicePath;
device_path = &*next;
}
}
total_size
}
unsafe fn copy_device_path_node(dst: &mut DevicePath, src: &DevicePath) {
... | Rust | 0 |
let emcc_path = get_emcc_path();
if emcc_path.is_ok() {
command = Command::new(emcc_path.unwrap());
command.current_dir(&language_dir);
} else {
return Err(emcc_path.unwrap_err());
}
} else if Command::new("docker").output().is_ok() {
comm... | Rust | 0 |
@property
def paginator(self) -> BasePagination | None:
"""Try to get view-specific paginator, if not set fall back to generic
paginator, if not set fall back to None.
"""
if not hasattr(self, "_paginator"):
if (
view_pagination_class := self.get_view_... | Python | 1 |
w_h),
(&window_x_grayscale, window_x_w, window_x_h),
1,
);
if ocr::ENABLE_DEBUG_IMAGE_OUTPUT {
bmp::save_gray_bmp(&w_g, w_w, w_h, "dbg/w_g.bmp");
bmp::save_gray_bmp(
&window_x_grayscale,
window_x_w,
... | Rust | 0 |
text.get().len() {
0 => None,
_ => Some(text_box.text.get()),
}
}
//dialog window for text tool
pub fn text_dialog(title: &str, text: &str, suggestion: &str) -> Option<(String,String)> {
let mut orb_window = Some(InnerWindow::new(100, 100, 480, 200, title).unwrap());
let mut new_window = Bo... | Rust | 0 |
properties: Vec<_> = o.iter().collect();
properties.sort_by_key(|(_, i)| i.index);
for (key, value) in o.iter() {
serializer.property(key, &value.item);
}
serializer.end_object();
}
Self::Array(a) => {
... | Rust | 0 |
index: FileIndex, file_count: u32 },
}
<filename>plmc/src/meta/manifest.rs
use anyhow::{Context, Result};
use clap::{App, Arg, ArgMatches};
use log::trace;
use polymc::meta::manifest::{Manifest, OS};
use std::fs::OpenOptions;
pub(crate) fn app() -> App<'static> {
App::new("manifest")
.about("Parse a minec... | Rust | 0 |
User @relation(fields: [userName], references: [firstName])
}
"#;
let errors = parse_error(dml);
errors.assert_is(DatamodelError::new_validation_error("The argument `references` must refer to a unique criteria in the related model `User`. But it is referencing the following fields that are not a... | Rust | 0 |
, Clone)]
#[serde(bound(
deserialize = "TIndex: Deserialize<'de>, TType: Deserialize<'de>, TId: Deserialize<'de>"
))]
pub struct BulkErrorsResponse<
TIndex = DefaultAllocatedField,
TType = DefaultAllocatedField,
TId = DefaultAllocatedField,
> {
took: u64,
errors: bool,
#[serde(deserialize_wi... | Rust | 0 |
rint_error(future);
Err(rc)
}
};
cass_future_free(future);
cass_statement_free(statement);
result
}
}
fn select_from_collections(session: &mut CassSession, key: &str) -> Result<(), CassError> {
unsafe {
let query = "SELECT items FROM examples... | Rust | 0 |
nodes/mynode/scale?");
assert_eq!(req.method(), "PATCH");
}
#[test]
fn replace_scale_path(){
let r = RawApi::v1Node();
let pp = PostParams::default();
let req = r.replace_scale("mynode", &pp, vec![]).unwrap();
assert_eq!(req.uri(), "/api/v1/nodes/mynode/scale?");
assert_eq!(req.method(), "PUT");... | Rust | 0 |
sys::general::membarrier_cmd::MEMBARRIER_CMD_PRIVATE_EXPEDITED as _,
/// `MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED`
RegisterPrivateExpedited =
linux_raw_sys::general::membarrier_cmd::MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED as _,
/// `MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE`
PrivateExpedite... | Rust | 0 |
ctx.add_diagnostic(case.span(), CODE, UseIsNaNMessage::CaseUnmatched);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn use_isnan_valid() {
assert_lint_ok! {
UseIsNaN,
"var x = NaN;",
"isNaN(NaN) === true;",
"isNaN(123) !== true;",
"Number.isNa... | Rust | 0 |
from lib.util_sqlalchemy import ResourceMixin
from lib.util_datetime import tzware_datetime
from snakeeyes.extensions import db
class Bet(ResourceMixin, db.Model):
__tablename__ = 'bets'
id = db.Column(db.Integer, primary_key=True)
# Relationships.
user_id = db.Column(db.Integer, db.ForeignKey('users... | Python | 1 |
64, TeraBit>::new(1.2));
println!("TeraByte: {}.", Measure::<f64, TeraByte>::new(1.2));
println!("TebiBit: {}.", Measure::<f64, TebiBit>::new(1.2));
println!("TebiByte: {}.", Measure::<f64, TebiByte>::new(1.2));
println!("BitPerSecond: {}.", Measure::<f64, BitPerSecond>::new(1.2));
println!(
... | Rust | 0 |
ariableSizeArray<DhcpServer>,
}
#[derive(Debug, Clone, Serialize, Deserialize, VppMessage)]
#[message_name_and_crc(dhcp6_duid_ll_set_0f6ca323)]
pub struct Dhcp6DuidLlSet {
pub client_index : u32,
pub context : u32,
pub duid_ll : FixedSizeArray<u8, typenum::U10>,
}
#[derive(Debug, Clone, Serialize, Deseriali... | Rust | 0 |
# -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='ro_access',
field=models.BooleanFie... | Python | 1 |
test_tbitem2")?)?,
tbdefinefromexcel: TestTbDefineFromExcel::new(&loader("test_tbdefinefromexcel")?)?,
tbdefinefromexcelone: TestTbDefineFromExcelOne::new(&loader("test_tbdefinefromexcelone")?)?,
tbtestindex: TestTbTestIndex::new(&loader("test_tbtestindex")?)?,
tbtestmap:... | Rust | 0 |
left: None,
right: Some(Rc::new(RefCell::new(TreeNode::new(3)))),
}
))),
}
)));
assert!(!Solution::is_symmetric(tree));
}
}<filename>src/lexer.rs
use std::{fmt, convert::TryFrom, str::FromStr};
use logos::Log... | Rust | 0 |
/api/winuser/ns-winuser-rawmouse)
///
/// The MSDN definition uses an anonymous union over the buttons flags and data
/// (u16 each) to combine them into a single value (u32), which gives the
/// combination an alignment of 4, and thus we get padding bytes in the middle
/// of the struct. Because accessing a union is a... | Rust | 0 |
import primeiro
def funcao2():
primeiro.funcao1()
if __name__ == '__main__':
funcao2()
print('segundo.py está sendo executado diretamente.')
else:
print(f'segundo.py foi importado. {__name__}')
| Python | 1 |
Ok(())
}
/// Inserts a value into the map.
pub fn insert(&self, value: V, flags: u64) -> Result<(), MapError> {
let fd = self.inner.deref().fd_or_err()?;
bpf_map_push_elem(fd, &value, flags).map_err(|(code, io_error)| {
MapError::SyscallError {
call: "bp... | Rust | 0 |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from time import sleep
def iniciar_driver():
chrome_options = Options()
arguments = ['--lang=pt-BR', '--incognito', '--start-maximized']
for argument in arguments:
chr... | Python | 1 |
struments(sequence)
if args.force_tempo:
sequence = note_sequence_utils.normalize_tempo(sequence, args.force_tempo)
# Get the updated downbeats
downbeats = [a.time for a in sequence.text_annotations
if (a.annotation_type, a.text) == (BEAT, D... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.