text string | label_name string | labels int64 |
|---|---|---|
nd truth')
gt = loadmat(CITY_GT_PATH)['truth']
if debug:
gt = gt[:debug_amt, :debug_amt]
elif name.lower() == 'college': # new college dataset
print('Loading the New College dataset...')
# Load images
print('Loading images')
if not os.path.isfile(COLLEGE_... | Python | 1 |
0.151667417958,-1.98847949505 m0.313824974,2.88371771574
l0.000462826974399,-0.000654117175145 m10.4860162735,
-2.15939834714 l-1.24286003411,-1.78383305669
-0.55390316993, -1.80988907814 l0.289762914181,
-1.793357133... | Python | 1 |
sometimes algorithms squeeze their data, be robust to that
gt_bboxes = gt_bboxes.squeeze()
bboxes = bboxes.squeeze()
if assign_result.labels is None:
gt_labels = None
else:
gt_labels = None # todo
if gt_labels is None:
add_gt_as_pro... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import re
import os
import argparse
parser = argparse.ArgumentParser(description='Create a couple galaxy/cluster with cti\'s malwares\nMust be in the mitre/cti/enterprise-attack/malware folder')
parser.add_argument("-v", "--version", type=int, required=True, h... | Python | 1 |
/ Try to convert a raw value into a LE-U channel identifier
pub fn le_try_from_raw(val: u16) -> Result<Self, ()> {
LeUserChannelIdentifier::try_from_raw(val).map(|c| c.into())
}
/// Try to convert a raw value into a ACL-U channel identifier
pub fn acl_try_from_raw(val: u16) -> Result<Self, ()> ... | Rust | 0 |
import numpy as np
from matplotlib import pyplot as plt
X = np.array([[ -0.074, 1.611],
[ 0.109, 0.518],
[ -0.409, -0.768],
[ 0.403, 1.099],
[ -1.823, 1.338],
[ 0.243, -0.76 ],
[ -0.019, 1.758],
[ 0.186, 0.239],
[-19.45 , -2.623],
[ -1.064, 1.16... | Python | 1 |
impl From<crate::R<APP_TG1_WDT_EDGE_INT_MAP_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<APP_TG1_WDT_EDGE_INT_MAP_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `APP_TG1_WDT_EDGE_INT_MAP` writer"]
pub struct W(crate::W<APP_TG1_WDT_EDGE_INT_MAP_SPEC>);
impl core::ops::Deref for W {
... | Rust | 0 |
, state: &mut H) {
for c in self.0.as_slice() {
state.write_u16(u16_tolower(*c));
}
}
}
impl PartialEq for EntryNameRef {
fn eq(&self, other: &Self) -> bool {
if self.0.len() != other.0.len() { false } else {
self.0.as_slice().iter().zip(other.0.as_slice())
.all(|(c1, c2)| u16_tolower(*c1) == u16_tol... | Rust | 0 |
::XOFS_SPEC>,
#[doc = "0xa8 - ADC Y Offset Correction Register"]
pub yofs: crate::Reg<yofs::YOFS_SPEC>,
#[doc = "0xac - ADC Gain Register"]
pub g: crate::Reg<g::G_SPEC>,
#[doc = "0xb0 - ADC User Gain Register"]
pub ug: crate::Reg<ug::UG_SPEC>,
#[doc = "0xb4 - ADC General Calibration Value Re... | Rust | 0 |
### Trabajo con datos incorrectos o faltantes ###
import findspark
findspark.init()
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
# Lee un DataFrame en formato Parquet desde el directorio local ./data
df = spark.read.parquet("./data/datos.parquet")
# Cuenta el número total de regis... | Python | 1 |
profile_text=current_profile_text,
generated_comment=comment,
style_used="unknown", # Could be comedic/flirty if you parse from the template
)
# Tap Like
tap(device, x_select_like_button, y_select_like_button)
print("Like tapped at:", x_s... | Python | 1 |
F_SINGLE_HUNK, &config);
ansi_test_utils::assert_line_has_style(&output, 8, "--- a/src/align.rs", "red", &config);
ansi_test_utils::assert_line_has_style(&output, 9, "+++ b/src/align.rs", "red", &config);
let output = strip_ansi_codes(&output);
assert!(output.contains(
"\
--... | Rust | 0 |
let printable = match *self {
ShutdownMethod::AlreadyExited => "Already Exited",
ShutdownMethod::GracefulTermination => "Graceful Termination",
ShutdownMethod::Killed => "Killed",
};
write!(f, "{}", printable)
}
}
pub struct HabChild {
inner: imp::Ch... | Rust | 0 |
@nightyScript(
name="Role Cloner",
author="AutoGPT",
description="Clone a role and its icon to another server.",
usage="<p>clonerole <role_id> <target_server_id>"
)
def role_cloner():
"""
ROLE CLONER
------------
Copy a role, including its icon, to another server.
COMMANDS:
<p>... | Python | 1 |
; DlogProverInput::SIZE_BYTES]) -> Option<DlogProverInput> {
Scalar::from_repr((*bytes).into())
.map(DlogProverInput::from)
.into()
}
/// Attempts to parse the given Base16-encoded byte array as an SEC-1-encoded scalar(secret key).
/// Returns None if the byte array does not... | Rust | 0 |
# Generated by Django 2.2.18 on 2021-03-24 21:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wells', '0125_alter_fieldsprovided_water_1658'),
]
operations = [
migrations.AlterField(
model_name='activitysubmission',
... | Python | 1 |
_mode()?.as_ref() {
GyroSensor::MODE_GYRO_G_AND_A => self.get_value0(),
GyroSensor::MODE_GYRO_ANG => self.get_value0(),
mode => Ev3Result::Err(Ev3Error::InternalError {
msg: format!("Cannot get angle while in {} mode", mode),
// Returns error
... | Rust | 0 |
UT);
assert_eq!(count_ons_in_50_area(&instructions), 590784);
}//! Linear layout
//!
//! A linear layout is a list of [`View`]s that are placed one after the other along
//! the horizontal or vertical axis.
//!
//! The main flow when working with a [`LinearLayout`] is the following:
//! - Create the layout
//! ... | Rust | 0 |
!(!$set.contains(&SET_TEST_E));
$set.insert(SET_TEST_A);
$set.insert(SET_TEST_C);
assert!($set.contains(&SET_TEST_A));
assert!(!$set.contains(&SET_TEST_B));
assert!($set.contains(&SET_TEST_C));
assert... | Rust | 0 |
::PwrScale2 => w.vos().scale2(),
VOSscale::PwrScale1 => w.vos().scale1(),
});
if config.overdrive {
pwr.cr1.modify(|_, w| w.oden().set_bit());
}
// Enable PLL
rcc.cr.modify(|_, w| w.pllon().on());
// Wait for PLL ... | Rust | 0 |
post_process_image_guided_detection(self, *args, **kwargs):
"""
This method forwards all its arguments to [`OwlViTImageProcessor.post_process_one_shot_object_detection`].
Please refer to the docstring of this method for more information.
"""
return self.image_processor.post_proc... | Python | 1 |
a.x(), a.y() + height);
let c = Coordinates::new(a.x() + length, a.y() + height);
let d = Coordinates::new(a.x() + length, a.y());
let uvs_ref = uvs.unwrap_or(default_uvs());
let contents = [
TexturedGlVertex::from((&a, &uvs_ref[0])),
TexturedGlVertex::from((&b, &... | Rust | 0 |
import requests
import os
import csv
'''
List of users in project 228504
https://api.inaturalist.org/v1/projects/228504/members?skip_counts=false
crono_secuencia_2 - user_id 9000660
crono_secuencia_3 - user_id 9000828
Observation created by userid crono_secuencia_2
https://api.inaturalist.org/v1/observations?user_i... | Python | 1 |
# coding: utf-8
"""
"law location" cli subprogram.
"""
import os
import six
from law.util import law_src_path
def setup_parser(sub_parsers):
"""
Sets up the command line parser for the *location* subprogram and adds it to *sub_parsers*.
"""
parser = sub_parsers.add_parser(
"location",
... | Python | 1 |
for i in 0..=255 {
assert_eq!(a.find_nth(i), Some(i));
}
}
#[test]
fn find_nth_sparse() {
let mut a = BitField256::default();
const STRIDE: usize = 256 / 31;
let mut bits = Vec::<u8>::new();
for i in (0..=255).step_by(STRIDE) {
a.set(... | Rust | 0 |
# Copyright 2010-2015 MongoDB, 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | Python | 1 |
pub fn __gmpn_gcdext_1(
arg1: *mut mp_limb_signed_t,
arg2: *mut mp_limb_signed_t,
arg3: mp_limb_t,
arg4: mp_limb_t,
) -> mp_limb_t;
}
extern "C" {
pub fn __gmpn_gcdext(
arg1: mp_ptr,
arg2: mp_ptr,
arg3: *mut mp_size_t,
arg4: mp_ptr,
ar... | Rust | 0 |
def measure(iterations):
with user_code_environment(self._path_to_entry_point_dir, self.
_project_root):
self._start_event.record()
for _ in range(iterations):
self._iteration(*inputs)
self._end_event.record()
torch.cuda.synchronize()
return self._start_event.elap... | Python | 1 |
usize);
pub fn Label_Repaint(AObj: usize);
pub fn Label_ScreenToClient(AObj: usize, Point: *mut TPoint, Result: *mut TPoint);
pub fn Label_ParentToClient(AObj: usize, Point: *mut TPoint, AParent: usize, Result: *mut TPoint);
pub fn Label_SendToBack(AObj: usize);
pub fn Label_SetBounds(AObj: usize, ALeft: i32... | Rust | 0 |
skip_serializing_if = "Option::is_none")]
pub h265_settings: Option<H265Settings>,
#[serde(rename = "Mpeg2Settings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub mpeg_2_settings: Option<Mpeg2Settings>,
}
/// <p>Video settings for this stream.</p>
#[derive(Clone, Debug, Default, Deserialize, P... | Rust | 0 |
ize_all_variables()
sess.run(init)
saver = tf.train.Saver(tf.all_variables())
if args.continue_training:
saver.restore(sess, ckpt.model_checkpoint_path)
for e in range(args.num_epochs):
sess.run(tf.assign(model.lr, args.learning_rate * (args.decay_rate ** e)))
... | Python | 1 |
f(k);
let overshoot = n - two_to_k;
k + (2.0 * overshoot) / n
}
pub fn depth_bits(weight: u64, total_weight: usize) -> f64 {
-(weight as f64 / total_weight as f64).log2()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bits_to_string() {
assert_eq!(bits_to_string(&[]), "".to_string());
a... | Rust | 0 |
ort] Failed to copy tile into canvas.");
cell_cnt += 1;
}
}
img_surface = canvas.into_surface();
println!("img_surface:");
println!(" . copied {} cells", cell_cnt);
println!(" . width = {}px", img_surface.width());
println!(" . height = {}px", img_surface.height());
... | Rust | 0 |
d_type_names = String::with_capacity(200);
for (t, _) in &valid_types {
if !valid_type_names.is_empty() {
valid_type_names.push_str(", ");
}
valid_type_names.push_str(&t.into_token_stream().to_string());
}
Err(Error::new(
ty.span(),... | Rust | 0 |
:time::SystemTime;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
pub struct SQLite {
/// WOF data directories
#[structopt(default_value = ".")]
pub directories: Vec<String>,
/// Where to store the final build file. If empty the code will attempt to create whosonfirst-data-latest.db the current working ... | Rust | 0 |
Success,
FailedInitialization,
OutputBufferTooSmall,
ExpectedMoreRawBytes,
BadCode,
Adler32,
BadRawBlock,
BadCompBlockSyncCheck,
BadZlibHeader,
NeedSeedBytes,
BadSeedBytes,
BadSyncBlock,
InvalidParameter,
// Not same as the actual `lzham_codec`. Conversion from th... | Rust | 0 |
# id 17679 ([Commerci Republic] Red Tide), field 865010011
sm.setSpeakerID(9390246) # Captain Blood
sm.setParam(56)
sm.setColor(1)
sm.sendNext("Your pirating days are over!")
sm.setParam(32)
sm.sendSay("Hahaha! Ye've walked into th' belly a' th' beast and ye don't even know it! ")
sm.setParam(56)
sm.sendSay("That's wha... | Python | 1 |
sage is from the assistant and has SQL, show an expander
if message["role"] == "assistant" and message.get("sql"):
with st.expander("View Generated SQL"):
formatted_sql_display = minimal_sql_formatter(message["sql"])
st.code(formatted_sql_display, language="sql")
# D... | Python | 1 |
d_groups=[{sensitive_attribute: 0}])
classification_metric = ClassificationMetric(dataset_true, dataset_predicted,
privileged_groups=[{sensitive_attribute: 1}],
unprivileged_groups=[{sensitive_attribute: 0... | Python | 1 |
import sys
from os.path import abspath, dirname
parent_dir = abspath(dirname(dirname(__file__)))
sys.path.append(parent_dir)
from clip import CLIP
from sklearn.metrics import confusion_matrix
from PIL import Image
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
def calculate_f... | Python | 1 |
ampion/loading/LeeSin_0.jpg".to_string())
}
pub fn lee_sin_1() -> Result<Vec<u8>, ()>{
cached_http_byte_request("https://ddragon.leagueoflegends.com/cdn/../src/api/ddragon_raw/img/champion/loading/LeeSin_1.jpg".to_string())
}
pub fn lee_sin_10() -> Result<Vec<u8>, ()>{
cached_http_byte_request("https:... | Rust | 0 |
to {:?}", msg);
let mut bridge = BRIDGE.write().unwrap();
trace!("Finished changing detailed state {:?}", msg);
let new_state = msg;
bridge.detailed_state = new_state;
}
fn set_last_amounts(minimum_to_exchange: u32, reserve_amount: u32) {
let mut amounts = AMOUNTS.write().unwrap();
*amounts = L... | Rust | 0 |
import time
import os
import psutil # Para coletar informações do sistema
import platform # Para obter informações sobre o sistema operacional
from http.server import SimpleHTTPRequestHandler, HTTPServer
from plyer import notification # Para notificações
# Função para coletar informações do dispositivo
def get_info... | Python | 1 |
!other.query_used)
&& (self.size || !other.size_used)
&& (self.regex || !other.regex_used)
}
Validator::Valid => true,
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use encode;
use value::Value;
use super::*;
fn rea... | Rust | 0 |
let tmp: HashSet<char> = pat.chars().into_iter().collect();
if mapping[1].difference(&tmp).count() == 1 {
mapping[6] = tmp;
} else if mapping[5].difference(&tmp).count() == 0 {
mapping[9] = tmp;
} else {
mapping... | Rust | 0 |
import sys
import pickle
##########################################################
# usage
# pypy find_4g.py xid_train.p ../../data/train
# xid_train.p is a list like ['loIP1tiwELF9YNZQjSUO',''....] to specify
# the order of samples in traing data
# ../../data/train is the path of original train data
##############... | Python | 1 |
import asyncio
from app.redis_db import DB
import app.parser as parser
from app.server import RedisReplicationServerProtocol, RedisServerProtocol, ProtocolFactory
from app.types import types, roles
import argparse
p = parser.Parser()
class PubSub:
def __init__(self):
self._channels = {}
def subsc... | Python | 1 |
'}') => false,
token => return Err(Error::unexpected_token(token)),
}
} else {
let (field, continues) = Model::<Asn<Unresolved>>::read_field(iter)?;
sequence.fields.push(field);
continues
};
if !cont... | Rust | 0 |
'''gsd-rfkill mock template
This creates the expected methods and properties of the main
org.gnome.SettingsDaemon.Rfkill object.
'''
# 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; eith... | Python | 1 |
ult<()> {
if token_index == QUOTE_INDEX {
Ok(self.update_quote(mango_cache, mango_account))
} else {
self.update_spot_val(
mango_group,
mango_cache,
mango_account,
&open_orders_ais[token_index],
token... | Rust | 0 |
# This actually "clicks" the element by calling focus() on it in JS.
self._js_call('focus')
self._move_text_cursor()
def _click_js(self, _click_target: usertypes.ClickTarget) -> None:
# FIXME:qtwebengine Have a proper API for this
# pylint: disable=protected-access
... | Python | 1 |
{
let rc = raw::libssh2_knownhost_checkp(
self.raw,
host.as_ptr(),
port as c_int,
key.as_ptr() as *const _,
key.len() as size_t,
flags,
0 as *mut _,
);
match rc {
... | Rust | 0 |
String> = pubkeys.lines()
.map(|s| s.trim().to_string())
.collect();
ensure_pubkeys(log, "root",&pubkeys)?;
}
/*
* Get userscript:
*/
if let Mdata::Found(userscript) = mdata_get(log, "user-script")? {
phase_userscript(log, &userscript)
.map_err... | Rust | 0 |
onfigure Flask app for development"""
# Enable debug mode
chat_app.config['DEBUG'] = True
# Enable testing mode
chat_app.config['TESTING'] = False
# Set development-specific settings
os.environ.setdefault('FLASK_ENV', 'development')
os.environ.setdefault('FLASK_DEBUG', 'true')
... | Python | 1 |
51722, -0o35136,
),
[
I16(-32768), I16(-21458), I16(-14942),
I16(-32768), I16(-21458), I16(-14942),
I16(-32768), I16(-21458), I16(-14942),
]
);
}
#[test]
fn i16_suffixed() {
assert_bytify_eq!(
bytify!(
-32768i16, -21458i16, ... | Rust | 0 |
scan_queue_remaining
elif self.fetch_count < 5:
self.fetch_count = 5
async def _fetch_task_from_db(self):
"""
从数据库中获取当前扫描目标的非扫描请求(新扫描任务)
"""
await self.new_scan_model.mark_result(self.mark_id, list(self.failed_task_set))
self.failed_task_set.clea... | Python | 1 |
5ntu67, bpgomqdsgq6, hfwgl4ijsj2 as ksbal78ta1f, licvczj_h5u, l9oni9ks0ne as l3v5f9duoz0, mmuq8v5ife2 as yyq7y9_7gl9
'# strain_batteries_message -> battery_recipient_pole'
@0j is not qhfw2_6qfnf not in kz_zipis6w5
def e0j2t067rdp(nb722ox641c: eib6iuejbou=False, iolbwj3we5t=0, rhq_7xzdsr9='', jjc1dbyt6s5: gzjfxqzo0y... | Python | 1 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# 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... | Python | 1 |
s.npy",np.array(type1_experiment_wise_episodic_smoothened_rewards))
np.save(expt_dir+expt+"-BASELINE-regrets.npy",np.array(type1_experiment_wise_smoothened_regrets))
np.save(expt_dir+expt+"-NO_BASELINE-rewards.npy",np.array(type2_experiment_wise_episodic_smoothened_rewards))
np.save(expt_dir+expt+"-NO_BASE... | Python | 1 |
import pytest
from unfazed.app import BaseAppConfig
from unfazed.conf import UnfazedSettings
from unfazed.core import Unfazed
SETTINGS = {
"DEBUG": True,
"PROJECT_NAME": "test_app",
}
def test_app_base() -> None:
unfazed = Unfazed(settings=UnfazedSettings.model_validate(SETTINGS))
app_common = Base... | Python | 1 |
import gym
import torch
from easydict import EasyDict
from ding.config import compile_config
from ding.envs import DingEnvWrapper
from ding.model import DQN
from ding.policy import DQNPolicy, single_env_forward_wrapper
from dizoo.taxi.config.taxi_dqn_config import create_config, main_config
from dizoo.taxi.envs.taxi_e... | Python | 1 |
!(
/// forest
/// .children(root)
/// .map(|node| *node.data())
/// .collect::<Vec<_>>(),
/// &["0", "1", "2"]
/// );
/// ```
#[inline]
#[must_use]
pub fn children(&self, node: Id) -> traverse::Siblings<'_, Id, T> {
self.node(node)
... | Rust | 0 |
net>);
impl ServiceConsumerProxyInterface for ServiceConsumer {
type ListPeersResponseFut = futures::future::MapErr<
futures::channel::oneshot::Receiver<Vec<Peer>>,
fn(futures::channel::oneshot::Canceled) -> fidl::Error,
>;
fn list_peers(&self) -> Self::ListPeersResponseFut {
let (... | Rust | 0 |
$Tuple) -> &'a $ArrayN<$S> {
unsafe { mem::transmute(v) }
}
}
impl<'a, $S> From<&'a mut $Tuple> for &'a mut $ArrayN<$S> {
#[inline]
fn from(v: &'a mut $Tuple) -> &'a mut $ArrayN<$S> {
unsafe { mem::transmute(v) }
}
... | Rust | 0 |
# Calcular métricas para la clase "real" (1)
precision_real = precision_score(y_real, y_pred, pos_label=1)
recall_real = recall_score(y_real, y_pred, pos_label=1)
f1_real = f1_score(y_real, y_pred, pos_label=1)
# Calcular métricas para la clase "fake" (0)
precision_fake = precision_score(y_real, y... | Python | 1 |
v_map2img(p_u_vis.detach(), p_v_vis.detach(), p_i_vis.detach())
else:
p_iuv_vis_i = iuv_map2img(p_u_vis.detach(), p_v_vis.detach(), p_i_vis.detach(),
ind_mapping=[0] + model.img2iuv.dp2smpl_mapping[i])
p_iuv_vis.append(p_iuv_vis_i)
... | Python | 1 |
from visdom import Visdom
import json
class Visualizer(object):
""" Visualizer
"""
def __init__(self, port='13579', env='main', id=None):
#self.cur_win = {}
self.vis = Visdom(port=port, env=env)
self.id = id
self.env = env
# Restore
#ori_win = self.vis.get_w... | Python | 1 |
to enable/disable the PMU"]
pub pmuenable: PMUENABLE,
_reserved29: [u8; 44usize],
#[doc = "0x250 - TPIU Control Register. Determines the clock enable and frequency for the M4's TPIU interface."]
pub tpiuctrl: TPIUCTRL,
_reserved30: [u8; 16usize],
#[doc = "0x264 - OTA (Over the Air) Update Point... | Rust | 0 |
import urllib.parse
class PackageIndex:
"""Represents a Package Index and provides easier access to endpoints"""
__slots__ = ["url", "netloc", "simple_url", "pypi_url", "file_storage_domain"]
def __init__(self, url: str, file_storage_domain: str) -> None:
super().__init__()
self.url = ur... | Python | 1 |
TreeArity::to_usize())
.map(|i| {
let replica = format!(
"{}-{}-{}-{}-{}-replica",
distinguisher,
i.to_string(),
j.to_string(),
base_tree_leaves,
... | Rust | 0 |
Some(Edge {
src: self.face.vertex(i),
dst: self.face.vertex((i + 1) % self.face.vertex_count()),
})
}
}
pub struct Polygon {
pub vertices: Vec<Pt3>,
}
impl Polygon {
pub fn new(vertices: Vec<Pt3>) -> Self {
Self {
vertices
}
}
}
impl... | Rust | 0 |
global_asm!(include_str!("boot.S"));
mod uart;
mod allocator;
use allocator::FRAME_ALLOCATOR;
#[no_mangle]
fn kernel_init() -> ! {
uart::init();
FRAME_ALLOCATOR.init();
let cute = "Hello World!";
println!("{}", cute);
println!("Goodbye :(");
panic!("Nothing else to do so I am panicking");
}
#... | Rust | 0 |
import random
from flask import Blueprint, render_template, request, redirect, url_for, jsonify
from flask_login import current_user
from sqlalchemy import func
from werkzeug.security import generate_password_hash
from sqlalchemy.sql import text
from app import db
from app.models import User, Drone, Pilot, Admin, Deli... | Python | 1 |
# --- ARP Leaderboard Tracker + Dashboard ---
# Automatically updates master leaderboard and visualizes top configs
import os
import pandas as pd
import matplotlib.pyplot as plt
RESULTS_DIR = "results"
LEADERBOARD_FILE = "results/master_leaderboard.csv"
# Load all CSVs in the results directory and summarize final pe... | Python | 1 |
Some(row) => row,
None => {
log::info!("Unprocessed user image upload not found in database!");
txn.rollback().await?;
return Ok(false);
}
};
let file = s3
.download_media_for_processing(
MediaLibrary::User,
id,
... | Rust | 0 |
istogram_img /= histogram_img.sum()
histogram_img_cdf = np.cumsum(histogram_img)
# 自然图像
histogram_natural = np.zeros_like(histogram_img)
for x in range(256):
histogram_natural[x] = weights[0] * self.image_processor.Laplace(x) + weights[1] * self.image_processor.Uniform(x) + w... | Python | 1 |
from django.contrib import admin
from .models import Provinsi, Regency, Distric, Village, SettingWebsite, HistoriTampung, ConfigurationWebsite
from import_export.admin import ImportExportModelAdmin
from import_export import resources, fields
from import_export.widgets import ForeignKeyWidget
from solo.admin import Sing... | Python | 1 |
l(b), SchemaPiece::Boolean) => Ok(Value::Boolean(*b)),
(JsonValue::Number(ref n), SchemaPiece::Int) => Ok(Value::Int(
n.as_i64()
.unwrap()
.try_into()
.map_err(|e: TryFromIntError| e.to_string())?,
)),
(JsonValue::Number(ref n), SchemaP... | Rust | 0 |
#CACLCULATING AND SAVING ENRICHMENT STATSDICT FOR TUNING VS ROI: START
#todo re-run once the proper ROIs are there
for U in Usel:
is_deep = S.check_layers(U.layer, ['5', '6'])
laydepth = 'deep' if is_deep else 'sup'
if U.roi == 0:
U.set_feature('roilaydepth', 'na')
else:
U.set_feature('... | Python | 1 |
"Defaults exclude caches/VCS/IDE/OS junk but include *.csv, *.mat, *.txt. "
"Writes to filetree.txt in the current directory."
)
)
p.add_argument("path", nargs="?", default=".", help="Root path (default: .)")
p.add_argument(
"-L", "--depth", type=int, default=None, help="Ma... | Python | 1 |
vp > 0.06:
vp = math.log((vp-0.06)*40+1) / 40 + 0.06
相关 *= vp
相关s.append(相关)
相关性阈值 = 0
if len(相关s) > sli.stop + 10:
相关性阈值 = sorted(相关s, reverse=True)[sli.stop + 10] / 10
with 计时(f'裁剪{keys}'):
if 候选:
候选, locs, 相关s = zip(*... | Python | 1 |
()> {
commands::file_pull(&self.conn, container, container_file.as_ref(), host_file.as_ref()).await
}
pub async fn file_push(
&self,
container: &LxdContainerName,
host_file: impl AsRef<Path>,
container_file: impl AsRef<Path>,
) -> Result<()> {
commands::file_... | Rust | 0 |
with a browser at http://127.0.0.1:{port}")
vars.serverstarted = True
socketio.run(app, port=port)
logger.init("Webserver", status="Closed")
else:
general_startup()
# Start flask & SocketIO
logger.init("Flask", status="Starting")
Session(app)
logger.init_ok("Flask", sta... | Python | 1 |
: ["pipeline/demo/*ttf",
"pipeline/demo/*css",
"pipeline/demo/*html",
"pipeline/demo/*js",
"pipeline/demo/*gif",],
},
include_package_data=True,
# Although 'package_data' is the preferred approach, in some case you may
# need to place data files outs... | Python | 1 |
e(always)]
pub fn mv_joint_vertical(joint_type: MvJointType) -> bool {
joint_type == MvJointType::MV_JOINT_HZVNZ
|| joint_type == MvJointType::MV_JOINT_HNZVNZ
}
#[inline(always)]
pub fn mv_joint_horizontal(joint_type: MvJointType) -> bool {
joint_type == MvJointType::MV_JOINT_HNZVZ
|| joint_type == MvJointT... | Rust | 0 |
["active_count"] += 1
# Count by file format
if file_path:
ext = (
file_path.split(".")[-1].lower() if "." in file_path else "unknown"
)
if ext not in summary["file_formats"]:
summary["file_formats"][ext] = ... | Python | 1 |
= open(GloVe_DIR, encoding="utf8")
for line in f:
values = line.split()
word = values[0]
try:
coefs = np.asarray(values[1:], dtype='float32')
except:
pass
embeddings_index[word] = coefs
f.close()
print('Total %s word vectors.' % len(embeddings... | Python | 1 |
'''
# Exploit Title: Login bypass and data leak - Lutron Quantum 2.0 - 3.2.243 firmware
# Date: 20-03-2018
# Exploit Author: David Castro
# Contact: https://twitter.com/SadFud75
# Vendor Homepage: http://www.lutron.com
# Software Link: http://www.lutron.com/en-US/Products/Pages/WholeBuildingSystems/Quantum/Overview.a... | Python | 1 |
import json
def calculate_f1_scores(file_path):
# Dictionaries to store total F1 scores and counts per complexity label
f1_scores = {}
counts = {}
# Open and read the JSONL file
with open(file_path, 'r') as file:
for line in file:
# Parse each line to a JSON object
... | Python | 1 |
prophet_model.fit(prophet_data)
# Create a DataFrame for future dates
future = prophet_model.make_future_dataframe(prophet_data, periods=forecast_steps, freq='M')
forecast = prophet_model.predict(future)
# Display forecast
... | Python | 1 |
rank -= 1;
file = 0;
}
}
write!(
f,
"{} {}{}{}{}{} {} {} {}",
if self.white_to_move {"w"} else {"b"},
if self.white_kingside_castle_available {"K"} else {""},
if self.white_queenside_castle_available {"Q"} ... | Rust | 0 |
"""
Suppose you are managing a manufacturing plant, and you need to optimize the production process to minimize costs. The total cost C(x) of producing x units of a product can be modeled by the equation:
C(x) = x^3 + 2 * x^2 + x - 1
where:
x is the number of units of the product produced.
You want to find the pro... | Python | 1 |
Mode::from_bits_truncate(
fs::metadata(&test_path)
.map(|md| md.permissions().mode())
.unwrap_or_else(|e| panic!("metadata failed: {}", e)),
);
assert!(
mode.contains(Mode::S_IXUSR | Mode::S_IXGRP | Mode::S_IXOTH),
"{:?} did not have e... | Rust | 0 |
box
// do not block the current thread to avoid deadlocks
.try_send(NetworkMsg::Propagate(PropagateMsg::Gossip(peer, gossip)))
.unwrap_or_else(|e| {
tracing::error!(
... | Rust | 0 |
os.makedirs('./plots')
fig, axs = plt.subplots(8, 1, figsize=(20, 8))
theta_space = ["S%d" % i for i in range(model.k_min)]
sns.barplot(x=theta_space, y=model.beta, ax=axs[0])
axs[0].set_ylabel("G")
axs[0].set_ylim(0, 0.5)
for i in range(1, 8):
sns.barplot(x=theta_space, y=mode... | Python | 1 |
# This file was auto-generated by Fern from our API Definition.
from .types import CreateEmbedJobRequestTruncate
__all__ = ["CreateEmbedJobRequestTruncate"]
| Python | 1 |
);
let po = PlaneOffset {
x: (bo_adj.x as isize) << BLOCK_TO_PLANE_SHIFT >> 2,
y: (bo_adj.y as isize) << BLOCK_TO_PLANE_SHIFT >> 2
};
let range = 64 * fi.me_range_scale as isize;
let (mvx_min, mvx_max, mvy_min, mvy_max) = get_mv_range(fi, &bo_adj, blk_w, blk_h);
let x_lo = po.x + (((-ran... | Rust | 0 |
ed in decimal degrees)
Parameters
----------
x : array, shape=(n_samples, 2)
the first list of coordinates (degrees)
y : array: shape=(n_samples, 2)
the second list of coordinates (degress)
Returns
-------
d : array, shape=(n_samples,)
the distance between corrdinates (km... | Python | 1 |
nfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
root_doc,
"PyDrive2",
"PyDrive2 Documentation",
author,
"PyDrive2",
"One line description of project.",
"Miscellaneous... | Python | 1 |
ST } else { HWND_TOP },
0,
0,
0,
0,
SWP_NOMOVE | SWP_NOSIZE,
))?;
}
Ok(())
}
pub fn remove_topmost(&self) -> Result<(), util::WinApiResultError> {
unsafe {
util::winapi_nullable_to_re... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.