file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
ethereum-block.ts | of this block. This
* can be calculated from the previous block’s difficulty level and the
* timestamp.
*/
difficulty: bigint;
/**
* A scalar value equal to the number of ancestor blocks. The genesis block
* has a number of zero.
*/
blockNumber: bigint;
/**
* A scalar value equal to the cu... |
const TRANSACTION_NONCE = 0;
const TRANSACTION_GASPRICE = 1;
const TRANSACTION_STARTGAS = 2;
const TRANSACTION_TO = 3;
const TRANSACTION_VALUE = 4;
const TRANSACTION_DATA = 5;
const TRANSACTION_V = 6;
const TRANSACTION_R = 7;
const TRANSACTION_S = 8;
/**
* Given a RLP-serialized list with an Ethereum transaction, de... | extraData: (header[HEADER_EXTRADATA] as Buffer),
mixHash: toBigIntBE(header[HEADER_MIXHASH] as Buffer),
nonce: toBigIntBE(header[HEADER_NONCE] as Buffer)
};
} | random_line_split |
ethereum-block.ts | TRANSACTION_STARTGAS] as Buffer),
(transaction[TRANSACTION_TO] as Buffer),
(transaction[TRANSACTION_VALUE] as Buffer),
(transaction[TRANSACTION_DATA] as Buffer),
Buffer.from([options.chainId]),
Buffer.from([]),
Buffer.from([]),
]) :
RlpEncode([
(transa... | pList: RlpList = [
removeNullPrefix(toBufferBE(transaction.nonce, 32)),
removeNullPrefix(toBufferBE(transaction.gasPrice, 32)),
removeNullPrefix(toBufferBE(transaction.gasLimit, 32)),
transaction.to === CONTRACT_CREATION ? Buffer.from([]) :
toBufferBE(transacti... | identifier_body | |
test_service.py | def test_info(self):
info = self.service.info
keys = ["build", "cpu_arch", "guid", "isFree", "isTrial", "licenseKeys",
"licenseSignature", "licenseState", "master_guid", "mode",
"os_build", "os_name", "os_version", "serverName", "version"]
for key in keys:
... | def test_default_app(self):
kwargs = self.opts.kwargs.copy()
kwargs.update({'app': None, 'owner': "admin"})
service_ns = client.connect(**kwargs)
service_ns.apps.list()
def test_app_wildcard(self):
kwargs = self.opts.kwargs.copy()
kwargs.update({'app': "-", 'owne... | random_line_split | |
test_service.py | def test_info(self):
info = self.service.info
keys = ["build", "cpu_arch", "guid", "isFree", "isTrial", "licenseKeys",
"licenseSignature", "licenseState", "master_guid", "mode",
"os_build", "os_name", "os_version", "serverName", "version"]
for key in keys:
... | (self):
kwargs = self.opts.kwargs.copy()
kwargs.update({'app': "search", 'owner': None})
service_ns = client.connect(**kwargs)
service_ns.apps.list()
def test_owner_wildcard(self):
kwargs = self.opts.kwargs.copy()
kwargs.update({'app': "search", 'owner': "-"})
... | test_app_namespace | identifier_name |
test_service.py | def test_info(self):
info = self.service.info
keys = ["build", "cpu_arch", "guid", "isFree", "isTrial", "licenseKeys",
"licenseSignature", "licenseState", "master_guid", "mode",
"os_build", "os_name", "os_version", "serverName", "version"]
for key in keys:
... |
def _create_unauthenticated_service(self):
return Service(**{
'host': self.opts.kwargs['host'],
'port': self.opts.kwargs['port'],
'scheme': self.opts.kwargs['scheme']
})
# To check the HEC event endpoint using Endpoint instance
@pytest.mark.smoke
de... | raise | conditional_block |
test_service.py | def test_info(self):
info = self.service.info
keys = ["build", "cpu_arch", "guid", "isFree", "isTrial", "licenseKeys",
"licenseSignature", "licenseState", "master_guid", "mode",
"os_build", "os_name", "os_version", "serverName", "version"]
for key in keys:
... |
def test_login_with_cookie(self):
self.service.login()
self.assertIsNotNone(self.service.get_cookies())
# Use the cookie from the other service as the only auth param (don't need user/password)
service2 = client.Service(**{"cookie": "%s=%s" % list(self.service.get_cookies().items()... | self.assertIsNotNone(self.service.get_cookies())
self.assertEqual(len(self.service.get_cookies()), 0)
self.service.login()
self.assertIsNotNone(self.service.get_cookies())
self.assertNotEqual(self.service.get_cookies(), {})
self.assertEqual(len(self.service.get_cookies()), 1) | identifier_body |
completion.rs | ,
/// The offset that the completion is/was started at. Used for positioning the completion elem
pub offset: usize,
/// The active completion index in the list of filtered items
pub active: RwSignal<usize>,
/// The current input that the user has typed which is being sent for consideration by the LS... | (&mut self) {
let count = self.display_count();
let active = self.active.get_untracked();
let new = Movement::Up.update_index(
active,
self.filtered_items.len(),
count,
false,
);
self.active.set(new);
}
/// The currently se... | previous_page | identifier_name |
completion.rs | Buf,
/// The offset that the completion is/was started at. Used for positioning the completion elem
pub offset: usize,
/// The active completion index in the list of filtered items
pub active: RwSignal<usize>,
/// The current input that the user has typed which is being sent for consideration by the... | // TODO: Possibly handle the 'is_incomplete' field on List.
CompletionResponse::List(list) => &list.items,
};
let items: im::Vector<ScoredCompletionItem> = items
.iter()
.map(|i| ScoredCompletionItem {
item: i.to_owned(),
pl... | random_line_split | |
completion.rs | ,
/// The offset that the completion is/was started at. Used for positioning the completion elem
pub offset: usize,
/// The active completion index in the list of filtered items
pub active: RwSignal<usize>,
/// The current input that the user has typed which is being sent for consideration by the LS... |
fn all_items(&self) -> im::Vector<ScoredCompletionItem> {
self.input_items
.get(&self.input)
.cloned()
.filter(|items| !items.is_empty())
.unwrap_or_else(move || {
self.input_items.get("").cloned().unwrap_or_default()
})
}
... | {
if self.status == CompletionStatus::Inactive {
return;
}
self.input = input;
// TODO: If the user types a letter that continues the current active item, we should
// try keeping that item active. Possibly give this a setting.
// ex: `p` has `print!` and `pri... | identifier_body |
feature_engineer.py | return data
pca=PCA(n_components=pca_threshold, svd_solver ='full')
data = pca.fit_transform(data)
return data
def _check_file_exist(file_path, flag_directed_graph):
if flag_directed_graph and os.path.exists(os.path.join(file_path,'NR_EB/STRAP_strap_frpca_d_U.npy')) and os.path.exists(os.path.j... | import os
def _pca_processing(data, pca_threshold=0.75):
if data.shape[1] == 0: | random_line_split | |
feature_engineer.py | .join(file_path,'NR_EB/STRAP_strap_frpca_u_V.npy')):
return True
else:
return False
def check_monotony(x, tol=5):
dx = np.diff(x[1:-1])
return np.all(dx < tol) or np.all(dx > -tol)
def get_value_counts_with_moving_average(x, use_moving_average=False, n=3):
x_dict = dict(Series(x).value... | (edge_index, edge_weight, num_nodes):
row, col = edge_index
in_deg = scatter_add(edge_weight, col, dim_size=num_nodes).numpy()
out_deg = scatter_add(edge_weight, row, dim_size=num_nodes).numpy()
degree = np.concatenate([np.expand_dims(in_deg,-1), np.expand_dims(out_deg,-1)], axis=-1)
return degree... | get_node_degree | identifier_name |
feature_engineer.py | .join(file_path,'NR_EB/STRAP_strap_frpca_u_V.npy')):
return True
else:
return False
def check_monotony(x, tol=5):
dx = np.diff(x[1:-1])
return np.all(dx < tol) or np.all(dx > -tol)
def get_value_counts_with_moving_average(x, use_moving_average=False, n=3):
x_dict = dict(Series(x).value... |
node_embed = np.concatenate([node_embed_u, node_embed | node_embed_v[np.isnan(node_embed_v)] = 0.0
logger.info('find nan in node_embed_V') | conditional_block |
feature_engineer.py | .join(file_path,'NR_EB/STRAP_strap_frpca_u_V.npy')):
return True
else:
return False
def check_monotony(x, tol=5):
dx = np.diff(x[1:-1])
return np.all(dx < tol) or np.all(dx > -tol)
def get_value_counts_with_moving_average(x, use_moving_average=False, n=3):
x_dict = dict(Series(x).value... |
def normalize(x):
norm_time = time.time()
tol = min(int(1e-3*x.shape[1]), 5)
normal_funs = ['l2', 'minmax', 'z-score']
normal_fun = normal_funs[0]
cont_feature_idx = [i for i in range(len(x)) if len(np.unique(x[i])) > 5 and check_continuous(x[i], tol)]
cate_feature_idx = [i for i in rang... | if len(np.unique(x)) > len(x) * 0.5:
return True
x = get_value_counts_with_moving_average(x)
max_index = np.argmax(x)
min_index = np.argmax(-np.array(x))
if check_monotony(x, tol):
return True
elif check_monotony(x[:max_index+1], tol) and check_monotony(x[max_index:], tol):
r... | identifier_body |
lib.rs | // use drop(&mut self) to call timeEnd.
// So function wrapped with Timer will automatically be timed.
// Then let _timer = Timer::new("Universe::tick");
// will cause every call to tick() to be timed and logged on console
pub struct Timer<'a> {
name: &'a str,
}
impl<'a> Timer<'a> {
pub fn new(name... | {
width: u32, // width of each row
height: u32, // number of rows
cells: Vec<Cell>, // width*height cells, each one byte
prevcells: Vec<Cell>, // cells from previous tick
mousedown: bool // set when shift-click event, so that associated click ignored
}
// methods for Universe, but not exposed... | Universe | identifier_name |
lib.rs | Random5050 = 1
}
// Define the 'Universe', a 1D array of Cell values (byte values, 0 or 1 per Cell def)
// Give the width of the universe, each row of the universe is the next set
// of 'width' cells, starting with the first row from indexes 0:<width>
#[wasm_bindgen]
pub struct Universe {
width: u32, // ... | {
log!("reset_board() : {:?}", pattern);
let width = self.width();
let height = self.height();
self.prevcells = self.cells.clone(); // current grid, needed for correct redraw
self.cells = generate_cells(width, height, pattern);
} | identifier_body | |
lib.rs | // use drop(&mut self) to call timeEnd.
// So function wrapped with Timer will automatically be timed.
// Then let _timer = Timer::new("Universe::tick");
// will cause every call to tick() to be timed and logged on console
pub struct Timer<'a> {
name: &'a str,
}
impl<'a> Timer<'a> {
pub fn new(name... |
+ if self.cells[self.get_index(down,right)] == Cell::Alive { 1 } else { 0 };
neighbors
}
}
// standalone method, not part of Universe directly
fn generate_cells(width: u32, height: u32, _pattern: InitialPattern) -> Vec<Cell> {
// expression generating Vec<Cell>
let cells = (0..width... | { 0 } | conditional_block |
lib.rs | // use drop(&mut self) to call timeEnd.
// So function wrapped with Timer will automatically be timed.
// Then let _timer = Timer::new("Universe::tick");
// will cause every call to tick() to be timed and logged on console
pub struct Timer<'a> {
name: &'a str,
}
impl<'a> Timer<'a> {
pub fn new(name... | }).collect();
inverted_cells
}
// Public methods, exposed to JS
#[wasm_bindgen]
impl Universe
{
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
// set_width -- set width of Universe, set all cells to Dead state
pub fn set_width(&m... | let inverted_cells = (0..count).map(|i|
{
if cells[i] == Cell::Alive { Cell::Dead } else { Cell::Alive } | random_line_split |
mod.rs | use crate::FnCtxt;
use hir::def_id::DefId;
use hir::{Body, HirId, HirIdMap, Node};
use rustc_data_structures::unord::{UnordMap, UnordSet};
use rustc_hir as hir;
use rustc_index::bit_set::BitSet;
use rustc_index::IndexVec;
use rustc_middle::hir::map::Map;
use rustc_middle::hir::place::{PlaceBase, PlaceWithHirId};
use ru... |
use self::cfg_build::build_control_flow_graph;
use self::record_consumed_borrow::find_consumed_and_borrowed; | random_line_split | |
mod.rs | agate;
mod cfg_visualize;
mod record_consumed_borrow;
pub fn compute_drop_ranges<'a, 'tcx>(
fcx: &'a FnCtxt<'a, 'tcx>,
def_id: DefId,
body: &'tcx Body<'tcx>,
) -> DropRanges {
if fcx.sess().opts.unstable_opts.drop_tracking {
let consumed_borrowed_places = find_consumed_and_borrowed(fcx, def_id,... | fmt | identifier_name | |
mod.rs | Id, HirIdMap, Node};
use rustc_data_structures::unord::{UnordMap, UnordSet};
use rustc_hir as hir;
use rustc_index::bit_set::BitSet;
use rustc_index::IndexVec;
use rustc_middle::hir::map::Map;
use rustc_middle::hir::place::{PlaceBase, PlaceWithHirId};
use rustc_middle::ty;
use std::collections::BTreeMap;
use std::fmt::... | else {
match self {
Self::Variable(hir_id) => write!(f, "Variable({hir_id:?})"),
Self::Temporary(hir_id) => write!(f, "Temporary({hir_id:?})"),
}
}
})
}
}
impl TrackedValue {
fn hir_id(&self) -> HirId {
match s... | {
write!(f, "{}", tcx.hir().node_to_string(self.hir_id()))
} | conditional_block |
mod.rs | _value_map: drop_ranges.tracked_value_map,
nodes: drop_ranges.nodes,
borrowed_temporaries: Some(borrowed_temporaries),
}
} else {
// If drop range tracking is not enabled, skip all the analysis and produce an
// empty set of DropRanges.
DropRanges {
... | {
self.tracked_value_map.len()
} | identifier_body | |
forward_chain_bandaid.py | # https://github.com/openshift/origin/pull/13465
'''
This entire script is a band-aid that needs to be in place until
https://github.com/openshift/origin/pull/13465 is merged and
backported to 3.4 and 3.5 and the hotfix that contains it is installed
on all clusters.
This script will:
1. create the OPENSHIFT-OUTPU... |
# assume that source_chain already exists
# flush the source_chain since we're about to recreate its rules
in_data += "-F %s\n" % self.source_chain
in_data += ("\n".join(updated_rules))+"\n"
in_data += "COMMIT\n"
cmd = self._build_restore_cmd()
# as seen on http:... | in_data += ":%s - [0:0]\n" % self.jump_chain | conditional_block |
forward_chain_bandaid.py | # https://github.com/openshift/origin/pull/13465
'''
This entire script is a band-aid that needs to be in place until
https://github.com/openshift/origin/pull/13465 is merged and
backported to 3.4 and 3.5 and the hotfix that contains it is installed
on all clusters.
This script will:
1. create the OPENSHIFT-OUTPU... |
# pylint: enable=too-few-public-methods
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-arguments
class TopRule(object):
'''A single rule that should be at the top of the chain'''
def __init__(self, table, source_chain, jump_chain, ver, top_rule, noop_rule):
'''Create the To... | '''A dummy context manager that does nothing so that a 'with' can conditionally do nothing'''
def __enter__(self):
return None
def __exit__(self, exc_type, exc_value, traceback_):
return False | identifier_body |
forward_chain_bandaid.py | # 2. this script should go away within a few weeks when it gets obsoleted by
# https://github.com/openshift/origin/pull/13465
'''
This entire script is a band-aid that needs to be in place until
https://github.com/openshift/origin/pull/13465 is merged and
backported to 3.4 and 3.5 and the hotfix that contains it ... | random_line_split | ||
forward_chain_bandaid.py | # https://github.com/openshift/origin/pull/13465
'''
This entire script is a band-aid that needs to be in place until
https://github.com/openshift/origin/pull/13465 is merged and
backported to 3.4 and 3.5 and the hotfix that contains it is installed
on all clusters.
This script will:
1. create the OPENSHIFT-OUTPU... | (self, *args):
'''
Create an iptables-restore or ip6tables-restore command
Return a list of command args suitable for use with subprocess.*
'''
cmd = 'iptables-restore' if self.ver == 'ipv4' else 'ip6tables-restore'
retval = ["/usr/sbin/%s" % cmd, '--noflush', '--table', ... | _build_restore_cmd | identifier_name |
jobOptions_TileLasMon.py | (path, runinput):
run = str(runinput)
while len(run) < 7:
run = '0' + run
files = []
fullname = []
if path.startswith("/castor") :
for f in popen('nsls %(path)s | grep %(run)s' % {'path': path, 'run':run }):
files.append(f)
elif path.startswith("/eos") :
... | FindFile | identifier_name | |
jobOptions_TileLasMon.py | elif path.startswith("/eos") :
for f in popen('eos ls %(path)s | grep %(run)s' % {'path': path, 'run':run }):
files.append(f)
else:
for f in popen('ls %(path)s | grep %(run)s' % {'path': path, 'run':run }):
files.append(f)
for nn in range(len(files)):
... | print(topSequence.TileLasMon)
import os
# -- use root histos --
|
topSequence.TileLasMon.AthenaMonTools += [ TileLasDQFragMon ];
print(TileLasDQFragMon) | random_line_split |
jobOptions_TileLasMon.py | )
elif path.startswith("/eos") :
for f in popen('eos ls %(path)s | grep %(run)s' % {'path': path, 'run':run }):
files.append(f)
else:
for f in popen('ls %(path)s | grep %(run)s' % {'path': path, 'run':run }):
files.append(f)
for nn in range(len(files)... |
if not 'FileNameVec' in dir():
if not 'FileName' in dir():
tmp = FindFile(InputDirectory,RunNumber)
FileNameVec = tmp[0]
FormattedRunNumber = tmp[1]
else:
FileNameVec = [ InputDirectory+'/'+FileName ]
FormattedRunNumber ... | if InputDirectory=="." or RunNumber<10:
RunFromLocal=True
else:
RunFromLocal=False | conditional_block |
jobOptions_TileLasMon.py |
for nn in range(len(files)):
temp = files[nn].split('\n')
fullname.append(path + '/' + temp[0])
return [fullname,run]
# include Flags jobOption
include( "TileMonitoring/TileRec_FlagOptions.py" )
## get a handle to the default top-level algorithm sequence
from AthenaCommon.AlgSequence import... | run = str(runinput)
while len(run) < 7:
run = '0' + run
files = []
fullname = []
if path.startswith("/castor") :
for f in popen('nsls %(path)s | grep %(run)s' % {'path': path, 'run':run }):
files.append(f)
elif path.startswith("/eos") :
for f in popen(... | identifier_body | |
trainer.py | next_item = self.queue.get()
if next_item is None:
raise StopIteration
return next_item
# Python 3 compatibility
def __next__(self):
return self.next()
def __iter__(self):
return self
class Prefetcher(object):
def __init__(self, dataloader):
... |
else:
return model(example, return_loss=False)
def train(self, data_loader, epoch, **kwargs):
self.model.train()
self.mode = "train"
self.data_loader = data_loader
self.length = len(data_loader)
self._max_iters = self._max_epochs * self.length
s... | losses = model(example, return_loss=True)
self.call_hook("after_forward")
loss, log_vars = parse_second_losses(losses)
del losses
outputs = dict(
loss=loss, log_vars=log_vars, num_samples=-1 # TODO: FIX THIS
)
self.call_hook("afte... | conditional_block |
trainer.py | next_item = self.queue.get()
if next_item is None:
raise StopIteration
return next_item
# Python 3 compatibility
def __next__(self):
return self.next()
def __iter__(self):
return self
class Prefetcher(object):
def __init__(self, dataloader):
... | self,
model,
batch_processor,
optimizer=None,
lr_scheduler=None,
work_dir=None,
log_level=logging.INFO,
logger=None,
**kwargs,
):
assert callable(batch_processor)
self.model = model
self.optimizer = optimizer
sel... | random_line_split | |
trainer.py | next_item = self.queue.get()
if next_item is None:
raise StopIteration
return next_item
# Python 3 compatibility
def __next__(self):
return self.next()
def __iter__(self):
return self
class Prefetcher(object):
def __init__(self, dataloader):
... | (self, optimizer):
"""Init the optimizer
Args:
optimizer (dict or :obj:`~torch.optim.Optimizer`)
Returns:
:obj:`~torch.optim.Optimizer`
Examples:
>>> optimizer = dict(type='SGD', lr=0.01, momentum=0.9)
>>> type(runner.init_optimizer(opti... | init_optimizer | identifier_name |
trainer.py | next_item = self.queue.get()
if next_item is None:
raise StopIteration
return next_item
# Python 3 compatibility
def __next__(self):
return self.next()
def __iter__(self):
return self
class Prefetcher(object):
def __init__(self, dataloader):
... | **kwargs,
):
assert callable(batch_processor)
self.model = model
self.optimizer = optimizer
self.lr_scheduler = lr_scheduler
self.batch_processor = batch_processor
# Create work_dir
if torchie.is_str(work_dir):
self.work_dir = osp.abspath... | """ A training helper for PyTorch
Args:
model:
batch_processor:
optimizer:
workdir:
log_level:
logger:
"""
def __init__(
self,
model,
batch_processor,
optimizer=None,
lr_scheduler=None,
work_dir=None,
l... | identifier_body |
path_planning.py | # square of diff from target speed
ds = (TARGET_SPEED - tfp.s_d[-1])**2
# 横向的损失函数
tfp.cd = KJ * Jp + KT * Ti + KD * tfp.d[-1]**2
# 纵向的损失函数
tfp.cv = KJ * Js + KT * Ti + KD * ds
# 总的损失函数为d 和 s方向的损失函数乘对应的系数相加
... | GPS_y = GPS_y - zero_cord_y
plt.plot(GPS_x,GPS_y, "-r", label="GPS point ")
plt.plot()
plt.show()
return GPS_x, GPS_y
class Info(object):
def __init__(self):
self.CurrGPS_lat = float(-1)
self.CurrGPS_lon = float(-1)
self.CurrentVelocity = float(-1)
self.Targ... | #print("cy:",cy)
zero_cord_x = GPS_x[0]
zero_cord_y = GPS_y[0]
GPS_x = GPS_x - zero_cord_x | random_line_split |
path_planning.py | of diff from target speed
ds = (TARGET_SPEED - tfp.s_d[-1])**2
# 横向的损失函数
tfp.cd = KJ * Jp + KT * Ti + KD * tfp.d[-1]**2
# 纵向的损失函数
tfp.cv = KJ * Js + KT * Ti + KD * ds
# 总的损失函数为d 和 s方向的损失函数乘对应的系数相加
#########... |
#########################################################
##############################
def load_global_path():
global zero_cord_x,zero_cord_y
bet = 0.1
blank = [] #buffer
white = [] ... | .cos(csp.calc_yaw(i_s)+math.pi / 2.0)
road_right_iy = iy - MAX_ROAD_WIDTH/2 * math.sin(csp.calc_yaw(i_s)+math.pi / 2.0)
road_left_x.append(road_left_ix)
road_left_y.append(road_left_iy)
road_right_x.append(road_right_ix)
road_right_y.append(road_right_iy)
return road_left_x, ... | identifier_body |
path_planning.py | square of diff from target speed
ds = (TARGET_SPEED - tfp.s_d[-1])**2
# 横向的损失函数
tfp.cd = KJ * Jp + KT * Ti + KD * tfp.d[-1]**2
# 纵向的损失函数
tfp.cv = KJ * Js + KT * Ti + KD * ds
# 总的损失函数为d 和 s方向的损失函数乘对应的系数相加
##... | gnss_message', GNSS_CAN, self.FeedbackCallbackGPSIMU,queue_size = 10) #订阅GPS数据
rospy.Subscriber("Motor_Feedback_mssage", Motor_Feedback,self.RVcallback,queue_size = 10)
def FeedbackCallbackGPSIMU(self, msg):
self.CurrGPS_lat = msg.latitude
self.Curr... | criber(' | identifier_name |
path_planning.py | square of diff from target speed
ds = (TARGET_SPEED - tfp.s_d[-1])**2
# 横向的损失函数
tfp.cd = KJ * Jp + KT * Ti + KD * tfp.d[-1]**2
# 纵向的损失函数
tfp.cv = KJ * Js + KT * Ti + KD * ds
# 总的损失函数为d 和 s方向的损失函数乘对应的系数相加
##... | #buffer
GPS_x = [] #所采集预描点的x
GPS_y = [] #所采集预描点的x
#读取预描点
nums, ber = np.loadtxt("/home/robot/Robot/Smart_robot_ws/sr... | #buffer
white = [] #buffer
yellow = [] | conditional_block |
pyNN_target_sim.py | ike_times)
if is_module_installed('pynn_object_serialisation'):
from pynn_object_serialisation.functions import intercept_simulator
current_time = time.strftime("_%H%M%S_%d%m%Y")
intercept_simulator(self.sim, "snn_toolbox_pynn_" + current_time)
self.sim.run(self._du... | ad_assembly(s | identifier_name | |
pyNN_target_sim.py | connections.append((new_i, j, weights[i, j], delay))
elif len(self.flatten_shapes) > 1:
raise RuntimeWarning("Not all Flatten layers have been consumed.")
else:
for i in range(weights.shape[0]):
for j in range(weights.shape[1]):
connections.ap... | """Write layers of neural network to disk.
The size, structure, labels of all the population of an assembly are
stored in a dictionary such that one can load them again using the
`load_assembly` function.
The term "assembly" refers to pyNN internal nomenclature, where
``Assembl... | identifier_body | |
pyNN_target_sim.py | .append(
(layer.name, get_shape_from_label(self.layers[-1].label)))
return
self.layers.append(self.sim.Population(
np.prod(layer.output_shape[1:], dtype=np.int).item(),
self.sim.IF_curr_exp, self.cellparams, label=layer.name))
self.layers[-1].initial... |
def end_sim(self):
self.sim.end()
def save(self, path, filename):
print("Saving model to {}...".format(path))
self.save_assembly(path, filename)
self.save_connections(path)
self.save_biases(path)
print("Done.\n")
def load(self, path, filename):
... | print("Resetting simulator...")
self.sim.reset()
print("Done.") | conditional_block |
pyNN_target_sim.py | (self.sim.Projection(
self.layers[-2], self.layers[-1],
self.sim.FromListConnector(connections, ['weight', 'delay'])))
def build_pooling(self, layer):
from snntoolbox.simulation.utils import build_pooling
delay = self.config.getfloat('cell', 'delay')
connect... | NEST.
Parameters | random_line_split | |
models.py | ', null=True, blank=True)
url_format = models.CharField(max_length=250, blank=True, null=True, verbose_name='URL format', help_text='Use <id> to create a placeholder for remote_id on links of this type.')
featured = models.BooleanField(db_index=True, blank=True, default=False)
public = models.BooleanField(db... | return True | conditional_block | |
models.py | =True, verbose_name='date/time modified')
timestamp_post = models.DateTimeField(default=timezone.now, db_index=True, verbose_name='date/time created')
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('category', kwargs={'cached_url':self.cached_url,})
@property
def cont... |
def save(self, *args, **kwargs):
if self.parent:
self.cached_url = '%s/%s' % (self.parent.cached_url, self.slug)
else:
self.cached_url = self.slug
super(category, self).save(*args, **kwargs)
def can_edit(self, request=False):
if not request:
return (False,'access_norequest')
else:
canview = ... | return self.summary_short | random_line_split |
models.py | , blank=True, default=False)
automated = models.BooleanField(db_index=True, blank=True, default=False)
notes = models.TextField(null=True, blank=True)
def __unicode__(self):
return '%s: %s' % (self.link_type.name, unicode(self.parent))
def get_absolute_url(self):
return self.url
@property
def url(self):... | get_absolute_url | identifier_name | |
models.py | =True, verbose_name='date/time modified')
timestamp_post = models.DateTimeField(default=timezone.now, db_index=True, verbose_name='date/time created')
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('category', kwargs={'cached_url':self.cached_url,})
@property
def cont... |
# ALIAS
@property
def rss_description(self):
return self.summary_short
class Meta:
ordering = ['slug',]
class tag_synonym(models.Model):
parent = models.ForeignKey(tag, on_delete=models.CASCADE, related_name='synonyms')
slug = models.SlugField(max_length=200,unique=True)
timestamp_mod = models.DateTime... | return self.get_summary(512) | identifier_body |
util.py | agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import dataclasses
import hashlib
import ... | # check if we need to patch
layer_tar = tarfile.open(fileobj=fileobj)
# normalise paths
layer_tar_paths = {
path.lstrip('./') for path in layer_tar.getnames()
}
have_match = bool(layer_tar_paths & remove_entries)
fileobj.seek(0)
if not have_ma... | layer_paths = set(manifest['Layers'])
changed_layer_hashes = [] # [(old, new),]
# copy everything that does not need to be patched
for tar_info in in_tarfile:
if not tar_info.isfile():
out_tarfile.addfile(tar_info)
continue
# cfg needs to be rewritten - so do not cp... | identifier_body |
util.py | to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import dataclasses
import hashlib
import json
im... | (
image_file,
out_file,
remove_entries,
):
ci.util.existing_file(image_file)
if not remove_entries:
raise ValueError('remove_entries must not be empty')
# allow absolute paths
remove_entries = [e.lstrip('/') for e in remove_entries]
with tarfile.open(image_file) as tf:
m... | filter_container_image | identifier_name |
util.py | agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import dataclasses
import hashlib
import ... | image_reference=target_ref,
digest=(layer_digest := 'sha256:' + layer_hash.hexdigest()),
octets_count=leng,
data=f,
)
# update copy of layers-list with new layer
new_layer = dataclasses.replace(layer, digest=layer_diges... | f.write(chunk)
f.seek(0)
oci_client.put_blob( | random_line_split |
util.py | if not oci_client:
oci_client = ccc.oci.oci_client()
# shortcut in case there are no filtering-rules
if not remove_files:
return oci.replicate_artifact(
src_image_reference=source_ref,
tgt_image_reference=target_ref,
oci_client=oci_client,
)
... | temptar.addfile(tar_info)
continue | conditional_block | |
kibana.py | ibanaSavedObjects(self, type='index-pattern', search=None, fields=None):
type = '&type=' + type if type else ''
search = '&search=' + search if search else ''
fields = '&fields=' + fields if fields else ''
resp = requests.get(self.kibanaUrl(f'/api/saved_objects/_find?{type}{search}{field... | # },
# 'title': title,
# 'type': visType,
# }
assert isinstance(viz, Visualization)
visState = viz.visState(title)
searchSourceJSON = {
"index":indexPatternUID,
"filter":[],
"query":{"language":"kuery","query":""}
... | # ],
# 'params': {
# 'type': 'histogram' | random_line_split |
kibana.py | }
if description is not None:
attributes['description'] = description
if sort is not None:
attributes['sort'] = sort
uid, res = self.postKibanaSavedObject(type='search', attributes=attributes)
if setDefaultSearch:
self._defaultSearchUID = uid
... | super(Histogram, self).__init__(field)
self.visType = 'histogram'
self.interval = interval | identifier_body | |
kibana.py |
how = how if isinstance(how, list) else [how]
url = self.kibanaUrl(*args, **kwargs)
if 'print' in how:
print(f"Open: {url}")
if 'webbrowser' in how:
import webbrowser
webbrowser.open(url)
if 'jupyter' in how or 'ipython' in how:
fr... | how = 'jupyter' if util.__IS_JUPYTER else 'webbrowser'
# TODO can we figure out "non-interactive" to put how='print' then? | conditional_block | |
kibana.py | anaSearch(self, title, columns, description=None, sort=None, setDefaultSearch=True, indexPatternUID=None):
if indexPatternUID is None:
indexPatternUID = self._defaultIndexPatternUID
searchSourceJSON = {
"index": indexPatternUID,
# "highlightAll": True,
# "... | TagCloud | identifier_name | |
mod.rs | {
pub symbols: Vec<ExampleSymbol>,
pub cursor: usize,
pub reductions: Vec<Reduction>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExampleSymbol {
Symbol(Symbol),
Epsilon,
}
#[derive(Copy, Clone, Default)]
pub struct ExampleStyles {
pub before_cursor: Style,
pub on_cursor: Style,
... |
fn starting_positions(&self, lengths: &[usize]) -> Vec<usize> {
lengths
.iter()
.scan(0, |counter, &len| {
let start = *counter;
// Leave space for "NT " (if "NT" is the name
// of the nonterminal).
*counter = start +... | {
let lengths = self.lengths();
let positions = self.positions(&lengths);
InlineBuilder::new()
.push(Box::new(ExamplePicture {
example: self,
positions,
styles,
}))
.indented()
.end()
} | identifier_body |
mod.rs | {
pub symbols: Vec<ExampleSymbol>,
pub cursor: usize,
pub reductions: Vec<Reduction>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExampleSymbol {
Symbol(Symbol),
Epsilon,
}
#[derive(Copy, Clone, Default)]
pub struct ExampleStyles {
pub before_cursor: Style,
pub on_cursor: Style,
... | (&self) -> Vec<::ascii_canvas::Row> {
let this = self.clone();
let content = this.into_picture(ExampleStyles::default());
let min_width = content.min_width();
let canvas = content.emit_to_canvas(min_width);
canvas.to_strings()
}
fn paint_on(&self, styles: &ExampleStyles,... | paint_unstyled | identifier_name |
mod.rs | ///
/// The top-line is the `symbols` vector. The groupings below are
/// stored in the `reductions` vector, in order from smallest to
/// largest (they are always properly nested). The `cursor` field
/// indicates the current lookahead token.
///
/// The `symbols` vector is actually `Option<Symbol>` to account
/// for... | /// ``` | random_line_split | |
install.go | "
}
func (ev *envValue) Freeze() {
ev.vars.Freeze()
ev.prependPath.Freeze()
ev.appendPath.Freeze()
}
func (ev *envValue) Truth() starlark.Bool {
return ev.vars.Len() > 0 || ev.prependPath.Len() > 0 || ev.appendPath.Len() > 0
}
func (ev *envValue) Hash() (uint32, error) {
//lint:ignore ST1005 referencing Environ... | {
return sortedStringDictKeys(mod.attrs)
} | identifier_body | |
install.go | biome to run inside")
return cmd
}
func (c *installCommand) run(ctx context.Context) (err error) {
db, err := openDB(ctx)
if err != nil {
return err
}
defer db.Close()
endFn, err := sqlitex.ImmediateTransaction(db)
if err != nil {
return err
}
defer endFn(&err)
rec, err := findBiome(db, c.biomeID)
if er... | return err
}
return nil
}
const threadContextKey = "zombiezen.com/go/biome.Context"
func threadContext(t *starlark.Thread) context.Context {
ctx, _ := t.Local(threadContextKey).(context.Context)
if ctx == nil {
ctx = context.Background()
}
return ctx
}
type envValue struct {
vars *starlark.Dict
pr... | return fmt.Errorf("install return value: %w", err)
}
if err := writeBiomeEnvironment(db, rec.id, rec.env.Merge(installEnv)); err != nil { | random_line_split |
install.go | {
return fmt.Errorf("`install` is declared as %s instead of function", installFuncValue.Type())
}
if !installFunc.HasKwargs() {
//lint:ignore ST1005 referencing Environment constructor
return fmt.Errorf("install function does not permit extra keyword arguments. " +
"Please add `**kwargs` to the end of insta... | {
arg, ok := starlark.AsString(args.Index(i))
if !ok {
return nil, fmt.Errorf("%s: could not convert arg[%d] to string", fn.Name(), i)
}
stringArgs = append(stringArgs, arg)
} | conditional_block | |
install.go | (ev *envValue) Type() string {
return "Environment"
}
func (ev *envValue) Freeze() {
ev.vars.Freeze()
ev.prependPath.Freeze()
ev.appendPath.Freeze()
}
func (ev *envValue) Truth() starlark.Bool {
return ev.vars.Len() > 0 || ev.prependPath.Len() > 0 || ev.appendPath.Len() > 0
}
func (ev *envValue) Hash() (uint32... | AttrNames | identifier_name | |
mod.rs | > = Vec::new();
let display_txt = |txt: &str| -> template_engine::Template {
let mut tmp_engine = template_engine::TemplateFactory::init()
.parse_in_template(txt)
.create_movable()
.collect();
let template = tmp_engine.padding(vec![1, 6, 6... | println!("t {}", test);
let x: &[_] = &['[', ']']; | random_line_split | |
mod.rs | template_engine::TemplateFactory::init()
.parse_in_template(txt)
.create_movable()
.collect();
let template = tmp_engine.padding(vec![1, 6, 6, 3]);
template.to_owned()
};
match self.query.as_str() {
"update" => {
... | {
let match_inside_brac = regex::Regex::new(r"^\[(.*)\]$").unwrap();
let test = "[Apple sauce bananan ba;;;a]";
println!("t {}", test);
let x: &[_] = &['[', ']'];
println!(
"test {:?} ",
(match_inside_brac.is_match(test), test.trim_matches(x))
);
} | identifier_body | |
mod.rs | 3 {
return Err("Insufficient parameters to run file operations!");
}
let capture = |index: usize| command_chunk.get(index).unwrap().to_owned();
let mut vc: [Vec<String>; 2] = [Vec::new(), Vec::new()];
if command_chunk.len() > 3 {
let v_param = command_chunk[3..com... | (result: &str) -> OriResult<String> {
if result.is_empty() {
let empty_err = FileError::new().set_message("The Folder is Empty inside");
Err(empty_err)
} else {
Ok(result.trim().to_string())
}
}
impl Operation for Fileconfig {
fn read(&self) -> OriResult<String> {
let fil... | checkempty | identifier_name |
sketch.js | 0)
{
textSize(72);
background(bg);
text("Pharah", 800, 100);
textSize(60);
text("Press (1) - EASY", 700, 200);
text("Press (2) - NORMAL", 700, 300);
text("Press (3) - HARD", 700, 400);
text("CONTROLS", 800, 500);
textSize(32);
text("Left / Right Arrow, or A / D", 700, 550);
... | {
score += 1;
if (score >= 6)
{
state = 2;
}
}
//Pharah takes damage if she touches people
if(pharah.detectHit(enemyArr[i].xPos, enemyArr[i].yPos))
{
pharah.health -= 10;
}
}
}
}
//standard gameov... | random_line_split | |
sketch.js |
//preload assets
function preload()
{
pharahSprite = loadImage("images/pharahSprite_small.png");
bg = loadImage("images/bg.png");
crosshairSprite = loadImage("images/crosshair.png");
bulletSprite = loadImage("images/bullet.png");
soundFormats("mp3");
shotSound = loadSound("sounds/exp.mp3");
//enemies, p... | {
// grab the range data as an integer
rangeData = int(clickedRange.value);
} | identifier_body | |
sketch.js | 0)
{
textSize(72);
background(bg);
text("Pharah", 800, 100);
textSize(60);
text("Press (1) - EASY", 700, 200);
text("Press (2) - NORMAL", 700, 300);
text("Press (3) - HARD", 700, 400);
text("CONTROLS", 800, 500);
textSize(32);
text("Left / Right Arrow, or A / D", 700, 550);
... | ()
{
//contain logic within borders
if (this.xPos + this.sprite.width > width)
{
this.xSpeed = 0;
this.collided = true;
this.xPos = width - this.sprite.width
}
if (this.xPos < 0)
{
this.xSpeed = 0;
this.collided = true;
this.xPos = 0;
}
if (this.yPos... | move | identifier_name |
sketch.js | 00);
text("CONTROLS", 800, 500);
textSize(32);
text("Left / Right Arrow, or A / D", 700, 550);
text("Press SPACEBAR to use Fuel", 700, 600);
text("Click to shoot!", 700, 650);
//EASY
if (keyIsDown(49))
{
ammo = 12;
health = 1500;
state = 1;
pharah = new Pharah(hea... | {
this.xSpeed -= this.gravity;
if (this.xSpeed < 0)
{
this.right = false;
this.left = true;
}
} | conditional_block | |
FactorPropertyController.js | ref: 'factorGrid'
},{
selector: '#factorPropertyGrid',
ref: 'factorPropertyGrid'
},{
selector: '#factorProperty',
ref: 'factorProperty'
},{
selector: '#factorDataGrid',
ref: 'factorDataGrid'
}],
init: function() {
this.control({
'#f... | Ext.MessageBox.alert('提示', '您选中的属性包含固有属性,因子固有属性不能删除!');
return;
}
}
Ext | if("1"===(sm.getSelection()[i].get('prototype')+"")){ | random_line_split |
FactorPropertyController.js | });
},
containerclick:function(){
// alert('containerclick');
document.getElementById('factorGrid_header').style.removeProperty('background-color');
document.getElementById('factorGrid_header').style.removeProperty('background-image');
document.getElementById('factorPropertyGrid... | }
Ext.Ajax.request({
url: '../work-platform/deleteFactorInstances.do',
params: {
deleteFactorInstances:Ext.encode | conditional_block | |
train_ibp.py | from keras.backend.tensorflow_backend import set_session
from models_ibp import SmallCNN, MediumCNN, LargeCNN, LargeCNN_2, \
ScheduleHyperParamCallback, ConstantSchedule, \
InterpolateSchedule, ibp_loss
import math
import argparse
from pathlib import Path
from datetime im... | (y_true, y_pred):
return model.robust_accuracy
if config.load_weights_from is not None:
model.load_weights(config.load_weights_from)
metrics = ["accuracy", robust_acc]
model.compile(loss=loss, optimizer=Adam(lr=config.lr), metrics=metrics)
model.summary()
##################
# Setup training #
#############... | robust_acc | identifier_name |
train_ibp.py | from keras.backend.tensorflow_backend import set_session
from models_ibp import SmallCNN, MediumCNN, LargeCNN, LargeCNN_2, \
ScheduleHyperParamCallback, ConstantSchedule, \
InterpolateSchedule, ibp_loss
import math
import argparse
from pathlib import Path
from datetime im... |
else:
mean, std = None, None
if config.model_name == "SmallCNN":
model = SmallCNN(input_shape=input_shape)
elif config.model_name == "MediumCNN":
model = MediumCNN(input_shape=input_shape)
elif config.model_name == "LargeCNN":
model = LargeCNN(input_shape=input_shape)
elif config.model_name == "LargeC... | mean, std = x_train.mean(axis=(0, 1, 2)), x_train.std(axis=(0, 1, 2)) + 1e-6
x_train = (x_train - mean) / std
x_valid = (x_valid - mean) / std
print("Normalising channels with values", mean, std) | conditional_block |
train_ibp.py | from keras.backend.tensorflow_backend import set_session
from models_ibp import SmallCNN, MediumCNN, LargeCNN, LargeCNN_2, \
ScheduleHyperParamCallback, ConstantSchedule, \
InterpolateSchedule, ibp_loss
import math
import argparse
from pathlib import Path
from datetime im... |
if config.load_weights_from is not None:
model.load_weights(config.load_weights_from)
metrics = ["accuracy", robust_acc]
model.compile(loss=loss, optimizer=Adam(lr=config.lr), metrics=metrics)
model.summary()
##################
# Setup training #
##################
# Prepare model model saving directory
mode... | return model.robust_accuracy | identifier_body |
train_ibp.py | from keras.backend.tensorflow_backend import set_session
from models_ibp import SmallCNN, MediumCNN, LargeCNN, LargeCNN_2, \
ScheduleHyperParamCallback, ConstantSchedule, \
InterpolateSchedule, ibp_loss
import math
import argparse
from pathlib import Path
from datetime im... | batch_size=config.batch_size,
callbacks=callbacks)
else:
print('Using real-time data augmentation.')
shift = 4 if config.dataset == "CIFAR10" else 2
# This will do preprocessing and realtime data augmentation:
datagen = Image | random_line_split | |
main.rs | char_cols;
match c {
'\n' => {
after = 0;
end = i;
space = true;
cols = max_cols + 1;
}
' ' => {
after = 0;
end = i;
space = true;
}
'-' | ... |
dir: Direction,
skip: bool,
}
#[derive(Clone)]
enum Direction {
Next,
Prev,
}
pub struct Bk<'a> {
quit: bool,
chapters: Vec<epub::Chapter>,
// position in the book
chapter: usize,
line: usize,
mark: HashMap<char, (usize, usize)>,
links: HashMap<String, (usize, usize)>,
... | archArgs { | identifier_name |
main.rs | char_cols;
match c {
'\n' => {
after = 0;
end = i;
space = true;
cols = max_cols + 1;
}
' ' => {
after = 0;
end = i;
space = true;
}
'-' | ... | }
false
}
}
}
}
#[derive(argh::FromArgs)]
/// read a book
struct Args {
#[argh(positional)]
path: Option<String>,
/// background color (eg 282a36)
#[argh(option)]
bg: Option<String>,
/// foreground color (eg f8f8f2)
#[argh(option)]
... | self.jump_byte(c, index);
return true;
}
| conditional_block |
main.rs | bk = Bk {
quit: false,
chapters,
chapter: 0,
line: 0,
mark: HashMap::new(),
links: epub.links,
colors: args.colors,
cols,
rows: rows as usize,
max_width: args.width,
view: if args.toc { &... | random_line_split | ||
colors.rs | /// [`SetConsoleTextAttribute`]: https://docs.microsoft.com/en-us/windows/console/setconsoletextattribute
pub fn set_text_attributes(h: HANDLE, attributes: u16) -> io::Result<()> {
if unsafe { SetConsoleTextAttribute(h, attributes) } == 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}... | cur_attr: TextAttributes,
}
#[derive(Clone, Copy, Debug)]
enum HandleKind {
Stdout,
Stderr,
}
impl HandleKind {
fn handle(&self) -> HANDLE {
match *self {
HandleKind::Stdout => io::stdout().as_raw_handle() as HANDLE,
HandleKind::Stderr => io::stderr().as_raw_handle() as... | #[derive(Debug)]
pub struct Console {
kind: HandleKind,
start_attr: TextAttributes, | random_line_split |
colors.rs | then an error
/// is returned.
pub fn bg(&mut self, intense: Intense, color: Color) -> io::Result<()> {
self.cur_attr.bg_color = color;
self.cur_attr.bg_intense = intense;
self.set()
}
/// Reset the console text attributes to their original settings.
///
/// The origina... | {
let attr = "leading bytes \x1b[1m trailing bytes";
let parsed = driver(parse_attr, attr).unwrap();
assert_eq!(parsed, b'1');
} | identifier_body | |
colors.rs | [`SetConsoleTextAttribute`]: https://docs.microsoft.com/en-us/windows/console/setconsoletextattribute
pub fn set_text_attributes(h: HANDLE, attributes: u16) -> io::Result<()> {
if unsafe { SetConsoleTextAttribute(h, attributes) } == 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
/... | () -> io::Result<Console> {
Self::create_for_stream(HandleKind::Stdout)
}
/// Create a new Console to stderr.
///
/// If there was a problem creating the console, then an error is returned.
pub fn stderr() -> io::Result<Console> {
Self::create_for_stream(HandleKind::Stderr)
}
... | stdout | identifier_name |
log.go | }\033[0m"
// DebugColorFormat with color
DebugColorFormat = "\033[1;33m%{level}\033[0m \033[1;36m%{time:2006-01-02 15:04:05.000}\033[0m \033[0;34m%{shortfile}\033[0m \033[0;32mgrtid:%{goroutineid}/gcnt:%{goroutinecount}\033[0m %{message}"
// CliFormat simple format
CliFormat = "\033[1;33m%{level}\033[0m \033[1;36m%... | filename
return lo
}
// SetLevel set log level
func (lo *LogOption) SetLevel(level string) *LogOption {
lo.Level = parseLogLevel(level)
return lo
}
// SetTypedLevel set log level
func (lo *LogOption) SetTypedLevel(level Level) *LogOption {
lo.Level = level
return lo
}
// SetFormat set log format
func (lo *LogO... | gFile = | identifier_name |
log.go | lstr {
case "critical":
return CRITICAL
case "error":
return ERROR
case "warning":
return WARNING
case "notice":
return NOTICE
case "info":
return INFO
case "debug":
return DEBUG
default:
return INFO
}
}
// LogOption log config options
type LogOption struct {
LogFile string
Level ... | func MustNoErr(err error, desc ...string) {
if err != nil {
stackInfo := debug.Stack()
start := 0 | random_line_split | |
log.go | }\033[0m"
// DebugColorFormat with color
DebugColorFormat = "\033[1;33m%{level}\033[0m \033[1;36m%{time:2006-01-02 15:04:05.000}\033[0m \033[0;34m%{shortfile}\033[0m \033[0;32mgrtid:%{goroutineid}/gcnt:%{goroutinecount}\033[0m %{message}"
// CliFormat simple format
CliFormat = "\033[1;33m%{level}\033[0m \033[1;36m%... | LogFp, "", 0)
backendInfoFormatter := logging.NewBackendFormatter(backendInfo, format)
backendInfoLeveld := logging.AddModuleLevel(backendInfoFormatter)
backendInfoLeveld.SetLevel(opt.Level.loggingLevel(), "")
leveldBackend = backendInfoLeveld
backends = append(backends, backendInfoLeveld)
opt.files = appen... | ", filename, err)
}
backendInfo := logging.NewLogBackend(info | conditional_block |
log.go | outinecount}\033[0m %{message}"
// CliFormat simple format
CliFormat = "\033[1;33m%{level}\033[0m \033[1;36m%{time:2006-01-02 15:04:05}\033[0m \033[0;32m%{message}\033[0m"
)
// Level log level
type Level int
const (
// CRITICAL level
CRITICAL Level = iota + 1
// ERROR level
ERROR
// WARNING level
WARNING
// ... | ltLgr.Criticalf(strings.TrimSpace(strings.Repeat("%+v ", len(args))), args...)
}
// Fatal write leveled log
func Fatal(args | identifier_body | |
appendlist.rs | with a `Vec`:
///
/// ```
/// use appendlist::AppendList;
///
/// let list = AppendList::new();
///
/// list.push(1);
/// let first_item = &list[0];
/// list.push(2);
/// let second_item = &list[1];
///
/// assert_eq!(*first_item, list[0]);
/// assert_eq!(*second_item, list[1]);
/// ```
///
/// # Implementation detail... | self.len.get() - chunk_start(self.chunks().len() - 1)
);
} else {
// No chunks
assert_eq!(0, self.chunks().len());
}
}
}
/// Create a new `AppendList`
pub fn new() -> Self {
Self {
chunk... | {
#[cfg(test)]
{
if self.len.get() > 0 {
// Correct number of chunks
assert_eq!(index_chunk(self.len.get() - 1), self.chunks().len() - 1);
// Every chunk holds enough items
for chunk_id in 0..self.chunks().len() {
... | identifier_body |
appendlist.rs | with a `Vec`:
///
/// ```
/// use appendlist::AppendList;
///
/// let list = AppendList::new();
///
/// list.push(1);
/// let first_item = &list[0];
/// list.push(2);
/// let second_item = &list[1];
///
/// assert_eq!(*first_item, list[0]);
/// assert_eq!(*second_item, list[1]);
/// ```
///
/// # Implementation detail... | (&self) -> usize {
self.check_invariants();
self.len.get()
}
/// Get an item from the list, if it is in bounds
///
/// Returns `None` if the `index` is out-of-bounds. Note that you can also
/// index with `[]`, which will panic on out-of-bounds.
pub fn get(&self, index: usize) ... | len | identifier_name |
appendlist.rs | illegal with a `Vec`:
///
/// ```
/// use appendlist::AppendList;
///
/// let list = AppendList::new();
///
/// list.push(1);
/// let first_item = &list[0];
/// list.push(2);
/// let second_item = &list[1];
///
/// assert_eq!(*first_item, list[0]);
/// assert_eq!(*second_item, list[1]);
/// ```
///
/// # Implementatio... | impl<'l, T> Iterator for Iter<'l, T> {
type Item = &'l T;
fn next(&mut self) -> Option<Self::Item> {
let item = self.list.get(self.index);
self.index += 1;
item
}
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.list.len() - self.index;
(r... | index: usize,
}
| random_line_split |
unified.rs | ParseError::InvalidEncoding(msg) => write!(f, "Invalid encoding: {}", msg),
ParseError::OnlyTransparent => write!(f, "UA only contains transparent receivers"),
}
}
}
impl Error for ParseError {}
/// The set of known Receivers for Unified Addresses.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]... | else {
typecodes.insert(t);
}
}
if typecodes.iter().all(|t| t.is_transparent()) {
Err(ParseError::OnlyTransparent)
} else {
// All checks pass!
Ok(Address(receivers))
}
}
}
impl Address {
/// Returns the raw encod... | {
return Err(ParseError::BothP2phkAndP2sh);
} | conditional_block |
unified.rs | {
/// The unified address contains both P2PKH and P2SH receivers.
BothP2phkAndP2sh,
/// The unified address contains a duplicated typecode.
DuplicateTypecode(Typecode),
/// The parsed typecode exceeds the maximum allowed CompactSize value.
InvalidTypecodeValue(u64),
/// The string is an inv... | ParseError | identifier_name | |
unified.rs | // Unknown typecodes are treated as not transparent for the purpose of disallowing
// only-transparent UAs, which can be represented with existing address encodings.
matches!(self, Typecode::P2pkh | Typecode::P2sh)
}
}
/// An error while attempting to parse a string as a Zcash address.
#[de... | impl Typecode {
fn is_transparent(&self) -> bool { | random_line_split | |
__init__.py |
return wrapped
return wrapper(_lambda)
def get_unique_path(filepath):
'''
Append `-###` to the base name of a file until a file path is found that
does not exist.
Args
----
filepath (str) : Full file path to target file.
Returns
-------
(path) : Full path w... | f(self, *f_args, **f_kwargs) | conditional_block | |
__init__.py | host_version = self.dropbot_dx_remote.host_software_version
remote_version = self.dropbot_dx_remote.remote_software_version
if remote_version != host_version:
response = yesno('The DropBot DX firmware version (%s) '
... | '''
Connect to dropbot-dx instrument.
'''
self.has_environment_data = False
self.environment_sensor_master = None
# if the dropbot dx plugin is installed and enabled, try getting its
# reference
try:
service = get_service_instance_by_name('wheelerlab.... | identifier_body | |
__init__.py | (Plugin, AppDataController, StepOptionsController):
"""
This class is automatically registered with the PluginManager.
"""
implements(IPlugin)
version = get_plugin_info(path(__file__).parent).version
plugin_name = get_plugin_info(path(__file__).parent).plugin_name
AppFields = Form.of(Float.... | DropBotDxAccessoriesPlugin | identifier_name | |
__init__.py | does not match the driver version (%s). '
'Update firmware?' % (remote_version,
host_version))
if response == gtk.RESPONSE_YES:
self.on_flash_firmware()
# turn on ... |
###########################################################################
# # Plugin signal handlers #
def get_schedule_requests(self, function_name):
"""
|
if valid:
options['dstat_params_file'] = response['dstat_params_file']
self.set_step_values(options) | random_line_split |
Script_graph_data.py | _data_reconstructed
def Export_in_files(COVID_data, COVID_data_reconstructed):
"""
Exports the raw and reconstructed data in seperate files
Parameters:
- COVID_data: Dictionnary of cases, deaths and positivity rate data throughout the world
- Covid_data_reconstructued: Reco... | Countries_to_annotate[Country] = Points_to_display[Country_inc] # The country has to be annotated
Annotations_mask[Annotation_slice] = True # All the elements in Annotations_mask in this area are set to True to signify there is now an annotation displayed there
| conditional_block | |
Script_graph_data.py | _data[Country].values()) # Extract the matrix containing the data and transpose it. That way, each element of a single list in the array corresponds to one column (see help of Main_script) and it makes it easier to navigate through each column and recontruct the missing elements
T_COVID_data_single_country = l... | """
Tells which countries to annotate and which not to. Since the lists in parameters are sorted by descending order of positivity rate, the countries with higher positivity rates will be examined first and thus annotatd with more priority
Parameters:
- Points_to_display: List of X and Y coordi... | identifier_body | |
Script_graph_data.py | coordinate are excluded (because log(0) doesn't exist).
# This double verification can't be done in one line because having None in a list you're trying to find the minimum of prompts an error
except: pass
if COVID_data_scatter[Date] == {}: COVID_data_scatter.pop(Da... | random_line_split | ||
Script_graph_data.py | (X_axis_inc = 1, Y_axis_inc = 7, Z_axis_inc = 12, Date_start = None, Date_end = None):
"""
Main routine to execute to download, extract, reconstruct and plot COVID data
Parameters:
- X_axis_inc: Integer, data to use for the X axis. Default is 1 (Total cases per million)
- Y_axis_i... | Main_script | identifier_name | |
script.js | 50,
rotating:50,
}
window.timeouts = {
}
window.maps = [
map1,
map2,
map3,
map4,
map5
]
window.state = {
paused:true,
gameStart:true,
crashed:false,
completed:false,
mapIndex:0,
}
///GLOBAL METHODS-----------------------------------------
window.killScreen = func... | (){
for(let key in activeKeys){
delete activeKeys[key]
}
}
function handleVictory(){
clearIntervals()
screens({
title:'Goal reached!',
content:"",
button:"Next Level",
})
state.paused=true
state.completed=true
}
var crashListener = setInte... | deleteKeys | identifier_name |
script.js | 50,
rotating:50,
}
window.timeouts = {
}
window.maps = [
map1,
map2,
map3,
map4,
map5
]
window.state = {
paused:true,
gameStart:true,
crashed:false,
completed:false,
mapIndex:0,
}
///GLOBAL METHODS-----------------------------------------
window.killScreen = func... |
}
function checkCrash(){
if(state.paused) return
let ratio = rotationPercentage()
function checkBoundaries(){
if(
(yPosition + (25 * ratio) ) < 0 | //TOP
((yPosition + mycar.offsetHeight) - (25 * ratio) ) > gameArea.offsetHeight | //BOTTOM
(xPosition - (25 * r... | {
return false
} | conditional_block |
script.js | 50,
rotating:50,
}
window.timeouts = {
}
window.maps = [
map1,
map2,
map3,
map4,
map5
]
window.state = {
paused:true,
gameStart:true,
crashed:false,
completed:false,
mapIndex:0,
}
///GLOBAL METHODS-----------------------------------------
window.killScreen = func... | timeouts[timeout].stopTimeout()
delete timeouts[timeout]
}
}
window.rotationPercentage = function(){
let ratio
(rotationAngle%360)/360 < 0 ? ratio = Math.abs((rotationAngle%360)/360 + 1) : ratio = (rotationAngle%360)/360
if(ratio >= 0.5) ratio = (1 - ratio)
ratio*=4
if(rat... | window.destroyTimeouts = function(){
for(let timeout in timeouts){ | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.