file_name large_stringlengths 4 69 | prefix large_stringlengths 0 26.7k | suffix large_stringlengths 0 24.8k | middle large_stringlengths 0 2.12k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
watched_bitfield.rs | use crate::{BitField8, Error};
use std::{
fmt::{self, Display},
str::FromStr,
};
/// (De)Serializable field that tracks which videos have been watched
/// and the latest one watched.
///
/// This is a [`WatchedBitField`] compatible field, (de)serialized
/// without the knowledge of `videos_ids`.
///
/// `{anch... | for i in 0..video_ids.len() {
// TODO: Check what will happen if we change it to `usize`
let id_in_prev = i as i32 + offset;
if id_in_prev >= 0 && (id_in_prev as usize) < bitfield.length {
resized_wbf.set(i, bitfield.get... | bitfield: BitField8::new(video_ids.len()),
video_ids: video_ids.clone(),
};
// rewrite the old buf into the new one, applying the offset | random_line_split |
main.rs | use std::{fmt::Display, ops::Index, str::FromStr};
use anyhow::{bail, Error};
use intcode::Computer;
static INPUT: &str = include_str!("input.txt");
struct View {
view: Vec<u8>,
width: usize,
height: usize,
}
impl FromStr for View {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Er... | o = n.0;
break;
}
}
if!found_turn {
break;
}
}
let route = Route(route);
Ok(route)
}
}
fn part_01(input: &str) -> Result<usize, Error> {
let mut aligment_parameters = 0;
le... | found_turn = true;
route.append(&mut o.orient(n.0)); | random_line_split |
main.rs | use std::{fmt::Display, ops::Index, str::FromStr};
use anyhow::{bail, Error};
use intcode::Computer;
static INPUT: &str = include_str!("input.txt");
struct View {
view: Vec<u8>,
width: usize,
height: usize,
}
impl FromStr for View {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Er... |
fn forward(&self, pos: (usize, usize), o: Orientation) -> Option<(usize, usize)> {
let width = self.width;
let height = self.height;
let d = o.delta();
pos.0
.checked_add_signed(d.0)
.and_then(|x| pos.1.checked_add_signed(d.1).map(|y| (x, y)))
.filt... | {
let width = self.width;
let height = self.height;
[
Orientation::Up,
Orientation::Down,
Orientation::Left,
Orientation::Right,
]
.into_iter()
.filter_map(move |o| {
let d = o.delta();
pos.0
... | identifier_body |
main.rs | use std::{fmt::Display, ops::Index, str::FromStr};
use anyhow::{bail, Error};
use intcode::Computer;
static INPUT: &str = include_str!("input.txt");
struct View {
view: Vec<u8>,
width: usize,
height: usize,
}
impl FromStr for View {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Er... | (&self, pos: (usize, usize), o: Orientation) -> Option<(usize, usize)> {
let width = self.width;
let height = self.height;
let d = o.delta();
pos.0
.checked_add_signed(d.0)
.and_then(|x| pos.1.checked_add_signed(d.1).map(|y| (x, y)))
.filter(move |(x, y)|... | forward | identifier_name |
main.rs | use std::{fmt::Display, ops::Index, str::FromStr};
use anyhow::{bail, Error};
use intcode::Computer;
static INPUT: &str = include_str!("input.txt");
struct View {
view: Vec<u8>,
width: usize,
height: usize,
}
impl FromStr for View {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Er... |
} else {
view.push(o);
}
}
let height = view.len() / width;
Ok(View {
view,
width,
height,
})
}
}
impl Index<(usize, usize)> for View {
type Output = u8;
fn index(&self, (x, y): (usize, usize)) -> ... | {
width = view.len();
} | conditional_block |
val.rs | //! A concrete implementation of `futures::Future`. It is similar in spirit as
//! `futures::Promise`, but is better suited for use with Tokio.
use futures::{Future, Poll, Task};
use std::mem;
use std::cell::Cell;
use std::sync::{Arc, Mutex};
use self::State::*;
/// A future representing the completion of an asynchro... | (&mut self, task: &mut Task) -> Poll<bool, ()> {
self.inner.poll(task)
}
fn schedule(&mut self, task: &mut Task) {
self.inner.schedule(task)
}
}
/*
*
* ===== Inner =====
*
*/
impl<T, E> Inner<T, E> {
/// Complete the future with the given result
fn complete(&self, res: Option<... | poll | identifier_name |
val.rs | //! A concrete implementation of `futures::Future`. It is similar in spirit as
//! `futures::Promise`, but is better suited for use with Tokio.
use futures::{Future, Poll, Task};
use std::mem;
use std::cell::Cell;
use std::sync::{Arc, Mutex};
use self::State::*;
/// A future representing the completion of an asynchro... | }).forget();
assert_eq!(123, rx.recv().unwrap());
}
#[test]
fn test_polling_aborted_future_panics() {
use std::thread;
let res = thread::spawn(|| {
let (c, val) = pair::<u32, ()>();
val.then(move |res| {
println!("WAT: {:?}", res);
... |
val.then(move |res| {
tx.send(res.unwrap()).unwrap();
res | random_line_split |
val.rs | //! A concrete implementation of `futures::Future`. It is similar in spirit as
//! `futures::Promise`, but is better suited for use with Tokio.
use futures::{Future, Poll, Task};
use std::mem;
use std::cell::Cell;
use std::sync::{Arc, Mutex};
use self::State::*;
/// A future representing the completion of an asynchro... |
/// Abort the computation. This will cause the associated `Val` to panic on
/// a call to `poll`.
pub fn abort(self) {
self.inner.complete(None, false);
}
/// Returns a `Future` representing the consuming end cancelling interest
/// in the future.
///
/// This function can onl... | {
self.inner.complete(Some(Err(err)), false);
} | identifier_body |
parser.rs | #[cfg(feature = "encoding")]
use encoding_rs::UTF_8;
use crate::encoding::Decoder;
use crate::errors::{Error, Result};
use crate::events::{BytesCData, BytesDecl, BytesEnd, BytesStart, BytesText, Event};
#[cfg(feature = "encoding")]
use crate::reader::EncodingRef;
use crate::reader::{is_whitespace, BangType, ParseState... | <'b>(&mut self, bytes: &'b [u8]) -> Result<Event<'b>> {
let mut content = bytes;
if self.trim_text_end {
// Skip the ending '<'
let len = bytes
.iter()
.rposition(|&b|!is_whitespace(b))
.map_or_else(|| bytes.len(), |p| p + 1);
... | emit_text | identifier_name |
parser.rs | #[cfg(feature = "encoding")]
use encoding_rs::UTF_8;
use crate::encoding::Decoder;
use crate::errors::{Error, Result};
use crate::events::{BytesCData, BytesDecl, BytesEnd, BytesStart, BytesText, Event};
#[cfg(feature = "encoding")]
use crate::reader::EncodingRef;
use crate::reader::{is_whitespace, BangType, ParseState... | /// Defines how to process next byte
pub state: ParseState,
/// Expand empty element into an opening and closing element
pub expand_empty_elements: bool,
/// Trims leading whitespace in Text events, skip the element if text is empty
pub trim_text_start: bool,
/// Trims trailing whitespace in... | #[derive(Clone)]
pub(super) struct Parser {
/// Number of bytes read from the source of data since the parser was created
pub offset: usize, | random_line_split |
parser.rs | #[cfg(feature = "encoding")]
use encoding_rs::UTF_8;
use crate::encoding::Decoder;
use crate::errors::{Error, Result};
use crate::events::{BytesCData, BytesDecl, BytesEnd, BytesStart, BytesText, Event};
#[cfg(feature = "encoding")]
use crate::reader::EncodingRef;
use crate::reader::{is_whitespace, BangType, ParseState... |
}
impl Default for Parser {
fn default() -> Self {
Self {
offset: 0,
state: ParseState::Init,
expand_empty_elements: false,
trim_text_start: false,
trim_text_end: false,
trim_markup_names_in_closing_tags: true,
check_end_n... | {
Decoder {
#[cfg(feature = "encoding")]
encoding: self.encoding.encoding(),
}
} | identifier_body |
parser.rs | #[cfg(feature = "encoding")]
use encoding_rs::UTF_8;
use crate::encoding::Decoder;
use crate::errors::{Error, Result};
use crate::events::{BytesCData, BytesDecl, BytesEnd, BytesStart, BytesText, Event};
#[cfg(feature = "encoding")]
use crate::reader::EncodingRef;
use crate::reader::{is_whitespace, BangType, ParseState... |
}
Ok(Event::Decl(event))
} else {
Ok(Event::PI(BytesText::wrap(&buf[1..len - 1], self.decoder())))
}
} else {
self.offset -= len;
Err(Error::UnexpectedEof("XmlDecl".to_string()))
}
}
/// Converts c... | {
self.encoding = EncodingRef::XmlDetected(encoding);
} | conditional_block |
context.rs | use super::{
branch_expander, data_expander, heap2stack, ir::*, normalizer, rewriter, simplifier, traverser,
};
use crate::ast;
use crate::module::ModuleSet;
use derive_new::new;
use if_chain::if_chain;
use std::collections::{hash_map, BTreeSet, HashMap};
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct Cont... | fn data_expansions(&mut self) -> &mut HashMap<CtId, data_expander::DataExpansion> {
self.data_expansions
}
}
#[derive(Debug, new)]
struct MatchExpander<'a> {
rt_id_gen: &'a mut RtIdGen,
data_expansions: &'a HashMap<CtId, data_expander::DataExpansion>,
}
impl<'a> branch_expander::Env for MatchE... | random_line_split | |
context.rs | use super::{
branch_expander, data_expander, heap2stack, ir::*, normalizer, rewriter, simplifier, traverser,
};
use crate::ast;
use crate::module::ModuleSet;
use derive_new::new;
use if_chain::if_chain;
use std::collections::{hash_map, BTreeSet, HashMap};
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct Cont... | (&mut self, def: CtDef) -> CtId {
let id = self.ct_id_gen.next();
self.defs.insert(id, def);
id
}
fn data_expansions(&mut self) -> &mut HashMap<CtId, data_expander::DataExpansion> {
self.data_expansions
}
}
#[derive(Debug, new)]
struct MatchExpander<'a> {
rt_id_gen: &'a... | add_def | identifier_name |
main.rs | extern crate fixedbitset;
extern crate getopts;
extern crate libc;
extern crate regex;
extern crate toml;
extern crate num_cpus;
use regex::Regex;
use std::fs;
use std::io;
use std::io::{Read, Write, BufRead};
use std::path;
use std::sync;
use std::sync::mpsc;
use std::thread;
#[cfg(not(test))]
fn main()
{
let arg... |
1 => {
let path = path::Path::new(&matches.free[0]);
match fs::File::open(&path) {
Err(why) => { panic!("can't open {}: {}", matches.free[0], why.to_string()) },
Ok(ref mut f) => { read_lines(f) },
}
}
_ => { panic!("too many f... | { read_lines(&mut io::stdin()) } | conditional_block |
main.rs | extern crate fixedbitset;
extern crate getopts;
extern crate libc;
extern crate regex;
extern crate toml;
extern crate num_cpus;
use regex::Regex;
use std::fs;
use std::io;
use std::io::{Read, Write, BufRead};
use std::path;
use std::sync;
use std::sync::mpsc;
use std::thread;
#[cfg(not(test))]
fn main()
{
let arg... | (spec: &Spec, line_index: usize, lines: &Vec<String>, sender: &mpsc::Sender<(isize, isize)>)
{
if let Some(ref rx) = spec.start {
if rx.is_match(&lines[line_index][..]) {
let sel_range = if spec.stop.is_some() || spec.whale.is_some() { try_select(&spec, lines, line_index as isize) } else { Some(... | process_spec | identifier_name |
main.rs | extern crate fixedbitset;
extern crate getopts;
extern crate libc;
extern crate regex;
extern crate toml;
extern crate num_cpus;
use regex::Regex;
use std::fs;
use std::io;
use std::io::{Read, Write, BufRead};
use std::path;
use std::sync;
use std::sync::mpsc;
use std::thread;
#[cfg(not(test))]
fn main()
{
let arg... |
#[derive(Clone)]
struct Spec
{
disable: bool,
start: Option<Regex>,
start_offset: isize,
stop: Option<Regex>,
stop_offset: isize,
whale: Option<Regex>,
backward: bool,
limit: isize,
}
impl Spec
{
fn new() -> Self
{
Spec { disable: false, start: None, start_offset: 0, s... | {
let path = path::Path::new(filename);
let mut file = match fs::File::open(&path) {
Err(why) => { panic!("can't open {}: {}", filename, why.to_string()) }
Ok(f) => f
};
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
let table = match content.parse... | identifier_body |
main.rs | extern crate fixedbitset;
extern crate getopts;
extern crate libc;
extern crate regex;
extern crate toml;
extern crate num_cpus;
use regex::Regex;
use std::fs;
use std::io;
use std::io::{Read, Write, BufRead};
use std::path;
use std::sync;
use std::sync::mpsc;
use std::thread;
#[cfg(not(test))]
fn main()
{
let arg... | }
}
}
if failed_files.len() > 0 {
println!("Summary of failed files:");
for ffn in failed_files { println!(" {}", ffn); }
panic!();
}
} | } else {
failed_files.push(toml_path_s);
println!("fail\n\t{} spec(s) recognized\n--- expected ---\n{}\n--- actual ---", specs.len(), &expected_content[..]);
println!("{}", std::str::from_utf8(&output).unwrap());
println!("--- end ---"); | random_line_split |
slice_test.rs | use std::mem;
fn print_slice(slice : &[i32]) {
for i in slice{
println!("{}", i);
}
}
fn move_in_array(mut arr : [i32; 8]) {
for i in &mut arr {
*i = *i + 1;
println!("{} ", i);
}
}
pub fn slice_size_len() {
println!("{}", mem::size_of::<&[i32]>());
// println!("{}", m... | // without errors. Here, the Rust borrow checker allows i1 and i2
// to simultaneously exists. Hence, it is important for the API designer
// to ensure that i1 and i2 do not refer to the same content in the original
// slice
println!("{}", i1);
println!("{}", i2);
// if i borrow from the g... | {
let mut array = [2,3,4,5,6,7];
let slice = &mut array[..];
let mut iter_mut = slice.iter_mut();
// i1 does not borrow from iter_mut, it is treated as a
// a borrow of slice, and extends the lifetime of slice
let i1 = iter_mut.next().unwrap();
// i2 is similar as i1
let i2 = ... | identifier_body |
slice_test.rs | use std::mem;
fn print_slice(slice : &[i32]) {
for i in slice{
println!("{}", i);
}
}
fn move_in_array(mut arr : [i32; 8]) {
for i in &mut arr {
*i = *i + 1;
println!("{} ", i);
}
}
pub fn slice_size_len() {
println!("{}", mem::size_of::<&[i32]>());
// println!("{}", m... |
}
let slice = &mut vec[..];
println!("printing the vec after insertion");
for i in slice {
println!("{}", i);
}
}
pub fn rotate_left() {
let slice = &mut [1,2,3,4,5][..];
slice.rotate_left(1);
println!("{:?}", slice);
}
fn manual_clone_from_slice<T : Clone>(dst : &mut [T], sr... | {
println!("please insert 109 at index {}", i);
vec.insert(i, 109);
} | conditional_block |
slice_test.rs | use std::mem;
fn print_slice(slice : &[i32]) {
for i in slice{
println!("{}", i);
}
}
fn move_in_array(mut arr : [i32; 8]) {
for i in &mut arr {
*i = *i + 1;
println!("{} ", i);
}
}
pub fn slice_size_len() {
println!("{}", mem::size_of::<&[i32]>());
// println!("{}", m... | () {
let mut vec = vec!(2,1,2,4,3,2,3,2,1,3,2,3,4,5);
println!("{:?}", &vec);
let slice = &mut vec[..];
slice.sort_unstable();
let res = slice.binary_search(&3);
match res {
Ok(i) => {
println!("found {} from index {}", slice[i], i);
},
Err(i) => {
... | sort_and_search | identifier_name |
slice_test.rs | use std::mem;
fn print_slice(slice : &[i32]) {
for i in slice{
println!("{}", i);
}
}
fn move_in_array(mut arr : [i32; 8]) {
for i in &mut arr { | }
pub fn slice_size_len() {
println!("{}", mem::size_of::<&[i32]>());
// println!("{}", mem::size_of::<[i32]>());
let sth = [1,2,3];
let slice = &sth[0..3];
println!("slice.len");
println!("{}",slice.len());
assert!(slice.first() == Some(&1));
}
pub fn slice_split_first() {
let slice ... | *i = *i + 1;
println!("{} ", i);
} | random_line_split |
session.rs | use chrono::{DateTime, Duration, Utc, Timelike, TimeZone};
use clacks_crypto::CSRNG;
use clacks_crypto::symm::AuthKey;
use clacks_mtproto::{AnyBoxedSerialize, BareSerialize, BoxedSerialize, ConstructorNumber, IntoBoxed, mtproto};
use clacks_mtproto::mtproto::wire::outbound_encrypted::OutboundEncrypted;
use clacks_mtpro... | (&mut self) -> i32 {
let ret = self.seq_no | 1;
self.seq_no += 2;
ret
}
fn next_seq_no(&mut self, content_message: bool) -> i32 {
if content_message {
self.next_content_seq_no()
} else {
self.seq_no
}
}
fn latest_server_salt(&mut ... | next_content_seq_no | identifier_name |
session.rs | use chrono::{DateTime, Duration, Utc, Timelike, TimeZone};
use clacks_crypto::CSRNG;
use clacks_crypto::symm::AuthKey;
use clacks_mtproto::{AnyBoxedSerialize, BareSerialize, BoxedSerialize, ConstructorNumber, IntoBoxed, mtproto};
use clacks_mtproto::mtproto::wire::outbound_encrypted::OutboundEncrypted;
use clacks_mtpro... | Either::Right(m) => self.serialize_encrypted_message(m),
}
}
pub fn bind_auth_key(&mut self, perm_key: AuthKey, expires_in: Duration) -> Result<MessageBuilder<EncryptedPayload>> {
let temp_key = self.fresh_auth_key()?;
let message_id = next_message_id();
let (session... | Either::Left(m) => self.serialize_plain_message(m), | random_line_split |
typechecking.rs | use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;
use std::fmt;
use std::fmt::Write;
/*
use std::collections::hash_set::Union;
use std::iter::Iterator;
use itertools::Itertools;
*/
use ast;
use util::ScopeStack;
use symbol_table::{SymbolSpec, SymbolTable};
pub type TypeName = Rc<String>;
type Ty... | Binding { name, expr,.. } => {
let ty = self.infer(expr)?;
self.bindings.insert(name.clone(), ty);
},
_ => return Err(format!("other formats not done"))
}
Ok(Void)
}
fn infer(&mut self, expr: &parsing::Expression) -> TypeResult<Type> {
use self::parsing::Expression;
... | use self::parsing::Declaration::*;
use self::Type::*;
match decl { | random_line_split |
typechecking.rs | use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;
use std::fmt;
use std::fmt::Write;
/*
use std::collections::hash_set::Union;
use std::iter::Iterator;
use itertools::Itertools;
*/
use ast;
use util::ScopeStack;
use symbol_table::{SymbolSpec, SymbolTable};
pub type TypeName = Rc<String>;
type Ty... | Value(name) => {
let s = match self.0.get(name) {
Some(sigma) => sigma.clone(),
None => return Err(format!("Unknown variable: {}", name))
};
self.instantiate(s)
},
_ => Type::Const(Unit)
})
}
}
/* GIANT TODO - use the rust im crate, unless I make thi... |
return Err(format!("NOTDONE"))
},
| conditional_block |
typechecking.rs | use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;
use std::fmt;
use std::fmt::Write;
/*
use std::collections::hash_set::Union;
use std::iter::Iterator;
use itertools::Itertools;
*/
use ast;
use util::ScopeStack;
use symbol_table::{SymbolSpec, SymbolTable};
pub type TypeName = Rc<String>;
type Ty... | ashMap<TypeName, Type>);
impl Substitution {
fn empty() -> Substitution {
Substitution(HashMap::new())
}
}
#[derive(Debug, PartialEq, Clone)]
struct TypeEnv(HashMap<TypeName, Scheme>);
impl TypeEnv {
fn default() -> TypeEnv {
TypeEnv(HashMap::new())
}
fn populate_from_symbols(&mut self, symbol_tabl... | bstitution(H | identifier_name |
lib.rs | /*!
This crate provides a robust regular expression parser.
This crate defines two primary types:
* [`Ast`](ast::Ast) is the abstract syntax of a regular expression.
An abstract syntax corresponds to a *structured representation* of the
concrete syntax of a regular expression, where the concrete syntax is the
p... | /// Returns true if and only if the given character is an ASCII word character.
///
/// An ASCII word character is defined by the following character class:
/// `[_0-9a-zA-Z]'.
pub fn is_word_byte(c: u8) -> bool {
match c {
b'_' | b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z' => true,
_ => false,
}
}
... | unicode::is_word_character(c)
}
| identifier_body |
lib.rs | /*!
This crate provides a robust regular expression parser.
This crate defines two primary types:
* [`Ast`](ast::Ast) is the abstract syntax of a regular expression.
An abstract syntax corresponds to a *structured representation* of the
concrete syntax of a regular expression, where the concrete syntax is the
p... | (c: char) -> bool {
match c {
'\\' | '.' | '+' | '*' | '?' | '(' | ')' | '|' | '[' | ']' | '{'
| '}' | '^' | '$' | '#' | '&' | '-' | '~' => true,
_ => false,
}
}
/// Returns true if the given character can be escaped in a regex.
///
/// This returns true in all cases that `is_meta_chara... | is_meta_character | identifier_name |
lib.rs | /*!
This crate provides a robust regular expression parser.
This crate defines two primary types:
* [`Ast`](ast::Ast) is the abstract syntax of a regular expression.
An abstract syntax corresponds to a *structured representation* of the
concrete syntax of a regular expression, where the concrete syntax is the
p... | /// For example, `%` is not a meta character, but it is escapeable. That is,
/// `%` and `\%` both match a literal `%` in all contexts.
///
/// The purpose of this routine is to provide knowledge about what characters
/// may be escaped. Namely, most regex engines permit "superfluous" escapes
/// where characters witho... | ///
/// This returns true in all cases that `is_meta_character` returns true, but
/// also returns true in some cases where `is_meta_character` returns false. | random_line_split |
main.rs | use std::env;
use std::ffi::OsStr;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process;
use std::result;
use imdb_index::{Index, IndexBuilder, NgramType, Searcher};
use lazy_static::lazy_static;
use tabwriter::TabWriter;
use walkdir::WalkDir;
use crate::rename::{RenamerBuilder, RenameAction};
use cra... |
fn download_all_update(&self) -> Result<()> {
download::update_all(&self.data_dir)
}
}
fn app() -> clap::App<'static,'static> {
use clap::{App, AppSettings, Arg};
lazy_static! {
// clap wants all of its strings tied to a particular lifetime, but
// we'd really like to determi... | {
download::download_all(&self.data_dir)
} | identifier_body |
main.rs | use std::env;
use std::ffi::OsStr;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process;
use std::result;
use imdb_index::{Index, IndexBuilder, NgramType, Searcher};
use lazy_static::lazy_static;
use tabwriter::TabWriter;
use walkdir::WalkDir;
use crate::rename::{RenamerBuilder, RenameAction};
use cra... |
let mut searcher = args.searcher()?;
let results = match args.query {
None => None,
Some(ref query) => Some(searcher.search(&query.parse()?)?),
};
if args.files.is_empty() {
let results = match results {
None => failure::bail!("run with a file to rename or --query")... | {
args.create_index()?;
} | conditional_block |
main.rs | use std::env;
use std::ffi::OsStr;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process;
use std::result;
use imdb_index::{Index, IndexBuilder, NgramType, Searcher};
use lazy_static::lazy_static;
use tabwriter::TabWriter;
use walkdir::WalkDir;
use crate::rename::{RenamerBuilder, RenameAction};
use cra... | .help("Choose the ngram size for indexing names. This is only \
used at index time and otherwise ignored."))
.arg(Arg::with_name("ngram-type")
.long("ngram-type")
.default_value("window")
.possible_values(NgramType::possible_names())
... | random_line_split | |
main.rs | use std::env;
use std::ffi::OsStr;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process;
use std::result;
use imdb_index::{Index, IndexBuilder, NgramType, Searcher};
use lazy_static::lazy_static;
use tabwriter::TabWriter;
use walkdir::WalkDir;
use crate::rename::{RenamerBuilder, RenameAction};
use cra... | (matches: &clap::ArgMatches) -> Result<Args> {
let files = collect_paths(
matches
.values_of_os("file")
.map(|it| it.collect())
.unwrap_or(vec![]),
matches.is_present("follow"),
);
let query = matches
.value_of_lossy... | from_matches | identifier_name |
producer.rs | // Copyright 2021, The Tremor Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | () -> Result<()> {
let _: std::result::Result<_, _> = env_logger::try_init();
let docker = DockerCli::default();
let container = redpanda_container(&docker).await?;
let port = container.get_host_port_ipv4(9092);
let mut admin_config = ClientConfig::new();
let broker = format!("127.0.0.1:{port}"... | connector_kafka_producer | identifier_name |
producer.rs | // Copyright 2021, The Tremor Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | "field1": 0.1,
"field3": []
},
"meta": {
"kafka_producer": {
"key": "nananananana: batchman!"
}
}
}
}, {
"data": {
"value": {
"field2": "just a string"
... | let batched_data = literal!([{
"data": {
"value": { | random_line_split |
producer.rs | // Copyright 2021, The Tremor Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | num_partitions,
TopicReplication::Fixed(num_replicas),
)],
&options,
)
.await?;
for r in res {
match r {
Err((topic, err)) => {
error!("Error creating topic {}: {}", &topic, err);
}
Ok(... | {
let _: std::result::Result<_, _> = env_logger::try_init();
let docker = DockerCli::default();
let container = redpanda_container(&docker).await?;
let port = container.get_host_port_ipv4(9092);
let mut admin_config = ClientConfig::new();
let broker = format!("127.0.0.1:{port}");
let topic ... | identifier_body |
producer.rs | // Copyright 2021, The Tremor Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... |
Ok(topic) => {
info!("Created topic {}", topic);
}
}
}
let connector_config = literal!({
"reconnect": {
"retry": {
"interval_ms": 1000_u64,
"max_retries": 10_u64
}
},
"codec": {"name... | {
error!("Error creating topic {}: {}", &topic, err);
} | conditional_block |
exec.rs | use std::{
ops::DerefMut,
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
};
use crate::vbus::{
BusSpawnedProcess, VirtualBusError, VirtualBusInvokable, VirtualBusProcess, VirtualBusScope,
};
use futures::Future;
use tokio::sync::mpsc;
use tracing::*;
use wasmer::{FunctionEnvMut, Instance, Mem... | else if self.commands.exists(name.as_str()) {
tracing::warn!("builtin command without a parent ctx - {}", name);
}
Err(VirtualBusError::NotFound)
}
}
#[derive(Debug)]
pub(crate) struct SpawnedProcess {
pub exit_code: Mutex<Option<ExitCode>>,
pub exit_code_rx: Mutex<mpsc::Unboun... | {
if self.commands.exists(name.as_str()) {
return self
.commands
.exec(parent_ctx, name.as_str(), store, builder);
}
} | conditional_block |
exec.rs | use std::{
ops::DerefMut,
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
};
use crate::vbus::{
BusSpawnedProcess, VirtualBusError, VirtualBusInvokable, VirtualBusProcess, VirtualBusScope,
};
use futures::Future;
use tokio::sync::mpsc;
use tracing::*;
use wasmer::{FunctionEnvMut, Instance, Mem... | (
module: Module,
store: Store,
env: WasiEnv,
runtime: &Arc<dyn WasiRuntime + Send + Sync +'static>,
) -> Result<BusSpawnedProcess, VirtualBusError> {
// Create a new task manager
let tasks = runtime.task_manager();
// Create the signaler
let pid = env.pid();
let signaler = Box::new... | spawn_exec_module | identifier_name |
exec.rs | use std::{
ops::DerefMut,
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
};
use crate::vbus::{
BusSpawnedProcess, VirtualBusError, VirtualBusInvokable, VirtualBusProcess, VirtualBusScope,
};
use futures::Future;
use tokio::sync::mpsc;
use tracing::*;
use wasmer::{FunctionEnvMut, Instance, Mem... |
unsafe impl Send for UnsafeWrapper {}
let inner = UnsafeWrapper {
inner: Box::new(task),
};
move || {
(inner.inner)();
}
};
tasks_outer.task_wasm(Box::new(task)).map_err(|err| {
error!("wasi[{}]::... | struct UnsafeWrapper {
inner: Box<dyn FnOnce() + 'static>,
} | random_line_split |
lib.rs | // Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... |
#[cfg(feature = "std")]
use std::fmt::Debug;
use sp_std::prelude::*;
pub mod abi;
pub mod contract_metadata;
pub mod gateway_inbound_protocol;
pub mod transfers;
pub use gateway_inbound_protocol::GatewayInboundProtocol;
pub type ChainId = [u8; 4];
#[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Encode, Decode, De... | use serde::{Deserialize, Serialize};
#[cfg(feature = "no_std")]
use sp_runtime::RuntimeDebug as Debug; | random_line_split |
lib.rs | // Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | {
/// The contract returned successfully.
///
/// There is a status code and, optionally, some data returned by the contract.
Success {
/// Flags that the contract passed along on returning to alter its exit behaviour.
/// Described in `pallet_contracts::exec::ReturnFlags`.
flag... | ComposableExecResult | identifier_name |
lib.rs | use url::*;
pub struct Example<'a> {
dirty: &'a str,
clean: &'a str,
}
impl<'a> Example<'a> {
pub const fn new(dirty: &'a str, clean: &'a str) -> Self {
Self { dirty, clean }
}
}
/// Contains directives on how to extract the link from a click-tracking link forwarder.
pub struct CleanInformati... | let cleaner = UrlCleaner::default();
let clean = cleaner.clean_url(&parsed).unwrap();
assert_eq!(clean, url_clean);
}
#[test]
fn clean_facebook2() {
let url_dirty ="https://l.facebook.com/l.php?u=https%3A%2F%2Fwww.banggood.com%2FXT30-V3-ParaBoard-Parallel-Charging-Board-Ban... | let parsed = Url::parse(&url_dirty).unwrap(); | random_line_split |
lib.rs | use url::*;
pub struct Example<'a> {
dirty: &'a str,
clean: &'a str,
}
impl<'a> Example<'a> {
pub const fn new(dirty: &'a str, clean: &'a str) -> Self {
Self { dirty, clean }
}
}
/// Contains directives on how to extract the link from a click-tracking link forwarder.
pub struct CleanInformati... | (&self, url: &url::Url) -> Option<String> {
if let Some(domain) = url.domain() {
// Check all rules that matches this domain, but return on the first clean
for domaininfo in self.cleaning_info.iter().filter(|&x| x.domain == domain) {
if domaininfo.path == url.path() {
... | clean_url | identifier_name |
lib.rs | use url::*;
pub struct Example<'a> {
dirty: &'a str,
clean: &'a str,
}
impl<'a> Example<'a> {
pub const fn new(dirty: &'a str, clean: &'a str) -> Self {
Self { dirty, clean }
}
}
/// Contains directives on how to extract the link from a click-tracking link forwarder.
pub struct CleanInformati... | else {
newurl.query_pairs_mut().append_pair(&key, &value);
}
}
(newurl, modified)
}
/// try to extract the destination url from the link if possible and also try to remove the click-id
/// query parameters that are available, if the content has been modified ret... | {
println!("key found: {:?}", key);
modified = true;
} | conditional_block |
lib.rs | use url::*;
pub struct Example<'a> {
dirty: &'a str,
clean: &'a str,
}
impl<'a> Example<'a> {
pub const fn new(dirty: &'a str, clean: &'a str) -> Self {
Self { dirty, clean }
}
}
/// Contains directives on how to extract the link from a click-tracking link forwarder.
pub struct CleanInformati... | // Check if there is a click identifier, and return if there is one
let (url, modified) = self.clean_query(&url);
if modified {
return Some(url.to_string());
}
}
None
}
pub fn try_clean_string(&self, url_string: String) -> String ... | {
if let Some(domain) = url.domain() {
// Check all rules that matches this domain, but return on the first clean
for domaininfo in self.cleaning_info.iter().filter(|&x| x.domain == domain) {
if domaininfo.path == url.path() {
println!("{}", url);
... | identifier_body |
gdb.rs | use gdbstub::common::{Signal, Tid};
use gdbstub::conn::Connection;
use gdbstub::stub::state_machine::GdbStubStateMachine;
use gdbstub::stub::{GdbStubBuilder, GdbStubError, MultiThreadStopReason};
use gdbstub::target::Target;
use crate::io::SerialRead;
use crate::platform::precursor::gdbuart::GdbUart;
mod breakpoints;... | {
let mut uart = GdbUart::new(receive_irq).unwrap();
uart.enable();
let mut target = XousTarget::new();
let server = GdbStubBuilder::new(uart)
.with_packet_buffer(unsafe { &mut GDB_BUFFER })
.build()
.expect("unable to build gdb server")
.run_state_machine(&mut target)
... | identifier_body | |
gdb.rs | use gdbstub::common::{Signal, Tid};
use gdbstub::conn::Connection;
use gdbstub::stub::state_machine::GdbStubStateMachine;
use gdbstub::stub::{GdbStubBuilder, GdbStubError, MultiThreadStopReason};
use gdbstub::target::Target;
use crate::io::SerialRead;
use crate::platform::precursor::gdbuart::GdbUart;
mod breakpoints;... |
}
}
_ => {
println!("GDB is in an unexpected state!");
return;
}
};
// If the user just hit Ctrl-C, then remove the pending interrupt that may or may not exist.
if let GdbStubStateMachine::CtrlCInterrupt(_) = &new_server {
target.unpatch... | {
println!("gdbstub error in DeferredStopReason.pump: {:?}", e);
return;
} | conditional_block |
gdb.rs | use gdbstub::common::{Signal, Tid};
use gdbstub::conn::Connection;
use gdbstub::stub::state_machine::GdbStubStateMachine;
use gdbstub::stub::{GdbStubBuilder, GdbStubError, MultiThreadStopReason};
use gdbstub::target::Target;
use crate::io::SerialRead;
use crate::platform::precursor::gdbuart::GdbUart;
mod breakpoints;... | pub server: GdbStubStateMachine<'a, XousTarget, crate::platform::precursor::gdbuart::GdbUart>,
}
static mut GDB_STATE: Option<XousDebugState> = None;
static mut GDB_BUFFER: [u8; 4096] = [0u8; 4096];
trait ProcessPid {
fn pid(&self) -> Option<xous_kernel::PID>;
fn take_pid(&mut self) -> Option<xous_kernel:... | random_line_split | |
gdb.rs | use gdbstub::common::{Signal, Tid};
use gdbstub::conn::Connection;
use gdbstub::stub::state_machine::GdbStubStateMachine;
use gdbstub::stub::{GdbStubBuilder, GdbStubError, MultiThreadStopReason};
use gdbstub::target::Target;
use crate::io::SerialRead;
use crate::platform::precursor::gdbuart::GdbUart;
mod breakpoints;... | () -> Self {
MicroRingBuf {
buffer: [0u8; N],
head: 0,
tail: 0,
}
}
}
impl<const N: usize> MicroRingBuf<N> {
// pub fn capacity(&self) -> usize {
// self.buffer.len()
// }
// pub fn len(&self) -> usize {
// self.head.wrapping_sub(self.... | default | identifier_name |
theme.rs | use cssparser::{self, BasicParseError, CompactCowStr, DeclarationListParser, Parser, ParseError, ParserInput, Token};
use orbclient::Color;
use std::collections::HashSet;
use std::sync::Arc;
use std::mem;
use std::ops::Add;
use std::path::Path;
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
static DEFA... | (data: u32) -> Color {
Color { data: 0xFF000000 | data }
}
| hex | identifier_name |
theme.rs | use cssparser::{self, BasicParseError, CompactCowStr, DeclarationListParser, Parser, ParseError, ParserInput, Token};
use orbclient::Color;
use std::collections::HashSet;
use std::sync::Arc;
use std::mem;
use std::ops::Add;
use std::path::Path;
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
static DEFA... | ,
_ => return Err(CustomParseError::InvalidColorHex(hash.into_owned()).into()),
}
}
t => {
let basic_error = BasicParseError::UnexpectedToken(t);
return Err(basic_error.into());
}
})
}
fn parse(s: &str) -> Vec<Rule> {
let mut input... | {
let mut x = match u32::from_str_radix(&hash, 16) {
Ok(x) => x,
Err(_) => return Err(CustomParseError::InvalidColorHex(hash.into_owned()).into()),
};
if hash.len() == 6 {
x |= 0xFF000000... | conditional_block |
theme.rs | use cssparser::{self, BasicParseError, CompactCowStr, DeclarationListParser, Parser, ParseError, ParserInput, Token};
use orbclient::Color;
use std::collections::HashSet;
use std::sync::Arc;
use std::mem;
use std::ops::Add;
use std::path::Path;
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
static DEFA... | }
#[derive(Clone, Debug, Default)]
pub struct Selector {
pub element: Option<String>,
pub classes: HashSet<String>,
pub pseudo_classes: HashSet<String>,
pub relation: Option<Box<SelectorRelation>>,
}
impl Selector {
pub fn new<S: Into<String>>(element: Option<S>) -> Self {
Selector {
... | self.0[2] + rhs.0[2],
])
} | random_line_split |
theme.rs | use cssparser::{self, BasicParseError, CompactCowStr, DeclarationListParser, Parser, ParseError, ParserInput, Token};
use orbclient::Color;
use std::collections::HashSet;
use std::sync::Arc;
use std::mem;
use std::ops::Add;
use std::path::Path;
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
static DEFA... |
pub fn without_pseudo_class<S: Into<String>>(mut self, pseudo_class: S) -> Self {
self.pseudo_classes.remove(&pseudo_class.into());
self
}
}
impl Selector {
pub fn is_empty(&self) -> bool {
self.element.is_none() && self.classes.is_empty() && self.pseudo_classes.is_empty()
}
}... | {
self.pseudo_classes.insert(pseudo_class.into());
self
} | identifier_body |
lib.rs | dli_fbase: *mut c_void, /* Load address of that object. */
dli_sname: *mut c_char, /* Name of nearest symbol. */
dli_saddr: *mut c_void, /* Exact value of nearest symbol. */
//dlerror
}
/* This is the type of elements in `Dl_serinfo', below.
The `dls_name' member points to space ... |
else{
Ok( DyLib(shared_lib_handle) )
}
}}
//Example
//let function : fn()->i32= transmute_copy((dlsym(shared_lib_handle, CString::new(name).unwrap().as_ptr()) as *mut ()).as_mut());
pub fn get_fn( shared_lib_handle: &DyLib, name: &str)-> Result<*mut (), String>{ unsafe{
... | {
println!("{:?}", get_error());
Err(format!("Shared lib is null! {} Check file path/name.", lib_path))
} | conditional_block |
lib.rs | 32; 4], color: [f32; 4], filled: bool){
let _color = [color[0], color[1], color[2]];
self.buffer.push( RenderStruct{rendertype: RenderType::Rectangle,
x: rect[0], y:rect[1], width: rect[2], height: rect[3],
alpha: color[3]... | global_storage_vec2 | identifier_name | |
lib.rs | dli_fbase: *mut c_void, /* Load address of that object. */
dli_sname: *mut c_char, /* Name of nearest symbol. */
dli_saddr: *mut c_void, /* Exact value of nearest symbol. */
//dlerror
}
/* This is the type of elements in `Dl_serinfo', below.
The `dls_name' member points to spac... | pub new_width: Option<f32>,// NOTE Testing out using a factional new width
pub new_height: Option<f32>,// NOTE Testing out using a factional new height
//Stings
pub char_buffer: String,
pub font_size: u32
}
#[derive(Default)]
pub struct RenderInstructions{
... |
//image related things
pub color_buffer: Vec<u8>,
pub rgba_type: RGBA, | random_line_split |
map_loader.rs | use serde_json::Value;
use specs::prelude::*;
use std::collections::HashMap;
use std::path::Path;
use super::super::super::prelude::{
hex_color, Attribute, Attributes, BackgroundColor, CanBeEmpty, Color,
GlobalTileIndex, InventoryLayer, ItemRecord, Layer, LayerData, Object,
Position, Screen, Sprite, Tiledmap, To... | }
}
if let Some(ndx) = mndx {
let inv_layer = layers.remove(ndx);
layers.insert(0, inv_layer);
}
}
pub fn insert_map(
&mut self,
map: &mut Tiledmap,
layer_group: Option<String>,
sprite: Option<Entity>,
) -> Result<LoadedLayers, String> {
self.sort_layers(&mut ma... | if let LayerData::Objects(_) = layer.layer_data {
if layer.name == "inventories" {
mndx = Some(i);
break 'find_ndx;
} | random_line_split |
map_loader.rs | use serde_json::Value;
use specs::prelude::*;
use std::collections::HashMap;
use std::path::Path;
use super::super::super::prelude::{
hex_color, Attribute, Attributes, BackgroundColor, CanBeEmpty, Color,
GlobalTileIndex, InventoryLayer, ItemRecord, Layer, LayerData, Object,
Position, Screen, Sprite, Tiledmap, To... | (file: String, lazy: &LazyUpdate) {
lazy.exec_mut(|world| {
let mut loader = MapLoader::new(world);
let file = file;
let map: &Tiledmap = loader.load_map(&file);
// Get the background color based on the loaded map
let bg: Color = map
.backgroundcolor
.as_ref()
.map... | load_it | identifier_name |
map_loader.rs | use serde_json::Value;
use specs::prelude::*;
use std::collections::HashMap;
use std::path::Path;
use super::super::super::prelude::{
hex_color, Attribute, Attributes, BackgroundColor, CanBeEmpty, Color,
GlobalTileIndex, InventoryLayer, ItemRecord, Layer, LayerData, Object,
Position, Screen, Sprite, Tiledmap, To... |
_ => None,
}
} else {
None
}
})
.flatten()
.collect()
} else {
// Return the layers as normal
layers.iter().collect()
};
let mut layers = LoadedLayers::new();
for layer in layers_to_load.iter() {
self.inc... | {
let variant_layers: Vec<&Layer> =
variant_layers.layers.iter().collect();
Some(variant_layers)
} | conditional_block |
map_loader.rs | use serde_json::Value;
use specs::prelude::*;
use std::collections::HashMap;
use std::path::Path;
use super::super::super::prelude::{
hex_color, Attribute, Attributes, BackgroundColor, CanBeEmpty, Color,
GlobalTileIndex, InventoryLayer, ItemRecord, Layer, LayerData, Object,
Position, Screen, Sprite, Tiledmap, To... |
}
pub struct MapLoader<'a> {
loaded_maps: HashMap<String, Tiledmap>,
pub z_level: ZLevel,
pub world: &'a mut World,
pub origin: V2,
pub layer_group: Option<String>,
pub sprite: Option<Entity>,
}
impl<'a> MapLoader<'a> {
pub fn load_it(file: String, lazy: &LazyUpdate) {
lazy.exec_mut(|world| {
... | {
let other_tops = other.top_level_entities.into_iter();
let other_groups = other.groups.into_iter();
self.top_level_entities.extend(other_tops);
self.groups.extend(other_groups);
} | identifier_body |
media_sessions.rs | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
anyhow::{format_err, Error},
fidl::encoding::Decodable as FidlDecodable,
fidl::endpoints::{create_proxy, create_request_stream},
fidl... | (
&self,
event_id: fidl_avrcp::NotificationEvent,
current: Notification,
pos_change_interval: u32,
responder: fidl_avrcp::TargetHandlerWatchNotificationResponder,
) -> Result<(), fidl::Error> {
let mut write = self.inner.write();
write.register_notification(ev... | register_notification | identifier_name |
media_sessions.rs | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
anyhow::{format_err, Error},
fidl::encoding::Decodable as FidlDecodable,
fidl::endpoints::{create_proxy, create_request_stream},
fidl... | }
async fn watch_media_sessions(
discovery: DiscoveryProxy,
mut watcher_requests: SessionsWatcherRequestStream,
sessions_inner: Arc<RwLock<MediaSessionsInner>>,
) -> Result<(), anyhow::Error> {
while let Some(req) =
watcher_requests.try_next().await.expect("Faile... | random_line_split | |
media_sessions.rs | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
anyhow::{format_err, Error},
fidl::encoding::Decodable as FidlDecodable,
fidl::endpoints::{create_proxy, create_request_stream},
fidl... | else {
return;
};
self.notifications = self
.notifications
.drain()
.map(|(event_id, queue)| {
let curr_value = state.session_info().get_notification_value(&event_id);
(
event_id,
queue... | {
state.clone()
} | conditional_block |
media_sessions.rs | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
anyhow::{format_err, Error},
fidl::encoding::Decodable as FidlDecodable,
fidl::endpoints::{create_proxy, create_request_stream},
fidl... |
}
| {} | identifier_body |
zhtta.rs | }
</style></head>
<body>";
//static mut visitor_count : usize = 0;
struct HTTP_Request {
// Use peer_name as the key to access TcpStream in hashmap.
// (Due to a bug in extra::arc in Rust 0.9, it is very inconvenient to use TcpStream without the "Freeze" bound.
// See issue: ... |
// TODO: Streaming file.
// TODO: Application-layer file caching.
fn respond_with_static_file(stream: std::old_io::net::tcp::TcpStream, path: &Path,cache : Arc<RwLock<HashMap<Path,(String,Mutex<usize>,u64)>>>,cache_len :Arc<Mutex<usize>>) {
let mut stream = stream;
let mut cache_str=S... | {
let mut stream = stream;
let response: String =
format!("{}{}<h1>Greetings, Krusty!</h1><h2>Visitor count: {}</h2></body></html>\r\n",
HTTP_OK, COUNTER_STYLE,
unsafe { visitor_count } );
debug!("Responding to counter request");
stream.write(respons... | identifier_body |
zhtta.rs | green }
</style></head>
<body>";
//static mut visitor_count : usize = 0;
struct HTTP_Request {
// Use peer_name as the key to access TcpStream in hashmap.
// (Due to a bug in extra::arc in Rust 0.9, it is very inconvenient to use TcpStream without the "Freeze" bound.
// See i... | });
}
});
}
fn respond_with_error_page(stream: std::old_io::net::tcp::TcpStream, path: &Path) {
let mut stream = stream;
let msg: String= format!("Cannot open: {}", path.as_str().expect("invalid path"));
stream.write(HTTP_BAD.as_bytes());
stream.write(msg.as_bytes());
... |
}
}
} | random_line_split |
zhtta.rs | _path.clone();
let request_queue_arc = self.request_queue_arc.clone();
let notify_tx = self.notify_tx.clone();
let stream_map_arc = self.stream_map_arc.clone();
let visitor_count=self.visitor_count.clone();
Thread::spawn(move|| {
let listener = std::old_io::TcpL... | int_usage(p | identifier_name | |
zhtta.rs | Thread::spawn(move|| {
let mut vc= visitor_count.lock().unwrap(); // Done
*vc+=1;
println!("inner thread:{}",*vc);
let request_queue_arc = queue_rx.recv().unwrap();//
let mut stream = match stream_raw {
... | matches.opt_str("ip").expect("invalid ip address?").to_owned()
} e | conditional_block | |
deps.rs | use std::{
collections::{HashMap, HashSet},
path::PathBuf,
};
use crate::{
error::{Error, Result, UserError},
target::Target,
util::ResultIterator,
};
use daggy::{petgraph::visit::IntoNeighborsDirected, NodeIndex as Nx};
type DependencyDag = daggy::Dag<Node, ()>;
type Identifier = PathBuf;
type F... | (
graph: &mut DependencyDag,
id_to_ix_map: &mut HashMap<Identifier, Nx>,
dependency_identifier: Identifier,
) {
id_to_ix_map
.entry(dependency_identifier.clone())
.or_insert_with(|| {
// `.add_node()` returns node's index
graph.ad... | add_leaf_node | identifier_name |
deps.rs | use std::{
collections::{HashMap, HashSet},
path::PathBuf,
};
use crate::{
error::{Error, Result, UserError},
target::Target,
util::ResultIterator,
};
use daggy::{petgraph::visit::IntoNeighborsDirected, NodeIndex as Nx};
type DependencyDag = daggy::Dag<Node, ()>;
type Identifier = PathBuf;
type F... | .map(|target| target.identifier)
.collect::<Vec<_>>();
let expected_target_sequence: Vec<PathBuf> =
vec!["b2".into(), "a2".into()];
assert_eq!(target_sequence, expected_target_sequence);
}
#[test]
fn test_find_obsolete_targets() {
// helper functio... | random_line_split | |
deps.rs | use std::{
collections::{HashMap, HashSet},
path::PathBuf,
};
use crate::{
error::{Error, Result, UserError},
target::Target,
util::ResultIterator,
};
use daggy::{petgraph::visit::IntoNeighborsDirected, NodeIndex as Nx};
type DependencyDag = daggy::Dag<Node, ()>;
type Identifier = PathBuf;
type F... | while let Some(target_ix) = queue.pop_front() {
let has_just_been_found = obsolete_ixs.insert(target_ix);
if has_just_been_found {
let dependants = graph
.neighbors_directed(target_ix, Direction::Incoming);
queue... | {
// reverse short circuiting bfs:
// skip the dependants of the targets
// that have already been marked as obsolete
let mut queue = VecDeque::<Nx>::new();
let mut obsolete_ixs = HashSet::<Nx>::new();
for leaf_ix in obsolete_leaf_nodes {
// no need to clear ... | identifier_body |
host_segfault.rs | // To handle out-of-bounds reads and writes we use segfaults right now. We only
// want to catch a subset of segfaults, however, rather than all segfaults
// happening everywhere. The purpose of this test is to ensure that we *don't*
// catch segfaults if it happens in a random place in the code, but we instead
// bail... | desc.push_str(&stderr.replace("\n", "\n "));
}
if stack_overflow {
if is_stack_overflow(&output.status, &stderr) {
assert!(
stdout.trim().ends_with(CONFIRM),
"failed to find confirmation in test `{}`\n{}",
name,
desc... | random_line_split | |
host_segfault.rs | // To handle out-of-bounds reads and writes we use segfaults right now. We only
// want to catch a subset of segfaults, however, rather than all segfaults
// happening everywhere. The purpose of this test is to ensure that we *don't*
// catch segfaults if it happens in a random place in the code, but we instead
// bail... |
#[cfg(unix)]
fn is_stack_overflow(status: &ExitStatus, stderr: &str) -> bool {
use std::os::unix::prelude::*;
// The main thread might overflow or it might be from a fiber stack (SIGSEGV/SIGBUS)
stderr.contains("has overflowed its stack")
|| match status.signal() {
Some(libc::SIGSEGV)... | {
use std::os::unix::prelude::*;
match status.signal() {
Some(libc::SIGSEGV) => true,
_ => false,
}
} | identifier_body |
host_segfault.rs | // To handle out-of-bounds reads and writes we use segfaults right now. We only
// want to catch a subset of segfaults, however, rather than all segfaults
// happening everywhere. The purpose of this test is to ensure that we *don't*
// catch segfaults if it happens in a random place in the code, but we instead
// bail... |
}
#[cfg(unix)]
fn is_segfault(status: &ExitStatus) -> bool {
use std::os::unix::prelude::*;
match status.signal() {
Some(libc::SIGSEGV) => true,
_ => false,
}
}
#[cfg(unix)]
fn is_stack_overflow(status: &ExitStatus, stderr: &str) -> bool {
use std::os::unix::prelude::*;
// The m... | {
if is_segfault(&output.status) {
assert!(
stdout.trim().ends_with(CONFIRM) && stderr.is_empty(),
"failed to find confirmation in test `{}`\n{}",
name,
desc
);
} else {
panic!("\n\nexpected a segfault on... | conditional_block |
host_segfault.rs | // To handle out-of-bounds reads and writes we use segfaults right now. We only
// want to catch a subset of segfaults, however, rather than all segfaults
// happening everywhere. The purpose of this test is to ensure that we *don't*
// catch segfaults if it happens in a random place in the code, but we instead
// bail... | (ptr: *const ()) {
assert_eq!(ptr as usize, 5);
}
}
fn main() {
if cfg!(miri) {
return;
}
// Skip this tests if it looks like we're in a cross-compiled situation and
// we're emulating this test for a different platform. In that scenario
// emulators (like QEMU) tend to not repo... | drop | identifier_name |
board.rs | //! The central part of this crate, uses all modules to load and run our world in memory.
//!
//! The `Board` struct is technically all you need to start your world but then you wouldn't be able to see it!
//! Graphics are provided by the [graphics] module; although you could implement your own.
//!
//! TODO: documenta... |
}
}
/// Performs the same function on `self.climate`, filling in `self.year`.
pub fn get_growth_since(&self, last_updated: f64) -> f64 {
return self
.climate
.get_growth_over_time_range(self.year, last_updated);
}
/// Returns the current growth rate (temperat... | {
i += 1;
} | conditional_block |
board.rs | //! The central part of this crate, uses all modules to load and run our world in memory.
//!
//! The `Board` struct is technically all you need to start your world but then you wouldn't be able to see it!
//! Graphics are provided by the [graphics] module; although you could implement your own.
//!
//! TODO: documenta... | board.maintain_creature_minimum();
return board;
}
/// Maintains the creature minimum by adding random creatures until there are at least `self.creature_minimum` creatures.
///
/// # Processing equivalent
/// This function is the equivalent of *Board.pde/maintainCreatureMinimum* wi... | random_line_split | |
board.rs | //! The central part of this crate, uses all modules to load and run our world in memory.
//!
//! The `Board` struct is technically all you need to start your world but then you wouldn't be able to see it!
//! Graphics are provided by the [graphics] module; although you could implement your own.
//!
//! TODO: documenta... | (&self) -> f64 {
self.climate.get_growth_rate(self.year)
}
/// Returns the current time, i.e. `self.year`.
pub fn get_time(&self) -> f64 {
return self.year;
}
/// Returns a tuple with the width and height of this `Board`.
///
/// Equivalent to `(board.get_board_width(), boa... | get_current_growth_rate | identifier_name |
board.rs | //! The central part of this crate, uses all modules to load and run our world in memory.
//!
//! The `Board` struct is technically all you need to start your world but then you wouldn't be able to see it!
//! Graphics are provided by the [graphics] module; although you could implement your own.
//!
//! TODO: documenta... |
/// Returns `self.creature_id_up_to`
pub fn get_creature_id_up_to(&self) -> usize {
self.creature_id_up_to
}
/// Gets the size of the current population; i.e. how many creatures are currently alive.
pub fn get_population_size(&self) -> usize {
return self.creatures.len();
... | {
self.creature_minimum
} | identifier_body |
stream.rs | #[cfg(uds_peercred)]
use super::util::get_peer_ucred;
#[cfg(uds_supported)]
use super::util::raw_shutdown;
#[cfg(unix)]
use super::super::{close_by_error, handle_fd_error};
use super::{
imports::*,
util::{
check_ancillary_unsound, enable_passcred, mk_msghdr_r, mk_msghdr_w, raw_get_nonblocking,
r... | if!success {
unsafe { return Err(handle_fd_error(socket)) };
}
unsafe { enable_passcred(socket).map_err(close_by_error(socket))? };
Ok(unsafe { Self::from_raw_fd(socket) })
}
/// Receives bytes from the socket stream.
///
/// # System calls
/// - `read`
... | {
let addr = path.try_to::<sockaddr_un>()?;
let socket = {
let (success, fd) = unsafe {
let result = libc::socket(AF_UNIX, SOCK_STREAM, 0);
(result != -1, result)
};
if success {
fd
} else {
r... | identifier_body |
stream.rs | #[cfg(uds_peercred)]
use super::util::get_peer_ucred;
#[cfg(uds_supported)]
use super::util::raw_shutdown;
#[cfg(unix)]
use super::super::{close_by_error, handle_fd_error};
use super::{
imports::*,
util::{
check_ancillary_unsound, enable_passcred, mk_msghdr_r, mk_msghdr_w, raw_get_nonblocking,
r... | (&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
self.fd.read_vectored(bufs)
}
/// Receives both bytes and ancillary data from the socket stream.
///
/// The ancillary data buffer is automatically converted from the supplied value, if possible. For that reason, mutable slices of bytes... | recv_vectored | identifier_name |
stream.rs | #[cfg(uds_peercred)]
use super::util::get_peer_ucred;
#[cfg(uds_supported)]
use super::util::raw_shutdown;
#[cfg(unix)]
use super::super::{close_by_error, handle_fd_error};
use super::{
imports::*,
util::{
check_ancillary_unsound, enable_passcred, mk_msghdr_r, mk_msghdr_w, raw_get_nonblocking,
r... |
};
let success = unsafe {
libc::connect(
socket,
&addr as *const _ as *const _,
size_of::<sockaddr_un>() as u32,
)
}!= 1;
if!success {
unsafe { return Err(handle_fd_error(socket)) };
}
un... | {
return Err(io::Error::last_os_error());
} | conditional_block |
stream.rs | #[cfg(uds_peercred)]
use super::util::get_peer_ucred;
#[cfg(uds_supported)]
use super::util::raw_shutdown;
#[cfg(unix)]
use super::super::{close_by_error, handle_fd_error};
use super::{
imports::*,
util::{
check_ancillary_unsound, enable_passcred, mk_msghdr_r, mk_msghdr_w, raw_get_nonblocking,
r... | /// conn.read_to_string(&mut string_buffer)?;
/// println!("Server answered: {}", string_buffer);
/// # }
/// # Ok(()) }
/// ```
pub struct UdStream {
fd: FdOps,
}
impl UdStream {
/// Connects to a Unix domain socket server at the specified path.
///
/// See [`ToUdSocketPath`] for an example of using va... | /// let mut conn = UdStream::connect("/tmp/example1.sock")?;
/// conn.write_all(b"Hello from client!")?;
/// let mut string_buffer = String::new(); | random_line_split |
client.rs | crate::u2client::types::{RssInfo, TorrentInfo};
use super::Result;
#[derive(Clone)]
pub struct U2client {
uid: String,
passkey: String,
container: reqwest::Client,
torrentClient: TransClient,
tempSpace: String,
workSpace: String,
}
impl U2client {
pub async fn new(
cookie: &str,
... |
pub async fn getUserInfo(&self) -> Result<UserInfo> {
let context = self
.get(format!(
"https://u2.dmhy.org/userdetails.php?id={}",
self.uid
))
.await?;
let username = Document::from(context.as_str())
.find(Name("a"))
... | {
let mut torrent = self.getWorkingTorrent().await?;
torrent.torrents.sort_by_key(|x| {
(
x.peers_getting_from_us.unwrap_or(0),
x.added_date.unwrap_or(0),
)
});
Ok(torrent.torrents.into_iter().take(5).collect())
} | identifier_body |
client.rs | crate::u2client::types::{RssInfo, TorrentInfo};
use super::Result;
#[derive(Clone)]
pub struct U2client {
uid: String,
passkey: String,
container: reqwest::Client,
torrentClient: TransClient,
tempSpace: String,
workSpace: String,
}
impl U2client {
pub async fn new(
cookie: &str,
... | .find(|x| match x.attr("class") {
Some(x) => x == "outer",
_ => false,
})
.ok_or("parseHtml:parse failed")?;
for _ in 0..timesOfReduce {
outer = outer
.find(Name("tbody"))
.next()
.ok_or("p... | e("td"))
| identifier_name |
client.rs |
use crate::u2client::types::{RssInfo, TorrentInfo};
use super::Result;
#[derive(Clone)]
pub struct U2client {
uid: String,
passkey: String,
container: reqwest::Client,
torrentClient: TransClient,
tempSpace: String,
workSpace: String,
}
impl U2client {
pub async fn new(
cookie: &s... | .get("https://u2.dmhy.org/index.php")
.send()
.await?;
if x.url().path() == "/index.php" {
let context = x.text().await?;
let uid = Document::from(context.as_str())
.find(Name("a"))
.filter(|x| match x.attr("class") {
... | let x = container | random_line_split |
tiles.rs | use std::cmp::min;
use std::fs::File;
use std::path::Path;
use std::io::{Read, Write, BufWriter, Error};
use game::base::*;
use io::base::*;
use map::constants::*;
use map::material::*;
pub type Tiles = Vec<Tile>;
pub type PosUnit = i32;
const CHUNK_TILES_X: PosUnit = 8;
const CHUNK_TILES_Y: PosUnit = 8;
const CHUN... |
pub fn get_chunk(&self, pos: Pos, size: Pos) -> MapChunk {
let (x0, y0, z0) = pos;
let (xlen, ylen, zlen) = size;
let mut tiles = Tiles::new();
for x in x0..(x0 + xlen) {
for y in y0..(y0 + ylen) {
for z in z0..(z0 + zlen) {
let ind... | {
let (x, y, z) = pos;
self.tiles = vec![AIR_TILE; (x * y * z) as usize];
self.xlen = x;
self.ylen = y;
self.zlen = z;
} | identifier_body |
tiles.rs | use std::cmp::min;
use std::fs::File;
use std::path::Path;
use std::io::{Read, Write, BufWriter, Error};
use game::base::*;
use io::base::*;
use map::constants::*;
use map::material::*;
pub type Tiles = Vec<Tile>;
pub type PosUnit = i32;
const CHUNK_TILES_X: PosUnit = 8;
const CHUNK_TILES_Y: PosUnit = 8;
const CHUN... | let zlen = min(CHUNK_TILES_Z, self.zlen - dz * CHUNK_TILES_Z);
let size = (xlen, ylen, zlen);
chunks.push(self.get_chunk(pos, size))
}
}
}
chunks
}
fn get_num_chunks(map_len: PosUnit, chunk_len: PosUnit) -... | let z = dz * CHUNK_TILES_Z;
let pos = (x, y, z);
let xlen = min(CHUNK_TILES_X, self.xlen - dx * CHUNK_TILES_X);
let ylen = min(CHUNK_TILES_Y, self.ylen - dy * CHUNK_TILES_Y); | random_line_split |
tiles.rs | use std::cmp::min;
use std::fs::File;
use std::path::Path;
use std::io::{Read, Write, BufWriter, Error};
use game::base::*;
use io::base::*;
use map::constants::*;
use map::material::*;
pub type Tiles = Vec<Tile>;
pub type PosUnit = i32;
const CHUNK_TILES_X: PosUnit = 8;
const CHUNK_TILES_Y: PosUnit = 8;
const CHUN... | {
pub tiles: Tiles,
pub pos: Pos,
pub xlen: PosUnit,
pub ylen: PosUnit,
pub zlen: PosUnit,
}
pub fn init_map(root: &Path) -> Map {
info!("Initializing map");
let test_path = root.join("static/inc/maps/smol_map_excel.sfm.csv");
let path_str = test_path
.to_str()
... | MapChunk | identifier_name |
main.rs |
// Get the size of the given type in bytes
fn size_of<T>() -> i32 {
mem::size_of::<T>() as i32
}
// Get an offset in bytes for n units of type T
fn offset<T>(n: u32) -> *const c_void {
(n * mem::size_of::<T>() as u32) as *const T as *const c_void
}
fn read_triangles_from_file() -> Result<Vec<f32>, ()> {
... | {
&val[0] as *const T as *const c_void
} | identifier_body | |
main.rs | ] as *const T as *const c_void
}
// Get the size of the given type in bytes
fn size_of<T>() -> i32 {
mem::size_of::<T>() as i32
}
// Get an offset in bytes for n units of type T
fn offset<T>(n: u32) -> *const c_void {
(n * mem::size_of::<T>() as u32) as *const T as *const c_void
}
fn read_triangles_from_file... |
}
}
// Get a null pointer (equivalent to an offset of 0)
// ptr::null()
// let p = 0 as *const c_void
// == // Modify and complete the function below for the first task
unsafe fn init_vao(vertices: &Vec<f32>, indices: &Vec<u32>, colors: &Vec<f32>) -> u32 {
// Returns the ID of the newly instantiated vertex a... | {
println!("Error message: {}", error);
std::process::exit(1);
} | conditional_block |
main.rs | 0] as *const T as *const c_void
}
// Get the size of the given type in bytes
fn size_of<T>() -> i32 {
mem::size_of::<T>() as i32
}
// Get an offset in bytes for n units of type T
fn offset<T>(n: u32) -> *const c_void {
(n * mem::size_of::<T>() as u32) as *const T as *const c_void
}
fn read_triangles_from_fil... | VirtualKeyCode::Right => {
rot_y += rot_step;
},
_ => {}
}
}
}
// Handle mouse movement. delta contains the x and y movement of the mouse since last frame in p... | VirtualKeyCode::Left => {
rot_y -= rot_step;
}, | random_line_split |
main.rs | ] as *const T as *const c_void
}
// Get the size of the given type in bytes
fn size_of<T>() -> i32 {
mem::size_of::<T>() as i32
}
// Get an offset in bytes for n units of type T
fn | <T>(n: u32) -> *const c_void {
(n * mem::size_of::<T>() as u32) as *const T as *const c_void
}
fn read_triangles_from_file() -> Result<Vec<f32>, ()> {
// Takes in an arbitraray amount of trinagles from a file
let mut vertices: Vec<f32>;
match File::open(".\\src\\triangles.txt") {
Ok(mut file) =... | offset | identifier_name |
cfg.rs | use anyhow::{bail, Context, Result};
use expanduser::expanduser;
use log::{debug, warn};
use std::collections::HashMap;
use std::default::Default;
use std::fmt::Display;
use std::fs::{read_dir, read_to_string};
use std::path::PathBuf;
use yaml_rust::{yaml::Hash, Yaml, YamlLoader};
use percent_encoding::{utf8_percent_e... | }
Ok(())
}
#[cfg(test)]
mod tests {
use crate::util;
#[test]
fn load_example_config() {
util::test::init().unwrap();
let cfg = crate::cfg::Config::load("example-config/asfa")
.unwrap()
.unwrap();
log::debug!("Loaded: {:?}", cfg);
assert_eq!(&cf... | bail! {"Prefix needs to be between 8 and 128 characters."}; | random_line_split |
cfg.rs | use anyhow::{bail, Context, Result};
use expanduser::expanduser;
use log::{debug, warn};
use std::collections::HashMap;
use std::default::Default;
use std::fmt::Display;
use std::fs::{read_dir, read_to_string};
use std::path::PathBuf;
use yaml_rust::{yaml::Hash, Yaml, YamlLoader};
use percent_encoding::{utf8_percent_e... |
}
impl Config {
pub fn load<T: AsRef<str> + Display>(dir: T) -> Result<Option<Config>> {
let config_dir = match expanduser(dir.as_ref()) {
Ok(p) => p,
Err(e) => {
bail!("Error when expanding path to config file: {}", e);
}
};
let global =... | {
Config {
auth: Auth::default(),
default_host: None,
expire: None,
hosts: HashMap::new(),
prefix_length: 32,
verify_via_hash: true,
}
} | identifier_body |
cfg.rs | use anyhow::{bail, Context, Result};
use expanduser::expanduser;
use log::{debug, warn};
use std::collections::HashMap;
use std::default::Default;
use std::fmt::Display;
use std::fs::{read_dir, read_to_string};
use std::path::PathBuf;
use yaml_rust::{yaml::Hash, Yaml, YamlLoader};
use percent_encoding::{utf8_percent_e... | (alias: String, input: &Yaml) -> Result<Host> {
Self::from_yaml_with_config(alias, input, &Config::default())
}
fn from_yaml_with_config(alias: String, input: &Yaml, config: &Config) -> Result<Host> {
log::trace!("Reading host: {}", alias);
if let Yaml::Hash(dict) = input {
... | from_yaml | identifier_name |
error.rs | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use core::{convert::TryInto, fmt, ptr::NonNull, task::Poll};
use errno::{errno, Errno};
use libc::c_char;
use s2n_tls_sys::*;
use std::{convert::TryFrom, ffi::CStr};
#[non_exhaustive]
#[derive(Debug, PartialEq... | match self.0 {
Context::InvalidInput | Context::MissingWaker => ErrorType::UsageError,
Context::Application(_) => ErrorType::Application,
Context::Code(code, _) => unsafe { ErrorType::from(s2n_error_get_type(code)) },
}
}
pub fn source(&self) -> ErrorSource {... |
pub fn kind(&self) -> ErrorType { | random_line_split |
error.rs | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use core::{convert::TryInto, fmt, ptr::NonNull, task::Poll};
use errno::{errno, Errno};
use libc::c_char;
use s2n_tls_sys::*;
use std::{convert::TryFrom, ffi::CStr};
#[non_exhaustive]
#[derive(Debug, PartialEq... |
}
enum Context {
InvalidInput,
MissingWaker,
Code(s2n_status_code::Type, Errno),
Application(Box<dyn std::error::Error + Send + Sync +'static>),
}
pub struct Error(Context);
pub trait Fallible {
type Output;
fn into_result(self) -> Result<Self::Output, Error>;
}
impl Fallible for s2n_statu... | {
match input as s2n_error_type::Type {
s2n_error_type::OK => ErrorType::NoError,
s2n_error_type::IO => ErrorType::IOError,
s2n_error_type::CLOSED => ErrorType::ConnectionClosed,
s2n_error_type::BLOCKED => ErrorType::Blocked,
s2n_error_type::ALERT => E... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.