text string | label_name string | labels int64 |
|---|---|---|
= [
0x61, 0x27, 0xc2, 0x4c, 0x05, 0xf3, 0x8a, 0x0a, 0xaa, 0xf6, 0x5c, 0x0e, 0xf0, 0x2c,
];
/// A factor in the short weirstrass curve (BE 64-bits limbs representation)
pub const A_LIMBS: [u64; 2] = [0x00006127c24c05f3, 0x8a0aaaf65c0ef02c];
/// B factor in the short weirstrass curve (BE bytes re... | Rust | 0 |
amma_pdf(x, h=h, z=z)
plt.plot(x, pdf, label=r'$h$ = {}, $z$ = {}'.format(h, z))
plt.xlabel('x', fontsize=12)
plt.ylabel('f(x)', fontsize=12)
plt.legend(loc=1)
plt.show()
======== =============================
Support :math:`x \in (0, \infty)`
Mean :math:... | Python | 1 |
.features = 5;
conv1.stride = [1, 1, 1];
conv1.zero_pad = [0, 0, 0];
let y = w.clone().conv(conv1, x.clone());
let mut y_h = MemArray5d::<f32>::zeros([4, 5, 6, 5, 1]);
let y_len = 4 * 5 * 6 * 5 * 1;
let t = txn();
w.persist(t);
y.eval(t);
y.serialize(t, &mut y_h);
println!("DEBUG: y: {:?}", &y_h.as... | Rust | 0 |
#!/usr/bin/env python
from distutils.command.build import build as _build
import re
from setuptools import setup, find_packages
import subprocess
import platform
class build(_build):
def run(self):
if platform.system() == "Darwin":
try:
# Build our C library
sub... | Python | 1 |
CH,
}
};
let file_attr = FileAttr {
ino: ZFF_OBJECT_FS_PHYSICAL_ATTR_INO,
size,
blocks: size / DEFAULT_BLOCKSIZE as u64 + 1,
atime: acquisition_end,
mtime: acquisition_end,
ctime: acquisition_end,
cr... | Rust | 0 |
*LV Name\s*(.*)$\s*VG Name\s*(.*)$(?:\n.*){3}$\s*LV Status\s*(.*)\n.*$\n\s*LV Size\s*(\d*).*$(?:\n.*){5}\s*Block device\s*(\d*):(\d*)$",
)?;
for lvm in re.captures_iter(&out).filter(|lvm| lvm[3] == vg_name) {
lvms_vec.push(LogVolume {
name: lvm[2].to_string(),
path: lvm[1].to_str... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
# Генерування прикладових даних
# Вхідні дані
X = np.array([
[9, 2, 1],
[9, 3, 1],
[2, 3, 2],
[9, 8, 7],
[2, 1, 3],
[9, 7, 5],
[9, 9, 7],
[8, 2, 3]
])
# Здійсне... | Python | 1 |
"library": "metric",
"display": {
"field": "count",
"prefix": "",
"suffix": " offers",
},
},
"offers-day": {
... | Python | 1 |
from app import app, db
from models import User, Role
from werkzeug.security import generate_password_hash
with app.app_context():
# 检查是否存在admin角色
admin_role = Role.query.filter_by(name='admin').first()
if not admin_role:
admin_role = Role(name='admin', description='管理员角色')
db.session.add(a... | Python | 1 |
}
impl<'a> InputTake for Tokens<'a> {
#[inline]
fn take(&self, count: usize) -> Self {
Tokens {
tok: &self.tok[0..count],
start: 0,
end: count,
}
}
#[inline]
fn take_split(&self, count: usize) -> (Self, Self) {
let (prefix, suffix) = sel... | Rust | 0 |
x64用コンパイラのメインルーチン
/// 機械独立なパスを呼び出した後x64依存のパスを処理する.
pub fn compile_main(
module_arena: common::module::ModuleArena,
main_module_id: common::module::ModuleId,
verbose_ir: bool,
debug: bool,
entry_point: String,
) -> x64::ir::Module {
let (fn_arena, ast_root, type_env, stack_frame) =
commo... | Rust | 0 |
<_>>,
Vec<Vector3<_>>,
) = (
Vec::with_capacity(3),
Vec::with_capacity(3),
Vec::with_capacity(3),
);
for &i in face {
let v = model.vertices[i as usize];
let vp: Vector3<_> = v.position.into();
screen_coords.pu... | Rust | 0 |
);
let builder = FsTreeBuilder {
root: workspace.to_path_buf(),
get_data: GET_APPARENT_SIZE,
reporter: ErrorOnlyReporter::new(ErrorReport::SILENT),
};
let mut data_tree: DataTree<OsStringDisplay, _> = builder.into();
data_tree.par_cull_insignificant_data(0.01);
data_tree.par... | Rust | 0 |
match sink.send(msg) {
Err(_) => fallback = true,
_ => fallback = false,
};
}
// discard sink on send error
if fallback {
*sink_lock.borrow_mut() = None;
}
}
if fallb... | Rust | 0 |
Bus-off. The CAN controller is currently not involved/prohibited from bus activity because the Transmit Error Counter reached its limiting value of 255."]
BUS_OFF_THE_CAN_CON = 1,
}
impl From<BS_A> for bool {
#[inline(always)]
fn from(variant: BS_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Read... | Rust | 0 |
from typing import List
from ravyn import Ravyn, RavynSettings
from ravyn.middleware.security import SecurityMiddleware
from lilya.middleware import DefineMiddleware
routes = [...]
content_policy_dict = {
"default-src": "'self'",
"img-src": [
"*",
"data:",
],
"connect-src": "'self'",
... | Python | 1 |
_base_ = [
'../_base_/models/mask_rcnn_r50_fpn.py',
'../_base_/datasets/coco_instance.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
model = dict(
rpn_head=dict(
anchor_generator=dict(type='LegacyAnchorGenerator', center_offset=0.5),
bbox_coder=dict(type='Le... | Python | 1 |
e::error::Error as CompilerError;
use crate::generator::module::Module;
use crate::generator::zinc_vm::State as ZincVMState;
use crate::generator::IBytecodeWritable;
use crate::semantic::analyzer::entry::Analyzer as EntryAnalyzer;
use crate::semantic::scope::Scope;
use crate::source::error::Error;
use crate::source::So... | Rust | 0 |
#!/usr/bin/env python3
import re
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# import user defined libraries
from players import *
from matches import *
from tournament import *
from display import *
PG_initial = []
Players_Total = 0
PayOff = []
RPM = 0 ... | Python | 1 |
orce,
close_on_trigger: data.close_on_trigger,
order_link_id: data.order_link_id,
take_profit: data.take_profit,
stop_loss: data.stop_loss,
tp_trigger_by: data.tp_trigger_by,
sl_trigger_by: data.sl_trigger_by,
... | Rust | 0 |
import logging
def init_logger(args):
log_format = logging.Formatter("[%(asctime)s %(levelname)s] %(message)s")
logger = logging.getLogger()
logger.setLevel(args.log_level)
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_format)
logger.handlers = [console_handler]
... | Python | 1 |
import math
import ctypes
from .clib_lookup import CLIBLookup
class timespec(ctypes.Structure):
_fields_ = [("sec", ctypes.c_long), ("nsec", ctypes.c_long)]
__slots__ = [name for name,type in _fields_]
@classmethod
def from_seconds(cls, secs):
c = cls()
c.seconds = secs
return ... | Python | 1 |
ln!("elapsed after rgba: {:?}", start.elapsed());
writer.write_image_data(&img).unwrap();
}
<filename>src/lib.rs<gh_stars>1-10
/* Copyright (C) 2015-2016 <NAME> */
//! This is a URL parsing library.
//!
//! The goal of this project is to provide simple parsing URL library
//! like urllib.parse in Python3.x.
//!
//... | Rust | 0 |
ning
ssid_value = None; password_value = None
access_ip_str = ""; ip = None
while True:
conn, addr = s.accept()
print("Got connection from %s" % str(addr))
# Socket receive()
request=conn.recv(1024)
# Socket send()
... | Python | 1 |
repr(C)]
pub struct os_eventq__bindgen_ty_1 {
pub stqh_first: *mut os_event,
pub stqh_last: *mut *mut os_event,
}
impl Default for os_eventq__bindgen_ty_1 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl Default for os_eventq {
fn default() -> Self {
unsafe { ::core... | Rust | 0 |
import os
import time
import json
import requests
BASE = os.getenv("API_BASE_URL", "http://127.0.0.1:8000")
def main():
payload = {
"tip_tx_hash": "0xdeadbeefc0de01",
"chain": "coston2",
"amount": "0.000000000000000001", # very small FLR as requested
"currency": "FLR",
"se... | Python | 1 |
fn poll_accept(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
let pin = self.get_mut();
match ready!(Pin::new(&mut pin.incoming).poll_accept(cx)) {
Some(Ok(sock)) => Poll::Ready(Some(Ok(TlsStream::new(sock, pin.conf... | Rust | 0 |
#!/usr/bin/env python3
import netfilterqueue
import scapy.all as scapy
import signal
import sys
def def_handler(sig, frame):
print(f"\n Saliendo...\n")
sys.exit(1)
signal.signal(signal.SIGINT, def_handler)
def process_packet(packet):
scapy_packet = scapy.IP(packet.get_payload())
if scapy_packet.has... | Python | 1 |
from enum import Enum
from utca.implementation.apis.google_cloud.schema import (
GoogleCloudClientConfig,
)
class GoogleSheetsClientConfig(GoogleCloudClientConfig):
"""
Google Spreadsheets default configuration
Args:
scopes (List[str]): Access scopes. Defaults to
["https://www.go... | Python | 1 |
st"]
pub mod events_fieldlost;
#[doc = "Marks the start of the first symbol of a transmitted frame\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::gene... | Rust | 0 |
"regular"
os.environ["NO_THIN_LTO"] = "0"
with self.assertRaises(RuntimeError) as cm:
validate_archive_configuration()
self.assertIn("ARCHIVE_BUILD_MODE=regular but NO_THIN_LTO=0", str(cm.exception))
def test_get_fastled_library_path_missing_file(self):
"""Test error ... | Python | 1 |
file_sharing::FileSharing::new(other_file.id, file_sharing::FileSharingScope::Public);
let app = test::build_mock_app()
.users(vec![user.clone(), other])
.files(vec![other_file])
.objects(vec![other_object])
.await
.sharings(vec![sharing.clone()])
... | Rust | 0 |
2.input(&hash.result()[..]);
hash2.result().into_iter().collect()
}
/// Validate provided generic base58 hash.
/// Returns the hash version/type if correct and an error otherwise.
pub fn validate_base58_hash(addr: &str) -> Result<usize, ValidationError> {
if addr.len() == 0 {
return Err(ValidationError... | Rust | 0 |
.clone();
let cond = cond.clone();
thread::spawn(move || {
let mut bytes: [u8; THREAD_BUFFER_SIZE] = [0; THREAD_BUFFER_SIZE];
let mut output = io::stdout();
'main_loop : loop {
let n = {
// Lock the buffer, but wait on it if it's em... | Rust | 0 |
r
letter_surf = constants.FONT_MEDIUM.render(
letter.upper(), True, constants.FONT_COLOR
)
letter_rect = letter_surf.get_rect(
center=(x_pos + button_width // 2, y_pos + button_height // 2)
)
self.gam... | Python | 1 |
# Prog04: Create a program that ask user to input 2 numbers.
# Print the quotient of the two numbers without the decimal point.
# ------------------------------------------------------------------
# Phase 1: Planning
# - Objective: I will create a program to calculate the quotient without decimal point of two user-... | Python | 1 |
里发消息
print(res.text)
def get_hot_token():
url = f"https://gmgn.ai/defi/quotation/v1/rank/sol/swaps/6h?orderby=swaps&direction=desc"
headers = {
"authority": "gmgn.ai",
"accept": "application/json, text/plain, */*'",
"accept-language": "zh,zh-CN;q=0.9",
"cache-control": "no-... | Python | 1 |
from villas.controller.components.gateway import Gateway
class VILLASnodeGateway(Gateway):
def __init__(self, manager, args):
# Some default properties
props = {
'category': 'gateway',
'type': 'node',
'sub_type': args['type'],
'realm': args.get('rea... | Python | 1 |
nown constant with type {}", exception.0),
}
}
}
pub struct IllegalConstant(pub u8, pub Exception);
impl From<IllegalConstant> for Exception {
fn from(exception: IllegalConstant) -> Self {
Exception {
exception_type: ExceptionType::Static,
name: "IllegalConstant".to_str... | Rust | 0 |
T_WIDTH,
);
append_be_fixed_width(
&mut sig_bits,
&self
.from_before
.witness
.account_witness
.pub_key_hash
.unwrap(),
NEW_PUBKEY_HASH_WIDTH,
);
append_be_fixed_width(
... | Rust | 0 |
\x15\x0db\x00\xd1\x18\xa06>B:p\x90\xa9\xd9\xf3\
|\xb6q\x8e\xb7\xae\xbc\xcb\xfa`\x1bQ\xd1\x0c\xea}\
\x88\xa8`\xb0\x16\xf3\xfc\x99\x11Td!\xeeb\x19\xc2\
\x9b*\xd2[l\xd1\xc6\x14[\xe4\x9du\xf2\xce:\xbd\
n\x13_\xf2.\xc2\xbcy\xc7@F\x10f\xe5\xbe\x1f\
\x1d\xabb\x10\x9a\xbc\xb0\x14E\x90h\x09\xa9J\xb8|\
\xc7,\x87~\xe6{\xbb\xe0\x... | Python | 1 |
"""
File: extension3_triangular_checker.py
Name: Chang Yen Yu
--------------------------
This program asks our user for input and checks if the input is an
triangular number or not.
The triangular number (Tn) is a number that can be represented in the form of a triangular
grid of points where the first row contains a ... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING
from typing import List, Optional, Union
from pydantic import Field
from pydantic_schemaorg.MedicalIntangible import MedicalIntangible
class DDxElement(MedicalIntangible):
"""An alternative, closely-related condition typically considered later... | Python | 1 |
#!python3
"""
A demo of large/small party bias in apportionment methods.
"""
import apportionment.methods as app
a = 19
x = 0.1
b = 7
y = 1-x
p = 0.5
print((a+x)/(a-1+p) > (b+y)/(b+p))
votes = [int(1000*(a+x)), int(1000*(b+y))]
seats = a+b+1
parties = ["A", "B"]
app.compute("webster", votes, seats, parties, verbos... | Python | 1 |
import os
from pathlib import Path
import re
import random
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from wordcloud import WordCloud
from matplotlib.ticker import FuncFormatter
from matplotlib.ticker import MaxNLocator
csv_path = os... | Python | 1 |
operation completed. [MDN documentation][mdn]
///
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/Events/seeked
Seeked,
"seeked",
sys::Event
}
event_ty! {
/// A <em>seek</em> operation began. [MDN documentation][mdn]
///
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/Ev... | Rust | 0 |
}
}
}
let s = self.slice_back(start);
// Use the default f64 parser now.
if let Ok(n) = f64::from_str(s) {
// inf, nan, etc. are an error.
if n.is_finite() {
return Ok(n);
}
}
Err(Error::InvalidNumber(0))
... | Rust | 0 |
(0)
.unwrap_or(&Null)
.as_str()
.ok_or_else(|| object!{"message" => "Message must be a string"})?
.as_bytes().to_vec()
};
let raw = hex::decode(params.get(1)
.unwrap_or(&Null)
.as_str()
.ok_or_else(|| ob... | Rust | 0 |
wagyu_model::{to_hex_string, Address, AddressError, PrivateKey};
use core::{convert::TryFrom, fmt, str::FromStr};
use regex::Regex;
use serde::Serialize;
use tiny_keccak::keccak256;
/// Represents an Ethereum address
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Hash)]
pub struct EthereumAddress(S... | Rust | 0 |
_addr: ifr_addr,
},
};
let sockfd = (self.sockfd_provider)()?;
unsafe { libc::ioctl(sockfd, libc::SIOCSIFADDR, &ifr) };
close(sockfd)
}
}
impl Upper for IfSetup {
fn up(&self) -> nix::Result<()> {
let ifr = ifreq{
ifr_name: self.name,
... | Rust | 0 |
}
#[cfg(test)]
mod tests {
use super::*;
use crate::compute_const;
use serde_json::json;
#[test]
fn default_null() {
assert_eq!(compute_const!(), Value::Bool(false));
assert_eq!(compute_const!(json!(null)), Value::Bool(false));
}
#[test]
fn test() {
assert_eq!... | Rust | 0 |
16], fov: T, aspect: T, near: T, far: T) -> &'a mut [T; 16] {
let ymax = near * (fov / T::from_isize(2isize)).tan();
let ymin = -ymax;
let xmin = ymin * aspect;
let xmax = ymax * aspect;
frustum(out, ymax, xmax, ymin, xmin, near, far)
}
#[inline]
pub fn orthographic<'a, 'b, T: Copy + Signed>(out:... | Rust | 0 |
cer_config
.set("produce.offset.report", "true")
.set("bootstrap.servers", brokers);
let topic = format!("{}-{:?}", topic, worker.index());
let producer = EventProducer::new(producer_config, topic);
worker.dataflow::<u64,_,_>(|scope|
(0 .. count)
... | Rust | 0 |
from coldtype.test import *
from coldtype.text.font import FontmakeCache
@test()
def test_instances(r):
font = Font.MutatorSans()
instances = font.instances(scaled=True)
assert len(instances) == 6
out = StyledString("HIHI", Style(font, 100, instance="BoldCondensed"))
assert out.variations["w... | Python | 1 |
import json
with open("iam2.json", "r") as f:
roles = json.loads(f.read())
nodes = []
SAs = set()
projects = set()
for role in roles:
for member in role["members"]:
SAs.add(member)
for identity in SAs:
if identity.endswith("@google.com"):
nodes.append({"data": {"id": identity, "type": "... | Python | 1 |
child process to finish
// The response has been collected from the plugin call
Ok(pipeline_data)
}
fn is_plugin(&self) -> Option<&PathBuf> {
Some(&self.filename)
}
}
// The next trait and functions are part of the plugin that is being created
// The `Plugin` trait defines the API... | Rust | 0 |
# Copyright 2021 The ChromiumOS Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Test zmake modules module."""
import pathlib
import tempfile
# pylint:disable=import-error
import hypothesis
import hypothesis.strategies as st
import zmake.modules
modul... | Python | 1 |
import asyncio
import unittest
from exo.viz.topology_viz import TopologyViz
from exo.topology.topology import Topology
from exo.topology.device_capabilities import DeviceCapabilities, DeviceFlops
from exo.topology.partitioning_strategy import Partition
class TestNodeViz(unittest.IsolatedAsyncioTestCase):
async def... | Python | 1 |
ensible = true, lb = "0", ub = "0")]
pub struct CellAccessMode(pub u8);
impl CellAccessMode {
pub const HYBRID: u8 = 0u8;
}
#[derive(Debug, AperCodec)]
#[asn(type = "ENUMERATED", extensible = true, lb = "0", ub = "2")]
pub struct CellActivationCause(pub u8);
impl CellActivationCause {
pub const APPLICATION_CON... | Rust | 0 |
rames = frames[:max_num_frames]
frames = frames.float().permute(0, 3, 1, 2).contiguous() # [F, C, H, W]
# Ensure resizing even if Decord already does some resize
frames = torch.stack([resize(f, size=(height, width)) for f in frames], dim=0)
return frames
def preprocess_video_with_buckets(
video... | Python | 1 |
impl KickedResponse {
pub fn new(next_url: String) -> Self {
KickedResponse { next_url: next_url }
}
pub fn generate<W: Write>(
&self,
writer: &mut xml::EventWriter<W>,
has_cwmp: bool,
) -> Result<(), GenerateError> {
writer.write(XmlEvent::start_element(
... | Rust | 0 |
bytes().to_vec(),
// }),
// };
// let tx = Transaction {
// inputs: vec![input0],
// outputs: vec![output],
// time_lock: Default::default(),
// }
// .sign_unchecked(&[utxo0], 0, &alice_pub_key);
// let new_utxo_hash = tx.outpoint(0... | Rust | 0 |
truct $name:ident <$($gen:ident)*> (where $(($wty:ident $($wtr:tt)*))*) $(($field:ident $typ:ty))*)) => {
struct $name<$($gen),*> where $($wty: $($wtr)*),* { $($field: $typ),* }
};
((deftype $name:ident $typ:ty)) => { type $name = $typ; };
((deftype $name:ident <$($gen:ident)*> $typ:ty)) => { type ... | Rust | 0 |
from posixpath import split
initial = int(input("Provide lower number for range to find out prime number \n"))
later = int(input("Provide higher number for range to find out prime number \n"))
def prime_num_range(num1, num2):
list = []
primeNum = []
el = num2 + 1
for i in range(num1, el):
if (... | Python | 1 |
# Copyright 2023 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | Python | 1 |
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from config import config
BASE_URL = config.db_url
engine = create_async_engine(BASE_URL, echo=False)
async_session_maker = async_sessionmaker(
engine,
expire_on_commit=False,
class_=AsyncSession,
)
| Python | 1 |
oạt động trước đó.")
else:
print(f"Không tìm thấy cửa sổ cho hồ sơ gần nhất")
else:
print("Vui lòng chọn một hồ sơ để khôi phục.")
# Hàm để đóng cửa sổ Chrome hoặc Cent Browser
@update_listbox_decorator
def close_chrome_window():
# Lấy title của cửa sổ chính của chương trình
mai... | Python | 1 |
find first parent path");
let child_path_with_file = path
.strip_prefix(first_parent)
.expect("Could not remove parent from child path");
let child_path = child_path_with_file.parent().unwrap_or(Path::new(""));
let file_stem = path.file_stem().unwrap().to_str().unwrap();
let path_without_e... | Rust | 0 |
.
# Here we assume a grouping with the cosine term, which requires us to
# transform the operator using phi -> phi + 2*pi*flux
noise_op = noise_op or self.sin_phi_operator(alpha=0.5, beta=0.5 * (2 * np.pi * self.flux)) # type: ignore
if not isinstance(noise_op, (ndarray, csc_matrix, qt... | Python | 1 |
("in ")]
#[token("or ")]
#[token("with ")]
#[token("not")]
#[token("and")]
#[token("assert")]
Keyword,
#[regex(r"@([a-zA-Z0-9]+_?)*")]
#[token("dict")]
#[token("list")]
#[token("set")]
#[token("int")]
#[token("str")]
#[token("float")]
#[token("None")]
#[token("bool")]
#[token("bytes")]
... | Rust | 0 |
pipe: MaybeUninit<<Backend as gfx_hal::Backend>::GraphicsPipeline>,
}
pub struct BoundPipe<
'a,
C: BorrowMut<<Backend as gfx_hal::Backend>::CommandBuffer>,
Vertex: VertexInfo,
Uniforms: UniformInfo,
Index: IndexType,
Constants: PushConstantInfo,
> {
pipeline: &'a Pipeline<'a, Vertex, Uniforms, Index, Constants... | Rust | 0 |
import sqlite3
# Vulnerable
con = sqlite3.connect('users.db')
user_input = "Mary"
sql_stmt = "INSERT INTO Users (user) VALUES ('" + user_input + "');"
con.executescript(sql_stmt)
"""
The above code is vulnerable to SQL injection because user_input is
passed unsanitized to the query logic. This makes the query logic
p... | Python | 1 |
num, dir) in self.dir_stack.iter().rev().enumerate() {
if short {
if num == 0 {
if len == 1 {
println!("{}", dir);
} else {
print!("[{}] ", dir);
}
} else if num < len ... | Rust | 0 |
5]</li>\n<li>01.28・29 - Zepp DiverCity [Ten hundred Miles Tour 2015]</li>\n<li>02.01 - 沖縄音市場 SPACE SHOWER TV“LIVE with YOU” 〜ONE OK ROCK〜 supported by uP!!!</li>\n<li>07.24 - <a href=\"/wiki/FUJI_ROCK_FESTIVAL\" class=\"mw-redirect\" title=\"FUJI ROCK FESTIVAL\">FUJI ROCK FESTIVAL</a>'15</li>\n<li>08.23 - <a href=\"/wi... | Python | 1 |
));
}
let mut args = args.into_iter().skip(1);
match args
.next_string()?
.parse::<SocketAddr>()
.map(|x| x.to_string())
{
Ok(addr) => {
let mut r = Replica::new(
addr.clone(),
server.node_id,
server.config.nod... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : adaboost.py
# @Data : 2020/5/27
# @Author : Luo Kun
# @Contact: luokun485@gmail.com
import numpy as np
from matplotlib import pyplot as plt
class AdaBoost:
def __init__(self, n_estimators: int, lr: float = 1e-2, eps: float = 1e-5):
"""
... | Python | 1 |
e_names, 1):
print(f"{i}. {feature}")
print(f"\n目标变量: {target_column}")
print(f"最终用于分析的数据维度: {X_complete.shape}")
print(f"目标变量的样本数量: {len(y_complete)}")
# 验证X和y的样本数量是否一致
if len(X_complete) != len(y_complete):
print("错误:特征矩阵和目标变量的样本数量不一致!")
return None, None, None
... | Python | 1 |
import FWCore.ParameterSet.Config as cms
process = cms.Process("convertLHE2HepMC")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(-1)
)
process.source = cms.Source("LHESource",
fileNames = cms.untracked.vstring()
)
process.source.file... | Python | 1 |
Future for Timeout {
type Item = ();
type Error = JsValue;
fn poll(&mut self) -> Poll<(), JsValue> {
let _obj = try_ready!(self.inner.poll());
Ok(().into())
}
}
impl Drop for Timeout {
fn drop(&mut self) {
clear_timeout(self.id);
}
}
<reponame>noctune/rust
// Test that... | Rust | 0 |
Other valid (possibly inherited) options. See:
https://leafletjs.com/reference.html#videooverlay
"""
_template = Template(
"""
{% macro script(this, kwargs) %}
var {{ this.get_name() }} = L.videoOverlay(
{{ this.video_url|tojson }},
{{ this... | Python | 1 |
page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'qatrack', 'QATrack+ Documentation',
[author], 1)
]
# -- Options for Texinfo output ------------------------------... | Python | 1 |
it<lens_rs::optics::#var_name<#prism_param>, #image_param> for #ty
where
#constraints
{
fn preview_ref(&self, optics: lens_rs::optics::#var_name<#prism_param>) -> Option<&#image_param> {
use #ty_name::*;
match self {
#var_name(x... | Rust | 0 |
# Copyright (c) 2013-2014 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functiona... | Python | 1 |
);
assert!(point.is_overlap);
}
}
<filename>openssl-sys/src/x509v3.rs<gh_stars>10-100
use libc::*;
use *;
pub enum CONF_METHOD {}
pub const GEN_OTHERNAME: c_int = 0;
pub const GEN_EMAIL: c_int = 1;
pub const GEN_DNS: c_int = 2;
pub const GEN_X400: c_int = 3;
pub const GEN_DIRNAME: c_int = 4;
pub const GE... | Rust | 0 |
rt = f"{get_current_path()}/files/self/full_chain.pem"
kdm_gen = KDMGenerator(server_private_key, server_cert)
dkdm_file = f"{get_current_path()}/files/dkdm/kdm_Test_des_equipements_de_projection_VO_Varietes_Les_Melun_4_110425_110426.xml"
target_cert_file = f"{get_current_path()}/files/certific... | Python | 1 |
# Code generated by Lark OpenAPI.
from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type
from lark_oapi.core.construct import init
from .tmp_download_url import TmpDownloadUrl
class BatchGetTmpDownloadUrlMediaResponseBody(object):
_types = {
"tmp_download_urls": List[TmpDownloadUrl]... | Python | 1 |
or arm in arms {
if_chain! {
if let PatKind::Lit(Expr {
kind: ExprKind::Lit(lit),
..
}) = arm.pat.kind;
if let LitKind::Str(symbol, _) = lit.node;
let input = symbol.as_str();
... | Rust | 0 |
tons_row.add_widget(self.open_output_folder_btn)
render_section.add_widget(buttons_row)
# Add progress bar
self.render_progress = ModernProgressBar()
render_section.add_widget(self.render_progress)
# Add to main content
self.scroll_content.add_w... | Python | 1 |
neighbors.push(v);
}
})
});
};
}
in_neighbors!("in_neighbors_10", 10);
in_neighbors!("in_neighbors_100", 100);
in_neighbors!("in_neighbors_500", 500);
in_neighbors!("in_neighbors_1000", 1000);
#[cfg(feature = "sbench")]
... | Rust | 0 |
lue: u8,
}
/// Control lights in accordance with the list of operations.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, new)]
pub struct LightCtrl {
/// The repeat count.
pub repeat: u8,
/// The number of operations.
pub num: u8,
/// The list of operations for lights.
pub ops: Ve... | Rust | 0 |
ale=10,
)
with gr.Row():
self.chat_left_arrow_btn = gr.Button("←")
self.n_rollout_text = gr.Textbox(
value="第0个回复/共0个回复",
interactive=False,
con... | Python | 1 |
time(yesterday_last_month).to_period('M'))]
yesterday_lt_calculate = lt_calculate.copy()
yesterday_last_month_lt_calculate = lt_calculate.copy()
# Дропаем когорты
yesterday_lt_calculate.drop(mask_until_matured_cogort_yesterday_index, inplace=True) # дропаем т.к они не полные
yesterday_last_month_... | Python | 1 |
from .main import main
if __name__ == "__main__":
main()
| Python | 1 |
(None),
symbols: HashMap::new()
},
origin: vec![]
}
},
readonly: true
}
);
}
/*fn remove(&mut self, name: String) {
self.symbols.remove(&name);
}*/
}
/... | Rust | 0 |
=r_{HA})}}{2}$")
plt.show()
## Delta masa ADM
def delta_mass_ADM(mass,t):
return np.abs(mass[t]-mass[0])/mass[0]
t_paper=240
delt_masas=[np.log10(delta_mass_ADM(msch_c,t_paper)),np.log10(delta_mass_ADM(msch_5,t_paper)),np.log10(delta_mass_ADM(msch_10,t_paper)),np.log10(delta_mass_ADM(msch_20,t_paper))]
plt.pl... | Python | 1 |
rt_sentences = sum(1 for s in sentences if len(s.split()) < 3)
# Should identify quality issues
self.assertGreater(avg_length, 3) # Average should be reasonable
self.assertGreater(short_sentences, 0) # Should detect short sentences
def test_outlier_detection(self):
"""Test detect... | Python | 1 |
"")
target_path = save_dir.parent / target_name / f"{short_name}.json"
if os.path.exists(target_path):
with open(target_path, "r") as f:
existing_results = json.load(f)
id_set = set(existing_results.keys())
print(f"Loaded {len(id_set)} existing IDs from {save_path}")
els... | Python | 1 |
ies = []
ies.append({ "iei" : "", "value" : "EMM cause", "type" : "EMM cause", "reference" : "9.9.3.9", "presence" : "M", "format" : "V", "length" : "1"})
ies.append({ "iei" : "5B", "value" : "T3442 value", "type" : "GPRS timer", "reference" : "9.9.3.16", "presence" : "C", "format" : "TV", "length" : "2"})
ies.append({... | Python | 1 |
ymin)
corner2 = shapely.Point(xmin + pixel_width_degrees, ymin)
corner3 = shapely.Point(xmin, ymin + abs(pixel_height_degrees))
# Project to UTM and calculate distances
corners_gdf = gpd.GeoDataFrame(geometry=[corner1, corner2, corner3], crs=4326).to_crs(utm_crs)
pixel_res_x = corners_gdf.geome... | Python | 1 |
#this program runs the style transfer in a video. Bitch you can even change the styles by pressing
#the letter 'n' for "next" <3
#import the necessary packages
from imutils.video import VideoStream
from imutils import paths
import itertools
import argparse
import imutils
import time
import cv2
#construct the argumen... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.