content stringlengths 12 392k | id int64 0 1.08k |
|---|---|
pub fn challenge_1() {
let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
let hex_string = hex::decode(input).expect("ok");
let b64_string = base64::encode(&hex_string);
println!("{} {:?}", input, b64_string);
} | 1,000 |
fn solve() -> String {
compute(1000).to_string()
} | 1,001 |
pub fn init() -> Result<(), SetLoggerError> {
log::set_logger(&LOGGER).map(|()| log::set_max_level(LevelFilter::Trace))
} | 1,002 |
fn roll_with_disadvantage(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) }
} | 1,003 |
fn generate_bindings<P>(output_file: &P)
where P: AsRef<Path> {
let bindings = bindgen::Builder::default()
.clang_arg("-IVulkan-Headers/include")
.header("VulkanMemoryAllocator/include/vk_mem_alloc.h")
.rustfmt_bindings(true)
.size_t_is_usize(true)
.blocklist_type("__darw... | 1,004 |
fn fuel_requirement(mass: i64) -> i64 {
let mut total_fuel = 0;
let mut cur_mass = mass;
loop {
cur_mass = (cur_mass / 3) - 2;
if cur_mass <= 0 {
break;
}
total_fuel += cur_mass;
}
return total_fuel;
} | 1,005 |
pub fn write_u16<W>(wr: &mut W, val: u16) -> Result<(), ValueWriteError>
where W: Write
{
try!(write_marker(wr, Marker::U16));
write_data_u16(wr, val)
} | 1,006 |
fn buf_to_state(buf: &[u8]) -> Result<Engine, serde_json::Error> {
serde_json::from_slice(buf)
} | 1,007 |
pub fn grid_9x9_keys() -> impl Iterator<Item=(usize, usize)>
{
let boxes = iproduct!(0..9, 0..9);
boxes
} | 1,008 |
fn calc_best_chunk_size(max_window_size: usize, core_count: usize, exp_bits: usize) -> usize {
// Best chunk-size (N) can also be calculated using the same logic as calc_window_size:
// n = e^window_size * window_size * 2 * core_count / exp_bits
(((max_window_size as f64).exp() as f64)
* (max_window... | 1,009 |
pub extern "C" fn app() {
init_statics()
.expect("init_statics failed");
init_timers();
/*
let enc1_pin = ENC1_PIN.lock()
.expect("Lock encoder 1 pin");
let enc2_pin = ENC2_PIN.lock()
.expect("Lock encoder 2 pin");
*/
// unsafe { glue::set_pwm(0.0, &mut htim2,... | 1,010 |
fn init_twice() {
let project = project("init_twice").build();
// First init should succeed and make all the things.
project.cargo_fuzz().arg("init").assert().success();
assert!(project.fuzz_dir().is_dir());
assert!(project.fuzz_cargo_toml().is_file());
assert!(project.fuzz_targets_dir().is_dir... | 1,011 |
pub fn unions() {
let mut iof = IntOrFloat {f: 25.5};
iof.i = 30;
process_value(iof);
} | 1,012 |
fn inc_17() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(Direct(SI)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 255, 198], OperandSize::Qword)
} | 1,013 |
fn main() {
from_command_line();
} | 1,014 |
fn read_or_create_default_database() -> Result<DataBase> {
let default_database_paths = get_default_database_paths();
if default_database_paths.is_empty() {
eprintln!("{}", format!(
"Could not find a location for the default database. \
Opening a database which cannot be saved."... | 1,015 |
pub fn build_advanced_process_tree(
ng: NameGen,
k: i64,
prog: Program,
t: RcTerm,
) -> Tree {
build_process_tree(AdvancedBuildStep {}, ng, k, prog, t)
} | 1,016 |
pub fn sampling() -> Sampling<(Normal, BosrClear, SrValid)> {
Sampling::<(Normal, BosrClear, SrValid)>::new()
} | 1,017 |
fn main() {
let list = Cons(1,
Box::new(Cons(2,
Box::new(Cons(3,
Box::new(Nil))))));
println!("Welcome to bolts-with-rust");
let x = 5;
let y = &x;
assert_eq!(5, x);
assert_eq!(5, *y);
} | 1,018 |
fn inc_26() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(Indirect(RSI, Some(OperandSize::Qword), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[72, 255, 6], OperandSize::Qword)
} | 1,019 |
fn compute(limit: u64) -> i32 {
let ps = PrimeSet::new();
let (a, b, _len) = ps
.iter()
.take_while(|&p| p < limit)
.filter_map(|p| {
let b = p as i32;
(-b..1000)
.map(|a| (a, b, get_limit_n(&ps, a, b)))
.max_by_key(|&(_a, _b, len)|... | 1,020 |
pub
fn
compare_exchange
(
&
self
current
:
T
new
:
T
)
-
>
Result
<
T
T
>
{
unsafe
{
atomic_compare_exchange_weak
(
self
.
as_ptr
(
)
current
new
)
}
} | 1,021 |
fn align_to(size: uint, align: uint) -> uint {
assert!(align != 0);
(size + align - 1) & !(align - 1)
} | 1,022 |
pub fn challenge_10() {
let mut file = File::open("data/10good.txt").unwrap();
let mut all_file = String::new();
file.read_to_string(&mut all_file).unwrap();
let data = base64::decode(&all_file).unwrap();
let key = "YELLOW SUBMARINE".as_bytes().to_vec();
let iv = vec![0x00;16];
let out = cr... | 1,023 |
pub extern "C" fn handle_button(button_state: u8, button_id: usize) {
use GlobalEvent::{PhysicalButton};
use crate::store::Buttons;
let button = match button_id {
0..=7 => Some(Buttons::S(button_id)),
8 => Some(Buttons::Shift),
9 => Some(Buttons::Play),
_ => None,
};
... | 1,024 |
fn run(path: String, debug_mode: bool) -> std::io::Result<()> {
let program = if path.ends_with(".tat") {
assembler::parse_file(&path)?
} else if path.ends_with(".rom") {
arch::Memory::from_rom_file(&path)?
} else {
return Err(std::io::Error::new(
std::io::ErrorKind::Inva... | 1,025 |
fn commit_coauthors(commit: &Commit) -> Vec<Author> {
let mut coauthors = vec![];
if let Some(msg) = commit.message_raw() {
lazy_static::lazy_static! {
static ref RE: Regex =
RegexBuilder::new(r"^Co-authored-by: (?P<name>.*) <(?P<email>.*)>")
.case_insensi... | 1,026 |
fn main() {
input!{
n: i64,
a: i64,
b: i64,
p: i64,
q: i64,
r: i64,
s: i64,
}
let template = ".".repeat((s-r+1) as usize);
let p1f = max(1 - a, 1 - b);
let p2f = max(1 -a, b - n);
let p1t = min(n - a, n - b);
let p2t = min(n - a, b - 1)... | 1,027 |
pub fn select1(r: usize, x: u64) -> Option<usize> {
let result = select1_raw(r, x);
if result == 72 {None} else {Some(result)}
} | 1,028 |
fn map_prefix(tok: IRCToken) -> Result<IRCToken, ~str> {
match tok {
Sequence([Unparsed(nick), Sequence([rest])]) => match rest {
Sequence([Sequence([rest]), Unparsed(~"@"), Unparsed(host)]) => match rest {
Sequence([Unparsed(~"!"), Unparsed(user)]) => Ok(PrefixT(Prefix {nick: ni... | 1,029 |
fn read_dir<P: AsRef<Path>>(path: P, recursive: bool) -> io::Result<Vec<DirEntry>> {
let path = path.as_ref();
let mut entries = Vec::new();
for entry in fs::read_dir(path)? {
let entry = entry?;
let path = entry.path().to_str().unwrap().to_string();
let children = if recursive && en... | 1,030 |
fn main() {
HttpServer::new(|| { App::new().service(web::resource("/").to(index)) })
.bind("0.0.0.0:8080")
.unwrap()
.run()
.unwrap();
} | 1,031 |
fn extract_ext_info(
info: &HandshakeControlInfo,
) -> Result<Option<&SrtControlPacket>, ConnectError> {
match &info.info {
HandshakeVsInfo::V5(hs) => Ok(hs.ext_hs.as_ref()),
_ => Err(UnsupportedProtocolVersion(4)),
}
} | 1,032 |
fn main() {
match env::args().nth(1) {
None => print_my_options(),
Some(interface_name) => {
let just_me = env::args().nth(2).unwrap_or_else(|| "false".to_string());
doit(&interface_name, just_me.to_lowercase() == "true")
}
}
} | 1,033 |
fn
compare_exchange_weak
(
&
self
_current
:
(
)
_new
:
(
)
_success
:
Ordering
_failure
:
Ordering
)
-
>
Result
<
(
)
(
)
>
{
Ok
(
(
)
)
} | 1,034 |
fn inc_23() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(Direct(EDX)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[255, 194], OperandSize::Qword)
} | 1,035 |
pub extern "x86-interrupt" fn alignment_check() { CommonExceptionHandler(17); } | 1,036 |
pub fn write_varuint1(buf: &mut Vec<u8>, u: u8) -> usize {
write_uint8(buf, u)
} | 1,037 |
fn find_compiler_crates(
builder: &Builder<'_>,
name: &Interned<String>,
crates: &mut HashSet<Interned<String>>
) {
// Add current crate.
crates.insert(*name);
// Look for dependencies.
for dep in builder.crates.get(name).unwrap().deps.iter() {
if builder.crates.get(dep).unwrap().is... | 1,038 |
fn
test_option
(
)
-
>
Result
<
(
)
>
{
let
db
=
checked_memory_handle
(
)
?
;
let
s
=
Some
(
"
hello
world
!
"
)
;
let
b
=
Some
(
vec
!
[
1u8
2
3
4
]
)
;
db
.
execute
(
"
INSERT
INTO
foo
(
t
)
VALUES
(
?
1
)
"
[
&
s
]
)
?
;
db
.
execute
(
"
INSERT
INTO
foo
(
b
)
VALUES
(
?
1
)
"
[
&
b
]
)
?
;
let
mut
stmt
=
db
.
prepa... | 1,039 |
pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState {
let mut player_entity = None;
let mut target = None;
<(Entity, &Player, &Targeting)>::query()
.iter(ecs)
.for_each(|(entity, _, targeting)| {
target = targeting.current_target;
player_enti... | 1,040 |
pub extern "x86-interrupt" fn segment_not_present() { CommonExceptionHandler(11); } | 1,041 |
fn get_handshake(packet: &Packet) -> Result<&HandshakeControlInfo, ConnectError> {
match packet {
Packet::Control(ControlPacket {
control_type: ControlTypes::Handshake(info),
..
}) => Ok(info),
Packet::Control(ControlPacket { control_type, .. }) => {
Err(H... | 1,042 |
pub fn canonicalize_url(url: &Url) -> Url {
let mut url = url.clone();
// Strip a trailing slash
if url.path().ends_with('/') {
url.path_segments_mut().unwrap().pop_if_empty();
}
// HACKHACK: For github URL's specifically just lowercase
// everything. GitHub treats both the same, but ... | 1,043 |
fn test_945() {
assert_eq!(1, min_increment_for_unique(vec![1, 2, 2]));
assert_eq!(2, min_increment_for_unique(vec![0, 0, 2, 2]));
assert_eq!(6, min_increment_for_unique(vec![3, 2, 1, 2, 1, 7]));
} | 1,044 |
fn reference_test() {
use std::collections::HashMap;
type Table = HashMap<String, Vec<String>>;
let mut table = Table::new();
table.insert(
"Gesualdo".to_string(),
vec![
"many madrigals".to_string(),
"Tenebrae Responsoria".to_string(),
],
);
table.... | 1,045 |
fn
swap
(
&
self
_val
:
(
)
_order
:
Ordering
)
{
} | 1,046 |
fn one_step() {
let scheduler = PctScheduler::new(2, 100);
let runner = Runner::new(scheduler, Default::default());
runner.run(|| {
thread::spawn(|| {});
});
} | 1,047 |
fn inc_7() {
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::Dword)
} | 1,048 |
async fn run() -> Result<(), ()> {
let res = wasi_http_tests::request(
Method::Get,
Scheme::Http,
"localhost:3000",
"/get?some=arg&goes=here",
None,
None,
)
.await
.context("localhost:3000 /get")
.unwrap();
println!("localhost:3000 /get: {res:?}")... | 1,049 |
fn main() {
// let mut echo_hello = Command::new("sh");
// let ret = echo_hello.arg("-c").arg("ls").output();
// println!("结果:{:?}",ret);
// let file = File::open( "./src/schema.json").unwrap();
// println!("文件打开成功:{:?}",file);
let contents:String = read_to_string("./src/schema.json").unwrap();... | 1,050 |
pub fn make_buffer_clone<T: Clone> (len: usize, init: &T) -> Box<[T]> {
make_buffer_with(len, move || init.clone())
} | 1,051 |
pub fn channel_put_raw(target: CAddr, value: u64) {
system_call(SystemCall::ChannelPut {
request: (target, ChannelMessage::Raw(value))
});
} | 1,052 |
fn get_limit_n(ps: &PrimeSet, a: i32, b: i32) -> u32 {
(0..)
.take_while(|&n| {
let val = n * n + a * n + b;
val >= 0 && ps.contains(val as u64)
})
.last()
.unwrap() as u32
} | 1,053 |
fn desearlizer_client(req: &mut reqwest::Response) -> Result<Client, Error> {
let mut buffer = String::new();
match req.read_to_string(&mut buffer) {
Ok(_) => (),
Err(e) => println!("error : {}", e.to_string())
};
println!("buffer before serializaztion: {}", buffer);
let v = match s... | 1,054 |
fn part1(filename: &Path) -> String {
Snafu::from(
iter_lines(filename)
.map(Snafu::from)
.map::<isize, _>(Snafu::into)
.sum::<isize>(),
)
.to_string()
} | 1,055 |
pub fn get_history(history_type: HistoryType) -> Result<String, ()> {
let configurator = Configurator::new();
let history = configurator.get_history(history_type);
// filter out empty string and not exist history path
let clean_history: Vec<&String> = match history_type {
HistoryType::WorkingFol... | 1,056 |
pub fn init(
src: String,
dst: String,
width: u32,
) -> std::io::Result<()> {
let mut logger = env_logger::Builder::new();
logger.init();
let mut window = Window::new((width, 200)).unwrap();
let mut popup = Popup::new(width, window.hidpi);
let mut renderer = popup.get_renderer(&mut wind... | 1,057 |
fn get_next_prefix(current: &str) -> String {
format!("{} ", current)
} | 1,058 |
fn init_finds_parent_project() {
let project = project("init_finds_parent_project").build();
project
.cargo_fuzz()
.current_dir(project.root().join("src"))
.arg("init")
.assert()
.success();
assert!(project.fuzz_dir().is_dir());
assert!(project.fuzz_cargo_toml().i... | 1,059 |
fn credit_checksum(number_check: &mut [u32; 16]) {
let test: u32 = number_check[15];
number_check[15] = 0;
for index in (0..15).step_by(2) {
let mut number = number_check[index] * 2;
if number > 9 {
number = 1 + (number - 10);
}
number_check[index] = nu... | 1,060 |
pub fn testing_constant() {
for i in 0..MAXIMUM_NUMBER {
println!("{}", i);
}
} | 1,061 |
fn find_common_id() -> Option<String> {
let input = fs::File::open("input.txt")
.expect("Something went wrong reading the file");
let reader = io::BufReader::new(input);
let mut box_ids: Vec<String> = reader.lines().map(|l| l.unwrap()).collect();
box_ids.sort();
for i in 0..box_ids.len() {
... | 1,062 |
pub fn arithmetic_op(inputs: OpInputs) -> EmulatorResult<()> {
let a = inputs.regs.a;
let b = inputs.regs.b;
let next_pc = offset(inputs.regs.current.idx, 1, inputs.core_size)?;
let war_id = inputs.warrior_id;
if inputs.core_size == 0 {
return Err(EmulatorError::InternalError("Core Size cann... | 1,063 |
fn CommonExceptionHandler(vector: u8){
let buffer: [u8; 2] = [
vector / 10 + '0' as u8, vector % 10 + '0' as u8
];
print_string( 0, 0, b"====================================================" );
print_string( 0, 1, b" Exception Occur ");
print_string( 0, 2, b" ... | 1,064 |
pub fn write_file(path: PathBuf, content: String) -> Result<(), String> {
fs::write(path, content).map_err(|e| e.to_string())
} | 1,065 |
pub extern "x86-interrupt" fn slave_PIC() { CommonInterruptHandler(34); } | 1,066 |
pub fn pivot<T: PartialOrd>(v: &mut [T]) -> usize {
let mut p = rand::read(v.len());
v.swap(p, 0);
p = 0;
for i in 1..v.len() {
if v[i] < v[p] {
// move our pivot forward 1, and put this element before it
v.swap(p+1, i);
v.swap(p, p+1);
p += 1
... | 1,067 |
pub fn acrn_read(file_path: &str) -> Result<String, String> {
let mut file = File::open(file_path).map_err(|e| e.to_string())?;
let mut contents = String::new();
file.read_to_string(&mut contents)
.map_err(|e| e.to_string())?;
Ok(contents)
} | 1,068 |
pub extern "x86-interrupt" fn timer() { CommonInterruptHandler(32); } | 1,069 |
pub fn setup_luigi_with_git() -> Result<Storage<Project>> {
trace!("setup_luigi()");
let working = try!(::CONFIG.get_str("dirs/working").ok_or("Faulty config: dirs/working does not contain a value"));
let archive = try!(::CONFIG.get_str("dirs/archive").ok_or("Faulty config: dirs/archive does not contain... | 1,070 |
fn count_char(s: &str) -> HashMap<char, i32> {
let mut map: HashMap<char, i32> = HashMap::new();
for c in s.chars() {
if let Some(count) = map.get_mut(&c) {
*count += 1;
} else {
map.insert(c, 1);
}
}
map
} | 1,071 |
pub fn test_bindgen(
generate_range: usize,
tests: u64,
output_path: Option<&Path>,
) {
if let Some(path) = output_path {
CONTEXT.lock().unwrap().output_path = Some(path.display().to_string());
}
QuickCheck::new()
.tests(tests)
.gen(Gen::new(generate_range))
.qui... | 1,072 |
unsafe
fn
atomic_swap
<
T
>
(
dst
:
*
mut
T
val
:
T
)
-
>
T
{
atomic
!
{
T
a
{
a
=
&
*
(
dst
as
*
const
_
as
*
const
_
)
;
let
res
=
mem
:
:
transmute_copy
(
&
a
.
swap
(
mem
:
:
transmute_copy
(
&
val
)
Ordering
:
:
AcqRel
)
)
;
mem
:
:
forget
(
val
)
;
res
}
{
let
_guard
=
lock
(
dst
as
usize
)
.
write
(
)
;
ptr
:
:
... | 1,073 |
fn print_expression(prefix: &str, exp: &IRExpression) {
let next_prefix = format!("{} ", prefix);
match exp {
&IRExpression::Value(ref value) => {
println!("{}Value: '{:?}'", prefix, value);
}
&IRExpression::Variable(ref name) => {
println!("{}Variable: '{:?}'", ... | 1,074 |
fn generate_guid(key: &[u8]) -> Uuid {
let namespace = Uuid::from_bytes(UUID_NAMESPACE);
Uuid::new_v5(&namespace, key)
} | 1,075 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.