content stringlengths 12 392k | id int64 0 1.08k |
|---|---|
fn input(user_message: &str) -> io::Result<String> {
use std::io::Write;
print!("{}", user_message);
io::stdout().flush()?;
let mut buffer: String = String::new();
io::stdin().read_line(&mut buffer)?;
Ok(buffer.trim_right().to_owned())
} | 700 |
fn test_combine_regions() {
// Make the region going from (0.0, 0.0) -> (2.0, 2.0)
let b = ((0.0, 0.0), (2.0, 2.0)).into_region();
// Make the region going from (0.5, 0.5) -> (1.5, 3)
let c = ((0.5, 0.5), (1.5, 3.0)).into_region();
let combined_region = b
.combine_region(&c)
.expec... | 701 |
fn print_my_options() {
println!("Run me as root with a name of a network interface");
println!("Example: sudo ports2 lo");
println!("Here are your network interfaces");
println!("Name: MAC:");
for i in datalink::interfaces().into_iter() {
println!("{:<9} {:?}", i.name, mac_to_string(i.... | 702 |
pub fn parse_command(opcode: u8, rom: &[u8]) -> Option<Box<dyn Instruction>> {
match opcode {
/* NOP */
0x00 =>
cmd!(noop::NoOp),
/* LD BC,nn */
0x01 =>
cmd!(load::Load16Bit::BC(u16!(rom))),
/* LD DE,nn */
0x11 =>
cmd!(load::Load16B... | 703 |
fn main() {
#[cfg(feature = "breakout")]
let memfile_bytes = include_bytes!("stm32h743zi_memory.x");
#[cfg(not(feature = "breakout"))]
let memfile_bytes = include_bytes!("stm32h743vi_memory.x");
// Put the linker script somewhere the linker can find it
let out = &PathBuf::from(env::var_os("OUT... | 704 |
fn extract_archive_into<P: AsRef<Path>>(
path: P,
response: reqwest::blocking::Response,
) -> Result<(), FrumError> {
#[cfg(unix)]
let extractor = archive::tar_xz::TarXz::new(response);
#[cfg(windows)]
let extractor = archive::zip::Zip::new(response);
extractor
.extract_into(path)
... | 705 |
fn read<T>() -> T
where
T: std::str::FromStr,
T::Err: std::fmt::Debug,
{
let mut buf = String::new();
stdin().read_line(&mut buf).unwrap();
return buf.trim().parse().unwrap();
} | 706 |
fn inc_2() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(Direct(SP)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 68], OperandSize::Dword)
} | 707 |
fn build_all() {
let project = project("build_all").with_fuzz().build();
// Create some targets.
project
.cargo_fuzz()
.arg("add")
.arg("build_all_a")
.assert()
.success();
project
.cargo_fuzz()
.arg("add")
.arg("build_all_b")
.ass... | 708 |
pub extern "x86-interrupt" fn SMID_error() { CommonExceptionHandler(19); } | 709 |
pub fn solve_n_queens(n: i32) -> Vec<Vec<String>> {
Board::new(n as usize).solve()
} | 710 |
fn parse_bag_list(input: &str) -> IResult<&str, Vec<(usize, &str)>> {
separated_list1(pair(char(','), space1), parse_bag_count)(input)
} | 711 |
fn index() -> Html<&'static str> {
Html(&INDEX)
} | 712 |
fn handle_client(mut stream: TcpStream) {
let mut hash = [0 as u8; 5];
let mut key = [0 as u8; 10];
let mut mes = [0 as u8;50];
while match stream.read(&mut hash) {
Ok(_) => {
stream.read(&mut key);
stream.read(&mut mes);
let text1 = from_utf8(&hash).unwrap()... | 713 |
fn
is_invalid_column_type
(
err
:
Error
)
-
>
bool
{
matches
!
(
err
Error
:
:
InvalidColumnType
(
.
.
)
)
} | 714 |
fn calc_window_size(n: usize, exp_bits: usize, core_count: usize) -> usize {
// window_size = ln(n / num_groups)
// num_windows = exp_bits / window_size
// num_groups = 2 * core_count / num_windows = 2 * core_count * window_size / exp_bits
// window_size = ln(n / num_groups) = ln(n * exp_bits / (2 * cor... | 715 |
async fn quic_to_link(mut link: LinkReceiver, quic: Arc<AsyncConnection>) -> Result<(), Error> {
let mut frame = [0u8; MAX_FRAME_LENGTH];
loop {
let n = quic.dgram_recv(&mut frame).await?;
link.received_frame(&mut frame[..n]).await
}
} | 716 |
pub extern "x86-interrupt" fn coprocessor_segment_overrun() { CommonExceptionHandler( 9); } | 717 |
pub(crate) fn cpu_relax(count: usize) {
for _ in 0..(1 << count) {
atomic::spin_loop_hint()
}
} | 718 |
fn parse_instruction(line: &str) -> Instruction {
let pieces: Vec<&str> = line.split_whitespace().collect();
let register = String::from(pieces[0]);
let increase = match pieces[1] {
"inc" => true,
"dec" => false,
_ => panic!("Expected 'inc' or 'dec'."),
};
let value ... | 719 |
fn find_part2_matches(input: &str) -> Option<(String, String)> {
for box_id_1 in input.lines() {
'test_inner: for box_id_2 in input.lines() {
if box_id_1 == box_id_2 {
continue;
}
let mut differences = 0;
for (letter_1, letter_2) in box_id_1.c... | 720 |
pub async fn accept_async<S>(stream: S) -> Result<WebSocketStream<TokioAdapter<S>>, Error>
where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
{
accept_hdr_async(stream, NoCallback).await
} | 721 |
pub fn task_set_stack_pointer(target: CAddr, ptr: u64) {
system_call(SystemCall::TaskSetStackPointer {
request: (target, ptr),
});
} | 722 |
pub fn sampling_with_mclk<MCLK>(_: MCLK) -> Sampling<(MCLK, SrInvalid)>
where
MCLK: Mclk,
{
Sampling::<(MCLK, SrInvalid)> {
data: 0b1000 << 9,
t: PhantomData::<(MCLK, SrInvalid)>,
}
} | 723 |
pub fn display_grid(g: &SudokuGrid)
{
// width = 1+max(len(values[s]) for s in boxes)
// let width = 2;
let line = std::iter::repeat("-").take(9).collect::<String>();
let line = std::iter::repeat(line).take(3).collect::<Vec<String>>().join("+");
for r in 0..9
{
let value_str = (0..9).map... | 724 |
pub fn u_nz8(x: u64) -> u64 {
(((x | H8) - L8) | x) & H8
} | 725 |
fn doit(interface_name: &str, just_me: bool) {
let interface_names_match = |iface: &NetworkInterface| iface.name == *interface_name;
// Find the network interface with the provided name
let interfaces = datalink::interfaces();
let interface_a = interfaces.into_iter().find(interface_names_match);
i... | 726 |
pub fn nbt_encode(input: TokenStream) -> TokenStream {
let ast: syn::DeriveInput = syn::parse(input).unwrap();
let receiver = nbt_encode::NbtEncodeReceiver::from_derive_input(&ast).unwrap();
let result = wrap_use(receiver.ident, "nbtencode", &receiver);
let mut tokens = quote::Tokens::new();
tokens... | 727 |
pub async fn connect_async<R>(
request: R,
) -> Result<(WebSocketStream<ConnectStream>, Response), Error>
where
R: IntoClientRequest + Unpin,
{
connect_async_with_config(request, None).await
} | 728 |
fn file() {
let file = CachedFile::new(Path::new("LICENSE"), None);
assert_eq!(file.expired(), true);
assert!(file.borrow().as_ref().map(|v| v.len()).unwrap_or(0) > 0);
assert_eq!(file.expired(), false);
file.free();
assert_eq!(file.expired(), true);
} | 729 |
pub fn runner(tests: &[&dyn Fn()]) {
println!("Running {} tests", tests.len());
for test in tests {
test();
}
success();
} | 730 |
fn cef_dir() -> PathBuf {
PathBuf::from(env_var("CEF_DIR"))
} | 731 |
fn differences(chain: &[i64], of: i64) -> usize {
let mut i = 0;
let mut last = chain[0];
for x in chain.iter().skip(1) {
if x - last == of {
i += 1;
}
last = *x;
}
i
} | 732 |
fn figure5_pct() {
// Change of hitting the bug should be 1 - (1 - 1/2)^20 > 99.9999%, so this should trip the assert
let scheduler = PctScheduler::new(1, 20);
let runner = Runner::new(scheduler, Default::default());
runner.run(figure5);
} | 733 |
pub fn generate(
base_dir: impl AsRef<Path>,
discovery_desc: &DiscoveryRestDesc,
) -> Result<(), Box<dyn Error>> {
let total_time = Instant::now();
let constants = shared::Standard::default();
let base_dir = base_dir.as_ref();
let lib_path = base_dir.join(&constants.lib_path);
let cargo_toml... | 734 |
fn borrow_call<'a>(
ident: &'a str,
args: &'a Vec<Expr<'a>>,
var_id: &mut u64,
ast: &'a Ast<'a>,
borrowstate: &mut State<(Vec<&'a str>, u64)>,
) -> Result<(Vec<&'a str>, u64), BorrowError<'a>> {
let Ast(functions) = ast;
let func = functions.get(ident).unwrap();
let mut varset = HashSet... | 735 |
fn expr_uses_argument(expr: &hir::Expr<'_>, params: &[hir::Param<'_>]) -> bool {
params.iter().any(|arg| {
if_chain! {
if let hir::PatKind::Binding(_, _, ident, _) = arg.pat.kind;
if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = expr.kind;
if let [p, ..] = ... | 736 |
fn harvest_candidate_lhs(
allocs: &mut Allocs,
func: &ir::Function,
val: ir::Value,
out: &mut mpsc::Sender<String>,
) {
allocs.reset();
let mut lhs = ast::LeftHandSideBuilder::default();
let mut non_var_count = 0;
// Should we keep tracing through the given `val`? Only if it is defined
... | 737 |
fn get_path_for_data(nodes: &HashMap<String, Node>, data_coords: &String) -> Vec<String> {
let (mut scan_list, data_used) = {
let data_node = nodes.get(data_coords).unwrap();
(vec![(data_node.clone(), Vec::new())], data_node.used)
};
let mut used_list: HashSet<String> = HashSet::new();
l... | 738 |
fn into_rdf(body: &[u8], content_type: &str) -> Result<Graph, Berr> {
fn parse<P>(p: P) -> Result<Graph, Berr>
where
P: TriplesParser,
<P as TriplesParser>::Error: 'static,
{
p.into_iter(|t| -> Result<_, Berr> { Ok(triple(t)?) })
.collect::<Result<Vec<om::Triple>, Berr>>(... | 739 |
fn part2(rules: &Vec<PasswordRule>) -> usize {
rules
.iter()
.filter(|rule| {
let first = if let Some(c) = rule.password.chars().nth(rule.min - 1) {
c == rule.letter
} else {
false
};
let second = if let Some(c) = rule.... | 740 |
fn tmin() {
let corpus = Path::new("fuzz").join("corpus").join("i_hate_zed");
let test_case = corpus.join("test-case");
let project = project("tmin")
.with_fuzz()
.fuzz_target(
"i_hate_zed",
r#"
#![no_main]
use libfuzzer_sys::fuzz_targe... | 741 |
pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {
unsafe {
file_descriptor_proto_lazy.get(|| {
parse_descriptor_proto()
})
}
} | 742 |
pub fn main() {
println!("Count: {}", RTL::get_device_count());
println!("Device Name: {:?}", RTL::get_device_name(0));
println!("USB Strings: {:?}", RTL::get_device_usb_strings(0));
} | 743 |
fn inc_11() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(Direct(CL)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[254, 193], OperandSize::Qword)
} | 744 |
fn app() -> App<
impl ServiceFactory<
ServiceRequest,
Response = ServiceResponse<impl MessageBody>,
Config = (),
InitError = (),
Error = Error,
>,
> {
App::new()
} | 745 |
pub fn acrn_write(file_path: &str, contents: &str) -> Result<(), String> {
let mut file = File::create(file_path).map_err(|e| e.to_string())?;
file.write_all(contents.as_bytes())
.map_err(|e| e.to_string())?;
Ok(())
} | 746 |
fn extract_comment_blocks_with_empty_lines(text: &str) -> Vec<Vec<String>> {
do_extract_comment_blocks(text, true)
} | 747 |
fn encode_byte(input_byte: u8) -> (u8, u8) {
let mut output = (0, 0);
let output_byte = input_byte.overflowing_add(42).0;
match output_byte {
LF | CR | NUL | ESCAPE => {
output.0 = ESCAPE;
output.1 = output_byte.overflowing_add(64).0;
}
_ => {
out... | 748 |
fn calculate_layout_hash(layout: &[VertexAttribute]) -> u64 {
let mut hasher = FxHasher::default();
layout.hash(&mut hasher);
hasher.finish()
} | 749 |
pub fn challenge_15() {
println!("TODO");
} | 750 |
pub fn insert(
module: Atom,
index: Index,
old_unique: OldUnique,
unique: Unique,
arity: Arity,
code: Code,
) {
RW_LOCK_CODE_BY_ARITY_BY_UNIQUE_BY_OLD_UNIQUE_BY_INDEX_BY_MODULE
.write()
.entry(module)
.or_insert_with(Default::default)
.entry(index)
.or... | 751 |
fn git(args: &[&str]) -> Result<String, Box<dyn std::error::Error>> {
let mut cmd = Command::new("git");
cmd.args(args);
cmd.stdout(Stdio::piped());
let out = cmd.spawn();
let mut out = match out {
Ok(v) => v,
Err(err) => {
panic!("Failed to spawn command `{:?}`: {:?}", c... | 752 |
pub fn sort_by<T, Cmp: Fn(&T, &T) -> Ordering>(xs: &mut [T], cmp: Cmp) { unsafe {
let mut h = LeoHeap { ptr: xs.as_mut_ptr().offset(-1), sizes: u2size::from(0),
less: |a, b| Ordering::Less == cmp(a, b) };
for _ in 0..xs.len() { h.push() }
for _ in 0..xs.len() { h.pop() }
} } | 753 |
fn figure1a_pct() {
const COUNT: usize = 5usize;
// n=2, d=1, so probability of finding the bug is at least 1/2
// So probability of hitting the bug in 20 iterations = 1 - (1 - 1/2)^20 > 99.9%
let scheduler = PctScheduler::new(1, 20);
let runner = Runner::new(scheduler, Default::default());
runn... | 754 |
pub fn fill_buffer_with_indexed<T, F: FnMut (usize) -> T> (b: &mut [T], mut f: F) {
b.iter_mut().enumerate().for_each(move |(i, e)| *e = f(i))
} | 755 |
fn should_update() -> bool {
std::env::args_os().nth(1).unwrap_or_default() == "--refresh"
} | 756 |
fn main() {
println!("\nBuffer - typical usage");
println!("--");
println!("\nCreate a new empty buffer:");
println!("let mut buf: Buffer<isize> = Buffer::new(3);");
let mut buf: Buffer<isize> = Buffer::new(3);
println!("\nAdd elements to it:");
println!("buf.add(1);");
println!("> {:?... | 757 |
fn yield_spin_loop_fair() {
yield_spin_loop(true);
} | 758 |
fn func_1() -> Option< u128 > {
unsafe { malloc( 123456 ); }
Some( CONSTANT )
} | 759 |
pub fn channel_take_cap(target: CAddr) -> CAddr {
let result = channel_take_nonpayload(target);
match result {
ChannelMessage::Cap(v) => return v.unwrap(),
_ => panic!(),
};
} | 760 |
pub fn index_of<E: PartialEq, I: Iterator<Item = E>> (i: I, el: E) -> Option<usize> {
i.enumerate()
.find(|(_, e)| el == *e)
.map(|(i, _)| i)
} | 761 |
pub extern "x86-interrupt" fn common_exception() { CommonExceptionHandler(20); } | 762 |
pub fn current_time() -> DateTime<Utc> {
Utc::now().round_subsecs(0)
} | 763 |
pub unsafe fn set_fs(data: *mut c_void) {
imp::syscalls::tls::set_fs(data)
} | 764 |
fn test_does_react() {
assert!(does_react('a', 'A'));
assert!(does_react('A', 'a'));
assert!(!does_react('a', 'a'));
assert!(!does_react('A', 'A'));
assert!(!does_react('a', 'B'));
assert!(!does_react('A', 'b'));
} | 765 |
fn test_into_point_impl() {
let _pt: Point = 0.1_f32.into_pt();
let _pt: Point = 0.1_f64.into_pt();
let _pt: Point = (0.5, 0.3).into_pt();
let _pt: Point = (1.0, -1.0).into_pt();
let _pt: Point = (1.0, 2.0, 3.0).into_pt();
} | 766 |
fn main() {
let mut state = read_init();
print_err!("ant xy: {} {} dir: {:?} grid: \n{}",
state.ant_x, state.ant_y, state.ant_dir, state.grid_string());
while state.turns_left > 0 {
state = state.step();
print_err!("ant xy: {} {} dir: {:?} grid: \n{}",
state.ant_x, state.... | 767 |
pub fn select1_raw(r: usize, x: u64) -> usize {
let r = r as u64;
let mut s = x - ((x & 0xAAAA_AAAA_AAAA_AAAA) >> 1);
s = (s & 0x3333_3333_3333_3333) + ((s >> 2) & 0x3333_3333_3333_3333);
s = ((s + (s >> 4)) & 0x0F0F_0F0F_0F0F_0F0F).wrapping_mul(L8);
let b = (i_le8(s, r.wrapping_mul(L8)) >> 7).wrapp... | 768 |
fn fist_6() {
run_test(&Instruction { mnemonic: Mnemonic::FIST, operand1: Some(IndirectScaledDisplaced(RDX, Eight, 1612856414, Some(OperandSize::Word), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[223, 20, 21... | 769 |
fn
test_str
(
)
-
>
Result
<
(
)
>
{
let
db
=
checked_memory_handle
(
)
?
;
let
s
=
"
hello
world
!
"
;
db
.
execute
(
"
INSERT
INTO
foo
(
t
)
VALUES
(
?
1
)
"
[
&
s
]
)
?
;
let
from
:
String
=
db
.
one_column
(
"
SELECT
t
FROM
foo
"
)
?
;
assert_eq
!
(
from
s
)
;
Ok
(
(
)
)
} | 770 |
fn parse_input_day2(input: &str) -> Result<Vec<PasswordRule>, impl Error> {
input.lines().map(|l| l.parse()).collect()
} | 771 |
fn main() {
let mut build = cc::Build::new();
build.include("Vulkan-Headers/include");
build.include("VulkanMemoryAllocator/include");
build.file("vma.cpp");
let target = env::var("TARGET").unwrap();
if target.contains("darwin") {
build
.flag("-std=c++17")
.flag... | 772 |
pub fn causet_partitioner_result_new() -> Box<CausetPartitionerResult> {
Box::new(CausetPartitionerResult::NotRequired)
} | 773 |
fn main() -> AppResult<()> {
#[cfg(debug_assertions)] // Only load env vars from .env in dev builds
dotenv::dotenv().ok();
let pool = util::pool::create_pool();
let app = Lock(RwLock::new(App::new(pool)?));
rocket::ignite()
.manage(app)
.mount("/", routes![index])
.mount("/",... | 774 |
pub fn melee(ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, melee_power: i32) {
// Check range and validity
let mut attacker_pos = None;
let mut defender_pos = None;
if let Ok(e) = ecs.entry_ref(attacker) {
if let Ok(pos) = e.get_component::<Position>() {
attacker... | 775 |
pub fn test_custom_syscall() {
let buffer = fs::read("tests/programs/syscall64").unwrap().into();
let core_machine =
DefaultCoreMachine::<u64, SparseMemory<u64>>::new(ISA_IMC, VERSION0, u64::max_value());
let mut machine = DefaultMachineBuilder::new(core_machine)
.syscall(Box::new(CustomSysc... | 776 |
pub fn write_sint<W>(wr: &mut W, val: i64) -> Result<Marker, ValueWriteError>
where W: Write
{
if -32 <= val && val <= 0 {
let marker = Marker::FixNeg(val as i8);
try!(write_fixval(wr, marker));
Ok(marker)
} else if -128 <= val && val < 128 {
write_i8(wr, val as i8).and(Ok(... | 777 |
fn init_with_target() {
let project = project("init_with_target").build();
project
.cargo_fuzz()
.arg("init")
.arg("-t")
.arg("custom_target_name")
.assert()
.success();
assert!(project.fuzz_dir().is_dir());
assert!(project.fuzz_cargo_toml().is_file());
... | 778 |
fn struct_in_fn() -> Food{
let chai = Food{
available : true,
restaurant : String::from("Baba ka dhaba"),
price : 100,
item : "Doodh patti".to_string(),
size : 2
};
chai
} | 779 |
pub fn create_salted_hashed_password(password: &[u8]) -> argon2::password_hash::Result<Zeroizing<String>> {
// Generate a 16-byte random salt
let passphrase_salt = SaltString::generate(&mut OsRng);
// Use the recommended OWASP parameters, which are not the default:
// https://cheatsheetseries.owasp.org... | 780 |
fn test_parse() {
use std::iter::FromIterator;
let test_input = "\
dotted black bags contain no other bags.
bright white bags contain 1 shiny gold bag.
light red bags contain 1 bright white bag, 2 muted yellow bags.
";
assert_eq!(parse_mapping(test_input).unwrap().1, BTreeM... | 781 |
pub fn returns_summarizable() -> impl Summary {
Tweet {
username: String::from("horse_ebooks"),
content: String::from(
"of course, as you probably already know, people",
),
reply: false,
retweet: false,
}
} | 782 |
pub fn task_set_buffer(target: CAddr, buffer: CAddr) {
system_call(SystemCall::TaskSetBuffer {
request: (target, buffer),
});
} | 783 |
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
} | 784 |
fn create_wrapper_file() {
let wrapper_file = PathBuf::from(env_var("CARGO_MANIFEST_DIR")).join("wrapper.h");
let cef_dir = cef_dir();
if !wrapper_file.is_file() {
let file = fs::File::create(wrapper_file).expect("Could not create wrapper.h file");
let mut file_writer = std::io::LineWriter... | 785 |
fn figure1b_pct() {
// n=2, k=20, d=2, so probability of finding the bug in one iteration is at least 1/(2*20)
// So probability of hitting the bug in 300 iterations = 1 - (1 - 1/40)^300 > 99.9%
let scheduler = PctScheduler::new(2, 300);
let runner = Runner::new(scheduler, Default::default());
runne... | 786 |
fn debug_fmt() {
let corpus = Path::new("fuzz").join("corpus").join("debugfmt");
let project = project("debugfmt")
.with_fuzz()
.fuzz_target(
"debugfmt",
r#"
#![no_main]
use libfuzzer_sys::fuzz_target;
use libfuzzer_sys::arb... | 787 |
pub fn default_audio_info() -> AudioInfo {
AUDIO_DEFAULT_SETTINGS.lock().unwrap().get_default_value().expect("no audio default settings")
} | 788 |
pub fn fill_buffer_with<T, F: FnMut () -> T> (b: &mut [T], mut f: F) {
fill_buffer_with_indexed(b, move |_| f())
} | 789 |
fn
fmt
(
&
self
f
:
&
mut
fmt
:
:
Formatter
<
'
_
>
)
-
>
fmt
:
:
Result
{
f
.
debug_struct
(
"
AtomicCell
"
)
.
field
(
"
value
"
&
self
.
load
(
)
)
.
finish
(
)
} | 790 |
fn find_pairs_for_node(nodes: &HashMap<String, Node>, node: &Node) -> Vec<String> {
let mut pairs: Vec<String> = Vec::new();
for (key, node2) in nodes {
if *key != node.coords {
if node.used > 0 && node.used <= node2.avail {
pairs.push(node2.coords.clone());
}
... | 791 |
fn main() {
// Resolve Directories
let root = env::current_dir()
.unwrap()
.join("..")
.canonicalize()
.unwrap();
let i_path = root.join("data/input").canonicalize().unwrap();
let o_path = root.join("data/rs").canonicalize().unwrap();
// File Names
let mut names = fs::read_dir(i_path)
.unwrap()
.map... | 792 |
pub extern fn pktproc_init(thread_id: u64, raw_ports: *mut libc::c_void, port_count: u32) {
let ports: &[PortInfo] = unsafe {
mem::transmute(slice::from_raw_parts_mut(raw_ports, port_count as usize))
};
CONTEXT.with(|ref ctx| {
let mut ctx = ctx.borrow_mut();
if ctx.is_none() {
... | 793 |
fn parse_to_chunk(tokens: Vec<NestedToken>, report: &Report) -> kailua_diag::Result<Chunk> {
let mut tokens = tokens.into_iter();
let chunk = Parser::new(&mut tokens, report).into_chunk();
chunk
} | 794 |
pub fn slt_op(inputs: OpInputs) -> EmulatorResult<()> {
// SLT compares the A-value to the B-value. If the A-value is less than
// the B-value, the instruction after the next instruction (PC + 2) is
// queued (skipping the next instruction). Otherwise, the next
// instruction is queued (PC + 1). SLT.... | 795 |
fn most_least_common(btm: BTreeMap<char, i32>) -> (char, char) {
let mut count_vec: Vec<_> = btm.into_iter().collect();
// Reverse sort the vector of pairs by "value" (sorted by "key" in case of tie)
count_vec.sort_by(|a, b| b.1.cmp(&a.1));
let m = count_vec.first().map(|&(k, _)| k).unwrap();
let l ... | 796 |
fn build_author_map(
repo: &Repository,
reviewers: &Reviewers,
mailmap: &Mailmap,
from: &str,
to: &str,
) -> Result<AuthorMap, Box<dyn std::error::Error>> {
match build_author_map_(repo, reviewers, mailmap, from, to) {
Ok(o) => Ok(o),
Err(err) => Err(ErrorContext(
for... | 797 |
pub fn handle_resize_events(gl_window: &GlWindow, gl: &gl::Gl, event: &Event) {
if let Event::WindowEvent {
event: WindowEvent::Resized(window_size),
..
} = event
{
let hidpi_factor = gl_window.get_hidpi_factor();
let phys_size = window_size.to_physical(hidpi_factor);
gl_window.resize(phys_siz... | 798 |
fn _ls(files: &Vec<String>, stdout: &mut impl io::Write) -> io::Result<()> {
for filename in files {
// Check whether this is a regular file or a directory
let stat = std::fs::metadata(filename)?;
if stat.is_dir() {
// If it's a directory, list every entry inside it
... | 799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.