file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
keys.rs | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long... |
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Value {
Escape,
Enter,
Down,
Up,
Left,
Right,
PageUp,
PageDown,
BackSpace,
BackTab,
Tab,
Delete,
Insert,
Home,
End,
Begin,
F(u8),
Char(char),
}
pub use self::Value::*;
impl Keys {
pub fn new(info: &info::Database) -> Self {
let mut map =... | Modifier::empty()
}
} | identifier_body |
keys.rs | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long... |
pub modifier: Modifier,
pub value: Value,
}
bitflags! {
pub struct Modifier: u8 {
const NONE = 0;
const ALT = 1 << 0;
const CTRL = 1 << 1;
const LOGO = 1 << 2;
const SHIFT = 1 << 3;
}
}
impl Default for Modifier {
fn default() -> Self {
Modifier::empty()
}
}
#[derive(Eq, PartialEq, Copy, C... | y { | identifier_name |
keys.rs | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long... | }));
}
let mut mods = Modifier::empty();
if input[0] == 0x1B {
mods.insert(Modifier::ALT);
input = &input[1..];
}
// Check if it's a control character.
if input[0] & 0b011_00000 == 0 {
return (&input[1..], Some(Key {
modifier: mods | Modifier::CTRL,
value: Char((input[0] | 0b010_00... | // Check if it's a single escape press.
if input == &[0x1B] {
return (&input[1..], Some(Key {
modifier: Modifier::empty(),
value: Escape, | random_line_split |
lib.rs | //! This crate provides an implementation of Chan-Vese level-sets
//! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/)
//! by T. Chan and L. Vese.
//! It is a port of the Python implementation by Kevin Keraudren on
//! [Github](https://github.com/kevin-keraudren/chanvese)
//! an... |
else {
0
}
}
| {
c + 1
} | conditional_block |
lib.rs | //! This crate provides an implementation of Chan-Vese level-sets
//! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/)
//! by T. Chan and L. Vese.
//! It is a port of the Python implementation by Kevin Keraudren on
//! [Github](https://github.com/kevin-keraudren/chanvese)
//! an... |
// Compute curvature along SDF
fn get_curvature(phi: &FloatGrid, idx: &Vec<(usize,usize)>) -> Vec<f64> {
// get central derivatives of SDF at x,y
let (phi_x, phi_y, phi_xx, phi_yy, phi_xy) = {
let (mut res_x, mut res_y, mut res_xx, mut res_yy, mut res_xy)
: (Vec<f64>, Vec<f64>, Vec<f64>, V... | {
let inv_init_a = {
let mut result = init_a.clone();
for (_, _, value) in result.iter_mut() {
*value = !*value;
}
result
};
let phi = {
let dist_a = bwdist(&init_a);
let dist_inv_a = bwdist(&inv_init_a);
let mut result = FloatGrid::new(in... | identifier_body |
lib.rs | //! This crate provides an implementation of Chan-Vese level-sets
//! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/)
//! by T. Chan and L. Vese.
//! It is a port of the Python implementation by Kevin Keraudren on
//! [Github](https://github.com/kevin-keraudren/chanvese)
//! an... |
for y in 0..grid.height() {
for x in 0..grid.width() {
let a_p_dval = *a.get(x, y).unwrap();
let a_n_dval = *a.get(x, y).unwrap();
let b_p_dval = *b.get(x, y).unwrap();
let b_n_dval = *b.get(x, y).unwrap();
let c_p_dval... | let mut d_n_res = FloatGrid::new(grid.width(), grid.height()); | random_line_split |
lib.rs | //! This crate provides an implementation of Chan-Vese level-sets
//! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/)
//! by T. Chan and L. Vese.
//! It is a port of the Python implementation by Kevin Keraudren on
//! [Github](https://github.com/kevin-keraudren/chanvese)
//! an... | (d: &FloatGrid) -> FloatGrid {
let mut res = FloatGrid::new(d.width(), d.height());
for (x, y, value) in res.iter_mut() {
let v = d.get(x, y).unwrap();
*value = v/(v*v + 1.).sqrt();
}
res
}
// Convergence test
fn convergence(p_mask: &BoolGrid,
n_mask: &BoolGrid,
... | sussman_sign | identifier_name |
controller.rs | //! Contains ZX Spectrum System contrller (like ula or so) of emulator
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
// use almost everything :D
use utils::{split_word, Clocks};
use utils::screen::*;
use utils::events::*;
use utils::InstantFlag;
use z80::Z80Bus;
use zx::{ZXMemory, RomType, RamT... | fn frame_pos(&self) -> f64 {
let val = self.frame_clocks.count() as f64 / self.machine.specs().clocks_frame as f64;
if val > 1.0 {
1.0
} else {
val
}
}
/// loads rom from file
/// for 128-K machines path must contain ".0" in the tail
/// and s... | out
}
/// returns current frame emulation pos in percents | random_line_split |
controller.rs | //! Contains ZX Spectrum System contrller (like ula or so) of emulator
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
// use almost everything :D
use utils::{split_word, Clocks};
use utils::screen::*;
use utils::events::*;
use utils::InstantFlag;
use z80::Z80Bus;
use zx::{ZXMemory, RomType, RamT... |
/// check events count
pub fn no_events(&self) -> bool {
self.events.is_empty()
}
/// Returns last event
pub fn pop_event(&mut self) -> Option<Event> {
self.events.receive_event()
}
/// Returns true if all frame clocks has been passed
pub fn frames_count(&self) -> usi... | {
self.events.clear();
} | identifier_body |
controller.rs | //! Contains ZX Spectrum System contrller (like ula or so) of emulator
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
// use almost everything :D
use utils::{split_word, Clocks};
use utils::screen::*;
use utils::events::*;
use utils::InstantFlag;
use z80::Z80Bus;
use zx::{ZXMemory, RomType, RamT... |
return 0xFF;
}
/// make contention
fn do_contention(&mut self) {
let contention = self.machine.contention_clocks(self.frame_clocks);
self.wait_internal(contention);
}
///make contention + wait some clocks
fn do_contention_and_wait(&mut self, wait_time: Clocks) {
... | {
if clocks % 2 == 0 {
return self.memory.read(bitmap_line_addr(row) + col as u16);
} else {
let byte = (row / 8) * 32 + col;
return self.memory.read(0x5800 + byte as u16);
};
} | conditional_block |
controller.rs | //! Contains ZX Spectrum System contrller (like ula or so) of emulator
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
// use almost everything :D
use utils::{split_word, Clocks};
use utils::screen::*;
use utils::events::*;
use utils::InstantFlag;
use z80::Z80Bus;
use zx::{ZXMemory, RomType, RamT... | (&mut self, port: u16) {
if self.addr_is_contended(port) {
self.do_contention();
};
self.wait_internal(Clocks(1));
}
/// Returns late IO contention clocks
fn io_contention_last(&mut self, port: u16) {
if self.machine.port_is_contended(port) {
self.do_... | io_contention_first | identifier_name |
storage.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
smoke_test_environment::new_local_swarm,
test_utils::{
assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins,
},
workspace_builder,
workspace_builder::workspa... |
transfer_coins(client, transaction_factory, account0, account1, 1);
}
Ok(())
}
| {
let current_version = client.get_metadata()?.into_inner().diem_version.unwrap();
let txn = root_account.sign_with_transaction_builder(
transaction_factory.update_diem_version(0, current_version + 1),
);
client.submit(&txn)?;
client.wait_for_s... | conditional_block |
storage.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
smoke_test_environment::new_local_swarm,
test_utils::{
assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins,
},
workspace_builder,
workspace_builder::workspa... |
pub(crate) fn db_restore(backup_path: &Path, db_path: &Path, trusted_waypoints: &[Waypoint]) {
let now = Instant::now();
let bin_path = workspace_builder::get_bin("db-restore");
let metadata_cache_path = TempPath::new();
metadata_cache_path.create_as_dir().unwrap();
let mut cmd = Command::new(bi... | {
let now = Instant::now();
let bin_path = workspace_builder::get_bin("db-backup");
let metadata_cache_path1 = TempPath::new();
let metadata_cache_path2 = TempPath::new();
let backup_path = TempPath::new();
metadata_cache_path1.create_as_dir().unwrap();
metadata_cache_path2.create_as_dir().... | identifier_body |
storage.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
smoke_test_environment::new_local_swarm,
test_utils::{
assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins,
},
workspace_builder,
workspace_builder::workspa... | (
client: &BlockingClient,
transaction_factory: &TransactionFactory,
root_account: &mut LocalAccount,
account0: &mut LocalAccount,
account1: &LocalAccount,
transfers: usize,
) -> Result<()> {
for _ in 0..transfers {
if random::<u16>() % 10 == 0 {
let current_version = cli... | transfer_and_reconfig | identifier_name |
storage.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
smoke_test_environment::new_local_swarm,
test_utils::{
assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins,
},
workspace_builder,
workspace_builder::workspa... |
fn wait_for_backups(
target_epoch: u64,
target_version: u64,
now: Instant,
bin_path: &Path,
metadata_cache_path: &Path,
backup_path: &Path,
trusted_waypoints: &[Waypoint],
) -> Result<()> {
for _ in 0..60 {
// the verify should always succeed.
db_backup_verify(backup_pat... | if !output.status.success() {
panic!("db-backup-verify failed, output: {:?}", output);
}
println!("Backup verified in {} seconds.", now.elapsed().as_secs());
} | random_line_split |
lib.rs | use crossbeam_channel as channel;
use indexmap::IndexMap as Map;
use isahc::{
config::{Configurable, RedirectPolicy},
HttpClient,
};
use once_cell::sync::Lazy;
use onig::Regex;
use rayon::prelude::*;
use select::{
document::Document,
predicate::{Class, Name},
};
use std::{
borrow::Cow,
env,
... | }
}
} | random_line_split | |
lib.rs | use crossbeam_channel as channel;
use indexmap::IndexMap as Map;
use isahc::{
config::{Configurable, RedirectPolicy},
HttpClient,
};
use once_cell::sync::Lazy;
use onig::Regex;
use rayon::prelude::*;
use select::{
document::Document,
predicate::{Class, Name},
};
use std::{
borrow::Cow,
env,
... | (output_dir: &Path) -> Cow<'_, Path> {
use std::fs;
use std::os::unix::fs::MetadataExt;
let os_tmp = env::temp_dir();
match (
fs::metadata(output_dir).map(|v| v.dev()),
fs::metadata(&os_tmp).map(|v| v.dev()),
) {
(Ok(num1), Ok(num2)) if num1 =... | get_tmp_dir | identifier_name |
lib.rs | use crossbeam_channel as channel;
use indexmap::IndexMap as Map;
use isahc::{
config::{Configurable, RedirectPolicy},
HttpClient,
};
use once_cell::sync::Lazy;
use onig::Regex;
use rayon::prelude::*;
use select::{
document::Document,
predicate::{Class, Name},
};
use std::{
borrow::Cow,
env,
... |
}
}
Ok(node.text())
})
});
match result {
... | {
return Err("Not a valid NPC ID".into());
} | conditional_block |
mmio.rs | #![cfg_attr(rustfmt, rustfmt::skip)]
//! Contains all the MMIO address definitions for the GBA's components.
//!
//! This module contains *only* the MMIO addresses. The data type definitions
//! for each MMIO control value are stored in the appropriate other modules such
//! as [`video`](crate::video), [`interrupts`](... |
// Timers
def_mmio!(0x0400_0100 = TIMER0_COUNT/["TM0CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 0 Count read");
def_mmio!(0x0400_0100 = TIMER0_RELOAD/["TM0CNT_L"]: VolAddress<u16, (), Safe>; "Timer 0 Reload write");
def_mmio!(0x0400_0102 = TIMER0_CONTROL/["TM0CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 0 con... | def_mmio!(0x0400_00DE = DMA3_CONTROL/["DMA3_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA3 Control Bits"); | random_line_split |
mmio.rs | #![cfg_attr(rustfmt, rustfmt::skip)]
//! Contains all the MMIO address definitions for the GBA's components.
//!
//! This module contains *only* the MMIO addresses. The data type definitions
//! for each MMIO control value are stored in the appropriate other modules such
//! as [`video`](crate::video), [`interrupts`](... |
#[inline]
#[must_use]
#[cfg_attr(feature="track_caller", track_caller)]
pub const fn obj_palbank(bank: usize) -> VolBlock<Color, Safe, Safe, 16> {
let u = OBJ_PALETTE.index(bank * 16).as_usize();
unsafe { VolBlock::new(u) }
}
// Video RAM (VRAM)
/// The VRAM byte offset per screenblock index.
///
/// This is th... | {
let u = BG_PALETTE.index(bank * 16).as_usize();
unsafe { VolBlock::new(u) }
} | identifier_body |
mmio.rs | #![cfg_attr(rustfmt, rustfmt::skip)]
//! Contains all the MMIO address definitions for the GBA's components.
//!
//! This module contains *only* the MMIO addresses. The data type definitions
//! for each MMIO control value are stored in the appropriate other modules such
//! as [`video`](crate::video), [`interrupts`](... | (bank: usize) -> VolBlock<Color, Safe, Safe, 16> {
let u = OBJ_PALETTE.index(bank * 16).as_usize();
unsafe { VolBlock::new(u) }
}
// Video RAM (VRAM)
/// The VRAM byte offset per screenblock index.
///
/// This is the same for all background types and sizes.
pub const SCREENBLOCK_INDEX_OFFSET: usize = 2 * 1_024;... | obj_palbank | identifier_name |
domain_models.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
import re
import structlog
from flask import current_app
from inspire_service_orcid ... | (
self,
orcid,
recid,
oauth_token,
pushing_duplicated_identifier=False,
record_db_version=None,
):
self.orcid = orcid
self.recid = str(recid)
self.oauth_token = oauth_token
self.pushing_duplicated_identifier = pushing_duplicated_identif... | __init__ | identifier_name |
domain_models.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details. | from flask import current_app
from inspire_service_orcid import exceptions as orcid_client_exceptions
from inspire_service_orcid.client import OrcidClient
from invenio_db import db
from invenio_pidstore.errors import PIDDoesNotExistError
from time_execution import time_execution
from inspirehep.records.api import Lite... |
import re
import structlog | random_line_split |
domain_models.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
import re
import structlog
from flask import current_app
from inspire_service_orcid ... |
return self.inspire_record.get("deleted", False)
@time_execution
def push(self): # noqa: C901
putcode = None
if not self._do_force_cache_miss:
putcode = self.cache.read_work_putcode()
if not self._is_record_deleted and not self.cache.has_work_content_changed(
... | LOGGER.debug(
"OrcidPusher force delete", recid=self.recid, orcid=self.orcid
)
return True | conditional_block |
domain_models.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
import re
import structlog
from flask import current_app
from inspire_service_orcid ... |
@time_execution
def _delete_work(self, putcode=None):
putcode = putcode or self._cache_all_author_putcodes()
if not putcode:
# Such recid does not exists (anymore?) in ORCID API.
return
# ORCID API allows 1 non-idempotent call only for the same orcid at
... | LOGGER.debug("New OrcidPusher cache all author putcodes", orcid=self.orcid)
if not self.cached_author_putcodes:
putcode_getter = OrcidPutcodeGetter(self.orcid, self.oauth_token)
putcodes_recids = list(
putcode_getter.get_all_inspire_putcodes_and_recids_iter()
... | identifier_body |
lib.rs | //! This crate adds support for subscriptions as defined in [here].
//!
//! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB
extern crate futures;
extern crate jsonrpc_client_core;
extern crate jsonrpc_client_utils;
#[macro_use]
extern crate serde;
extern crate serde_json;
extern crate tokio;
#[macro_... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
SubscriptionId::Num(n) => write!(f, "{}", n),
SubscriptionId::String(s) => write!(f, "{}", s),
}
}
}
#[derive(Debug)]
enum SubscriberMsg {
NewMessage(SubscriptionMessage),
NewSubscriber(SubscriptionId, mps... | fmt | identifier_name |
lib.rs | //! This crate adds support for subscriptions as defined in [here].
//!
//! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB
extern crate futures;
extern crate jsonrpc_client_core;
extern crate jsonrpc_client_utils;
#[macro_use]
extern crate serde;
extern crate serde_json;
extern crate tokio;
#[macro_... |
_ => true,
},
}
}
}
impl Future for NotificationHandler {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
while self.ready_for_next_connection() {
match self.messages.poll()? {
Async::NotReady => {
... | {
self.current_future = Some(fut);
false
} | conditional_block |
lib.rs | //! This crate adds support for subscriptions as defined in [here]. | extern crate jsonrpc_client_utils;
#[macro_use]
extern crate serde;
extern crate serde_json;
extern crate tokio;
#[macro_use]
extern crate log;
#[macro_use]
extern crate error_chain;
use futures::{future, future::Either, sync::mpsc, Async, Future, Poll, Sink, Stream};
use jsonrpc_client_core::server::{
types::... | //!
//! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB
extern crate futures;
extern crate jsonrpc_client_core; | random_line_split |
boxed.rs | #![allow(unsafe_code)]
use crate::ffi::sodium;
use crate::traits::*;
use std::cell::Cell;
use std::fmt::{self, Debug};
use std::ptr::NonNull;
use std::slice;
use std::thread;
/// The page protection applied to the memory underlying a [`Box`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Prot {
/// Any attem... |
#[test]
#[should_panic(expected = "secrets: releases exceeded retains")]
fn it_doesnt_allow_unbalanced_locking() {
let boxed = Box::<u64>::zero(4);
let _ = boxed.unlock();
boxed.lock();
boxed.lock();
}
#[test]
#[should_panic(expected = "secrets: cannot unloc... | #[should_panic(expected = "secrets: releases exceeded retains")]
fn it_doesnt_allow_negative_users() {
Box::<u64>::zero(10).lock();
} | random_line_split |
boxed.rs | #![allow(unsafe_code)]
use crate::ffi::sodium;
use crate::traits::*;
use std::cell::Cell;
use std::fmt::{self, Debug};
use std::ptr::NonNull;
use std::slice;
use std::thread;
/// The page protection applied to the memory underlying a [`Box`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Prot {
/// Any attem... |
#[test]
fn it_initializes_with_zero_refs() {
let boxed = Box::<u8>::zero(10);
assert_eq!(0, boxed.refs.get());
}
#[test]
fn it_tracks_ref_counts_accurately() {
let mut boxed = Box::<u8>::random(10);
let _ = boxed.unlock();
let _ = boxed.unlock();
... | {
let boxed_1 = Box::<u8>::from(&mut [0, 0, 0, 0][..]);
let boxed_2 = Box::<u8>::from(&mut [0, 0, 0, 0, 0][..]);
assert_ne!(boxed_1, boxed_2);
assert_ne!(boxed_2, boxed_1);
} | identifier_body |
boxed.rs | #![allow(unsafe_code)]
use crate::ffi::sodium;
use crate::traits::*;
use std::cell::Cell;
use std::fmt::{self, Debug};
use std::ptr::NonNull;
use std::slice;
use std::thread;
/// The page protection applied to the memory underlying a [`Box`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Prot {
/// Any attem... | (&self) {
// When releasing, we should always have at least one retain
// outstanding. This is enforced by all users through
// refcounting on allocation and drop.
proven!(self.refs.get() != 0,
"secrets: releases exceeded retains");
// When releasing, our protection ... | release | identifier_name |
boxed.rs | #![allow(unsafe_code)]
use crate::ffi::sodium;
use crate::traits::*;
use std::cell::Cell;
use std::fmt::{self, Debug};
use std::ptr::NonNull;
use std::slice;
use std::thread;
/// The page protection applied to the memory underlying a [`Box`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Prot {
/// Any attem... |
}
/// Returns true if the protection level is [`NoAccess`]. Ignores
/// ref count.
fn is_locked(&self) -> bool {
self.prot.get() == Prot::NoAccess
}
}
impl<T: Bytes + Randomizable> Box<T> {
/// Instantiates a new [`Box`] with crypotgraphically-randomized
/// contents.
pub(crat... | {
mprotect(self.ptr.as_ptr(), Prot::NoAccess);
self.prot.set(Prot::NoAccess);
} | conditional_block |
route.go | // Copyright (c) 2018 Cisco and/or its 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 applicabl... | (key string, route *l3.Route) (metadata interface{}, err error) {
err = d.routeHandler.VppAddRoute(context.TODO(), route)
if err != nil {
return nil, err
}
return nil, nil
}
// Delete removes VPP static route.
func (d *RouteDescriptor) Delete(key string, route *l3.Route, metadata interface{}) error {
err := d.... | Create | identifier_name |
route.go | // Copyright (c) 2018 Cisco and/or its 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 applicabl... | Key: l3.VrfTableKey(route.ViaVrfId, protocol),
})
}
// if destination network is netalloc reference, then the address must be allocated first
allocDep, hasAllocDep := d.addrAlloc.GetAddressAllocDep(route.DstNetwork,
"", "dst_network-")
if hasAllocDep {
dependencies = append(dependencies, allocDep)
}
/... | })
}
if route.Type == l3.Route_INTER_VRF && route.ViaVrfId != 0 {
dependencies = append(dependencies, kvs.Dependency{
Label: viaVrfTableDep, | random_line_split |
route.go | // Copyright (c) 2018 Cisco and/or its 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 applicabl... |
a1 := net.ParseIP(addr1)
a2 := net.ParseIP(addr2)
if a1 == nil || a2 == nil {
// if parsing fails, compare as strings
return strings.EqualFold(addr1, addr2)
}
return a1.Equal(a2)
}
// getGwAddr returns the GW address chosen in the given route, handling the cases
// when it is left undefined.
func getGwAddr(r... | {
return addr1 == addr2
} | conditional_block |
route.go | // Copyright (c) 2018 Cisco and/or its 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 applicabl... |
// Dependencies lists dependencies for a VPP route.
func (d *RouteDescriptor) Dependencies(key string, route *l3.Route) []kvs.Dependency {
var dependencies []kvs.Dependency
// the outgoing interface must exist and be UP
if route.OutgoingInterface != "" {
dependencies = append(dependencies, kvs.Dependency{
Lab... | {
// prepare expected configuration with de-referenced netalloc links
nbCfg := make(map[string]*l3.Route)
expCfg := make(map[string]*l3.Route)
for _, kv := range correlate {
dstNetwork := kv.Value.DstNetwork
parsed, err := d.addrAlloc.GetOrParseIPAddress(kv.Value.DstNetwork,
"", netalloc_api.IPAddressForm_AD... | identifier_body |
models.py | from datetime import timedelta
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils import timezone
from django.utils.functional import cached_property
from .util import random_number_token
class DeviceMana... |
@property
def persistent_id(self):
"""
A stable device identifier for forms and APIs.
"""
return '{0}/{1}'.format(self.model_label(), self.id)
@classmethod
def model_label(cls):
"""
Returns an identifier for this Django model class.
This is jus... | try:
user = self.user
except ObjectDoesNotExist:
user = None
return "{0} ({1})".format(self.name, user) | identifier_body |
models.py | from datetime import timedelta
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils import timezone
from django.utils.functional import cached_property
from .util import random_number_token
class DeviceMana... |
:param str token: The OTP token provided by the user.
:rtype: bool
"""
_now = timezone.now()
if (
(self.token is not None)
and (token == self.token)
and (_now < self.valid_until)
):
self.token = None
self.vali... | random_line_split | |
models.py | from datetime import timedelta
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils import timezone
from django.utils.functional import cached_property
from .util import random_number_token
class DeviceMana... | (models.Model):
"""
Abstract base model for a :term:`device` attached to a user. Plugins must
subclass this to define their OTP models.
.. _unsaved_device_warning:
.. warning::
OTP devices are inherently stateful. For example, verifying a token is
logically a mutating operation on... | Device | identifier_name |
models.py | from datetime import timedelta
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils import timezone
from django.utils.functional import cached_property
from .util import random_number_token
class DeviceMana... |
device = device_set.first()
except (ValueError, LookupError):
pass
return device
def is_interactive(self):
"""
Returns ``True`` if this is an interactive device. The default
implementation returns ``True`` if
:meth:`~django_otp.models.De... | device_set = device_set.select_for_update() | conditional_block |
NetHandler.ts | import { Global as G } from "System/global";
import { Macros } from 'System/protocol/Macros'
import { Profiler } from "System/utils/Profiler"
export enum EnumNetId {
base = 1,
cross,
}
enum ConnectStatus {
none = 0, // 空闲
connecting = 1, // 正在连接
connected = 2, // 已连接
closed = 3, // 已关闭
... | his.close();
// 多个url用|分开
this.ips = ips;
this.hostList = ips.split("|");
//先暂时定为一个
this.port = port;
let hostCount: number = this.hostList.length;
// 创建ping
let curSocketCnt: number = this.sockets.length;
for (let i = 0; i < hostCount - curSocke... | ,不能list两次role,所以每次都要断开重连
t | identifier_body |
NetHandler.ts | import { Global as G } from "System/global";
import { Macros } from 'System/protocol/Macros'
import { Profiler } from "System/utils/Profiler"
export enum EnumNetId {
base = 1,
cross,
}
enum ConnectStatus {
none = 0, // 空闲
connecting = 1, // 正在连接
connected = 2, // 已连接
closed = 3, // 已关闭
... | this.onDisconnectCallback();
}
}
}
private onRecv(id: number, data: any, size: number, busy: boolean) {
if (null != this.workSocket && this.workSocket.Id == id) {
let msgid = G.Dr.msgid(data, size);
if (msgid < 0) {
uts.bugRepo... | if (null != this.onDisconnectCallback) { | random_line_split |
NetHandler.ts | import { Global as G } from "System/global";
import { Macros } from 'System/protocol/Macros'
import { Profiler } from "System/utils/Profiler"
export enum EnumNetId {
base = 1,
cross,
}
enum ConnectStatus {
none = 0, // 空闲
connecting = 1, // 正在连接
connected = 2, // 已连接
closed = 3, // 已关闭
... | Socket.send(G.Dr.packBuf(), packlen);
// 记录发送时间
if (Macros.MsgID_SyncTime_Request == msgId) {
// 将延迟设置为0
this.sendTimeStatArray.push(UnityEngine.Time.realtimeSinceStartup);
}
}
private onConnect(id: number, isSuccess: boolean, reason: number) {
if (null ... | rn;
}
this.work | conditional_block |
NetHandler.ts | import { Global as G } from "System/global";
import { Macros } from 'System/protocol/Macros'
import { Profiler } from "System/utils/Profiler"
export enum EnumNetId {
base = 1,
cross,
}
enum ConnectStatus {
none = 0, // 空闲
connecting = 1, // 正在连接
connected = 2, // 已连接
closed = 3, // 已关闭
... | s.status = ConnectStatus.closed;
this.host = null;
this.port = 0;
}
send(data: any, size: number) {
this.tcp.send(data, size);
}
private doConnect() {
this.curTryTimes++;
this.tcp.close();
this.tcp.connect(this.host, this.port, 5000 * 4); // 20 seconds ... | thi | identifier_name |
zsy_3pandas.py | from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 带有索引的numpy1
# obj = Series([4, 7, -5, 3])
# print(obj)
# print(obj.values)
# print(obj.index)
# 2
# obj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
# print(obj2)
# print(obj2.index)
# print(obj2['a'])
... | eturn Series([x.min(), x.max()], index=['min', 'max'])
# print(frame.apply(f))
format = lambda x: '%.2f' % x
# print(frame.applymap(format))
# print(frame['e'].map(format))
# 13
obj = Series(range(4), index=['d', 'a', 'b', 'c'])
# print(obj)
# print(obj.sort_index())
frame = DataFrame(np.arange(8).reshape((2, 4)), ind... | r | identifier_name |
zsy_3pandas.py | from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 带有索引的numpy1
# obj = Series([4, 7, -5, 3])
# print(obj)
# print(obj.values)
# print(obj.index)
# 2
# obj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
# print(obj2)
# print(obj2.index)
# print(obj2['a'])
... | rame.apply(f))
format = lambda x: '%.2f' % x
# print(frame.applymap(format))
# print(frame['e'].map(format))
# 13
obj = Series(range(4), index=['d', 'a', 'b', 'c'])
# print(obj)
# print(obj.sort_index())
frame = DataFrame(np.arange(8).reshape((2, 4)), index=['three', 'one'],
columns=['d', 'a', 'b', '... | ies([x.min(), x.max()], index=['min', 'max'])
# print(f | identifier_body |
zsy_3pandas.py | from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 带有索引的numpy1
# obj = Series([4, 7, -5, 3])
# print(obj)
# print(obj.values)
# print(obj.index)
# 2
# obj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
# print(obj2)
# print(obj2.index)
# print(obj2['a'])
... | # 22
frame = DataFrame({'a': range(7), 'b': range(7, 0, -1),
'c': ['one', 'one', 'one', 'two', 'two', 'two', 'two'],
'd': [0, 1, 2, 0, 1, 2, 3]})
# print(frame)
frame2 = frame.set_index(['c', 'd'])
# print(frame2)
# print(frame.set_index(['c', 'd'], drop=False))
# print(frame2.rese... | random_line_split | |
movement.py | #Libraries
import time
from adafruit_servokit import ServoKit
import curses
import adafruit_bno055
from adafruit_extended_bus import ExtendedI2C as I2C
import busio
import board
import pynmea2
import serial
from math import sin, cos, sqrt, atan2, radians, degrees
import numpy as np
import csv
import inspect
import pyre... |
pipeline.stop()
return
##############EXTEDNDED KALMAN FILTER CODE#########################################
# A matrix
# 3x3 matrix -> number of states x number of states matrix
# Expresses how the state of the system [x,y,yaw] changes
# from k-1 to k when no control command is executed.
# Typically ... | depth = frames.get_depth_frame()
for y in range(0,480,40):
for x in range(0,600,40):
dist = depth.get_distance(x,y)
if y == 480:
pipeline.stop()
return
if dist > 0.1 and dist < 1:
... | conditional_block |
movement.py | #Libraries
import time
from adafruit_servokit import ServoKit
import curses
import adafruit_bno055
from adafruit_extended_bus import ExtendedI2C as I2C
import busio
import board
import pynmea2
import serial
from math import sin, cos, sqrt, atan2, radians, degrees
import numpy as np
import csv
import inspect
import pyre... | # Get ready for the next timestep by updating the variable values
state_estimate_k_minus_1 = optimal_state_estimate_k
P_k_minus_1 = covariance_estimate_k
#get and calculate the bearing the rover should be heading
desired_lat, desired_lon = gpsread(count)
... | random_line_split | |
movement.py | #Libraries
import time
from adafruit_servokit import ServoKit
import curses
import adafruit_bno055
from adafruit_extended_bus import ExtendedI2C as I2C
import busio
import board
import pynmea2
import serial
from math import sin, cos, sqrt, atan2, radians, degrees
import numpy as np
import csv
import inspect
import pyre... |
def forward():
print("forward\r\n")
pca.servo[LeftMotor].angle = 97 #forward above 80 reverse below 15
pca.servo[RightMotor].angle = 50 #forward below 50 reverse above 50
pca.servo[Blower].angle = Max_Speed
time.sleep(0.05)
def left():
print("left\r\n")
pca.servo[LeftMoto... | print("starting manual movement\n")
print("press wasd to control the movement\n")
try:
while True:
key = stdscr.getch()
#Forward
if key == ord('w'):
forward()
#Move Left
elif key == ord('a'):
left()
#... | identifier_body |
movement.py | #Libraries
import time
from adafruit_servokit import ServoKit
import curses
import adafruit_bno055
from adafruit_extended_bus import ExtendedI2C as I2C
import busio
import board
import pynmea2
import serial
from math import sin, cos, sqrt, atan2, radians, degrees
import numpy as np
import csv
import inspect
import pyre... | ():
print("right\r\n")
pca.servo[LeftMotor].angle = 95
pca.servo[RightMotor].angle = 95
pca.servo[Blower].angle = Max_Speed
time.sleep(0.05)
def reverse():
print("reverse\r\n")
pca.servo[LeftMotor].angle = 50
pca.servo[RightMotor].angle = 97
pca.servo[Blower].angle = Max_Speed
t... | right | identifier_name |
model.py | from sklearn import preprocessing
from random import shuffle
import numpy as np
import collections
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from tensorflow.keras.layers import Dense, Dropout, Activation, Conv1D, GlobalMaxPooling1D
from tensorflow.keras.models import Sequential, model_from_json
from t... | Get word embeddings for the training data.
'''
shuffle(dataset)
data = [s['data'] for s in dataset]
#labels = [s['label'] for s in dataset]
labels = [[s['label']] for s in dataset]
#le_encoder = preprocessing.LabelEncoder()
if le_encoder is None:
... | random_line_split | |
model.py | from sklearn import preprocessing
from random import shuffle
import numpy as np
import collections
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from tensorflow.keras.layers import Dense, Dropout, Activation, Conv1D, GlobalMaxPooling1D
from tensorflow.keras.models import Sequential, model_from_json
from t... |
def load(path):
print(f'loading model from {path}')
structure_file = os.path.join(path, 'structure.json')
weight_file = os.path.join(path, 'weight.h5')
labels_file = os.path.join(path, 'classes.npy')
with open(structure_file, "r") as json_file:
json_string = json_file.read()
model... | '''
save model based on model, encoder
'''
if not os.path.exists(path):
os.makedirs(path, exist_ok=True)
print(f'saving model to {path}')
structure_file = os.path.join(path, 'structure.json')
weight_file = os.path.join(path, 'weight.h5')
labels_file = os.path.join(path, 'classes')
... | identifier_body |
model.py | from sklearn import preprocessing
from random import shuffle
import numpy as np
import collections
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from tensorflow.keras.layers import Dense, Dropout, Activation, Conv1D, GlobalMaxPooling1D
from tensorflow.keras.models import Sequential, model_from_json
from t... | (self, dataset, le_encoder=None):
'''
Preprocess the dataset, transform the categorical labels into numbers.
Get word embeddings for the training data.
'''
shuffle(dataset)
data = [s['data'] for s in dataset]
#labels = [s['label'] for s in dataset]
labels ... | __preprocess | identifier_name |
model.py | from sklearn import preprocessing
from random import shuffle
import numpy as np
import collections
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from tensorflow.keras.layers import Dense, Dropout, Activation, Conv1D, GlobalMaxPooling1D
from tensorflow.keras.models import Sequential, model_from_json
from t... |
new_data.append(temp)
return new_data
def save(model, le, path, history):
'''
save model based on model, encoder
'''
if not os.path.exists(path):
os.makedirs(path, exist_ok=True)
print(f'saving model to {path}')
structure_file = os.path.join(path, 'structure.json')
we... | temp = sample | conditional_block |
mod.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... | (
account: sr25519::Pair,
shard: ShardIdentifier,
direct_client: &DirectClient,
) -> Index {
let getter = Getter::trusted(
TrustedGetter::nonce(account.public().into()).sign(&KeyPair::Sr25519(account.clone())),
);
let getter_start_timer = Instant::now();
let getter_result = get_state(direct_client, shard, &ge... | get_nonce | identifier_name |
mod.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... |
// Create new account.
let account_keys: sr25519::AppPair = store.generate().unwrap();
let new_account =
get_pair_from_str(trusted_args, account_keys.public().to_string().as_str());
println!(" Transfer amount: {}", EXISTENTIAL_DEPOSIT);
println!(" From: {:?}", client.account.public(... | {
random_wait(random_wait_before_transaction_ms);
} | conditional_block |
mod.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... |
output
})
.collect();
println!(
"Finished benchmark with {} clients and {} transactions in {} ms",
self.number_clients,
self.number_iterations,
overall_start.elapsed().as_millis()
);
print_benchmark_statistic(outputs, self.wait_for_confirmation)
}
}
fn get_balance(
account: sr25519::Pa... | break;
}
}
client.client_api.close().unwrap(); | random_line_split |
app.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
from scipy.misc import comb
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler,LabelEncoder
from sklearn.model_selection import cross_val_score
from sklearn.... | , 'Alcohol',
'Malic acid', 'Ash',
'Alcalinity of ash',
'Magnesium', 'Total phenols',
'Flavanoids', 'Nonflavanoid phenols',
'Proanthocyanins',
'Color intensity', 'Hue',
... | 315 of diluted wines',
ha='center',va='center',fontsize=12)
plt.show()
############################AdaBoost算法###############################
#
def function5():
from sklearn.ensemble import AdaBoostClassifier
df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/'
'mac... | conditional_block |
app.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
from scipy.misc import comb
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler,LabelEncoder
from sklearn.model_selection import cross_val_score
from sklearn.... |
# 单颗决策树(弱学习机)
tree = tree.fit(X_train,y_train)
y_train_pred = tree.predict(X_train)
y_test_pred = tree.predict(X_test)
tree_train = accuracy_score(y_train, y_train_pred)
tree_test = accuracy_score(y_test, y_test_pred)
print('Decision tree train/test accuracies %.3f/%.3f' % (tree_train, tree... | n_estimators=500,
learning_rate=0.1,
random_state=1) | random_line_split |
app.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
from scipy.misc import comb
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler,LabelEncoder
from sklearn.model_selection import cross_val_score
from sklearn.... | enols',
'Proanthocyanins',
'Color intensity', 'Hue',
'OD280/OD315 of diluted wines',
'Proline']
# drop 1 class
df_wine = df_wine[df_wine['Class label'] != 1]
y = df_wine['Class label'].values
X = df_wine[['Alcoho... | vanoid ph | identifier_name |
app.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
from scipy.misc import comb
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler,LabelEncoder
from sklearn.model_selection import cross_val_score
from sklearn.... | random_state=1)
clf2 = DecisionTreeClassifier(max_depth=1,criterion='entropy',random_state=0)
clf3 = KNeighborsClassifier(n_neighbors=1,p=2,metric='minkowski')
pipe1 = Pipeline([['sc',StandardScaler()],['clf',clf1]])
pipe3 = Pipeline([['sc',StandardScaler()],['clf',clf3]])
mv_clf = MajoritVoteClass... | range,linestyle='--',label='base error',lw='2')
plt.plot(error_range,ens_errors,label='ensemble error',lw='2')
plt.xlabel("base error")
plt.ylabel("base/ensemble error")
plt.legend(loc='upper left')
plt.grid(alpha=0.5)
plt.show()
#################集成分类器---简单投票分类器#################################... | identifier_body |
nargs.go | package nargs
import (
"fmt"
"go/ast"
"go/build"
"go/token"
"log"
"sort"
"strconv"
"strings"
)
func init() {
build.Default.UseAllFiles = true
}
// Flags contains configuration specific to nargs
// * IncludeTests - include test files in analysis
// * SetExitStatus - set exit status to 1 if any issues are fou... | (paramMap map[string]bool, fieldList *ast.FieldList, exprList []ast.Expr, stmtList []ast.Stmt) ([]ast.Expr, []ast.Stmt) {
if fieldList == nil {
return exprList, stmtList
}
for _, field := range fieldList.List {
exprList = append(exprList, field.Type)
handleIdents(paramMap, field.Names)
}
return exprList, st... | handleFieldList | identifier_name |
nargs.go | package nargs
import (
"fmt"
"go/ast"
"go/build"
"go/token"
"log"
"sort"
"strconv"
"strings"
)
func init() {
build.Default.UseAllFiles = true
}
// Flags contains configuration specific to nargs
// * IncludeTests - include test files in analysis
// * SetExitStatus - set exit status to 1 if any issues are fou... |
if v.includeNamedReturns && funcDecl.Type.Results != nil {
for _, paramList := range funcDecl.Type.Results.List {
for _, name := range paramList.Names {
if name.Name == "_" {
continue
}
paramMap[name.Name] = false
}
}
}
}
if v.includeReceivers && funcDecl.Recv != nil {
for ... | {
for _, paramList := range funcDecl.Type.Params.List {
for _, name := range paramList.Names {
if name.Name == "_" {
continue
}
paramMap[name.Name] = false
}
}
} | conditional_block |
nargs.go | package nargs
import (
"fmt"
"go/ast"
"go/build"
"go/token"
"log"
"sort"
"strconv"
"strings"
)
func init() {
build.Default.UseAllFiles = true
}
// Flags contains configuration specific to nargs
// * IncludeTests - include test files in analysis
// * SetExitStatus - set exit status to 1 if any issues are fou... |
// Visit implements the ast.Visitor Visit method.
func (v *unusedVisitor) Visit(node ast.Node) ast.Visitor {
var stmtList []ast.Stmt
var file *token.File
paramMap := make(map[string]bool)
var funcDecl *ast.FuncDecl
switch topLevelType := node.(type) {
case *ast.FuncDecl:
funcDecl = topLevelType
if funcDec... | { a[i], a[j] = a[j], a[i] } | identifier_body |
nargs.go | package nargs
import (
"fmt"
"go/ast"
"go/build"
"go/token"
"log"
"sort"
"strconv"
"strings"
)
func init() {
build.Default.UseAllFiles = true
}
// Flags contains configuration specific to nargs
// * IncludeTests - include test files in analysis
// * SetExitStatus - set exit status to 1 if any issues are fou... | default:
log.Printf("ERROR: unknown spec type %T\n", specType)
}
}
case *ast.FuncDecl:
initialStmts = v.handleFuncDecl(paramMap, d, initialStmts)
default:
log.Printf("ERROR: unknown decl type %T\n", d)
}
}
return initialStmts
}
// paramMap is passed in for cases where we have an outer fun... | // no-op, ImportSpecs do not contain functions
| random_line_split |
raft.go | package raft
//
// this is an outline of the API that raft must expose to
// the service (or tester). see comments below for
// each of these functions for more details.
//
// rf = Make(...)
// create a new Raft server.
// rf.Start(command interface{}) (index, term, isleader)
// start agreement on a new log entry
... | (command interface{}) (int, int, bool) {
index := -1
term := -1
isLeader := true
// Your code here (2B).
rf.mu.Lock()
defer rf.mu.Unlock()
index = rf.commitIndex + 1
term = rf.currentTerm
isLeader = rf.currentState == StateLeader
return index, term, isLeader
}
//
// the tester doesn't halt goroutines creat... | Start | identifier_name |
raft.go | package raft
//
// this is an outline of the API that raft must expose to
// the service (or tester). see comments below for
// each of these functions for more details.
//
// rf = Make(...)
// create a new Raft server.
// rf.Start(command interface{}) (index, term, isleader)
// start agreement on a new log entry
... |
rf.tryEnterFollowState(args.Term)
rf.currentTerm = args.Term
rf.votedFor = args.CandidateId
reply.VoteGranted = true
}
//
// example code to send a RequestVote RPC to a server.
// server is the index of the target server in rf.peers[].
// expects RPC arguments in args.
// fills in *reply with RPC reply, so call... | {
// If this node is more up-to-date than candidate, then reject vote
//DPrintf("Raft node (%v) LastLogIndex: %v, LastLogTerm: %v, args (%v, %v)\n", rf.me,
// lastLogIndex, lastLogEntry.Term, args.LastLogIndex, args.LastLogTerm)
reply.VoteGranted = false
return
} | conditional_block |
raft.go | package raft
//
// this is an outline of the API that raft must expose to
// the service (or tester). see comments below for
// each of these functions for more details.
//
// rf = Make(...)
// create a new Raft server.
// rf.Start(command interface{}) (index, term, isleader)
// start agreement on a new log entry
... |
//
// save Raft's persistent state to stable storage,
// where it can later be retrieved after a crash and restart.
// see paper's Figure 2 for a description of what should be persistent.
//
func (rf *Raft) persist() {
// Your code here (2C).
// Example:
// w := new(bytes.Buffer)
// e := labgob.NewEncoder(w)
// ... | {
//var term int
//var isleader bool
// Your code here (2A).
rf.mu.Lock()
defer rf.mu.Unlock()
return rf.currentTerm, rf.currentState == StateLeader
} | identifier_body |
raft.go | package raft
//
// this is an outline of the API that raft must expose to
// the service (or tester). see comments below for
// each of these functions for more details.
//
// rf = Make(...)
// create a new Raft server.
// rf.Start(command interface{}) (index, term, isleader)
// start agreement on a new log entry
... | // (Initialized to leader last log index + 1)
nextIndex []int
// For each server, index of the highest log entry known to be
// replicated on server
// (Initialized to 0, increases monotonically)
matchIndex []int
// Handle AppendEntriesRPC reply int this channel
appendEntriesReplyHandler chan AppendEntriesRepl... | // Volatile fields on leader, reinitialized after election
//
// For each server, index of the highest log entry to send to that server | random_line_split |
svc.go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package manifest
import (
"errors"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"gopkg.in/yaml.v3"
)
const (
// LoadBalancedWebServiceType is a web service with a load bal... | () bool {
return r.ScalingConfig.IsEmpty() && r.Value == nil
}
// IsEmpty returns whether AdvancedScalingConfig is empty
func (a *AdvancedScalingConfig[_]) IsEmpty() bool {
return a.Cooldown.IsEmpty() && a.Value == nil
}
// IsEmpty returns whether Cooldown is empty
func (c *Cooldown) IsEmpty() bool {
return c.Scal... | IsEmpty | identifier_name |
svc.go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package manifest
import (
"errors"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"gopkg.in/yaml.v3"
)
const (
// LoadBalancedWebServiceType is a web service with a load bal... |
// RangeConfig containers a Min/Max and an optional SpotFrom field which
// specifies the number of services you want to start placing on spot. For
// example, if your range is 1-10 and `spot_from` is 5, up to 4 services will
// be placed on dedicated Fargate capacity, and then after that, any scaling
// event will p... | {
minMax := strings.Split(string(r), "-")
if len(minMax) != 2 {
return 0, 0, fmt.Errorf("invalid range value %s. Should be in format of ${min}-${max}", string(r))
}
min, err = strconv.Atoi(minMax[0])
if err != nil {
return 0, 0, fmt.Errorf("cannot convert minimum value %s to integer", minMax[0])
}
max, err =... | identifier_body |
svc.go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package manifest
import (
"errors"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"gopkg.in/yaml.v3"
)
const (
// LoadBalancedWebServiceType is a web service with a load bal... | if err := value.Decode(&r.Value); err != nil {
return errors.New(`unable to unmarshal into int or composite-style map`)
}
return nil
}
// IsEmpty returns whether Count is empty.
func (c *Count) IsEmpty() bool {
return c.Value == nil && c.AdvancedCount.IsEmpty()
}
// Desired returns the desiredCount to be set on... | return nil
}
| random_line_split |
svc.go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package manifest
import (
"errors"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"gopkg.in/yaml.v3"
)
const (
// LoadBalancedWebServiceType is a web service with a load bal... |
if !r.ScalingConfig.IsEmpty() {
// Successfully unmarshalled ScalingConfig fields, return
return nil
}
if err := value.Decode(&r.Value); err != nil {
return errors.New(`unable to unmarshal into int or composite-style map`)
}
return nil
}
// IsEmpty returns whether Count is empty.
func (c *Count) IsEmpty(... | {
switch err.(type) {
case *yaml.TypeError:
break
default:
return err
}
} | conditional_block |
lib.rs | //! dfconfig is a lib for parsing and manipulating Dwarf Fortress' `init.txt` and `d_init.txt` config files (and possibly many others using the same format).
//! This lib's functionality has been specifically tailored to behave similar as DF internal parser, which implies:
//!
//! * [`Config::get`] returns the last occ... | (&self) -> &str {
&self.value
}
pub fn get_key(&self) -> &str {
&self.key
}
pub fn set_value(&mut self, value: String) {
self.value = value;
}
}
/// The main struct of this crate. Represents DF config file, while also providing functions to parse and manipulate the data.
/... | get_value | identifier_name |
lib.rs | //! dfconfig is a lib for parsing and manipulating Dwarf Fortress' `init.txt` and `d_init.txt` config files (and possibly many others using the same format).
//! This lib's functionality has been specifically tailored to behave similar as DF internal parser, which implies:
//!
//! * [`Config::get`] returns the last occ... | if let Line::Entry(entry) = e {
if entry.get_key() == key {
entry.set_value(value.clone());
n += 1;
}
}
}
if n == 0 {
self.lines
.push(Line::Entry(Entry::new(key.to_string(), valu... | }
let mut n = 0;
for e in self.lines.iter_mut() { | random_line_split |
lib.rs | //! dfconfig is a lib for parsing and manipulating Dwarf Fortress' `init.txt` and `d_init.txt` config files (and possibly many others using the same format).
//! This lib's functionality has been specifically tailored to behave similar as DF internal parser, which implies:
//!
//! * [`Config::get`] returns the last occ... |
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::fs::read_to_string;
use std::iter;
use super::*;
fn random_alphanumeric() -> String {
let mut rng ... | {
let mut output = HashMap::new();
conf.keys_values_iter().for_each(|(key, value)| {
output.insert(key.to_owned(), value.to_owned());
});
output
} | identifier_body |
ctrl_map.rs | //! Maps MIDI controllers to synth parameters.
use super::{ParamId, MenuItem};
use super::SoundData;
use super::SynthParam;
use super::ValueRange;
use log::{info, trace};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
#[derive(... | (&mut self, ctrl_no: u64, ctrl_type: MappingType) {
let val_range = MenuItem::get_val_range(self.param_id.function, self.param_id.parameter);
self.map.add_mapping(1,
ctrl_no,
ctrl_type,
self.param_id,
... | add_controller | identifier_name |
ctrl_map.rs | //! Maps MIDI controllers to synth parameters.
use super::{ParamId, MenuItem};
use super::SoundData;
use super::SynthParam;
use super::ValueRange;
use log::{info, trace};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
#[derive(... |
MappingType::None => panic!(),
};
Ok(result)
}
// Load controller mappings from file
pub fn load(&mut self, filename: &str) -> std::io::Result<()> {
info!("Reading controller mapping from {}", filename);
let file = File::open(filename)?;
let mut reader =... | {
// For relative: Increase/ decrease value
let sound_value = sound.get_value(&mapping.id);
let delta = if value >= 64 { -1 } else { 1 };
result.value = mapping.val_range.add_value(sound_value, delta);
} | conditional_block |
ctrl_map.rs | //! Maps MIDI controllers to synth parameters.
use super::{ParamId, MenuItem};
use super::SoundData;
use super::SynthParam;
use super::ValueRange;
use log::{info, trace};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
#[derive(... | controller: u64,
value: u64,
sound: &SoundData) -> Result<SynthParam, ()> {
// Get mapping
if !self.map[set].contains_key(&controller) {
return Err(());
}
let mapping = &self.map[set][&controller];
let mut re... | set: usize, | random_line_split |
ctrl_map.rs | //! Maps MIDI controllers to synth parameters.
use super::{ParamId, MenuItem};
use super::SoundData;
use super::SynthParam;
use super::ValueRange;
use log::{info, trace};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
#[derive(... |
#[test]
fn value_can_be_changed_absolute() {
let mut context = TestContext::new();
assert_eq!(context.has_value(50.0), true);
context.add_controller(1, MappingType::Absolute);
assert_eq!(context.handle_controller(1, 0), true);
assert_eq!(context.has_value(0.0), true);
}
#[test]
fn relative_contro... | {
let mut context = TestContext::new();
context.add_controller(1, MappingType::Absolute);
assert_eq!(context.handle_controller(1, 50), true);
} | identifier_body |
random.rs | use alloc::boxed::Box;
use std::f64::consts::PI;
use std::num::Wrapping;
use std::sync::Arc;
use std::vec::Vec;
use common::bytes::{Buf, Bytes};
use common::io::Readable;
use common::{ceil_div, errors::*};
use executor::sync::Mutex;
use file::LocalFile;
use math::big::{BigUint, SecureBigUint};
use math::integer::Integ... |
pub fn seed_u32(&mut self, seed: u32) {
self.x.resize(self.n, 0);
self.index = self.n;
self.x[0] = seed;
for i in 1..self.n {
self.x[i] = (self.x[i - 1] ^ (self.x[i - 1] >> (self.w - 2)))
.wrapping_mul(self.f)
.wrapping_add(i as u32);
... | {
Self {
w: 32,
n: 624,
m: 397,
r: 31,
a: 0x9908B0DF,
u: 11,
d: 0xffffffff,
s: 7,
b: 0x9D2C5680,
t: 15,
c: 0xEFC60000,
l: 18,
f: 1812433253,
x... | identifier_body |
random.rs | use alloc::boxed::Box;
use std::f64::consts::PI;
use std::num::Wrapping;
use std::sync::Arc;
use std::vec::Vec;
use common::bytes::{Buf, Bytes};
use common::io::Readable;
use common::{ceil_div, errors::*};
use executor::sync::Mutex;
use file::LocalFile;
use math::big::{BigUint, SecureBigUint};
use math::integer::Integ... | }
}
} | assert!(bucket > 71254 && bucket < 81780, "Bucket is {}", bucket); | random_line_split |
random.rs | use alloc::boxed::Box;
use std::f64::consts::PI;
use std::num::Wrapping;
use std::sync::Arc;
use std::vec::Vec;
use common::bytes::{Buf, Bytes};
use common::io::Readable;
use common::{ceil_div, errors::*};
use executor::sync::Mutex;
use file::LocalFile;
use math::big::{BigUint, SecureBigUint};
use math::integer::Integ... | () -> Self {
Self {
state: Mutex::new(ChaCha20RNGState {
key: [0u8; CHACHA20_KEY_SIZE],
nonce: 0,
plaintext: [0u8; CHACHA20_BLOCK_SIZE],
}),
}
}
}
#[async_trait]
impl SharedRng for ChaCha20RNG {
fn seed_size(&self) -> usize... | new | identifier_name |
random.rs | use alloc::boxed::Box;
use std::f64::consts::PI;
use std::num::Wrapping;
use std::sync::Arc;
use std::vec::Vec;
use common::bytes::{Buf, Bytes};
use common::io::Readable;
use common::{ceil_div, errors::*};
use executor::sync::Mutex;
use file::LocalFile;
use math::big::{BigUint, SecureBigUint};
use math::integer::Integ... |
let mut buf = vec![];
buf.resize(upper.byte_width(), 0);
let mut num_bytes = ceil_div(upper.value_bits(), 8);
let msb_mask: u8 = {
let r = upper.value_bits() % 8;
if r == 0 {
0xff
} else {
!((1 << (8 - r)) - 1)
}
};
// TODO: Refactor o... | {
return Err(err_msg("Invalid upper/lower range"));
} | conditional_block |
main.rs | use futures_util::future::Either;
use futures_util::stream::StreamExt;
use std::collections::{BTreeMap, HashMap};
use std::io::{self};
use structopt::StructOpt;
use termion::raw::IntoRawMode;
use tokio::prelude::*;
use tui::backend::Backend;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Lay... | {
window: BTreeMap<usize, String>,
}
fn main() -> Result<(), io::Error> {
let opt = Opt::from_args();
if termion::is_tty(&io::stdin().lock()) {
eprintln!("Don't type input to this program, that's silly.");
return Ok(());
}
let stdout = io::stdout().into_raw_mode()?;
let backe... | Thread | identifier_name |
main.rs | use futures_util::future::Either;
use futures_util::stream::StreamExt;
use std::collections::{BTreeMap, HashMap};
use std::io::{self};
use structopt::StructOpt;
use termion::raw::IntoRawMode;
use tokio::prelude::*;
use tui::backend::Backend;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Lay... | lines.push(Text::styled(
format!(" {}{}\n", frame, offset),
Style::default().modifier(Modifier::DIM),
));
}
}
lines.push(Text::raw("\n"));
}
terminal.draw(|mut f| {
let chunks = Layout::default()
... | } else { | random_line_split |
main.rs | use futures_util::future::Either;
use futures_util::stream::StreamExt;
use std::collections::{BTreeMap, HashMap};
use std::io::{self};
use structopt::StructOpt;
use termion::raw::IntoRawMode;
use tokio::prelude::*;
use tui::backend::Backend;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Lay... |
}
Either::Right(key) => {
let key = key?;
if let termion::event::Key::Char('q') = key {
break;
}
}
}
}
terminal.clear()?;
Ok(())
})
}
fn draw<B: ... | {
assert!(inframe.is_some());
stack.push_str(line.trim());
stack.push(';');
} | conditional_block |
main.rs | use futures_util::future::Either;
use futures_util::stream::StreamExt;
use std::collections::{BTreeMap, HashMap};
use std::io::{self};
use structopt::StructOpt;
use termion::raw::IntoRawMode;
use tokio::prelude::*;
use tui::backend::Backend;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Lay... |
fn draw<B: Backend>(
terminal: &mut Terminal<B>,
threads: &mut BTreeMap<usize, Thread>,
) -> Result<(), io::Error> {
// keep our window relatively short
let mut latest = 0;
for thread in threads.values() {
if let Some(&last) = thread.window.keys().next_back() {
latest = std::cm... | {
let opt = Opt::from_args();
if termion::is_tty(&io::stdin().lock()) {
eprintln!("Don't type input to this program, that's silly.");
return Ok(());
}
let stdout = io::stdout().into_raw_mode()?;
let backend = TermionBackend::new(stdout);
let mut terminal = Terminal::new(backend... | identifier_body |
sbot.py | #!/usr/bin/python
import subprocess
import os
import sys
import time
import random
from PIL import Image
from PIL import ImageFile
from pytesser import *
import cv2
from adbInterface import adbInterface as adb
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
adbpath = '..\\platform-tools\\.\\adb'
serial = ""
... |
else:
if rarity == "Legend":
keep = True
else:
# keep = False
if rarity == "Hero" and hasSpeedSub:
keep = True
else:
keep = False
print("keep? " + str(keep))
if keep == False:
prin... | if rarity == "Rare" and not hasSpeedSub:
keep = False
else:
keep = True | conditional_block |
sbot.py | #!/usr/bin/python
import subprocess
import os
import sys
import time
import random
from PIL import Image
from PIL import ImageFile
from pytesser import *
import cv2
from adbInterface import adbInterface as adb
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
adbpath = '..\\platform-tools\\.\\adb'
serial = ""
... |
def adbdevices():
return adb.adbdevices()
def touchscreen_devices():
return adb.touchscreen_devices()
def tap(x, y):
command = "input tap " + str(x) + " " + str(y)
command = str.encode(command)
adbshell(command.decode('utf-8'))
def screenCapture():
# perform a search in th... | return adb.adbpull(command) | identifier_body |
sbot.py | #!/usr/bin/python
import subprocess
import os
import sys
import time
import random
from PIL import Image
from PIL import ImageFile
from pytesser import *
import cv2
from adbInterface import adbInterface as adb
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
adbpath = '..\\platform-tools\\.\\adb'
serial = ""
... | ():
i = 2
keep = True
hasSpeedSub = False
foundRare = False
global soldRunes
global keptRunes
while i > 0:
i-=1
performOCR()
fileN = crop(1200,350,50,100,"capcha") # Rarity
convPNG2TIF(fileN)
try:
img = ... | keepOrSellRune | identifier_name |
sbot.py | #!/usr/bin/python
import subprocess
import os
import sys
import time
import random
from PIL import Image
from PIL import ImageFile
from pytesser import *
import cv2
from adbInterface import adbInterface as adb
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
adbpath = '..\\platform-tools\\.\\adb'
serial = ""
... | return adb.touchscreen_devices()
def tap(x, y):
command = "input tap " + str(x) + " " + str(y)
command = str.encode(command)
adbshell(command.decode('utf-8'))
def screenCapture():
# perform a search in the sdcard of the device for the SummonerBot
# folder. if we found it, we delet... | def adbdevices():
return adb.adbdevices()
def touchscreen_devices():
| random_line_split |
triggers.go | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
... | (c *cli.Context) error {
resTriggers, err := getTriggers(c, t.client)
if err != nil {
return err
}
fnName := c.Args().Get(1)
w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
if len(fnName) != 0 {
fmt.Fprint(w, "NAME", "\t", "ID", "\t", "TYPE", "\t", "SOURCE", "\t", "ENDPOINT", "\n")
for _, trigger := ... | list | identifier_name |
triggers.go | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
... |
// CreateTrigger request
func CreateTrigger(client *fnclient.Fn, trigger *models.Trigger) error {
resp, err := client.Triggers.CreateTrigger(&apiTriggers.CreateTriggerParams{
Context: context.Background(),
Body: trigger,
})
if err != nil {
switch e := err.(type) {
case *apiTriggers.CreateTriggerBadRequ... | {
if !strings.HasPrefix(ts, "/") {
ts = "/" + ts
}
return ts
} | identifier_body |
triggers.go | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
... |
fn, err := fn.GetFnByName(client, app.ID, fnName)
if err != nil {
return nil, err
}
trigger, err := GetTriggerByName(client, app.ID, fn.ID, triggerName)
if err != nil {
return nil, err
}
return trigger, nil
}
// GetTriggerByAppFnAndTriggerNames looks up a trigger using app, fn and trigger names
func Get... | {
return nil, err
} | conditional_block |
triggers.go | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
... | endpoint := resp.Payload.Annotations["fnproject.io/trigger/httpEndpoint"]
fmt.Println("Trigger Endpoint:", endpoint)
return nil
}
func (t *triggersCmd) list(c *cli.Context) error {
resTriggers, err := getTriggers(c, t.client)
if err != nil {
return err
}
fnName := c.Args().Get(1)
w := tabwriter.NewWriter(os... | }
fmt.Println("Successfully created trigger:", resp.Payload.Name) | random_line_split |
sql_utils.rs | //! Module for SQL Utility functions
use diesel::prelude::*;
use std::{
borrow::Cow,
fs::File,
io::BufReader,
path::Path,
};
use crate::error::IOErrorToError;
use super::archive::import::{
detect_archive_type,
import_ytdlr_json_archive,
ArchiveType,
ImportProgress,
};
/// All migrations from "libytdlr/migra... |
#[test]
fn test_input_unknown_archive() {
let string0 = "
youtube ____________
youtube ------------
youtube aaaaaaaaaaaa
soundcloud 0000000000
";
let (path, _tempdir) = write_file_with_content(string0, "unknown_ytdl");
let pgcounter = RwLock::new(Vec::<ImportProgress>::new());
let re... | {
return |imp| c.write().expect("write failed").push(imp);
} | identifier_body |
sql_utils.rs | //! Module for SQL Utility functions
use diesel::prelude::*;
use std::{
borrow::Cow,
fs::File,
io::BufReader,
path::Path,
};
use crate::error::IOErrorToError;
use super::archive::import::{
detect_archive_type,
import_ytdlr_json_archive,
ArchiveType,
ImportProgress,
};
/// All migrations from "libytdlr/migra... |
assert!(res.is_err());
let res = match res {
Ok(_) => panic!("Expected a Error value"),
Err(err) => err,
};
assert!(res
.to_string()
.contains("Unknown Archive type to migrate, maybe try importing"));
assert_eq!(0, pgcounter.read().expect("read failed").len());
}
#[test]
fn test_... | random_line_split | |
sql_utils.rs | //! Module for SQL Utility functions
use diesel::prelude::*;
use std::{
borrow::Cow,
fs::File,
io::BufReader,
path::Path,
};
use crate::error::IOErrorToError;
use super::archive::import::{
detect_archive_type,
import_ytdlr_json_archive,
ArchiveType,
ImportProgress,
};
/// All migrations from "libytdlr/migra... | ,
ArchiveType::JSON => {
debug!("Applying Migration from JSON to SQLite");
// handle case where the input path matches the changed path
if migrate_to_path == archive_path {
return Err(crate::Error::other(
"Migration cannot be done: Input path matches output path (setting extension to \".db\")",
... | {
return Err(crate::Error::other(
"Unknown Archive type to migrate, maybe try importing",
))
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.