{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\"#;\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134628,"cells":{"blob_id":{"kind":"string","value":"bf75c93bf34b5cdcdba2d75f29be12308ed49214"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"lazylook2/rust_study"},"path":{"kind":"string","value":"/src/error.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3938,"string":"3,938"},"score":{"kind":"number","value":3.703125,"string":"3.703125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::fs::File;\nuse std::io::{ErrorKind, Read, Error};\nuse std::{io, fs};\n\n/*pub fn e1 () {\n// 使用result处理潜在的错误\n// enum Result {\n// Ok(T),\n// Err(E),\n// }\n let f = File::open(\"fuck.txt\");\n let f = match f {\n Ok(file) => file,\n Err(error) => match error.kind() {\n ErrorKind::NotFound => match File::create(\"fuck.txt\") {\n Ok(fc) => fc,\n Err(e) => panic!(\"Problem creating the file: {:?}\", e),\n },\n other_kind=> panic!(\"Problem opening the file: {:?}\", other_error),\n }\n };\n // 用了闭包\n let f = File::open(\"fuck.txt\").unwrap_or_else(|error| {\n if error.kind() == ErrorKind::NotFound {\n File::create(\"fuck.txt\").unwrap_or_else(|error| {\n panic!(\"Problem creating the file: {:?}\", error);\n })\n } else {\n panic!(\"Problem opening the file: {:?}\", error);\n }\n });\n// 失败时 panic 的简写:unwrap 和 expect\n\n// unwrap 那样使用默认的 panic! 信息\n// expect 用来调用 panic! 的错误信息将会作为参数传递给 expect\n\n // 如果 Result 值是成员 Ok,unwrap 会返回 Ok 中的值。\n // 如果 Result 是成员 Err,unwrap 会为我们调用 panic!。\n let f = File::open(\"hello.txt\").unwrap();\n\n\n // 使用 expect 提供一个好的错误信息可以表明你的意图并更易于追踪 panic 的根源。\n let f = File::open(\"hello.txt\").expect(\"无法打开。。。。 hello.txt\");\n}*/\npub fn e2 () {\n// 传播错误(方法里编写,直接抛出错误)\n fn read_username_from_file() -> Result {\n let mut f = File::open(\"fuck.txt\");\n let mut f = match f {\n Ok(file) => file,\n Err(e) => return Err(e),\n };\n let mut s = String::new();\n match f.read_to_string(&mut s) {\n Ok(_) => Ok(s),\n Err(e) => Err(e),\n }\n }\n let f = read_username_from_file();\n\n match f {\n Ok(string) => println!(\"fuck.txt的内容为:{}\", string),\n Err(e) => panic!(\"读取fuck.txt的内容失败: {:?}\", e),\n }\n\n /// Result 值之后的 ? 与match 表达式有着完全相同的工作方式。\n /// 如果 Result 的值是 Ok,这个表达式将会返回 Ok 中的值而程序将继续执行。\n /// 如果值是 Err,Err 中的值将作为整个函数的返回值,就好像使用了 return 关键字一样\n fn read_username_from_file1() -> Result {\n /*let mut f = File::open(\"fuck.txt\")?;\n let mut s = String::new();\n f.read_to_string(&mut s)?;*/\n // 可以链式调用,下面可以取代注释内容\n\n /*let mut s = String::new();\n File::open(\"fuck.txt\")?.read_to_string(&mut s)?;*/\n // 更简便的写法如下:\n fs::read_to_string(\"fuck.txt\")\n\n }\n let f = read_username_from_file();\n\n match f {\n Ok(string) => println!(\"fuck.txt的内容为:{}\", string),\n Err(e) => panic!(\"读取fuck.txt的内容失败: {:?}\", e),\n }\n\n let secret_number = 3;\n loop {\n let mut guess = String::new();\n // --snip--\n let guess: i32 = match guess.trim().parse() {\n Ok(num) => num,\n Err(_) => continue,\n };\n if guess < 1 || guess > 100 {\n println!(\"The secret number will be between 1 and 100.\");\n continue;\n }\n match guess.cmp(&secret_number) {\n _ => (),\n }\n }\n pub struct Guess {\n value: i32,\n }\n\n impl Guess {\n pub fn new(value: i32) -> Guess {\n if value < 1 || value > 100 {\n panic!(\"Guess value must be between 1 and 100, got {}.\", value);\n }\n Guess {\n value\n }\n }\n pub fn value(&self) -> i32 {\n self.value\n }\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134629,"cells":{"blob_id":{"kind":"string","value":"6d411a13e52a02551c4bc56a8ef6155e41fd01fb"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"N1ghtStorm/actix_send"},"path":{"kind":"string","value":"/examples/basic.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3738,"string":"3,738"},"score":{"kind":"number","value":3.546875,"string":"3.546875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use std::time::Duration;\n\nuse futures_util::stream::StreamExt;\n\nuse actix_send::prelude::*;\n\nuse crate::my_actor::*;\n\n/*\n By default we don't enable async-std runtime. Please run this example with:\n\n cargo run --example basic --no-default-features --features async-std-runtime\n*/\n\n#[async_std::main]\nasync fn main() {\n // create an actor instance. The create function would return our Actor struct.\n let builder = MyActor::builder(|| async {\n let state1 = String::from(\"running\");\n let state2 = String::from(\"running\");\n MyActor { state1, state2 }\n });\n\n // build and start the actor(s).\n let address: Address = builder.start().await;\n\n // construct new messages.\n let msg = Message1 {\n from: \"a simple test\".to_string(),\n };\n let msg2 = Message2(22);\n let msg3 = Message3;\n\n // use address to send messages to actor and await on result.\n\n // send method would return the message's result type in #[message] macro together with a possible actix_send::prelude::ActixSendError\n let res: Result = address.send(msg).await;\n let res = res.unwrap();\n\n let res2 = address.send(msg2).await.unwrap();\n\n let res3 = address.send(msg3).await.unwrap();\n\n println!(\"We got result for Message1\\r\\nResult is: {}\\r\\n\", res);\n println!(\"We got result for Message2\\r\\nResult is: {}\\r\\n\", res2);\n println!(\"We got result for Message3\\r\\nResult is: {:?}\\r\\n\", res3);\n\n // register an interval future for actor with given duration.\n let handler = address\n .run_interval(Duration::from_secs(1), |actor| {\n // Box the closure directly and wrap some async code in it.\n Box::pin(async move {\n println!(\"actor state is: {}\", &actor.state1);\n })\n })\n .await\n .unwrap();\n\n let mut interval = async_std::stream::interval(Duration::from_secs(1));\n\n for i in 0..5 {\n if i == 3 {\n // cancel the interval future after 3 seconds.\n handler.cancel();\n println!(\"interval future stopped\");\n }\n\n interval.next().await;\n }\n println!(\"example finish successfully\");\n}\n\n/* Implementation of actor */\n\n// we pack all possible messages types and all handler methods for one actor into a mod.\n// actor_mod macro would take care for the detailed implementation.\n#[actor_mod]\npub mod my_actor {\n use super::*;\n\n // our actor type\n #[actor]\n pub struct MyActor {\n pub state1: String,\n pub state2: String,\n }\n\n // message types\n\n #[message(result = \"u8\")]\n pub struct Message1 {\n pub from: String,\n }\n\n #[message(result = \"u16\")]\n pub struct Message2(pub u32);\n\n #[message(result = \"()\")]\n pub struct Message3;\n\n // we impl handler trait for all message types\n // The compiler would complain if there are message types don't have an according Handler trait impl.\n\n #[handler]\n impl Handler for MyActor {\n // The msg and handle's return type must match former message macro's result type.\n async fn handle(&mut self, msg123: Message1) -> u8 {\n println!(\"Actor State1 : {}\", self.state1);\n println!(\"We got an Message1.\\r\\nfrom : {}\\r\\n\", msg123.from);\n 8\n }\n }\n\n #[handler]\n impl Handler for MyActor {\n async fn handle(&mut self, msg: Message2) -> u16 {\n println!(\"Actor State2 : {}\", self.state2);\n println!(\"We got an Message2.\\r\\nsize : {}\\r\\n\", msg.0);\n 16\n }\n }\n\n #[handler]\n impl Handler for MyActor {\n async fn handle(&mut self, _msg: Message3) {\n println!(\"We got an Message3.\\r\\n\");\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134630,"cells":{"blob_id":{"kind":"string","value":"0120848d62fb530c6873a74b25fd139004aef59d"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"kebabtent/aoc2020"},"path":{"kind":"string","value":"/day11/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1472,"string":"1,472"},"score":{"kind":"number","value":3.1875,"string":"3.1875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use common::read_lines;\nuse X::*;\n\n#[derive(Clone, Copy, PartialEq)]\nenum X {\n\tF,\n\tE,\n\tO,\n}\n\nimpl From for X {\n\tfn from(c: char) -> Self {\n\t\tmatch c {\n\t\t\t'.' => F,\n\t\t\t'L' => E,\n\t\t\t'#' => O,\n\t\t\t_ => unreachable!(),\n\t\t}\n\t}\n}\n\nfn n(d: &[(isize, isize)], f: bool, p: &Vec>, ix: isize, iy: isize) -> usize {\n\tlet mut c = 0;\n\tlet ly = p.len() as isize;\n\tlet lx = p[0].len() as isize;\n\tfor &(dx, dy) in d {\n\t\tlet mut x = ix;\n\t\tlet mut y = iy;\n\t\tloop {\n\t\t\tx += dx;\n\t\t\ty += dy;\n\t\t\tif x < 0 || x >= lx || y < 0 || y >= ly {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlet v = p[y as usize][x as usize];\n\t\t\tif f || v != F {\n\t\t\t\tif v == O {\n\t\t\t\t\tc += 1;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tc\n}\n\nfn u(d: &[(isize, isize)], f: bool, mut p: Vec>) -> usize {\n\tlet mut a;\n\tlet t = if f { 4 } else { 5 };\n\tloop {\n\t\ta = 0;\n\t\tlet q = p.clone();\n\t\tfor y in 0..p.len() {\n\t\t\tfor x in 0..p[0].len() {\n\t\t\t\tlet n = n(d, f, &q, x as isize, y as isize);\n\t\t\t\tp[y][x] = match q[y][x] {\n\t\t\t\t\tE if n == 0 => O,\n\t\t\t\t\tO if n >= t => E,\n\t\t\t\t\tv => v,\n\t\t\t\t};\n\t\t\t\tif p[y][x] == O {\n\t\t\t\t\ta += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif p == q {\n\t\t\tbreak;\n\t\t}\n\t}\n\ta\n}\n\nfn main() {\n\tlet mut d = Vec::with_capacity(8);\n\tfor i in -1isize..=1 {\n\t\tfor j in -1isize..=1 {\n\t\t\tif i == 0 && j == 0 {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\td.push((i, j));\n\t\t}\n\t}\n\n\tlet p: Vec> = read_lines(\"11\")\n\t\t.map(|l| l.chars().map(|c| c.into()).collect())\n\t\t.collect();\n\n\tlet a = u(&d, true, p.clone());\n\tlet b = u(&d, false, p);\n\tprintln!(\"{}\", a);\n\tprintln!(\"{}\", b);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134631,"cells":{"blob_id":{"kind":"string","value":"5550b6e49b01f2b73508374af95cb89361110a9a"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"stanislav-tkach/mlc"},"path":{"kind":"string","value":"/src/logger.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":866,"string":"866"},"score":{"kind":"number","value":2.8125,"string":"2.8125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"extern crate simplelog;\n\nuse simplelog::*;\n\narg_enum! {\n #[derive(Debug)]\n pub enum LogLevel {\n Info,\n Warn,\n Debug\n }\n}\n\nimpl Default for LogLevel {\n fn default() -> Self {\n LogLevel::Warn\n }\n}\n\npub fn init(log_level: &LogLevel) {\n let level_filter = match log_level {\n LogLevel::Info => LevelFilter::Info,\n LogLevel::Warn => LevelFilter::Warn,\n LogLevel::Debug => LevelFilter::Debug,\n };\n\n let mut logger_array = vec![];\n match TermLogger::new(level_filter, Config::default(), TerminalMode::Mixed) {\n Some(logger) => logger_array.push(logger as Box),\n None => logger_array.push(SimpleLogger::new(level_filter, Config::default())),\n }\n\n CombinedLogger::init(logger_array).expect(\"No logger should be already set\");\n debug!(\"Initialized logging\")\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134632,"cells":{"blob_id":{"kind":"string","value":"e8e1915d987ccd6c290b4cb3dcf611ba8addf311"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"atsamd-rs/atsamd"},"path":{"kind":"string","value":"/hal/src/sercom/uart/flags.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3779,"string":"3,779"},"score":{"kind":"number","value":3.015625,"string":"3.015625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference","Apache-2.0"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\",\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"//! Flag definitions\n\nuse bitflags::bitflags;\nuse core::convert::TryFrom;\n\n//=============================================================================\n// Interrupt flags\n//=============================================================================\nconst DRE: u8 = 0x01;\nconst TXC: u8 = 0x02;\nconst RXC: u8 = 0x04;\nconst RXS: u8 = 0x08;\npub(super) const CTSIC: u8 = 0x10;\nconst RXBRK: u8 = 0x20;\nconst ERROR: u8 = 0x80;\n\n/// Interrupt flags available for RX transactions\npub const RX_FLAG_MASK: u8 = RXC | RXS | RXBRK | ERROR;\n/// Interrupt flags available for TX transactions\npub const TX_FLAG_MASK: u8 = DRE | TXC;\n/// Interrupt flags available for Duplex transactions\npub const DUPLEX_FLAG_MASK: u8 = RX_FLAG_MASK | TX_FLAG_MASK;\n\nbitflags! {\n /// Interrupt bit flags for UART Rx transactions\n ///\n /// The available interrupt flags are `DRE`, `TXC`, `RXC`, `RXS`, `CTSIC`, `RXBRK` and\n /// `ERROR`. The binary format of the underlying bits exactly matches the\n /// INTFLAG bits.\n pub struct Flags: u8 {\n const DRE = DRE;\n const TXC = TXC;\n const RXC = RXC;\n const RXS = RXS ;\n const CTSIC = CTSIC;\n const RXBRK = RXBRK;\n const ERROR = ERROR;\n }\n}\n\n//=============================================================================\n// Status flags\n//=============================================================================\n\nconst PERR: u16 = 0x01;\nconst FERR: u16 = 0x02;\nconst BUFOVF: u16 = 0x04;\nconst CTS: u16 = 0x08;\nconst ISF: u16 = 0x10;\nconst COLL: u16 = 0x20;\n\n/// Status flags available for RX transactions\npub const RX_STATUS_MASK: u16 = PERR | FERR | BUFOVF | ISF | COLL;\n/// Status flags available for Duplex transactions\npub const DUPLEX_STATUS_MASK: u16 = RX_STATUS_MASK;\n\nbitflags! {\n /// Status flags for UART Rx transactions\n ///\n /// The available status flags are `PERR`, `FERR`, `BUFOVF`,\n /// `CTS`, `ISF` and `COLL`.\n /// The binary format of the underlying bits exactly matches\n /// the STATUS bits.\n pub struct Status: u16 {\n const PERR = PERR;\n const FERR = FERR;\n const BUFOVF = BUFOVF;\n const CTS = CTS;\n const ISF = ISF;\n const COLL = COLL;\n }\n}\n\n//=============================================================================\n// Error\n//=============================================================================\n\n/// Errors available for UART transactions\n#[derive(Debug, Clone, Copy, Eq, PartialEq)]\n#[cfg_attr(feature = \"defmt\", derive(defmt::Format))]\npub enum Error {\n /// Detected a parity error\n ParityError,\n /// Detected a frame error\n FrameError,\n /// Detected a buffer overflow\n Overflow,\n /// Detected an inconsistent sync field\n InconsistentSyncField,\n /// Detected a collision\n CollisionDetected,\n}\n\nimpl TryFrom for () {\n type Error = Error;\n\n #[inline]\n fn try_from(errors: Status) -> Result<(), Error> {\n use Error::*;\n if errors.contains(Status::PERR) {\n Err(ParityError)\n } else if errors.contains(Status::FERR) {\n Err(FrameError)\n } else if errors.contains(Status::BUFOVF) {\n Err(Overflow)\n } else if errors.contains(Status::ISF) {\n Err(InconsistentSyncField)\n } else if errors.contains(Status::COLL) {\n Err(CollisionDetected)\n } else {\n Ok(())\n }\n }\n}\n\nimpl From for Status {\n #[inline]\n fn from(err: Error) -> Self {\n use Error::*;\n match err {\n ParityError => Status::PERR,\n FrameError => Status::FERR,\n Overflow => Status::BUFOVF,\n InconsistentSyncField => Status::ISF,\n CollisionDetected => Status::COLL,\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134633,"cells":{"blob_id":{"kind":"string","value":"a23d9ed634f9fd9dadbc3bc30482a483b3b2a04f"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Detegr/readline-sys"},"path":{"kind":"string","value":"/src/readline/funmap.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8517,"string":"8,517"},"score":{"kind":"number","value":3.046875,"string":"3.046875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"//! [2.4.4 Associating Function Names and Bindings]\n//! [2.4.4 associating function names and bindings]: https://goo.gl/CrXrWQ\n//!\n//! These functions allow you to find out what keys invoke named functions and the functions invoked\n//! by a particular key sequence. You may also associate a new function name with an arbitrary\n//! function.\nuse readline::{CommandFunction, Keymap};\nuse readline::binding::BindType;\nuse std::ffi::{CStr, CString};\nuse std::ptr;\n\nmod ext_funmap {\n use libc::{c_char, c_int};\n use readline::{CommandFunction, Keymap};\n\n extern \"C\" {\n pub fn rl_named_function(name: *const c_char) -> Option;\n pub fn rl_function_of_keyseq(keyseq: *const c_char,\n map: Keymap,\n bind_type: *mut c_int)\n -> Option;\n pub fn rl_invoking_keyseqs(f: CommandFunction) -> *mut *mut c_char;\n pub fn rl_invoking_keyseqs_in_map(f: CommandFunction, map: Keymap) -> *mut *mut c_char;\n pub fn rl_function_dumper(readable: c_int) -> ();\n pub fn rl_list_funmap_names() -> ();\n pub fn rl_add_funmap_entry(name: *const c_char, f: CommandFunction) -> c_int;\n }\n}\n\n/// Return the function with name `name`.\n///\n/// # Examples\n///\n/// ```\n/// use rl_sys::readline::{funmap, util};\n///\n/// util::init();\n///\n/// assert!(funmap::named_function(\"self-insert\").is_ok())\n/// ```\npub fn named_function(name: &str) -> Result {\n let csname = try!(CString::new(name));\n let func_ptr = unsafe {\n ext_funmap::rl_named_function(csname.as_ptr())\n };\n if func_ptr.is_none() {\n Err(::ReadlineError::new(\"Funmap Error\", \"Unable to find name function!\"))\n } else {\n Ok(func_ptr.expect(\"Unable to get function pointer\"))\n }\n}\n\n/// Return the function invoked by `keyseq` in keymap `map`. If `map` is None, the current keymap is\n/// used. If `add_type` is true, the type of the object is returned (one of `Func`, `Kmap`, or\n/// `Macr`).\n///\n/// # Examples\n///\n/// ```\n/// use rl_sys::readline::binding::BindType;\n/// use rl_sys::readline::{funmap, util};\n///\n/// util::init();\n///\n/// match funmap::function_of_keyseq(\"1\", None, true) {\n/// Ok((_, Some(t))) => assert!(t == BindType::from(0)),\n/// Ok((_, None)) => assert!(false),\n/// Err(_) => assert!(false),\n/// }\n/// ```\npub fn function_of_keyseq\n (keyseq: &str,\n map: Option,\n add_type: bool)\n -> Result<(Option, Option), ::ReadlineError> {\n\n let cskeyseq = try!(CString::new(keyseq));\n let km = match map {\n Some(km) => km,\n None => ptr::null_mut(),\n };\n let bind_type: *mut i32 = if add_type { &mut 1 } else { ptr::null_mut() };\n let func_ptr = unsafe {\n ext_funmap::rl_function_of_keyseq(cskeyseq.as_ptr(), km, bind_type)\n };\n if func_ptr.is_none() {\n Err(::ReadlineError::new(\"Funmap Error\",\n \"Unable to get function associated with keyseq!\"))\n } else if add_type {\n Ok((func_ptr, Some(BindType::from(unsafe { *bind_type }))))\n } else {\n Ok((func_ptr, None))\n }\n}\n\n/// Return an array of strings representing the key sequences used to invoke function in the current\n/// keymap.\n///\n/// # Examples\n///\n/// ```\n/// use rl_sys::readline::{funmap, util};\n///\n/// util::init();\n///\n/// let cmd = funmap::named_function(\"self-insert\").unwrap();\n/// let names = funmap::invoking_keyseqs(cmd).unwrap();\n/// assert!(names.len() > 0);\n/// ```\npub fn invoking_keyseqs(f: CommandFunction) -> Result, ::ReadlineError> {\n unsafe {\n let arr_ptr = ext_funmap::rl_invoking_keyseqs(f);\n\n if arr_ptr.is_null() {\n Err(::ReadlineError::new(\"Funmap Error\", \"Unable to find invoking key seqs!\"))\n } else {\n let mut entries = Vec::new();\n for i in 0.. {\n let entry_ptr = *arr_ptr.offset(i as isize);\n if entry_ptr.is_null() {\n break;\n } else {\n entries.push(CStr::from_ptr(entry_ptr).to_string_lossy().into_owned());\n }\n }\n Ok(entries)\n }\n }\n}\n\n/// Return an array of strings representing the key sequences used to invoke function in the current\n/// keymap.\n///\n/// # Examples\n///\n/// ```\n/// use rl_sys::readline::{funmap, keymap, util};\n///\n/// util::init();\n///\n/// let cmd = funmap::named_function(\"self-insert\").unwrap();\n/// let km = keymap::get().unwrap();\n/// let names = funmap::invoking_keyseqs_in_map(cmd, km).unwrap();\n/// assert!(names.len() > 0);\n/// ```\npub fn invoking_keyseqs_in_map(f: CommandFunction,\n map: Keymap)\n -> Result, ::ReadlineError> {\n unsafe {\n let arr_ptr = ext_funmap::rl_invoking_keyseqs_in_map(f, map);\n\n if arr_ptr.is_null() {\n Err(::ReadlineError::new(\"Funmap Error\", \"Unable to find invoking key seqs in map!\"))\n } else {\n let mut entries = Vec::new();\n for i in 0.. {\n let entry_ptr = *arr_ptr.offset(i as isize);\n if entry_ptr.is_null() {\n break;\n } else {\n entries.push(CStr::from_ptr(entry_ptr).to_string_lossy().into_owned());\n }\n }\n Ok(entries)\n }\n }\n}\n\n/// Print the readline function names and the key sequences currently bound to them to\n/// `rl_outstream`. If `readable` is true, the list is formatted in such a way that it can be made\n/// part of an `inputrc` file and re-read.\n///\n/// # Examples\n///\n/// ```\n/// use rl_sys::readline::{funmap, util};\n///\n/// util::init();\n///\n/// funmap::function_dumper(true);\n/// ```\npub fn function_dumper(readable: bool) -> () {\n let i = if readable { 1 } else { 0 };\n unsafe { ext_funmap::rl_function_dumper(i) }\n}\n\n/// Print the names of all bindable Readline functions to `rl_outstream`.\n///\n/// # Examples\n///\n/// ```\n/// use rl_sys::readline::{funmap, util};\n///\n/// util::init();\n///\n/// funmap::list_funmap_names();\n/// ```\npub fn list_funmap_names() -> () {\n unsafe { ext_funmap::rl_list_funmap_names() }\n}\n\n/// Add `name` to the list of bindable Readline command names, and make function `f` the function to\n/// be called when `name` is invoked.\n///\n/// # Examples\n///\n/// ```rust\n/// # extern crate libc;\n/// # extern crate rl_sys;\n/// # fn main() {\n/// use libc::c_int;\n/// use rl_sys::readline::{funmap, util};\n///\n/// util::init();\n///\n/// extern \"C\" fn test_cmd_func(_count: c_int, _key: c_int) -> c_int {\n/// 0\n/// }\n///\n/// match funmap::add_funmap_entry(\"test-cmd\", test_cmd_func) {\n/// Ok(res) => assert!(res >= 0),\n/// Err(_) => assert!(false),\n/// }\n/// # }\n/// ```\npub fn add_funmap_entry(name: &str, cmd: CommandFunction) -> Result {\n let csname = try!(CString::new(name));\n let res = unsafe {\n ext_funmap::rl_add_funmap_entry(csname.as_ptr(), cmd)\n };\n if res >= 0 {\n Ok(res)\n } else {\n Err(::ReadlineError::new(\"Funmap Error\", \"Unable to add funmap entry!\"))\n }\n}\n\n#[cfg(test)]\nmod test {\n use readline::util;\n use readline::binding::BindType;\n use super::*;\n\n // #[test]\n // fn test_function_dumper() {\n // util::init();\n // function_dumper(true);\n // }\n //\n // #[test]\n // fn test_list_funmap_names() {\n // util::init();\n // list_funmap_names();\n // }\n\n #[test]\n fn test_function_of_keyseq() {\n util::init();\n match function_of_keyseq(\"1\", None, true) {\n Ok((_, Some(t))) => assert!(t == BindType::from(0)),\n Ok((_, None)) => assert!(false),\n Err(_) => assert!(false),\n }\n\n match function_of_keyseq(\"2\", None, false) {\n Ok((_, Some(_))) => assert!(false),\n Ok((_, None)) => assert!(true),\n Err(_) => assert!(false),\n }\n }\n\n #[test]\n fn test_add_funmap_entry() {\n use libc::c_int;\n\n #[no_mangle]\n #[allow(private_no_mangle_fns)]\n extern \"C\" fn test_cmd_func(_count: c_int, _key: c_int) -> c_int {\n 0\n }\n\n util::init();\n\n match add_funmap_entry(\"test-cmd\", test_cmd_func) {\n Ok(res) => assert!(res >= 0),\n Err(_) => assert!(false),\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134634,"cells":{"blob_id":{"kind":"string","value":"2ee3f0e6374b8b30b68b60e38fb243dce2df9a37"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"creativcoder/forest"},"path":{"kind":"string","value":"/ipld/hamt/src/hamt.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":9006,"string":"9,006"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","Apache-2.0"],"string":"[\n \"MIT\",\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"// Copyright 2020 ChainSafe Systems\n// SPDX-License-Identifier: Apache-2.0, MIT\n\nuse crate::node::Node;\nuse crate::{Error, Hash, HashAlgorithm, Sha256, DEFAULT_BIT_WIDTH};\nuse cid::{Cid, Code::Blake2b256};\nuse forest_hash_utils::BytesKey;\nuse ipld_blockstore::BlockStore;\nuse serde::{de::DeserializeOwned, Serialize, Serializer};\nuse std::borrow::Borrow;\nuse std::error::Error as StdError;\nuse std::marker::PhantomData;\n\n/// Implementation of the HAMT data structure for IPLD.\n///\n/// # Examples\n///\n/// ```\n/// use ipld_hamt::Hamt;\n///\n/// let store = db::MemoryDB::default();\n///\n/// let mut map: Hamt<_, _, usize> = Hamt::new(&store);\n/// map.set(1, \"a\".to_string()).unwrap();\n/// assert_eq!(map.get(&1).unwrap(), Some(&\"a\".to_string()));\n/// assert_eq!(map.delete(&1).unwrap(), Some((1, \"a\".to_string())));\n/// assert_eq!(map.get::<_>(&1).unwrap(), None);\n/// let cid = map.flush().unwrap();\n/// ```\n#[derive(Debug)]\npub struct Hamt<'a, BS, V, K = BytesKey, H = Sha256> {\n root: Node,\n store: &'a BS,\n\n bit_width: u32,\n hash: PhantomData,\n}\n\nimpl Serialize for Hamt<'_, BS, V, K, H>\nwhere\n K: Serialize,\n V: Serialize,\n H: HashAlgorithm,\n{\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n self.root.serialize(serializer)\n }\n}\n\nimpl<'a, K: PartialEq, V: PartialEq, S: BlockStore, H: HashAlgorithm> PartialEq\n for Hamt<'a, S, V, K, H>\n{\n fn eq(&self, other: &Self) -> bool {\n self.root == other.root\n }\n}\n\nimpl<'a, BS, V, K, H> Hamt<'a, BS, V, K, H>\nwhere\n K: Hash + Eq + PartialOrd + Serialize + DeserializeOwned,\n V: Serialize + DeserializeOwned,\n BS: BlockStore,\n H: HashAlgorithm,\n{\n pub fn new(store: &'a BS) -> Self {\n Self::new_with_bit_width(store, DEFAULT_BIT_WIDTH)\n }\n\n /// Construct hamt with a bit width\n pub fn new_with_bit_width(store: &'a BS, bit_width: u32) -> Self {\n Self {\n root: Node::default(),\n store,\n bit_width,\n hash: Default::default(),\n }\n }\n\n /// Lazily instantiate a hamt from this root Cid.\n pub fn load(cid: &Cid, store: &'a BS) -> Result {\n Self::load_with_bit_width(cid, store, DEFAULT_BIT_WIDTH)\n }\n\n /// Lazily instantiate a hamt from this root Cid with a specified bit width.\n pub fn load_with_bit_width(cid: &Cid, store: &'a BS, bit_width: u32) -> Result {\n match store.get(cid)? {\n Some(root) => Ok(Self {\n root,\n store,\n bit_width,\n hash: Default::default(),\n }),\n None => Err(Error::CidNotFound(cid.to_string())),\n }\n }\n\n /// Sets the root based on the Cid of the root node using the Hamt store\n pub fn set_root(&mut self, cid: &Cid) -> Result<(), Error> {\n match self.store.get(cid)? {\n Some(root) => self.root = root,\n None => return Err(Error::CidNotFound(cid.to_string())),\n }\n\n Ok(())\n }\n\n /// Returns a reference to the underlying store of the Hamt.\n pub fn store(&self) -> &'a BS {\n self.store\n }\n\n /// Inserts a key-value pair into the HAMT.\n ///\n /// If the HAMT did not have this key present, `None` is returned.\n ///\n /// If the HAMT did have this key present, the value is updated, and the old\n /// value is returned. The key is not updated, though;\n ///\n /// # Examples\n ///\n /// ```\n /// use ipld_hamt::Hamt;\n ///\n /// let store = db::MemoryDB::default();\n ///\n /// let mut map: Hamt<_, _, usize> = Hamt::new(&store);\n /// map.set(37, \"a\".to_string()).unwrap();\n /// assert_eq!(map.is_empty(), false);\n ///\n /// map.set(37, \"b\".to_string()).unwrap();\n /// map.set(37, \"c\".to_string()).unwrap();\n /// ```\n pub fn set(&mut self, key: K, value: V) -> Result, Error>\n where\n V: PartialEq,\n {\n self.root\n .set(key, value, self.store, self.bit_width, true)\n .map(|(r, _)| r)\n }\n\n /// Inserts a key-value pair into the HAMT only if that key does not already exist.\n ///\n /// If the HAMT did not have this key present, `true` is returned and the key/value is added.\n ///\n /// If the HAMT did have this key present, this function will return false\n ///\n /// # Examples\n ///\n /// ```\n /// use ipld_hamt::Hamt;\n ///\n /// let store = db::MemoryDB::default();\n ///\n /// let mut map: Hamt<_, _, usize> = Hamt::new(&store);\n /// let a = map.set_if_absent(37, \"a\".to_string()).unwrap();\n /// assert_eq!(map.is_empty(), false);\n /// assert_eq!(a, true);\n ///\n /// let b = map.set_if_absent(37, \"b\".to_string()).unwrap();\n /// assert_eq!(b, false);\n /// assert_eq!(map.get(&37).unwrap(), Some(&\"a\".to_string()));\n ///\n /// let c = map.set_if_absent(30, \"c\".to_string()).unwrap();\n /// assert_eq!(c, true);\n /// ```\n pub fn set_if_absent(&mut self, key: K, value: V) -> Result\n where\n V: PartialEq,\n {\n self.root\n .set(key, value, self.store, self.bit_width, false)\n .map(|(_, set)| set)\n }\n\n /// Returns a reference to the value corresponding to the key.\n ///\n /// The key may be any borrowed form of the map's key type, but\n /// `Hash` and `Eq` on the borrowed form *must* match those for\n /// the key type.\n ///\n /// # Examples\n ///\n /// ```\n /// use ipld_hamt::Hamt;\n ///\n /// let store = db::MemoryDB::default();\n ///\n /// let mut map: Hamt<_, _, usize> = Hamt::new(&store);\n /// map.set(1, \"a\".to_string()).unwrap();\n /// assert_eq!(map.get(&1).unwrap(), Some(&\"a\".to_string()));\n /// assert_eq!(map.get(&2).unwrap(), None);\n /// ```\n #[inline]\n pub fn get(&self, k: &Q) -> Result, Error>\n where\n K: Borrow,\n Q: Hash + Eq,\n V: DeserializeOwned,\n {\n match self.root.get(k, self.store, self.bit_width)? {\n Some(v) => Ok(Some(v)),\n None => Ok(None),\n }\n }\n\n /// Returns `true` if a value exists for the given key in the HAMT.\n ///\n /// The key may be any borrowed form of the map's key type, but\n /// `Hash` and `Eq` on the borrowed form *must* match those for\n /// the key type.\n ///\n /// # Examples\n ///\n /// ```\n /// use ipld_hamt::Hamt;\n ///\n /// let store = db::MemoryDB::default();\n ///\n /// let mut map: Hamt<_, _, usize> = Hamt::new(&store);\n /// map.set(1, \"a\".to_string()).unwrap();\n /// assert_eq!(map.contains_key(&1).unwrap(), true);\n /// assert_eq!(map.contains_key(&2).unwrap(), false);\n /// ```\n #[inline]\n pub fn contains_key(&self, k: &Q) -> Result\n where\n K: Borrow,\n Q: Hash + Eq,\n {\n Ok(self.root.get(k, self.store, self.bit_width)?.is_some())\n }\n\n /// Removes a key from the HAMT, returning the value at the key if the key\n /// was previously in the HAMT.\n ///\n /// The key may be any borrowed form of the HAMT's key type, but\n /// `Hash` and `Eq` on the borrowed form *must* match those for\n /// the key type.\n ///\n /// # Examples\n ///\n /// ```\n /// use ipld_hamt::Hamt;\n ///\n /// let store = db::MemoryDB::default();\n ///\n /// let mut map: Hamt<_, _, usize> = Hamt::new(&store);\n /// map.set(1, \"a\".to_string()).unwrap();\n /// assert_eq!(map.delete(&1).unwrap(), Some((1, \"a\".to_string())));\n /// assert_eq!(map.delete(&1).unwrap(), None);\n /// ```\n pub fn delete(&mut self, k: &Q) -> Result, Error>\n where\n K: Borrow,\n Q: Hash + Eq,\n {\n self.root.remove_entry(k, self.store, self.bit_width)\n }\n\n /// Flush root and return Cid for hamt\n pub fn flush(&mut self) -> Result {\n self.root.flush(self.store)?;\n Ok(self.store.put(&self.root, Blake2b256)?)\n }\n\n /// Returns true if the HAMT has no entries\n pub fn is_empty(&self) -> bool {\n self.root.is_empty()\n }\n\n /// Iterates over each KV in the Hamt and runs a function on the values.\n ///\n /// This function will constrain all values to be of the same type\n ///\n /// # Examples\n ///\n /// ```\n /// use ipld_hamt::Hamt;\n ///\n /// let store = db::MemoryDB::default();\n ///\n /// let mut map: Hamt<_, _, usize> = Hamt::new(&store);\n /// map.set(1, 1).unwrap();\n /// map.set(4, 2).unwrap();\n ///\n /// let mut total = 0;\n /// map.for_each(|_, v: &u64| {\n /// total += v;\n /// Ok(())\n /// }).unwrap();\n /// assert_eq!(total, 3);\n /// ```\n #[inline]\n pub fn for_each(&self, mut f: F) -> Result<(), Box>\n where\n V: DeserializeOwned,\n F: FnMut(&K, &V) -> Result<(), Box>,\n {\n self.root.for_each(self.store, &mut f)\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134635,"cells":{"blob_id":{"kind":"string","value":"e0cf4cbd5bebfaf65522c756e6b4c780487ac8f1"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"scotttrinh/automerge-rs"},"path":{"kind":"string","value":"/automerge/src/sync/state.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2041,"string":"2,041"},"score":{"kind":"number","value":2.8125,"string":"2.8125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use std::{borrow::Cow, collections::HashSet};\n\nuse super::{decode_hashes, encode_hashes, BloomFilter};\nuse crate::{decoding, decoding::Decoder, ChangeHash};\n\nconst SYNC_STATE_TYPE: u8 = 0x43; // first byte of an encoded sync state, for identification\n\n/// The state of synchronisation with a peer.\n#[derive(Debug, Clone, Default)]\npub struct State {\n pub shared_heads: Vec,\n pub last_sent_heads: Vec,\n pub their_heads: Option>,\n pub their_need: Option>,\n pub their_have: Option>,\n pub sent_hashes: HashSet,\n}\n\n/// A summary of the changes that the sender of the message already has.\n/// This is implicitly a request to the recipient to send all changes that the\n/// sender does not already have.\n#[derive(Debug, Clone, Default)]\npub struct Have {\n /// The heads at the time of the last successful sync with this recipient.\n pub last_sync: Vec,\n /// A bloom filter summarising all of the changes that the sender of the message has added\n /// since the last sync.\n pub bloom: BloomFilter,\n}\n\nimpl State {\n pub fn new() -> Self {\n Default::default()\n }\n\n pub fn encode(&self) -> Vec {\n let mut buf = vec![SYNC_STATE_TYPE];\n encode_hashes(&mut buf, &self.shared_heads);\n buf\n }\n\n pub fn decode(bytes: &[u8]) -> Result {\n let mut decoder = Decoder::new(Cow::Borrowed(bytes));\n\n let record_type = decoder.read::()?;\n if record_type != SYNC_STATE_TYPE {\n return Err(decoding::Error::WrongType {\n expected_one_of: vec![SYNC_STATE_TYPE],\n found: record_type,\n });\n }\n\n let shared_heads = decode_hashes(&mut decoder)?;\n Ok(Self {\n shared_heads,\n last_sent_heads: Vec::new(),\n their_heads: None,\n their_need: None,\n their_have: Some(Vec::new()),\n sent_hashes: HashSet::new(),\n })\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134636,"cells":{"blob_id":{"kind":"string","value":"03eb98277ce924ee5a3cc7eb835dc6b00d4bd79e"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"sww1235/connection-diagram-manager"},"path":{"kind":"string","value":"/src/datatypes/internal_types.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":65989,"string":"65,989"},"score":{"kind":"number","value":3.046875,"string":"3.046875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","MIT"],"string":"[\n \"Apache-2.0\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"///`cable_type` represents a cable with multiple cores\npub mod cable_type;\n/// `connector_type` represents a connector\npub mod connector_type;\n/// `equipment_type` represents a type of equipment\npub mod equipment_type;\n/// `location_type` represents a type of location\npub mod location_type;\n/// `pathway_type` represents a type of pathway for wires or cables\npub mod pathway_type;\n/// `svg` represents a complete SVG image\npub mod svg;\n/// `term_cable_type` represents a cable that has connectors assembled on to it\npub mod term_cable_type;\n/// `wire_type` represents an individual wire with optional insulation\npub mod wire_type;\n\n/// `equipment` represents an instance of an `EquipmentType`. This is a physical item\n/// you hold in your hand.\npub mod equipment;\n/// `location` represents an instance of a `LocationType`\npub mod location;\n/// `pathway` represents an instance of a `PathwayType`\npub mod pathway;\n/// `wire_cable` represents an instance of either a `WireType`, `CableType` or `TermCableType`\npub mod wire_cable;\n\nuse log::{error, trace, warn};\n\nuse std::cell::RefCell;\nuse std::collections::HashMap;\nuse std::rc::Rc;\n\nuse super::file_types::DataFile;\nuse super::util_types::CrossSection;\nuse cable_type::CableCore;\nuse svg::Svg;\n\n/// `Library` represents all library data used in program\n#[derive(Debug, Default, PartialEq)]\npub struct Library {\n /// contains all wire types read in from file, and/or added in via program logic\n pub wire_types: HashMap>>,\n /// contains all cable types read in from file, and/or added in via program logic\n pub cable_types: HashMap>>,\n /// contains all terminated cable types read in from file, and/or added in via program logic\n pub term_cable_types: HashMap>>,\n /// contains all location types read in from file, and/or added in via program logic\n pub location_types: HashMap>>,\n /// contains all connector types read in from file, and/or added in via program logic\n pub connector_types: HashMap>>,\n /// contains all equipment types read in from file, and/or added in via program logic\n pub equipment_types: HashMap>>,\n /// contains all pathway types read in from file\n pub pathway_types: HashMap>>,\n}\n\n/// `Project` represents all project specific data used in program\n#[derive(Debug, Default, PartialEq)]\npub struct Project {\n /// `equipment` contains all equipment instances read in from files, and/or added in via program logic\n pub equipment: HashMap>>,\n /// `wire_cables` contains all wire, cable and termcable instances read in from files, and/or\n /// added in via program logic\n pub wire_cables: HashMap>>,\n /// `pathways`contains all pathway instances read in from files and/or added in via program\n /// logic\n pub pathways: HashMap>>,\n /// `locations` contains all location instances read in from files and/or added in via program\n /// logic\n pub locations: HashMap>>,\n}\n\n/// `Mergable` indicates that an object has the necessary utilities to merge itself with another\n/// instance of the same object type.\npub trait Mergable {\n /// `merge_prompt` assists the user in merging 2 object instances by prompting the user with\n /// the difference between the object, field by field, and providing sensible defaults.\n fn merge_prompt(\n &mut self,\n other: &Self,\n prompt_fn: fn(HashMap) -> HashMap,\n ) -> Self;\n // pass a hashmap of string arrays, return a hashmap of integers which are the selected value\n // index out of the array, with keys as struct field names\n}\n\n/// `Empty` indicates that an object can be checked for PartialEq to Object::new()\npub trait Empty {\n /// `is_empty` checks to see if self is PartialEq to Object::new()\n fn is_empty(&self) -> bool;\n}\n\n/// `PartialEmpty` indicates that an object can be checked to be almost PartialEq to Object::new(),\n/// excepting the id field\npub trait PartialEmpty {\n /// `is_partial_empty` checks to see if self is almost PartialEq to Object::new() but id can be\n /// different\n fn is_partial_empty(&self) -> bool;\n}\n\n//TODO: need to add datafile reference to each internal_type struct so each appropriate datafile\n//can be updated with new serialized data\nimpl Library {\n ///Initializes an empty `Library`\n pub fn new() -> Self {\n Library {\n wire_types: HashMap::new(),\n cable_types: HashMap::new(),\n term_cable_types: HashMap::new(),\n location_types: HashMap::new(),\n connector_types: HashMap::new(),\n equipment_types: HashMap::new(),\n pathway_types: HashMap::new(),\n }\n }\n /// `from_datafiles` converts between the textual representation of datafiles, and the struct\n /// object representation of the internal objects\n pub fn from_datafiles(&mut self, datafiles: Vec) {\n // parse all datafiles\n for datafile in datafiles {\n self.from_datafile(datafile)\n }\n for (_, wire_type) in &self.wire_types {\n //TODO: check for empty objects\n }\n for (_, cable_type) in &self.cable_types {\n //TODO: check for empty objects\n }\n for (_, term_cable_type_type) in &self.term_cable_types {\n //TODO: check for empty objects\n }\n for (_, location_type) in &self.location_types {\n //TODO: check for empty objects\n }\n for (_, connector_type) in &self.connector_types {\n //TODO: check for empty objects\n }\n for (_, equipment_type) in &self.equipment_types {\n //TODO: check for empty objects\n }\n for (_, pathway_type) in &self.pathway_types {\n //TODO: check for empty objects\n }\n }\n\n /// inserts the correct values from a datafile into the called upon `Library` struct\n #[allow(clippy::wrong_self_convention)]\n // this is not a type conversion function so does not\n // need to follow the same rules\n // TODO: maybe rename this to something that doesn't\n // sound like a type conversion function\n fn from_datafile(&mut self, datafile: DataFile) {\n // wire_types\n if let Some(wire_types) = datafile.wire_types {\n for (k, v) in &wire_types {\n if self.wire_types.contains_key(k) {\n //TODO: do something: ignore dupe, prompt user for merge, try to merge\n //automatically\n warn! {concat!{\n \"WireType: {} with contents: {:#?} \",\n \"has already been loaded. Found again \",\n \"in file {}. Check this and merge if necessary\"},\n k, v, datafile.file_path.display()\n }\n } else {\n trace! {\"Inserted WireType: {}, value: {:#?} into main library.\",k,v}\n self.wire_types.insert(\n k.to_string(),\n Rc::new(RefCell::new(wire_type::WireType {\n id: k.to_string(),\n manufacturer: wire_types[k].manufacturer.clone(),\n model: wire_types[k].model.clone(),\n part_number: wire_types[k].part_number.clone(),\n manufacturer_part_number: wire_types[k]\n .manufacturer_part_number\n .clone(),\n supplier: wire_types[k].supplier.clone(),\n supplier_part_number: wire_types[k].supplier_part_number.clone(),\n material: wire_types[k].material.clone(),\n insulated: wire_types[k].insulated,\n insulation_material: wire_types[k].insulation_material.clone(),\n wire_type_code: wire_types[k].wire_type_code.clone(),\n conductor_cross_sect_area: wire_types[k].conductor_cross_sect_area,\n overall_cross_sect_area: wire_types[k].overall_cross_sect_area,\n stranded: wire_types[k].stranded,\n num_strands: wire_types[k].num_strands,\n strand_cross_sect_area: wire_types[k].strand_cross_sect_area,\n insul_volt_rating: wire_types[k].insul_volt_rating,\n insul_temp_rating: wire_types[k].insul_temp_rating,\n insul_color: wire_types[k].insul_color.clone(),\n })),\n );\n }\n }\n }\n // cable_types\n if let Some(cable_types) = datafile.cable_types {\n for (k, v) in &cable_types {\n if self.cable_types.contains_key(k) {\n warn! {concat!{\n \"CableType: {} with contents: {:#?} \",\n \"has already been loaded. Found again in \",\n \"file {}. Check this and merge if necessary\"},\n k, v, datafile.file_path.display()\n }\n\n //TODO: do something: ignore dupe, prompt user for merge, try to merge\n //automatically\n } else {\n trace! {\"Inserted CableType: {}, value: {:#?} into main datastore.\",k,v}\n // need to build cable_core first, so we can insert into self.cable_types if\n // needed.\n let mut cable_core_map = HashMap::new();\n for (core_id, core) in &cable_types[k].cable_core {\n //TODO: this could result in issues where the cable type is in\n //the file, but not read before it is checked for here.\n if core.is_wire && self.wire_types.contains_key(&core.type_str) {\n cable_core_map.insert(\n core_id.to_string(),\n CableCore::WireType(self.wire_types[&core.type_str].clone()),\n );\n } else if !core.is_wire && self.cable_types.contains_key(&core.type_str) {\n cable_core_map.insert(\n core_id.to_string(),\n CableCore::CableType(self.cable_types[&core.type_str].clone()),\n );\n } else {\n warn! {concat!{\n \"can't find CableCore Type: {} \",\n \"referenced in CableType: {} in \",\n \"datafile: {}, in any file or \",\n \"library imported into Project. \",\n \"Creating empty object for now\"},\n core.type_str, k, datafile.file_path.display()\n }\n if core.is_wire {\n let new_wire_type =\n Rc::new(RefCell::new(wire_type::WireType::new()));\n // need to set id of wire type correctly. type_str not\n // core_id\n new_wire_type.borrow_mut().id = core.type_str.to_string();\n // insert new_wire_type as core into cable_core_map\n cable_core_map.insert(\n core_id.to_string(),\n CableCore::WireType(new_wire_type.clone()),\n );\n // also insert new_wire_type into library\n self.wire_types\n .insert(core.type_str.to_string(), new_wire_type.clone());\n } else {\n //cable type\n let new_cable_type =\n Rc::new(RefCell::new(cable_type::CableType::new()));\n new_cable_type.borrow_mut().id = core.type_str.to_string();\n // insert new_cable_type as core into cable_core_map\n cable_core_map.insert(\n core_id.to_string(),\n CableCore::CableType(new_cable_type.clone()),\n );\n // also insert new_cable_type into library\n self.cable_types\n .insert(core.type_str.to_string(), new_cable_type.clone());\n }\n }\n }\n self.cable_types.insert(\n k.to_string(),\n Rc::new(RefCell::new(cable_type::CableType {\n id: k.to_string(),\n manufacturer: cable_types[k].manufacturer.clone(),\n model: cable_types[k].model.clone(),\n part_number: cable_types[k].part_number.clone(),\n manufacturer_part_number: cable_types[k].manufacturer_part_number.clone(),\n supplier: cable_types[k].supplier.clone(),\n supplier_part_number: cable_types[k].supplier_part_number.clone(),\n cable_type_code: cable_types[k].cable_type_code.clone(),\n cross_sect_area: cable_types[k].cross_sect_area,\n height: cable_types[k].height,\n width: cable_types[k].width,\n diameter: cable_types[k].diameter,\n cross_section: {\n match cable_types[k].cross_section.to_uppercase().as_str() {\n \"OVAL\" => CrossSection::Oval,\n \"CIRCULAR\" => CrossSection::Circular,\n \"SIAMESE\" => CrossSection::Siamese,\n //TODO: handle this better\n _ => panic! {concat!{\n \"Cross Section: {} in CableType: {} \",\n \"in file: {} not recognized. \",\n \"Check your spelling and try again.\"}\n ,cable_types[k].cross_section, k, datafile.file_path.display()\n }\n }\n },\n // cable_core_map defined above main struct definition to avoid multiple mutable\n // borrows of self.cable_types\n cable_core: cable_core_map,\n insul_layers: {\n let mut new_layers = Vec::new();\n for layer in &cable_types[k].insul_layers {\n let new_layer = cable_type::CableLayer {\n layer_number: layer.layer_number,\n layer_type: layer.layer_type.clone(),\n material: layer.material.clone(),\n volt_rating: layer.volt_rating,\n temp_rating: layer.temp_rating,\n color: layer.color.clone(),\n };\n new_layers.push(new_layer);\n }\n new_layers\n },\n })),\n );\n }\n }\n }\n\n // pathway_types\n if let Some(pathway_types) = datafile.pathway_types {\n for (k, v) in &pathway_types {\n if self.pathway_types.contains_key(k) {\n warn! {concat!{\"PathwayType : {} with \",\n \"contents: {:#?} has already been \",\n \"loaded. Found again in file {}. \",\n \"Check this and merge if necessary\"},\n k, v, datafile.file_path.display()}\n //TODO: do something: ignore dupe, prompt user for merge, try to merge\n //automatically\n } else {\n trace! {\"Inserted PathwayType: {}, value: {:#?} into main datastore.\",k,v}\n self.pathway_types.insert(\n k.to_string(),\n Rc::new(RefCell::new(pathway_type::PathwayType {\n id: k.to_string(),\n manufacturer: pathway_types[k].manufacturer.clone(),\n model: pathway_types[k].model.clone(),\n part_number: pathway_types[k].part_number.clone(),\n manufacturer_part_number: pathway_types[k]\n .manufacturer_part_number\n .clone(),\n supplier: pathway_types[k].supplier.clone(),\n supplier_part_number: pathway_types[k].supplier_part_number.clone(),\n description: pathway_types[k].description.clone(),\n size: pathway_types[k].size.clone(),\n trade_size: pathway_types[k].trade_size.clone(),\n // no clone needed since numeric types have easy copy implementation\n cross_sect_area: pathway_types[k].cross_sect_area,\n material: pathway_types[k].material.clone(),\n })),\n );\n }\n }\n }\n // location_types\n if let Some(location_types) = datafile.location_types {\n for (k, v) in &location_types {\n if self.location_types.contains_key(k) {\n warn! {concat!{\"LocationType : {} with \",\n \"contents: {:#?} has already been loaded. \",\n \"Found again in file {}. Check this \",\n \"and merge if necessary\"},\n k, v, datafile.file_path.display()}\n //TODO: do something: ignore dupe, prompt user for merge, try to merge\n //automatically\n } else {\n trace! {\"Inserted LocationType: {}, value: {:#?} into main datastore.\",k,v}\n self.location_types.insert(\n k.to_string(),\n Rc::new(RefCell::new(location_type::LocationType {\n id: k.to_string(),\n manufacturer: location_types[k].manufacturer.clone(),\n model: location_types[k].model.clone(),\n part_number: location_types[k].part_number.clone(),\n manufacturer_part_number: location_types[k]\n .manufacturer_part_number\n .clone(),\n supplier: location_types[k].supplier.clone(),\n supplier_part_number: location_types[k].supplier_part_number.clone(),\n description: location_types[k].description.clone(),\n material: location_types[k].material.clone(),\n height: location_types[k].height,\n width: location_types[k].width,\n depth: location_types[k].depth,\n usable_width: location_types[k].usable_width,\n usable_height: location_types[k].usable_height,\n usable_depth: location_types[k].usable_depth,\n })),\n );\n }\n }\n }\n\n // connector_types\n if let Some(connector_types) = datafile.connector_types {\n for (k, v) in &connector_types {\n if self.connector_types.contains_key(k) {\n warn! {concat!{\n \"ConnectorType : {} with contents: \",\n \"{:#?} has already been loaded. Found \",\n \"again in file {}. Check this and merge if necessary\"\n },\n k, v, datafile.file_path.display()}\n //TODO: do something: ignore dupe, prompt user for merge, try to merge\n //automatically\n } else {\n trace! {\"Inserted ConnectorType: {}, value: {:#?} into main datastore.\",k,v}\n self.connector_types.insert(\n k.to_string(),\n Rc::new(RefCell::new(connector_type::ConnectorType {\n id: k.to_string(),\n manufacturer: connector_types[k].manufacturer.clone(),\n model: connector_types[k].model.clone(),\n part_number: connector_types[k].part_number.clone(),\n manufacturer_part_number: connector_types[k]\n .manufacturer_part_number\n .clone(),\n supplier: connector_types[k].supplier.clone(),\n supplier_part_number: connector_types[k].supplier_part_number.clone(),\n description: connector_types[k].description.clone(),\n mount_type: connector_types[k].mount_type.clone(),\n panel_cutout: connector_types[k].panel_cutout.clone(),\n gender: connector_types[k].gender.clone(),\n height: connector_types[k].height,\n width: connector_types[k].width,\n depth: connector_types[k].depth,\n diameter: connector_types[k].diameter,\n pins: {\n let mut new_pins = Vec::new();\n for pin in &connector_types[k].pins {\n let new_pin = connector_type::ConnectorPin {\n id: pin.id.clone(),\n label: pin.label.clone(),\n signal_type: pin.signal_type.clone(),\n color: pin.color.clone(),\n visual_rep: pin.visual_rep.clone().map(Svg::from),\n gender: pin.gender.clone(),\n };\n new_pins.push(new_pin);\n }\n new_pins\n },\n visual_rep: Svg::from(connector_types[k].visual_rep.clone()),\n })),\n );\n }\n }\n }\n // term_cable_types\n if let Some(term_cable_types) = datafile.term_cable_types {\n for (k, v) in &term_cable_types {\n if self.term_cable_types.contains_key(k) {\n warn! {concat!{\n \"TermCableType : {} with contents: \",\n \"{:#?} has already been loaded. \",\n \"Found again in file {}. Check this and merge if necessary\"},\n k, v, datafile.file_path.display()}\n //TODO: do something: ignore dupe, prompt user for merge, try to merge\n //automatically\n } else {\n trace! {\"Inserted TermCableType: {}, value: {:#?} into main datastore.\",k,v}\n self.term_cable_types.insert(k.to_string(),\n Rc::new(RefCell::new(term_cable_type::TermCableType {\n id: k.to_string(),\n manufacturer: term_cable_types[k].manufacturer.clone(),\n model: term_cable_types[k].model.clone(),\n part_number: term_cable_types[k].part_number.clone(),\n manufacturer_part_number: term_cable_types[k].manufacturer_part_number.clone(),\n supplier: term_cable_types[k].supplier.clone(),\n supplier_part_number: term_cable_types[k].supplier_part_number.clone(),\n description: term_cable_types[k].description.clone(),\n wire_cable: {\n\n if term_cable_types[k].wire.is_some() && term_cable_types[k].cable.is_some() {\n panic! {concat!{\n \"Both wire and cable \",\n \"values of TermCableType {} \",\n \"are specified. Please correct this.\"}, k}\n } else if term_cable_types[k].wire.is_none() && term_cable_types[k].cable.is_none() {\n\n panic! {concat!{\n \"Neither wire or cable \",\n \"values of TermCableType {} \",\n \"are specified. Please correct this.\"}, k}\n } else {\n #[allow(clippy::collapsible_else_if)] // This would change the\n // meaning of the logic\n if let Some(wire_type_id) = term_cable_types[k].wire.clone() {\n if self.wire_types.contains_key(&wire_type_id) {\n term_cable_type::WireCable::WireType(self.wire_types[&wire_type_id].clone())\n } else {\n warn!{concat!{\n \"WireType: {} in TermCableType: \",\n \"{} specified in datafile: {} is not \",\n \"found in any library either read from \",\n \"datafiles, or implemented in program \",\n \"logic. Creating empty object for now\"},\n wire_type_id, k, datafile.file_path.display()\n }\n let new_wire_type = Rc::new(RefCell::new(\n wire_type::WireType::new()));\n new_wire_type.borrow_mut().id = wire_type_id.to_string();\n // first insert new_wire_type into library\n self.wire_types.insert(wire_type_id.to_string(),\n new_wire_type.clone());\n // then return reference to insert into struct field\n term_cable_type::WireCable::WireType(new_wire_type.clone())\n }\n\n } else if let Some(cable_type_id) = &term_cable_types[k].cable {\n\n if self.cable_types.contains_key(cable_type_id) {\n term_cable_type::WireCable::CableType(\n self.cable_types[cable_type_id].clone())\n } else {\n warn!{concat!{\n \"WireType: {} in TermCableType: \",\n \"{} specified in datafile: {} is not \",\n \"found in any library either read from \",\n \"datafiles, or implemented in program \",\n \"logic. Creating empty object for now\"},\n cable_type_id, k, datafile.file_path.display()\n }\n let new_cable_type = Rc::new(RefCell::new(\n cable_type::CableType::new()));\n new_cable_type.borrow_mut().id = cable_type_id.to_string();\n // insert new_cable_type into library\n self.cable_types.insert(cable_type_id.to_string(),\n new_cable_type.clone());\n // then return reference to insert into struct field\n term_cable_type::WireCable::CableType(new_cable_type.clone())\n }\n } else {\n //TODO: fix this\n panic! {concat!{\n \"Neither wire or cable \",\n \"values of TermCableType {} \",\n \"are specified. Please correct this.\"}, k}\n }\n }\n },\n nominal_length: term_cable_types[k].nominal_length,\n actual_length: term_cable_types[k].actual_length,\n end1: {\n let mut new_end1 = Vec::new();\n for connector in &term_cable_types[k].end1 {\n let new_connector = term_cable_type::TermCableConnector {\n connector_type: {\n if self.connector_types.contains_key(&connector.connector_type) {\n self.connector_types[&connector.connector_type].clone()\n } else {\n warn! {concat!{\n \"End 1 of TermCableType: {} \",\n \"in datafile: {}, contains \",\n \"ConnectorType: {} that does \",\n \"not exist in any library data, \",\n \"either read from file, or \",\n \"created via program logic. \",\n \"Creating empty object for now.\"},\n k, datafile.file_path.display(),\n &connector.connector_type}\n let new_connector_type = Rc::new(RefCell::new(\n connector_type::ConnectorType::new()));\n // insert new_connector_type into library\n self.connector_types.insert(\n connector.connector_type.to_string(),\n new_connector_type.clone());\n // then return reference to insert into struct\n // field\n new_connector_type.clone()\n\n }\n },\n terminations: {\n if let Some(terminations) = &connector.terminations {\n let mut new_terminations = Vec::new();\n for termination in terminations {\n let new_termination = term_cable_type::TermCableConnectorTermination {\n core: termination.core,\n pin: termination.pin,\n };\n new_terminations.push(new_termination);\n }\n Some(new_terminations)\n } else {None}\n },\n };\n new_end1.push(new_connector);\n }\n new_end1\n },\n end2: {\n let mut new_end2 = Vec::new();\n for connector in &term_cable_types[k].end2 {\n let new_connector = term_cable_type::TermCableConnector {\n connector_type: {\n if self.connector_types.contains_key(&connector.connector_type) {\n self.connector_types[&connector.connector_type].clone()\n } else {\n warn! {concat!{\n \"End 2 of TermCableType: {} \",\n \"in datafile: {}, contains \",\n \"ConnectorType: {} that does \",\n \"not exist in any library data, \",\n \"either read from file, or \",\n \"created via program logic. \",\n \"Creating empty object for now.\"},\n k, datafile.file_path.display(),\n &connector.connector_type}\n let new_connector_type = Rc::new(RefCell::new(\n connector_type::ConnectorType::new()));\n // insert new_connector_type into library\n self.connector_types.insert(\n connector.connector_type.to_string(),\n new_connector_type.clone());\n // then return reference to insert into struct\n // field\n new_connector_type.clone()\n }\n },\n terminations: {\n if let Some(terminations) = &connector.terminations {\n let mut new_terminations = Vec::new();\n for termination in terminations {\n let new_termination = term_cable_type::TermCableConnectorTermination {\n core: termination.core,\n pin: termination.pin,\n };\n new_terminations.push(new_termination);\n }\n Some(new_terminations)\n } else {None}\n },\n };\n new_end2.push(new_connector);\n }\n new_end2\n },\n },\n )));\n }\n }\n }\n\n // equipment_types\n if let Some(equipment_types) = datafile.equipment_types {\n for (k, v) in &equipment_types {\n if self.equipment_types.contains_key(k) {\n warn! {concat!{\"EquipmentType : {} with \",\n \"contents: {:#?} has already been loaded. \",\n \"Found again in file {}. \",\n \"Check this and merge if necessary\"},\n k, v, datafile.file_path.display()}\n //TODO: do something: ignore dupe, prompt user for merge, try to merge\n //automatically\n } else {\n trace! {\"Inserted EquipmentType: {}, value: {:#?} into main datastore.\",k,v}\n self.equipment_types.insert(k.to_string(),\n Rc::new(RefCell::new(equipment_type::EquipmentType {\n id: k.to_string(),\n manufacturer: equipment_types[k].manufacturer.clone(),\n model: equipment_types[k].model.clone(),\n part_number: equipment_types[k].part_number.clone(),\n manufacturer_part_number: equipment_types[k].manufacturer_part_number.clone(),\n supplier: equipment_types[k].supplier.clone(),\n supplier_part_number: equipment_types[k].supplier_part_number.clone(),\n description: equipment_types[k].description.clone(),\n mount_type: equipment_types[k].mount_type.clone(),\n equip_type: equipment_types[k].equip_type.clone(),\n faces: {\n if let Some(faces) = &equipment_types[k].faces {\n let mut new_faces = Vec::new();\n for face in faces {\n let new_face = equipment_type::EquipFace {\n name: face.name.to_string(),\n vis_rep: face.vis_rep.clone().map(Svg::from),\n connectors: {\n if let Some(connectors) = &face.connectors {\n let mut new_connectors = Vec::new();\n for connector in connectors {\n let new_connector = equipment_type::EquipConnector {\n connector_type: {\n if self.connector_types.contains_key(&connector.connector_type) {\n self.connector_types[&connector.connector_type].clone()\n } else {\n warn! {concat!{\n \"ConnectorType: {} in Equipment: {} \",\n \"from datafile: {}, not found \",\n \"in any library data, \",\n \"either read from file, or \",\n \"created via program logic. \",\n \"Creating empty object for now.\"},\n &connector.connector_type,\n k, datafile.file_path.display()\n }\n let new_connector_type = Rc::new(RefCell::new(\n connector_type::ConnectorType::new()));\n // insert new_connector_type into library\n self.connector_types.insert(\n connector.connector_type.to_string(),\n new_connector_type.clone());\n // then return reference to insert into struct\n // field\n new_connector_type.clone()\n }\n },\n direction: connector.direction.clone(),\n x: connector.x,\n y: connector.y,\n };\n new_connectors.push(new_connector);\n }\n Some(new_connectors)\n } else {None}\n },\n };\n new_faces.push(new_face);\n }\n Some(new_faces)\n } else {\n None\n }\n },\n visual_rep: Svg::from(equipment_types[k].visual_rep.clone()),\n },\n )));\n }\n }\n }\n }\n}\n\nimpl Project {\n ///Initializes an empty `Project`\n pub fn new() -> Self {\n Project {\n locations: HashMap::new(),\n equipment: HashMap::new(),\n pathways: HashMap::new(),\n wire_cables: HashMap::new(),\n }\n }\n /// `from_datafiles` converts between the textual representation of datafiles, and the struct\n /// object representation of the internal objects\n pub fn from_datafiles(&mut self, datafiles: Vec, library: &Library) {\n // parse all datafiles\n for datafile in datafiles {\n self.from_datafile(datafile, library)\n }\n for (_, location) in &self.locations {\n //TODO: check for empty objects\n }\n for (_, equipment) in &self.equipment {\n //TODO: check for empty objects\n }\n for (_, pathway) in &self.pathways {\n //TODO: check for empty objects\n }\n for (_, wire_cable) in &self.wire_cables {\n //TODO: check for empty objects\n }\n }\n\n /// `from_datafile` takes a `DataFile` and a `Library` and imports all Project data found\n /// within, into the `Project` struct this method is called on. It will check `Library` for\n /// defined types to assign as references within the various project data imported from\n /// `datafile`\n #[allow(clippy::wrong_self_convention)]\n // this is not a type conversion function so does not\n // need to follow the same rules\n // TODO: maybe rename this to something that doesn't\n // sound like a type conversion function\n fn from_datafile(&mut self, datafile: DataFile, library: &Library) {\n // pathway\n if let Some(pathways) = datafile.pathways {\n for (k, v) in &pathways {\n if self.pathways.contains_key(k) {\n warn! {\"Pathway : {} with contents: {:#?} has already been loaded. Found again in file {}. Check this and merge if necessary\", k, v, datafile.file_path.display()}\n //TODO: do something: ignore dupe, prompt user for merge, try to merge\n //automatically\n } else {\n trace! {\"Inserted Pathway: {}, value: {:#?} into main datastore.\",k,v}\n self.pathways.insert(k.to_string(),\n Rc::new(\n RefCell::new(\n pathway::Pathway {\n id: k.to_string(),\n path_type: {\n if library.pathway_types.contains_key(&pathways[k].path_type) {\n library.pathway_types[&pathways[k].path_type].clone()\n } else {\n //TODO: handle this more intelligently\n panic! {\"Failed to find PathwayType: {} used in Pathway: {} in file {}, in any imported library dictionary or file. Please check spelling, or add it, if this was not intentional.\", pathways[k].path_type, &k, datafile.file_path.display() }\n }\n },\n identifier: pathways[k].identifier.clone(),\n description: pathways[k].description.clone(),\n length: pathways[k].length,\n\n }\n\n )\n )\n );\n }\n }\n }\n // wire_cables\n if let Some(wire_cables) = datafile.wire_cables {\n for (k, v) in &wire_cables {\n if self.wire_cables.contains_key(k) {\n warn! {concat!{\n \"WireCable: {} with contents: \",\n \"{:#?} has already been loaded. \",\n \"Found again in file {}. \",\n \"Check this and merge if necessary\"},\n k, v, datafile.file_path.display()}\n //TODO: do something: ignore dupe, prompt user for merge, try to merge\n //automatically\n } else {\n trace! {\"Inserted WireCable: {}, value: {:#?} into main project.\",k,v}\n self.wire_cables.insert(\n k.to_string(),\n Rc::new(RefCell::new(wire_cable::WireCable {\n id: k.to_string(),\n ctw_type: {\n // Checking to make sure only one of wire, cable, or term_cable are set\n if (wire_cables[k].wire.is_some()\n && wire_cables[k].cable.is_some()\n && wire_cables[k].term_cable.is_some())\n || (wire_cables[k].wire.is_some()\n && wire_cables[k].cable.is_some())\n || (wire_cables[k].cable.is_some()\n && wire_cables[k].term_cable.is_some())\n || (wire_cables[k].wire.is_some()\n && wire_cables[k].term_cable.is_some())\n {\n panic! {concat!{\n \"More than one of wire, \",\n \"cable and term_cable of \",\n \"WireCable {} are specified. \",\n \"Please correct this.\"}, &k}\n } else if wire_cables[k].wire.is_none()\n && wire_cables[k].cable.is_none()\n && wire_cables[k].term_cable.is_none()\n {\n panic! {concat!{\"Neither wire, cable \",\n \"or term_cable values of WireCable {} \",\n \"are specified. Please correct this.\"}, &k}\n } else {\n // at this point, only one of wire, cable and term_cable should\n // be set.\n //\n // clone string here to avoid moving value out of hashmap.\n if let Some(wire_type) = wire_cables[k].wire.clone() {\n if library.wire_types.contains_key(&wire_type) {\n wire_cable::WireCableType::WireType(\n library.wire_types[&wire_type].clone(),\n )\n } else {\n // since this is project, not library, we want to error\n // for types not found in library, since they should\n // all have been parsed before parsing project.\n panic! {concat!{\n \"WireType: {} in \",\n \"WireCable: {} specified in \",\n \"datafile: {} is not found in \",\n \"any library either read from \",\n \"datafiles, or implemented in program \",\n \"logic. Check your spelling\"},\n wire_type, k, datafile.file_path.display()}\n }\n // clone string here to avoid moving value out of hashmap.\n } else if let Some(cable_type) = wire_cables[k].cable.clone() {\n if library.cable_types.contains_key(&cable_type) {\n wire_cable::WireCableType::CableType(\n library.cable_types[&cable_type].clone(),\n )\n } else {\n // since this is project, not library, we want to error\n // for types not found in library, since they should\n // all have been parsed before parsing project.\n panic! {concat!{\n \"CableType: {} in \",\n \"WireCable: {} specified in \",\n \"datafile: {} is not found in \",\n \"any library either read from \",\n \"datafiles, or implemented in program \",\n \"logic. Check your spelling\"},\n cable_type, k, datafile.file_path.display()}\n }\n // clone string here to avoid moving value out of hashmap.\n } else if let Some(term_cable_type) =\n wire_cables[k].term_cable.clone()\n {\n if library.term_cable_types.contains_key(&term_cable_type) {\n wire_cable::WireCableType::TermCableType(\n library.term_cable_types[&term_cable_type].clone(),\n )\n } else {\n // since this is project, not library, we want to error\n // for types not found in library, since they should\n // all have been parsed before parsing project.\n panic! {concat!{\n \"TermCableType: {} in \",\n \"WireCable: {} specified in \",\n \"datafile: {} is not found in \",\n \"any library either read from \",\n \"datafiles, or implemented in program \",\n \"logic. Check your spelling\"},\n term_cable_type, k, datafile.file_path.display()}\n }\n } else {\n //TODO: fix this\n panic! {concat!{\n \"Neither wire, cable \",\n \"or termcable type values \",\n \"of WireCable {} are specified. \",\n \"Please correct this.\"}, &k}\n }\n }\n },\n identifier: wire_cables[k].identifier.clone(),\n description: wire_cables[k].description.clone(),\n length: wire_cables[k].length,\n pathway: {\n // clone string here to avoid moving value out of hashmap.\n if let Some(pathway) = wire_cables[k].pathway.clone() {\n if self.pathways.contains_key(k) {\n Some(self.pathways[k].clone())\n } else {\n error! {concat!{\n \"WireCable: {} is assigned to \",\n \"Pathway: {} in datafile: {}, \",\n \"that doesn't exist in any \",\n \"library either read in from \",\n \"datafile, or added via program \",\n \"logic. Not assigning pathway to \",\n \"WireCable {}. Please check your spelling \"},\n k, pathway, datafile.file_path.display(), k}\n let new_pathway =\n Rc::new(RefCell::new(pathway::Pathway::new()));\n // insert new_pathway into Project\n self.pathways.insert(pathway, new_pathway.clone());\n // then return reference for struct field\n Some(new_pathway)\n }\n } else {\n None\n }\n },\n })),\n );\n }\n }\n }\n // locations\n if let Some(locations) = datafile.locations {\n for (k, v) in &locations {\n if self.locations.contains_key(k) {\n warn! {concat!{\"Location: {} with \",\n \"contents: {:#?} has already been \",\n \"loaded. Found again in file {}. \",\n \"Check this and merge if necessary\"},\n k, v, datafile.file_path.display()}\n //TODO: do something: ignore dupe, prompt user for merge, try to merge\n //automatically\n } else {\n trace! {\"Inserted Location: {}, value: {:#?} into main project.\",k,v}\n self.locations.insert(\n k.to_string(),\n Rc::new(RefCell::new(location::Location {\n id: k.to_string(),\n location_type: {\n if library\n .location_types\n .contains_key(&locations[k].location_type)\n {\n library.location_types[&locations[k].location_type].clone()\n } else {\n // since this is project, not library, we want to error\n // for types not found in library, since they should\n // all have been parsed before parsing project.\n panic! {concat!{\n \"Failed to find \",\n \"LocationType: {} used in \",\n \"Location: {} in file {}, \",\n \"in any imported library dictionary \",\n \"or file. Please check spelling, or \",\n \"add it, if this was not intentional.\"},\n locations[k].location_type, &k,\n datafile.file_path.display() }\n }\n },\n identifier: locations[k].identifier.clone(),\n description: locations[k].description.clone(),\n physical_location: locations[k].physical_location.clone(),\n })),\n );\n }\n }\n }\n\n // equipment\n if let Some(equipment) = datafile.equipment {\n for (k, v) in &equipment {\n if self.equipment.contains_key(k) {\n warn! {\"Equipment: {} with contents: {:#?} has already been loaded. Found again in file {}. Check this and merge if necessary\", k, v, datafile.file_path.display()}\n //TODO: do something: ignore dupe, prompt user for merge, try to merge\n //automatically\n } else {\n trace! {\"Inserted Equipment: {}, value: {:#?} into main project.\",k,v}\n self.equipment.insert(\n k.to_string(),\n Rc::new(RefCell::new(equipment::Equipment {\n id: k.to_string(),\n equip_type: {\n if library\n .equipment_types\n .contains_key(&equipment[k].equipment_type)\n {\n library.equipment_types[&equipment[k].equipment_type].clone()\n } else {\n // since this is project, not library, we want to error\n // for types not found in library, since they should\n // all have been parsed before parsing project.\n panic! {concat!{\n \"Failed to find \",\n \"EquipmentType: {} used \",\n \"in Equipment: {} in \",\n \"file {}, in any imported \",\n \"library dictionary or \",\n \"file. Please check spelling, \",\n \"or add it, if this was not intentional.\"},\n equipment[k].equipment_type, &k,\n datafile.file_path.display() }\n }\n },\n identifier: equipment[k].identifier.clone(),\n mounting_type: equipment[k].mounting_type.clone(),\n location: {\n // clone string here to avoid moving value out of hashmap.\n if let Some(file_location) = equipment[k].location.clone() {\n #[allow(clippy::map_entry)]\n // TODO: use entry mechanic to fix this, allowing for now\n if self.locations.contains_key(&file_location) {\n Some(self.locations[k].clone())\n } else {\n error! {concat!{\n \"Location: {} is assigned to \",\n \"Equipment: {} in datafile: {}, \",\n \"that doesn't exist in any library \",\n \"either read in from datafile, or \",\n \"added via program logic. Check your spelling\"},\n k, file_location, datafile.file_path.display()}\n let new_location =\n Rc::new(RefCell::new(location::Location::new()));\n // add new_location to Project\n self.locations.insert(file_location, new_location.clone());\n // then return reference to struct field\n Some(new_location.clone())\n }\n } else {\n None\n }\n },\n description: equipment[k].description.clone(),\n })),\n );\n }\n }\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n use std::collections::HashMap;\n\n #[test]\n fn new_library() {\n assert_eq!(\n Library::new(),\n Library {\n wire_types: HashMap::new(),\n cable_types: HashMap::new(),\n term_cable_types: HashMap::new(),\n location_types: HashMap::new(),\n connector_types: HashMap::new(),\n equipment_types: HashMap::new(),\n pathway_types: HashMap::new(),\n }\n )\n }\n\n #[test]\n fn new_project() {\n assert_eq!(\n Project::new(),\n Project {\n locations: HashMap::new(),\n equipment: HashMap::new(),\n pathways: HashMap::new(),\n wire_cables: HashMap::new(),\n }\n )\n }\n\n // TODO: testing ideas (for both project and library):\n // - test import of datafile containing each individual object\n // - test import of basic datafile, minimal amount of data necessary\n // - test import of full datafile, with multiple defined dictionary entries for each dictionary\n // - test failure of multiple of the top level dicts defined in one file\n // - test to make sure only one of wire, cable, termcable is set in project parsing, both\n // positive and negative\n // - test importing a cable/termcable type with a missing wiretype (also for equipment, etc)\n // - test complicated term_cable\n // - test all project datatypes with both present and absent library values\n // - test all panics\n // - test library types that refer to each other, make sure objects are always parsed in\n // correct order\n // - same with project types, except with both library and project assets\n #[test]\n fn read_datafile_library() {}\n\n #[test]\n fn read_datafile_project() {}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134637,"cells":{"blob_id":{"kind":"string","value":"348ee467114341334ab05f9b2f2b83429e4b15cf"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"ikfr/orz"},"path":{"kind":"string","value":"/src/byteslice.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1067,"string":"1,067"},"score":{"kind":"number","value":2.9375,"string":"2.9375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"pub trait ByteSliceExt {\n unsafe fn read(&self, offset: usize) -> T;\n unsafe fn write(&mut self, offset: usize, value: T);\n unsafe fn read_forward(&self, offset: &mut usize) -> T;\n unsafe fn write_forward(&mut self, offset: &mut usize, value: T);\n}\n\nimpl ByteSliceExt for [u8] {\n unsafe fn read(&self, offset: usize) -> T {\n return std::ptr::read_unaligned(self.as_ptr().add(offset) as *const T);\n }\n\n unsafe fn write(&mut self, offset: usize, value: T) {\n std::ptr::write_unaligned(self.as_mut_ptr().add(offset) as *mut T, value);\n }\n\n unsafe fn read_forward(&self, offset: &mut usize) -> T {\n let t = std::ptr::read_unaligned(self.as_ptr().add(*offset) as *const T);\n std::ptr::write(offset, *offset + std::mem::size_of::());\n return t;\n }\n\n unsafe fn write_forward(&mut self, offset: &mut usize, value: T) {\n std::ptr::write_unaligned(self.as_mut_ptr().add(*offset) as *mut T, value);\n std::ptr::write(offset, *offset + std::mem::size_of::());\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134638,"cells":{"blob_id":{"kind":"string","value":"7a8fde05b2c5ea29a8d5af5dad7e31ba787e3a75"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"fanyangxi/erno-cube-solver-repo"},"path":{"kind":"string","value":"/erno-cube-solver/src/models/cube.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2312,"string":"2,312"},"score":{"kind":"number","value":3.578125,"string":"3.578125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use crate::models::face::Face;\nuse std::fmt;\n\npub struct Cube {\n pub front: Face, // Front\n pub back: Face, // Back\n pub left: Face, // Left\n pub right: Face, // Right\n pub up: Face, // Up\n pub down: Face, // Down\n}\n\nimpl Cube {\n pub fn new(faces: [Face; 6]) -> Self {\n Cube {\n front: faces[0],\n back: faces[1],\n left: faces[2],\n right: faces[3],\n up: faces[4],\n down: faces[5],\n }\n }\n}\n\nimpl fmt::Display for Cube {\n fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {\n write!(fmt, \"Cube: {} {} {} {} {} {}\",\n self.front, self.back,\n self.left, self.right,\n self.up, self.down)\n }\n}\n\n#[cfg(test)]\nmod cross_tests {\n use crate::models::cube::Cube;\n use crate::models::colors::Color;\n use crate::models::face::Face;\n\n #[test]\n fn it_works() {\n\n let face1 = Face::new([\n [Color::Red,Color::Red,Color::Red],\n [Color::Red,Color::Red,Color::Red],\n [Color::Red,Color::Red,Color::Red],\n ]);\n let face2 = Face::new([\n [Color::Green,Color::Green,Color::Green],\n [Color::Green,Color::Green,Color::Green],\n [Color::Green,Color::Green,Color::Green],\n ]);\n let face3 = Face::new([\n [Color::Yellow,Color::Yellow,Color::Yellow],\n [Color::Yellow,Color::Yellow,Color::Yellow],\n [Color::Yellow,Color::Yellow,Color::Yellow],\n ]);\n let face4 = Face::new([\n [Color::Blue,Color::Blue,Color::Blue],\n [Color::Blue,Color::Blue,Color::Blue],\n [Color::Blue,Color::Blue,Color::Blue],\n ]);\n let face5 = Face::new([\n [Color::Orange,Color::Orange,Color::Orange],\n [Color::Orange,Color::Orange,Color::Orange],\n [Color::Orange,Color::Orange,Color::Orange],\n ]);\n let face6 = Face::new([\n [Color::White,Color::White,Color::White],\n [Color::White,Color::White,Color::White],\n [Color::White,Color::White,Color::White],\n ]);\n\n let _cube = Cube::new([face1, face2, face3, face4, face5, face6]);\n println!(\"Cube fmt: [{}].\", _cube);\n // assert_eq!(\"x\", _cube);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134639,"cells":{"blob_id":{"kind":"string","value":"195b5e4e0121d3581534f20c2d2be49a506d6d1b"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Pwootage/os.rv"},"path":{"kind":"string","value":"/kernel/src/peripherals/memory_size.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":397,"string":"397"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use volatile_register::RO;\n\npub struct MemorySize {\n p: &'static mut MemorySizeRegisters\n}\n\n#[repr(C)]\nstruct MemorySizeRegisters {\n pub size: RO\n}\n\nimpl MemorySize {\n pub fn new() -> MemorySize {\n MemorySize {\n p: unsafe { &mut *(0x7FFF_0000 as *mut MemorySizeRegisters) }\n }\n }\n\n pub fn max_size(&self) -> usize {\n self.p.size.read()\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134640,"cells":{"blob_id":{"kind":"string","value":"145b2fc10cd99ff1bd5b1f3132e847fd22dcc1f9"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"bartosz-lipinski/solana-program-library"},"path":{"kind":"string","value":"/examples/rust/cross-program-invocation/src/processor.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1614,"string":"1,614"},"score":{"kind":"number","value":2.75,"string":"2.75"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"//! Program instruction processor\n\nuse solana_program::{\n account_info::{next_account_info, AccountInfo},\n entrypoint::ProgramResult,\n program::invoke_signed,\n program_error::ProgramError,\n pubkey::Pubkey,\n system_instruction,\n};\n\n/// Amount of bytes of account data to allocate\npub const SIZE: usize = 42;\n\n/// Instruction processor\npub fn process_instruction(\n program_id: &Pubkey,\n accounts: &[AccountInfo],\n instruction_data: &[u8],\n) -> ProgramResult {\n // Create in iterator to safety reference accounts in the slice\n let account_info_iter = &mut accounts.iter();\n\n // Account info for the program being invoked\n let system_program_info = next_account_info(account_info_iter)?;\n // Account info to allocate\n let allocated_info = next_account_info(account_info_iter)?;\n\n let expected_allocated_key =\n Pubkey::create_program_address(&[b\"You pass butter\", &[instruction_data[0]]], program_id)?;\n if *allocated_info.key != expected_allocated_key {\n // allocated key does not match the derived address\n return Err(ProgramError::InvalidArgument);\n }\n\n // Invoke the system program to allocate account data\n invoke_signed(\n &system_instruction::allocate(allocated_info.key, SIZE as u64),\n // Order doesn't matter and this slice could include all the accounts and be:\n // `&accounts`\n &[\n system_program_info.clone(), // program being invoked also needs to be included\n allocated_info.clone(),\n ],\n &[&[b\"You pass butter\", &[instruction_data[0]]]],\n )?;\n\n Ok(())\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134641,"cells":{"blob_id":{"kind":"string","value":"a31bca6802210b96d355eef962e016ea4b36de3e"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"kosslab-kr/rust"},"path":{"kind":"string","value":"/src/test/compile-fail/issue-28992-empty.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":805,"string":"805"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","Apache-2.0","NCSA","ISC","LicenseRef-scancode-public-domain","BSD-3-Clause","BSD-2-Clause","Unlicense","LicenseRef-scancode-other-permissive"],"string":"[\n \"MIT\",\n \"Apache-2.0\",\n \"NCSA\",\n \"ISC\",\n \"LicenseRef-scancode-public-domain\",\n \"BSD-3-Clause\",\n \"BSD-2-Clause\",\n \"Unlicense\",\n \"LicenseRef-scancode-other-permissive\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"// Copyright 2015 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 or the MIT license\n// , at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// Can't use constants as tuple struct patterns\n\n#![feature(associated_consts)]\n\nconst C1: i32 = 0;\n\nstruct S;\n\nimpl S {\n const C2: i32 = 0;\n}\n\nfn main() {\n if let C1(..) = 0 {} //~ ERROR expected variant or struct, found constant `C1`\n if let S::C2(..) = 0 {} //~ ERROR `S::C2` does not name a tuple variant or a tuple struct\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134642,"cells":{"blob_id":{"kind":"string","value":"c586445d10cb77226604b521c5e748fadf87ff0a"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"alexkursell/subotai"},"path":{"kind":"string","value":"/src/node/tests.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":9577,"string":"9,577"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use {node, routing, time, hash, storage};\nuse std::collections::VecDeque;\nuse std::str::FromStr;\nuse std::thread;\nuse std::time::Duration as StdDuration;\nuse std::net;\nuse node::receptions;\n\npub const POLL_FREQUENCY_MS: u64 = 50;\npub const TRIES: u8 = 5;\n\n#[test]\nfn node_ping() {\n let alpha = node::Node::new().unwrap();\n let beta = node::Node::new().unwrap();\n let beta_seed = beta.resources.local_info().address;\n\n // Bootstrapping alpha:\n assert!(alpha.bootstrap(&beta_seed).is_ok());\n \n match alpha.state() {\n node::State::OffGrid => (), \n _ => panic!(\"Should be off grid with this few nodes\"),\n }\n\n // Alpha pings beta.\n assert!(alpha.resources.ping(&beta.local_info().address).is_ok());\n}\n\n#[test]\nfn reception_iterator_times_out_correctly() {\n let alpha = node::Node::new().unwrap(); \n let span = time::Duration::seconds(1);\n let maximum = time::Duration::seconds(3);\n let receptions = alpha.receptions().during(span);\n\n let before = time::SteadyTime::now(); \n\n // nothing is happening, so this should time out in around a second (not necessarily precise)\n assert_eq!(0, receptions.count());\n\n let after = time::SteadyTime::now();\n\n assert!(after - before < maximum);\n}\n\n#[test]\nfn bootstrapping_and_finding_on_simulated_network() {\n let mut nodes = simulated_network(30);\n\n // Head finds tail in a few steps.\n let head = nodes.pop_front().unwrap();\n let tail = nodes.pop_back().unwrap();\n\n assert_eq!(head.resources.locate(tail.id()).unwrap().id, tail.resources.local_info().id);\n}\n\n#[test]\nfn finding_on_simulated_unresponsive_network() {\n\n let mut nodes = simulated_network(35);\n nodes.drain(10..20);\n assert_eq!(nodes.len(), 25);\n \n // Head finds tail in a few steps.\n let head = nodes.pop_front().unwrap();\n let tail = nodes.pop_back().unwrap();\n\n assert_eq!(head.resources.locate(tail.id()).unwrap().id, tail.resources.local_info().id);\n}\n\n#[test]\nfn finding_a_nonexisting_node_in_a_simulated_network_times_out() {\n\n let mut nodes = simulated_network(30);\n \n // Head finds tail in a few steps.\n let head = nodes.pop_front().unwrap();\n\n let random_hash = hash::SubotaiHash::random();\n assert!(head.resources.locate(&random_hash).is_err());\n}\n\nfn simulated_network(network_size: usize) -> VecDeque {\n let cfg: node::Configuration = Default::default();\n assert!(network_size > cfg.k_factor, \"You can't build a network with so few nodes!\");\n\n let nodes: VecDeque = (0..network_size).map(|_| { node::Node::new().unwrap() }).collect();\n {\n let origin = nodes.front().unwrap();\n for node in nodes.iter().skip(1) {\n node.bootstrap(&origin.resources.local_info().address).unwrap();\n }\n for node in nodes.iter() {\n node.wait_for_state(node::State::OnGrid);\n }\n }\n nodes\n}\n\n#[test]\nfn updating_table_with_full_bucket_starts_the_conflict_resolution_mechanism()\n{\n let node = node::Node::new().unwrap();\n let cfg = &node.resources.configuration;\n\n node.resources.table.fill_bucket(8, cfg.k_factor as u8); // Bucket completely full\n\n let mut id = node.id().clone();\n id.flip_bit(8);\n id.raw[0] = 0xFF;\n let info = node_info_no_net(id);\n\n node.resources.update_table(info);\n assert_eq!(node.resources.conflicts.lock().unwrap().len(), 1);\n}\n\n#[test]\nfn generating_a_conflict_causes_a_ping_to_the_evicted_node()\n{\n let alpha = node::Node::new().unwrap();\n let beta = node::Node::new().unwrap();\n let cfg = &alpha.resources.configuration;\n alpha.resources.update_table(beta.resources.local_info());\n \n let index = alpha.resources.table.bucket_for_node(beta.id());\n\n // We fill the bucket corresponding to Beta until we are ready to cause a conflict.\n alpha.resources.table.fill_bucket(index, (cfg.k_factor -1) as u8);\n\n // We expect a ping to beta\n let pings = beta.receptions()\n .of_kind(receptions::KindFilter::Ping)\n .during(time::Duration::seconds(2));\n\n // Adding a new node causes a conflict.\n let mut id = beta.id().clone();\n id.raw[0] = 0xFF;\n let info = node_info_no_net(id);\n alpha.resources.update_table(info);\n \n assert_eq!(pings.count(), 1);\n}\n\n#[test]\nfn generating_too_many_conflicts_causes_the_node_to_enter_defensive_state()\n{\n let node = node::Node::new().unwrap();\n let cfg = &node.resources.configuration;\n\n for index in 0..(cfg.k_factor + cfg.max_conflicts) {\n let mut id = node.id().clone();\n id.flip_bit(140); // Arbitrary bucket\n id.raw[0] = index as u8;\n let info = node_info_no_net(id);\n node.resources.update_table(info);\n }\n\n let state = node.state();\n match state {\n node::State::Defensive => (),\n _ => panic!(),\n }\n\n // Trying to add new conflictive nodes while in defensive state will fail.\n let mut id = node.id().clone();\n id.flip_bit(140); // Arbitrary bucket\n id.raw[0] = 0xFF;\n let info = node_info_no_net(id.clone());\n\n node.resources.update_table(info);\n assert!(node.resources.table.specific_node(&id).is_none());\n\n // However, if they would fall in a different bucket, it's ok.\n id.flip_bit(155);\n let info = node_info_no_net(id.clone());\n node.resources.update_table(info);\n assert!(node.resources.table.specific_node(&id).is_some());\n}\n\n#[test]\nfn node_probing_in_simulated_network()\n{\n let cfg: node::Configuration = Default::default();\n let mut nodes = simulated_network(40);\n // We manually collect the info tags of all nodes.\n let mut info_nodes: Vec = nodes\n .iter()\n .map(|ref node| node.resources.local_info())\n .collect();\n\n let head = nodes.pop_front().unwrap();\n let tail = nodes.pop_back().unwrap();\n let probe_results = head.resources.probe(tail.id(), cfg.k_factor).unwrap();\n\n // We sort our manual collection by distance to the tail node.\n info_nodes.sort_by(|ref info_a, ref info_b| (&info_a.id ^ tail.id()).cmp(&(&info_b.id ^ tail.id())));\n info_nodes.truncate(cfg.k_factor); // This guarantees us the closest ids to the tail\n \n assert_eq!(info_nodes.len(), probe_results.len());\n\n for (a, b) in probe_results.iter().zip(info_nodes.iter()) {\n assert_eq!(a.id, b.id);\n }\n}\n\n#[test]\nfn node_probing_in_simulated_unresponsive_network()\n{\n let cfg: node::Configuration = Default::default();\n let mut nodes = simulated_network(40);\n // We manually collect the info tags of all nodes.\n let mut info_nodes: Vec = nodes\n .iter()\n .map(|ref node| node.resources.local_info())\n .collect();\n\n nodes.drain(10..20);\n let head = nodes.pop_front().unwrap();\n let tail = nodes.pop_back().unwrap();\n let probe_results = head.resources.probe(tail.id(), cfg.k_factor).unwrap();\n\n // We sort our manual collection by distance to the tail node.\n info_nodes.sort_by(|ref info_a, ref info_b| (&info_a.id ^ tail.id()).cmp(&(&info_b.id ^ tail.id())));\n info_nodes.truncate(cfg.k_factor); // This guarantees us the closest ids to the tail\n \n assert_eq!(info_nodes.len(), probe_results.len());\n for (a, b) in probe_results.iter().zip(info_nodes.iter()) {\n assert_eq!(a.id, b.id);\n }\n}\n\n#[test]\nfn bucket_pruning_removes_dead_nodes() {\n let mut nodes = simulated_network(40);\n let head = nodes.pop_front().unwrap();\n\n // let's find a bucket with nodes\n let index = (0..160).rev().find(|i| head.resources.table.nodes_from_bucket(*i).len() > 0).unwrap();\n let initial_nodes = head.resources.table.nodes_from_bucket(index).len();\n head.resources.prune_bucket(index).unwrap();\n assert_eq!(initial_nodes, head.resources.table.nodes_from_bucket(index).len());\n\n // Now when we kill the nodes, the pruning will work.\n nodes.clear();\n head.resources.prune_bucket(index).unwrap();\n\n assert_eq!(0, head.resources.table.nodes_from_bucket(index).len());\n}\n\n#[test]\nfn store_retrieve_in_simulated_network()\n{\n let mut nodes = simulated_network(40);\n let key = hash::SubotaiHash::random();\n let entry = storage::StorageEntry::Value(hash::SubotaiHash::random());\n let head = nodes.pop_front().unwrap();\n let tail = nodes.pop_back().unwrap();\n\n head.store(key.clone(), entry.clone()).unwrap();\n let retrieved_entries = tail.retrieve(&key).unwrap();\n assert_eq!(entry, retrieved_entries[0]);\n\n let key = hash::SubotaiHash::random();\n let blob: Vec = vec![0x00, 0x01, 0x02];\n let entry = storage::StorageEntry::Blob(blob.clone());\n\n head.store(key.clone(), entry.clone()).unwrap();\n let retrieved_entries = tail.retrieve(&key).unwrap();\n assert_eq!(entry, retrieved_entries[0]);\n\n // Now for mass storage\n let arbitrary_expiration = time::now() + time::Duration::minutes(30);\n let collection: Vec<_> = (0..10)\n .map(|_| (storage::StorageEntry::Value(hash::SubotaiHash::random()), arbitrary_expiration)).collect();\n let collection_key = hash::SubotaiHash::random();\n head.resources.mass_store(collection_key.clone(), collection.clone()).unwrap();\n\n // We must sleep here to prevent asking a node for the entries as it's halfway through storing them.\n thread::sleep(StdDuration::new(5,0));\n let retrieved_collection = tail.retrieve(&collection_key).unwrap();\n let collection_entries: Vec<_> = collection.into_iter().map(|(entry, _)| entry).collect();\n assert_eq!(collection_entries.len(), retrieved_collection.len());\n assert_eq!(collection_entries, retrieved_collection);\n}\n\nfn node_info_no_net(id : hash::SubotaiHash) -> routing::NodeInfo {\n routing::NodeInfo {\n id : id,\n address : net::SocketAddr::from_str(\"0.0.0.0:0\").unwrap(),\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134643,"cells":{"blob_id":{"kind":"string","value":"6f9542160fe3c64cd416089ed666f60f02f2d33e"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"xcaptain/rust-algorithms"},"path":{"kind":"string","value":"/algorithms/src/misc/shortest_seq.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1103,"string":"1,103"},"score":{"kind":"number","value":3.6875,"string":"3.6875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::cmp::min;\n\n/// 使用尺取法,计算最短连续子数组长度大于某个值\npub fn shortest_seq(arr: Vec, target: usize) -> (usize, usize, usize) {\n let mut sum = 0;\n let mut start = 0;\n let mut end = 0;\n let len = arr.len();\n let mut ans = len + 1;\n\n loop {\n while sum < target && end < len {\n sum += arr[end];\n end += 1;\n }\n if sum < target {\n break;\n }\n ans = min(ans, end - start);\n sum -= arr[start];\n start += 1;\n }\n if ans > len {\n return (0, 0, 0);\n }\n (ans, start - 1, end - 1)\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_1() {\n assert_eq!((3, 2, 4), shortest_seq(vec![1, 2, 3, 5, 6], 12));\n }\n\n #[test]\n fn test_2() {\n assert_eq!((2, 3, 4), shortest_seq(vec![1, 2, 3, 5, 6], 11));\n }\n\n #[test]\n fn test_3() {\n assert_eq!((2, 3, 4), shortest_seq(vec![1, 2, 3, 5, 6], 10));\n }\n\n #[test]\n fn test_4() {\n assert_eq!((0, 0, 0), shortest_seq(vec![1, 2, 3, 5, 6], 20));\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134644,"cells":{"blob_id":{"kind":"string","value":"56f40e3007637c45febed4717ecee7fab4fe78af"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"vinc/geodate"},"path":{"kind":"string","value":"/src/moon_phase.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":11351,"string":"11,351"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use math::*;\nuse julian::*;\nuse delta_time::*;\n\nuse core::ops::Rem;\n#[cfg(not(feature = \"std\"))]\nuse num_traits::Float;\n\n#[repr(usize)]\n#[derive(Clone, Copy)]\nenum MoonPhase {\n NewMoon,\n FirstQuarterMoon,\n FullMoon,\n LastQuarterMoon\n}\n\n// From \"Astronomical Algorithms\"\n// By Jean Meeus\nfn get_time_of(phase: MoonPhase, lunation_number: f64) -> i64 {\n /*\n // TODO: use `lunation_number: i64`\n let k = match phase {\n MoonPhase::NewMoon => (lunation_number as f64) + 0.00;\n MoonPhase::FirstQuarterMoon => (lunation_number as f64) + 0.25;\n MoonPhase::FullMoon => (lunation_number as f64) + 0.50;\n MoonPhase::LastQuarterMoon => (lunation_number as f64) + 0.75;\n };\n */\n\n let k = lunation_number;\n let t = k / 1236.85;\n\n let e = 1.0 - 0.002_516 * t - 0.000_007_4 * t.powi(2);\n\n // Sun's mean anomaly at time JDE\n let s = 2.5534\n + 29.105_356_7 * k\n - 0.000_001_4 * t.powi(2)\n - 0.000_000_11 * t.powi(3);\n\n // Moon's mean anomaly\n let m = 201.5643\n + 385.816_935_28 * k\n + 0.010_758_2 * t.powi(2)\n + 0.000_012_38 * t.powi(3)\n - 0.000_000_058 * t.powi(4);\n\n // Moon's argument of latitude\n let f = 160.7108\n + 390.670_502_84 * k\n - 0.001_611_8 * t.powi(2)\n - 0.000_002_27 * t.powi(3)\n + 0.000_000_011 * t.powi(4);\n\n // Longitude of the ascending node of the lunar orbit\n let o = 124.7746\n - 1.563_755_88 * k\n + 0.002_0672 * t.powi(2)\n + 0.000_002_15 * t.powi(3);\n\n let e = (e.rem(360.0) + 360.0).rem(360.0);\n let s = (s.rem(360.0) + 360.0).rem(360.0);\n let m = (m.rem(360.0) + 360.0).rem(360.0);\n let f = (f.rem(360.0) + 360.0).rem(360.0);\n let o = (o.rem(360.0) + 360.0).rem(360.0);\n\n let jde = 2_451_550.097_660\n + 29.530_588_861 * k\n + 0.000_154_370 * t.powi(2)\n - 0.000_000_150 * t.powi(3)\n + 0.000_000_000_730 * t.powi(4);\n\n // Correction to be added to JDE\n\n // [New Moon, First Quarter, Full Moon, Last Quarter]\n let num_cors = vec![\n [-0.40720, -0.62801, -0.40614, -0.62801],\n [ 0.17241, 0.17172, 0.17302, 0.17172],\n [ 0.01608, -0.01183, 0.01614, -0.01183],\n [ 0.01039, 0.00862, 0.01043, 0.00862],\n [ 0.00739, 0.00804, 0.00734, 0.00804],\n [-0.00514, 0.00454, -0.00515, 0.00454],\n [ 0.00208, 0.00204, 0.00209, 0.00204],\n [-0.00111, -0.00180, -0.00111, -0.00180],\n [-0.00057, -0.00070, -0.00057, -0.00070],\n [ 0.00056, -0.00040, 0.00056, -0.00040],\n [-0.00042, -0.00034, -0.00042, -0.00034],\n [ 0.00042, 0.00032, 0.00042, 0.00032],\n [ 0.00038, 0.00032, 0.00038, 0.00032],\n [-0.00024, -0.00028, -0.00024, -0.00028],\n [-0.00017, 0.00027, -0.00017, 0.00027],\n [-0.00007, -0.00017, -0.00007, -0.00017],\n [ 0.00004, -0.00005, 0.00004, -0.00005],\n [ 0.00004, 0.00004, 0.00004, 0.00004],\n [ 0.00003, -0.00004, 0.00003, -0.00004],\n [ 0.00003, 0.00004, 0.00003, 0.00004],\n [-0.00003, 0.00003, -0.00003, 0.00003],\n [ 0.00003, 0.00003, 0.00003, 0.00003],\n [-0.00002, 0.00002, -0.00002, 0.00002],\n [-0.00002, 0.00002, -0.00002, 0.00002],\n [ 0.00002, -0.00002, 0.00002, -0.00002]\n ];\n\n // Multiply each previous terms by E to a given power\n // [new moon, first quarter, full moon, last quarter]\n let pow_cors = vec![\n [0, 0, 0, 0],\n [1, 1, 1, 1],\n [0, 1, 0, 1],\n [0, 0, 0, 0],\n [1, 0, 1, 0],\n [1, 1, 1, 1],\n [2, 2, 2, 2],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [1, 0, 1, 0],\n [0, 1, 0, 1],\n [1, 1, 1, 1],\n [1, 1, 1, 1],\n [1, 2, 1, 2],\n [0, 1, 0, 1],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]\n ];\n\n // Sum the following terms multiplied a number of times\n // given in the next table, and multiply the sinus of the\n // result by the previously obtained number.\n let terms = [s, m, f, o];\n\n // [new and full moon, first and last quarter]\n let mul_cors = vec![\n [[ 0.0, 1.0, 0.0, 0.0], [ 0.0, 1.0, 0.0, 0.0]],\n [[ 1.0, 0.0, 0.0, 0.0], [ 1.0, 0.0, 0.0, 0.0]],\n [[ 0.0, 2.0, 0.0, 0.0], [ 1.0, 1.0, 0.0, 0.0]],\n [[ 0.0, 0.0, 2.0, 0.0], [ 0.0, 2.0, 0.0, 0.0]],\n [[-1.0, 1.0, 0.0, 0.0], [ 0.0, 0.0, 2.0, 0.0]],\n [[ 1.0, 1.0, 0.0, 0.0], [-1.0, 1.0, 0.0, 0.0]],\n [[ 2.0, 0.0, 0.0, 0.0], [ 2.0, 0.0, 0.0, 0.0]],\n [[ 0.0, 1.0, -2.0, 0.0], [ 0.0, 1.0, -2.0, 0.0]],\n [[ 0.0, 1.0, 2.0, 0.0], [ 0.0, 1.0, 2.0, 0.0]],\n [[ 1.0, 2.0, 0.0, 0.0], [ 0.0, 3.0, 0.0, 0.0]],\n [[ 0.0, 3.0, 0.0, 0.0], [-1.0, 2.0, 0.0, 0.0]],\n [[ 1.0, 0.0, 2.0, 0.0], [ 1.0, 0.0, 2.0, 0.0]],\n [[ 1.0, 0.0, -2.0, 0.0], [ 1.0, 0.0, -2.0, 0.0]],\n [[-1.0, 2.0, 0.0, 0.0], [ 2.0, 1.0, 0.0, 0.0]],\n [[ 0.0, 0.0, 0.0, 1.0], [ 1.0, 2.0, 0.0, 0.0]],\n [[ 2.0, 1.0, 0.0, 0.0], [ 0.0, 0.0, 0.0, 1.0]],\n [[ 0.0, 2.0, -2.0, 0.0], [-1.0, 1.0, -2.0, 0.0]],\n [[ 3.0, 0.0, 0.0, 0.0], [ 0.0, 2.0, 2.0, 0.0]],\n [[ 1.0, 1.0, -2.0, 0.0], [ 1.0, 1.0, 2.0, 0.0]],\n [[ 0.0, 2.0, 2.0, 0.0], [-2.0, 1.0, 0.0, 0.0]],\n [[ 1.0, 1.0, 2.0, 0.0], [ 1.0, 1.0, -2.0, 0.0]],\n [[-1.0, 1.0, 2.0, 0.0], [ 3.0, 0.0, 0.0, 0.0]],\n [[-1.0, 1.0, -2.0, 0.0], [ 0.0, 2.0, -2.0, 0.0]],\n [[ 1.0, 3.0, 0.0, 0.0], [-1.0, 1.0, 2.0, 0.0]],\n [[ 0.0, 4.0, 0.0, 0.0], [ 1.0, 3.0, 0.0, 0.0]]\n ];\n\n let j = phase as usize;\n let cor = (0..25).fold(0.0, |acc, i| {\n let sin_cor = (0..4).fold(0.0, |sa, si| {\n sa + mul_cors[i][j % 2][si] * terms[si]\n });\n\n acc + num_cors[i][j] * e.powi(pow_cors[i][j]) * sin_deg(sin_cor)\n });\n\n // Additional corrections for quarters\n let w = 0.00306\n - 0.00038 * e * cos_deg(s)\n + 0.00026 * cos_deg(m)\n - 0.00002 * cos_deg(m - s)\n + 0.00002 * cos_deg(m + s)\n + 0.00002 * cos_deg(2.0 * f);\n\n let cor = match phase {\n MoonPhase::FirstQuarterMoon => cor + w,\n MoonPhase::LastQuarterMoon => cor - w,\n _ => cor\n };\n\n // Additional corrections for all phases\n let add = 0.0\n + 0.000_325 * sin_deg(299.77 + 0.107_408 * k - 0.009_173 * t.powi(2))\n + 0.000_165 * sin_deg(251.88 + 0.016_321 * k)\n + 0.000_164 * sin_deg(251.83 + 26.651_886 * k)\n + 0.000_126 * sin_deg(349.42 + 36.412_478 * k)\n + 0.000_110 * sin_deg( 84.66 + 18.206_239 * k)\n + 0.000_062 * sin_deg(141.74 + 53.303_771 * k)\n + 0.000_060 * sin_deg(207.14 + 2.453_732 * k)\n + 0.000_056 * sin_deg(154.84 + 7.306_860 * k)\n + 0.000_047 * sin_deg( 34.52 + 27.261_239 * k)\n + 0.000_042 * sin_deg(207.19 + 0.121_824 * k)\n + 0.000_040 * sin_deg(291.34 + 1.844_379 * k)\n + 0.000_037 * sin_deg(161.72 + 24.198_154 * k)\n + 0.000_035 * sin_deg(239.56 + 25.513_099 * k)\n + 0.000_023 * sin_deg(331.55 + 3.592_518 * k);\n\n let jde = jde + cor + add;\n\n terrestrial_to_universal_time(julian_to_unix(jde))\n}\n\npub fn get_new_moon(lunation_number: f64) -> i64 {\n get_time_of(MoonPhase::NewMoon, lunation_number)\n}\n\npub fn get_first_quarter_moon(lunation_number: f64) -> i64 {\n get_time_of(MoonPhase::FirstQuarterMoon, lunation_number)\n}\n\npub fn get_full_moon(lunation_number: f64) -> i64 {\n get_time_of(MoonPhase::FullMoon, lunation_number)\n}\n\npub fn get_last_quarter_moon(lunation_number: f64) -> i64 {\n get_time_of(MoonPhase::LastQuarterMoon, lunation_number)\n}\n\n/*\n// TODO: get_lunation_number(timestamp: i64, numbering: LunationNumbering)\n// TODO: get_meeus_lunation_number(timestamp: i64)\nenum LunationNumbering {\n Islamic,\n Thai,\n Brown,\n Meeus\n}\n*/\n\n/// Computes the Lunation Number since the first new moon of 2000\npub fn get_lunation_number(timestamp: i64) -> f64 {\n ((unix_to_year(timestamp) - 2000.0) * 12.3685).floor() // TODO: `as i64`\n}\n\npub fn get_next_new_moon(timestamp: i64) -> i64 {\n let new_moon = get_new_moon(get_lunation_number(timestamp));\n if new_moon > timestamp {\n new_moon\n } else {\n get_new_moon(get_lunation_number(timestamp) + 1.0)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use utils::*;\n\n #[test]\n fn get_lunation_number_test() {\n // Example 49.a from \"Astronomical Algoritms\"\n // New Moon: 1977-02-18 03:37:42 TD\n let t = terrestrial_to_universal_time(parse_time(\"1977-02-18T03:37:42.00+00:00\"));\n assert_eq!(-283.0, get_lunation_number(t));\n\n // Later in the day\n let t = parse_time(\"1977-02-18T12:00:00.00+00:00\");\n assert_eq!(-283.0, get_lunation_number(t));\n\n // Later in the month\n let t = parse_time(\"1977-02-28T12:00:00.00+00:00\");\n assert_eq!(-283.0, get_lunation_number(t));\n\n // Earlier in the day\n let t = parse_time(\"1977-02-18T01:00:00.00+00:00\");\n assert_eq!(-283.0, get_lunation_number(t));\n\n // A few days before\n let t = parse_time(\"1977-02-14T12:00:00.00+00:00\");\n assert_eq!(-283.0, get_lunation_number(t)); // FIXME: should be -284\n\n // A week before\n let t = parse_time(\"1977-02-11T12:00:00.00+00:00\");\n assert_eq!(-284.0, get_lunation_number(t));\n\n // Meeus Lunation 0\n let t = parse_time(\"2000-01-06T18:14:00.00+00:00\");\n assert_eq!(0.0, get_lunation_number(t));\n\n // Brown Lunation 1\n let t = parse_time(\"1923-01-17T02:41:00.00+00:00\");\n assert_eq!(-952.0, get_lunation_number(t));\n\n // Islamic Lunation 1\n let t = parse_time(\"0622-07-16T00:00:00.00+00:00\");\n assert_eq!(-17037.0, get_lunation_number(t));\n\n // Thai Lunation 0\n let t = parse_time(\"0638-03-22T00:00:00.00+00:00\");\n assert_eq!(-16843.0, get_lunation_number(t)); // FIXME: should be -16842\n }\n\n #[test]\n fn get_new_moon_test() {\n // Example 49.a from \"Astronomical Algoritms\"\n // New Moon: 1977-02-18 03:37:42 TD\n let lunation_number = -283.0;\n let t = terrestrial_to_universal_time(parse_time(\"1977-02-18T03:37:42.00+00:00\"));\n assert_eq!(t, get_new_moon(lunation_number));\n\n // First new moon of 1970\n let t = parse_time(\"1970-01-07T20:35:27.00+00:00\");\n assert_eq!(t, get_new_moon(get_lunation_number(0) + 1.0));\n }\n\n #[test]\n fn get_last_quarter_moon_test() {\n // Example 49.b from \"Astronomical Algoritms\"\n // Last Quarter Moon: 2044-01-21 23:48:17 TD\n let lunation_number = 544.75;\n let t = terrestrial_to_universal_time(parse_time(\"2044-01-21T23:48:17+00:00\"));\n assert_eq!(t, get_last_quarter_moon(lunation_number));\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134645,"cells":{"blob_id":{"kind":"string","value":"cf3a09868e3f3cb30f6234511e4fb445993b4aef"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"asciiu/blackjack"},"path":{"kind":"string","value":"/src/blackjack.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4947,"string":"4,947"},"score":{"kind":"number","value":3.515625,"string":"3.515625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"pub mod shoe;\n\nuse shoe::Shoe;\nuse shoe::Card;\nuse std::io;\n\nenum PlayerInput {\n Double,\n Hit,\n Stand,\n Split,\n Unknown,\n}\n\nstruct Player {\n cards: Vec\n}\n\nimpl Player {\n fn new() -> Player {\n Player{ cards: Vec::new() }\n }\n\n fn score(&mut self) -> i32 {\n let mut total = 0;\n\n for c in &self.cards {\n let v = match c.text() {\n 'K' | 'Q' | 'J' | 'T' => 10,\n 'A' => 0,\n _ => c.text().to_string().parse::().unwrap()\n };\n total += v;\n }\n\n // add up all aces\n for c in &self.cards {\n if c.text() == 'A' {\n total += 11;\n \n if total > 31 {\n total -= 20;\n } else if total > 21 {\n total -= 10;\n }\n }\n }\n\n total \n }\n\n fn print_hand(&mut self, label: &str) {\n print!(\"{}: \", label);\n for c in self.cards.iter() {\n print!(\"{} \", c);\n }\n print!(\"[{}]\\n\", self.score());\n }\n}\n\nfn read_input(can_double: bool) -> PlayerInput {\n if can_double {\n println!(\"\\n(h)it (s)tand (d)ouble: \");\n } else {\n println!(\"\\n(h)it (s)tand: \");\n }\n\n let mut input = String::new();\n\n io::stdin()\n .read_line(&mut input)\n .expect(\"Failed to read line\");\n println!(\"\");\n\n // trim trailing new line\n input = String::from(input.trim());\n\n match (can_double, input.trim()) {\n (true, \"d\") => PlayerInput::Double,\n (_, \"h\") => PlayerInput::Hit,\n (_, \"s\") => PlayerInput::Stand,\n (_, \"p\") => PlayerInput::Split,\n _ => PlayerInput::Unknown,\n }\n}\n\npub struct Blackjack {\n shoe: Shoe,\n player: Player,\n dealer: Player,\n}\n\nimpl Blackjack {\n pub fn new() -> Blackjack {\n Blackjack{\n shoe: Shoe::new(), \n player: Player::new(),\n dealer: Player::new()\n }\n }\n\n fn deal_card(&mut self) -> Card {\n match self.shoe.pop_card() {\n Some(card) => card,\n None => {\n self.shoe = Shoe::new();\n self.shoe.pop_card().unwrap()\n }\n }\n }\n\n pub fn play_round(&mut self, balance: i32, mut wager: i32) -> i32 {\n let dealer_card: Card = self.deal_card(); \n self.dealer.cards.push(dealer_card);\n\n while self.player.cards.len() < 2 {\n let card: Card = self.deal_card(); \n self.player.cards.push(card);\n }\n\n let mut player_score = self.player.score();\n let mut dealer_score = self.dealer.score();\n let mut stand = false;\n\n self.player.print_hand(\"Player\");\n self.dealer.print_hand(\"Dealer\");\n\n while player_score < 21 && !stand {\n let can_double = self.player.cards.len() == 2 && (balance - wager) >= wager;\n let input = read_input(can_double);\n\n match input {\n PlayerInput::Double => {\n wager += wager;\n let player_card: Card = self.deal_card(); \n self.player.cards.push(player_card);\n\n self.player.print_hand(\"Player\");\n self.dealer.print_hand(\"Dealer\");\n\n player_score = self.player.score();\n stand = true;\n }\n PlayerInput::Hit => {\n let player_card: Card = self.deal_card(); \n self.player.cards.push(player_card);\n\n self.player.print_hand(\"Player\");\n self.dealer.print_hand(\"Dealer\");\n\n player_score = self.player.score();\n }\n PlayerInput::Stand => {\n stand = true;\n self.player.print_hand(\"Player\");\n }\n _ => ()\n }\n }\n\n while dealer_score < 17 {\n let dealer_card: Card = self.deal_card(); \n self.dealer.cards.push(dealer_card);\n dealer_score = self.dealer.score();\n }\n \n self.dealer.print_hand(\"Dealer\");\n self.player.cards.clear();\n self.dealer.cards.clear();\n\n if player_score > dealer_score && player_score <= 21 {\n println!(\"Player (win!)\\n\");\n wager\n } else if player_score < dealer_score && dealer_score <= 21 {\n println!(\"Player (lose)\\n\");\n -wager\n } else if player_score > 21 && dealer_score <= 21 {\n println!(\"Player (lose)\\n\");\n -wager\n } else if dealer_score > 21 && player_score <= 21 {\n println!(\"Player (win!)\\n\");\n wager\n } else if dealer_score == player_score {\n println!(\"push\\n\");\n 0 \n } else {\n println!(\"push\\n\");\n 0 \n }\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134646,"cells":{"blob_id":{"kind":"string","value":"34a07abc0a1488168980127397c1166b00e82c15"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"MingweiSamuel/Riven"},"path":{"kind":"string","value":"/riven/src/consts/team.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":669,"string":"669"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use num_enum::{IntoPrimitive, TryFromPrimitive};\nuse serde_repr::{Deserialize_repr, Serialize_repr};\n\n/// League of Legends team.\n#[derive(\n Debug,\n Copy,\n Clone,\n Eq,\n PartialEq,\n Hash,\n Ord,\n PartialOrd,\n Serialize_repr,\n Deserialize_repr,\n IntoPrimitive,\n TryFromPrimitive,\n)]\n#[repr(u16)]\npub enum Team {\n /// Team ID zero for 2v2v2v2 Arena `CHERRY` game mode. (TODO: SUBJECT TO CHANGE?)\n ZERO = 0,\n\n /// Blue team (bottom left on Summoner's Rift).\n BLUE = 100,\n /// Red team (top right on Summoner's Rift).\n RED = 200,\n\n /// \"killerTeamId\" when Baron Nashor spawns and kills Rift Herald.\n OTHER = 300,\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134647,"cells":{"blob_id":{"kind":"string","value":"573d1089fa944ab3954efe3278b6139c58f71755"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"kyleburton/sandbox"},"path":{"kind":"string","value":"/examples/rust/bin-with-lib/src/utils.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":182,"string":"182"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use time;\n\npub fn say_hello() {\n println!(\"Hello, world at {}!\", time::now().asctime());\n}\n\npub fn say_goodbye() {\n println!(\"Goodbye, world at {}!\", time::now().asctime());\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134648,"cells":{"blob_id":{"kind":"string","value":"fc6c866276dbb0e0440feecb43f4d6f20969ed4e"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"ItiharaYuuko/file_crypto_base64"},"path":{"kind":"string","value":"/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8338,"string":"8,338"},"score":{"kind":"number","value":3,"string":"3"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use base64::{decode, encode};\nuse std::convert::AsRef;\nuse std::env;\nuse std::fs;\nuse std::fs::File;\nuse std::io::prelude::*;\nuse std::path::Path;\n\ntrait SplitAt {\n fn get_split_at(self, sep: &str, index: usize) -> String;\n}\n\nimpl SplitAt for String {\n fn get_split_at(self, sep: &str, index: usize) -> String {\n format!(\"{}\", self.split(sep).collect::>()[index])\n }\n}\n\nimpl SplitAt for &str {\n fn get_split_at(self, sep: &str, index: usize) -> String {\n format!(\"{}\", self.split(sep).collect::>()[index])\n }\n}\n\nfn entry_self_check(ent: &fs::DirEntry) -> bool {\n let flg_pa: bool;\n let app_self: Vec = env::args().collect();\n if ent\n .path()\n .file_name()\n .unwrap()\n .to_str()\n .unwrap()\n .contains(&app_self[0])\n {\n flg_pa = true;\n } else {\n flg_pa = false;\n }\n flg_pa\n}\n\nfn entry_contians(ent: &fs::DirEntry, context: &str) -> bool {\n let flg_pa: bool;\n if ent\n .path()\n .file_name()\n .unwrap()\n .to_str()\n .unwrap()\n .contains(context)\n {\n flg_pa = true;\n } else {\n flg_pa = false;\n }\n flg_pa\n}\n\nfn entry_to_str(ent: &fs::DirEntry) -> String {\n let ent_str = String::from(ent.path().file_name().unwrap().to_str().unwrap());\n ent_str\n}\n\nfn chunk_encode>(input: T) -> String {\n encode(&input)\n}\n\nfn chunk_decode>(input: T) -> Vec {\n decode(&input).unwrap()\n}\n\nfn genfile_data(f_name: &str) -> Vec {\n let insert_file = File::open(f_name).unwrap();\n let mut copyx = insert_file.try_clone().unwrap();\n let mut vexc: Vec = Vec::new();\n copyx.read_to_end(&mut vexc).unwrap();\n vexc\n}\n\nfn creat_crypto_file(f_name: &str) {\n let data_vec = genfile_data(&f_name);\n let crypto_context = chunk_encode(&data_vec);\n let out_file_name = file_name_reorganization(f_name, \"Cryptod\");\n fs::write(out_file_name.as_str(), &crypto_context).unwrap();\n}\n\nfn creat_decrypto_file(f_name: &str) {\n let data_vec = genfile_data(f_name);\n let crypto_context = chunk_decode(&data_vec);\n let out_file_name = file_name_reorganization(f_name, \"Deryptod\");\n fs::write(out_file_name.as_str(), &crypto_context).unwrap();\n}\n\nfn file_name_reorganization(f_name: &str, bet_flg: &str) -> String {\n let tmp_str: String;\n if f_name.contains(\"Cryptod\") {\n tmp_str = format!(\"{}\", f_name.get_split_at(\"%^%\", 1));\n } else {\n tmp_str = format!(\"{}%^%{}\", bet_flg, f_name);\n }\n tmp_str\n}\n\nfn file_name_crypto(f_name: &String) -> String {\n let cry_name = chunk_encode(f_name);\n fs::rename(f_name, &cry_name).unwrap();\n cry_name\n}\n\nfn file_name_decrypto(f_name: &String) -> String {\n let dec_name = String::from_utf8(chunk_decode(f_name)).unwrap();\n fs::rename(f_name, &dec_name).unwrap();\n dec_name\n}\n\nfn purge_mata_file(purge_flag: bool) {\n let ctr_pat = Path::new(\".\");\n for entry in ctr_pat.read_dir().unwrap() {\n if let Ok(entry) = entry {\n let mata_flag: bool;\n if purge_flag {\n mata_flag = !entry_contians(&entry, \"%^%\");\n } else {\n mata_flag = entry_contians(&entry, \"%^%\");\n }\n if mata_flag && !entry_self_check(&entry) {\n fs::remove_file(entry_to_str(&entry)).unwrap();\n println!(\n \"[-]{} was removed.\",\n entry_to_str(&entry)\n );\n }\n }\n }\n}\n\nfn major_progress() {\n let pleaseholder_information = \"\n Wrong console argument after application.\\n\n Please choise:\\n\n user$ file_crypto_base64 -c [file names separated by blank] #Crypto selected files.\\n\n user$ file_crypto_base64 -d [file names separated by blank] #Decrypto selected files.\\n\n user$ file_crypto_base64 -lc #Crypto current folders all files.\\n\n user$ file_crypto_base64 -ld #Decrypto current folders all files.\\n\n user$ file_crypto_base64 -pm #Remove all meta files.\\n\n user$ file_crypto_base64 -pc #Remove all cryptod files.\\n\n user$ file_crypto_base64 -cn #Crypto current folders all files name.\\n\n user$ file_crypto_base64 -dn #Decrypto current folders all files name.\\n\n Note: square brackets was files list it doesnt contain thire self.\\n\";\n\n let arg_flg_loc: usize = 1;\n let mut file_index: u32 = 1;\n let mut list_file_count: u32 = 1;\n let operation_flg = env::args().collect::>();\n if operation_flg.len() > 1 {\n let current_path = Path::new(\".\");\n if operation_flg[arg_flg_loc].as_str() == \"-c\" {\n for file_name in &operation_flg[2..] {\n creat_crypto_file(&file_name);\n println!(\n \"[+]{} files cryptod, current file is {}\",\n file_index, file_name\n );\n file_index += 1\n }\n } else if operation_flg[arg_flg_loc].as_str() == \"-d\" {\n for file_name in &operation_flg[2..] {\n creat_decrypto_file(&file_name);\n println!(\n \"[+]{} files decryptod, current file is {}\",\n file_index, file_name\n );\n file_index += 1;\n }\n } else if operation_flg[arg_flg_loc].as_str() == \"-lc\" {\n for entry in current_path.read_dir().unwrap() {\n if let Ok(entry) = entry {\n if !entry_self_check(&entry) && !entry_contians(&entry, \"%^%\") {\n let out_name = file_name_reorganization(\n entry_to_str(&entry).as_str(),\n \"Cryptod\",\n );\n creat_crypto_file(entry_to_str(&entry).as_str());\n println!(\n \"[+]{} files cryptod, current file is {}\",\n &list_file_count, &out_name\n );\n }\n }\n list_file_count += 1;\n }\n } else if operation_flg[arg_flg_loc].as_str() == \"-ld\" {\n for entry in current_path.read_dir().unwrap() {\n if let Ok(entry) = entry {\n if !entry_self_check(&entry) {\n let out_name = file_name_reorganization(\n entry_to_str(&entry).as_str(),\n \"Deryptod\",\n );\n creat_decrypto_file(entry_to_str(&entry).as_str());\n println!(\n \"[+]{} files decryptod, current file is {}\",\n &list_file_count, &out_name\n );\n }\n }\n list_file_count += 1;\n }\n } else if operation_flg[arg_flg_loc].as_str() == \"-cn\" {\n for entry in current_path.read_dir().unwrap() {\n if let Ok(entry) = entry {\n if !entry_self_check(&entry) {\n let cryptoed_name = file_name_crypto(&entry_to_str(&entry));\n println!(\n \"[#]{} crytpod to {}\",\n &entry_to_str(&entry), &cryptoed_name\n );\n }\n }\n }\n } else if operation_flg[arg_flg_loc].as_str() == \"-dn\" {\n for entry in current_path.read_dir().unwrap() {\n if let Ok(entry) = entry {\n if !entry_self_check(&entry) {\n let mata_name = file_name_decrypto(&entry_to_str(&entry));\n println!(\n \"[#]{} decryptod to {}\",\n &entry_to_str(&entry), &mata_name\n );\n }\n }\n }\n } else if operation_flg[1].as_str() == \"-pm\" {\n purge_mata_file(true);\n } else if operation_flg[1].as_str() == \"-pc\" {\n purge_mata_file(false);\n } else {\n panic!(\"{}\", &pleaseholder_information);\n }\n } else {\n panic!(\"{}\", &pleaseholder_information);\n }\n}\n\nfn main() {\n major_progress();\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134649,"cells":{"blob_id":{"kind":"string","value":"8cb8b4a314a1865481975599133155b90ad56301"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"lpil/decksterity"},"path":{"kind":"string","value":"/src/engine/dsp_node/player_node.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2002,"string":"2,002"},"score":{"kind":"number","value":2.84375,"string":"2.84375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::mem;\nuse super::super::{dsp, media};\nuse dsp::{Frame, Node};\nuse super::super::super::engine;\n\n#[derive(Debug)]\npub struct PlayerNode {\n is_playing: bool,\n offset: f64,\n pitch: f64,\n buffer: Vec,\n}\n\nimpl PlayerNode {\n pub fn new() -> Self {\n Self {\n is_playing: false,\n offset: 0.0,\n pitch: 1.0,\n buffer: vec![],\n }\n }\n\n pub fn toggle_play_pause(&mut self) -> bool {\n let Self {\n ref mut is_playing, ..\n } = *self;\n let new_value = !*is_playing;\n *is_playing = new_value;\n new_value\n }\n\n pub fn adjust_pitch(&mut self, delta: f64) -> f64 {\n let Self { ref mut pitch, .. } = *self;\n let new_pitch = *pitch + delta;\n *pitch = new_pitch;\n new_pitch\n }\n\n pub fn set_media(&mut self, media: media::Media) {\n let Self {\n ref mut offset,\n ref mut buffer,\n ..\n } = *self;\n mem::replace(buffer, media);\n *offset = 0.0;\n }\n\n // pub fn set_pitch(&mut self, new_pitch: f64) -> f64 {\n // let Self { ref mut pitch, .. } = *self;\n // *pitch = new_pitch;\n // new_pitch\n // }\n}\n\nimpl Node for PlayerNode {\n fn audio_requested(&mut self, out_buffer: &mut [engine::Frame], _sample_hz: f64) {\n if !self.is_playing {\n return; // When not playing the Player does nothing.\n }\n\n let Self {\n ref mut offset,\n pitch,\n ref buffer,\n ..\n } = *self;\n\n dsp::slice::map_in_place(out_buffer, |_| {\n let frame = buffer.get(*offset as usize).unwrap_or_else(|| {\n *offset = 0.0;\n &buffer[0]\n });\n\n // Why is the input audio SUPER loud?\n let quiet_frame = frame.map(|s| s * 0.00003);\n *offset += pitch;\n quiet_frame\n })\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134650,"cells":{"blob_id":{"kind":"string","value":"5d0e5f4ae3cf4e90e8b4758de7c501b0488276e4"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"benruijl/reform"},"path":{"kind":"string","value":"/src/poly/exponent.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":629,"string":"629"},"score":{"kind":"number","value":3.015625,"string":"3.015625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use std::ops::Sub;\nuse num_traits::{CheckedAdd, One, Zero};\nuse num_traits::cast::{FromPrimitive, AsPrimitive};\nuse std::hash::Hash;\nuse std::fmt::{Debug, Display};\n\n/// Trait for exponents in polynomials.\npub trait Exponent\n : Hash\n + Zero\n + Debug\n + Display\n + One\n + FromPrimitive\n + AsPrimitive\n + CheckedAdd\n + Sub\n + Ord\n + Clone {\n}\n\nimpl<\n T: Hash\n + Zero\n + Debug\n + Display\n + One\n + FromPrimitive\n + AsPrimitive\n + CheckedAdd\n + Sub\n + Ord\n + Clone,\n> Exponent for T\n{\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134651,"cells":{"blob_id":{"kind":"string","value":"3f10da46a3a36431b077292807da93bc8fd3243e"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"LDA111222/GraphScope"},"path":{"kind":"string","value":"/interactive_engine/src/executor/Pegasus/src/common/mod.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":13194,"string":"13,194"},"score":{"kind":"number","value":3.046875,"string":"3.046875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause","LicenseRef-scancode-generic-cla","BSL-1.0","Apache-2.0","LicenseRef-scancode-public-domain","BSD-2-Clause","MIT","LicenseRef-scancode-unknown-license-reference","LicenseRef-scancode-elastic-license-2018","LicenseRef-scancode-other-permissive"],"string":"[\n \"BSD-3-Clause\",\n \"LicenseRef-scancode-generic-cla\",\n \"BSL-1.0\",\n \"Apache-2.0\",\n \"LicenseRef-scancode-public-domain\",\n \"BSD-2-Clause\",\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\",\n \"LicenseRef-scancode-elastic-license-2018\",\n \"LicenseRef-scancode-other-permissive\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"//\n//! Copyright 2020 Alibaba Group Holding Limited.\n//! \n//! Licensed under the Apache License, Version 2.0 (the \"License\");\n//! you may not use this file except in compliance with the License.\n//! You may obtain a copy of the License at\n//! \n//! http://www.apache.org/licenses/LICENSE-2.0\n//! \n//! Unless required by applicable law or agreed to in writing, software\n//! distributed under the License is distributed on an \"AS IS\" BASIS,\n//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//! See the License for the specific language governing permissions and\n//! limitations under the License.\n\nuse std::iter::Iterator;\nuse std::fmt;\nuse std::sync::Arc;\nuse std::any::Any;\nuse std::ops::{Deref, DerefMut};\nuse std::cell::RefCell;\nuse std::io;\n\npub trait Paging: Send {\n type Item;\n\n fn next_page(&mut self) -> Option>;\n}\n\nimpl> + Send> Paging for T {\n type Item = D;\n\n fn next_page(&mut self) -> Option> {\n self.next()\n }\n}\n\n#[derive(Debug, Default)]\npub struct OnePage {\n inner: Option>\n}\n\nimpl OnePage {\n #[inline]\n pub fn take(&mut self) -> Option> {\n self.inner.take()\n }\n}\n\nimpl ::std::convert::From> for OnePage {\n #[inline]\n fn from(src: Vec) -> Self {\n OnePage {\n inner: Some(src)\n }\n }\n}\n\nimpl Paging for OnePage {\n type Item = D;\n\n #[inline]\n fn next_page(&mut self) -> Option> {\n self.take()\n }\n}\n\n/// Modify the origin vector, retain the elements whose `preicate` is true,\n/// return a new vector consist of elements whose `preicate` is false;\n/// This function is O(n);\n/// # Note:\n/// This function will change the order of elements in the origin vec;\n/// # Examples\n/// ```\n/// use pegasus::common::retain;\n/// // create a new numeric list;\n/// let mut origin = (0..64).collect::>();\n/// // remove elements which is less than 32;\n/// let removed = retain(&mut origin, |item| *item > 31);\n///\n/// assert_eq!(32, origin.len());\n/// assert_eq!(32, removed.len());\n/// assert!(origin.iter().all(|item| *item > 31));\n/// assert!(removed.iter().all(|item| *item <= 31));\n/// ```\n#[inline]\npub fn retain bool>(origin: &mut Vec, predicate: F) -> Vec {\n let mut target = Vec::new();\n let mut index = origin.len();\n while index > 0 {\n if !predicate(&origin[index - 1]) {\n let item = if index == origin.len() {\n origin.remove(index - 1)\n } else {\n origin.swap_remove(index - 1)\n };\n target.push(item);\n }\n index -= 1;\n }\n target\n}\n\n#[derive(Copy, Clone, Hash, Eq, PartialEq)]\npub struct Port {\n pub index: usize,\n pub port: usize,\n}\n\nimpl Port {\n #[inline(always)]\n pub fn first(index: usize) -> Self {\n Port {index, port: 0}\n }\n\n #[inline(always)]\n pub fn second(index: usize) -> Self {\n Port {index, port: 1}\n }\n\n #[inline(always)]\n pub fn new(index: usize, port: usize) -> Self {\n Port {index, port}\n }\n}\n\nimpl fmt::Debug for Port {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"({}.{})\", self.index, self.port)\n }\n}\n\n#[derive(Copy,Clone)]\nstruct Slice(pub *mut u8, pub usize);\n\nimpl Slice {\n pub fn as_slice(&self) -> &[u8] {\n unsafe {\n ::std::slice::from_raw_parts(self.0, self.1)\n }\n }\n\n pub fn as_mut_slice(&mut self) -> &mut [u8] {\n unsafe {\n ::std::slice::from_raw_parts_mut(self.0, self.1)\n }\n }\n}\n\npub struct Bytes {\n slice: Slice,\n backend: Arc>\n}\n\nimpl Bytes {\n pub fn from(bytes: B) -> Self where B: DerefMut + 'static {\n let mut boxed = Box::new(bytes) as Box;\n\n let ptr = boxed.downcast_mut::().unwrap().as_mut_ptr();\n let len = boxed.downcast_ref::().unwrap().len();\n let backend = Arc::new(boxed);\n let slice = Slice(ptr, len);\n Bytes {\n slice,\n backend\n }\n }\n\n pub fn extract_to(&mut self, index: usize) -> Bytes {\n assert!(index <= self.slice.1);\n\n let result = Bytes {\n slice: Slice(self.slice.0, index),\n backend: self.backend.clone(),\n };\n\n unsafe { self.slice.0 = self.slice.0.offset(index as isize); }\n self.slice.1 -= index;\n\n result\n }\n\n pub fn try_recover(self) -> Result where B: DerefMut+'static {\n match Arc::try_unwrap(self.backend) {\n Ok(bytes) => Ok(*bytes.downcast::().unwrap()),\n Err(arc) => Err(Bytes {\n slice: self.slice,\n backend: arc,\n }),\n }\n }\n\n pub fn try_regenerate(&mut self) -> bool where B: DerefMut+'static {\n if let Some(boxed) = Arc::get_mut(&mut self.backend) {\n let downcast = boxed.downcast_mut::().expect(\"Downcast failed\");\n self.slice = Slice(downcast.as_mut_ptr(), downcast.len());\n true\n }\n else {\n false\n }\n }\n}\n\nimpl Deref for Bytes {\n type Target = [u8];\n fn deref(&self) -> &[u8] {\n self.slice.as_slice()\n }\n}\n\nimpl DerefMut for Bytes {\n fn deref_mut(&mut self) -> &mut [u8] {\n self.slice.as_mut_slice()\n }\n}\n\nimpl AsRef<[u8]> for Bytes {\n #[inline]\n fn as_ref(&self) -> &[u8] {\n self.slice.as_slice()\n }\n}\n\n/// It is carefully managed to make sure that no overlap of byte range between threads;\nunsafe impl Send for Bytes { }\n\n/// All Bytes are only be transformed between threads through mpmc channel, no sync;\n// unsafe impl Sync for Bytes { }\n\n/// A large binary allocation for writing and sharing.\n///\n/// A bytes slab wraps a `Bytes` and maintains a valid (written) length, and supports writing after\n/// this valid length, and extracting `Bytes` up to this valid length. Extracted bytes are enqueued\n/// and checked for uniqueness in order to recycle them (once all shared references are dropped).\npub struct BytesSlab {\n buffer: Bytes, // current working buffer.\n in_progress: Vec>, // buffers shared with workers.\n stash: Vec, // reclaimed and resuable buffers.\n shift: usize, // current buffer allocation size.\n valid: usize, // buffer[..valid] are valid bytes.\n}\n\nimpl BytesSlab {\n /// Allocates a new `BytesSlab` with an initial size determined by a shift.\n pub fn new(shift: usize) -> Self {\n BytesSlab {\n buffer: Bytes::from(vec![0u8; 1 << shift].into_boxed_slice()),\n in_progress: Vec::new(),\n stash: Vec::new(),\n shift,\n valid: 0,\n }\n }\n /// The empty region of the slab.\n #[inline]\n pub fn empty(&mut self) -> &mut [u8] {\n &mut self.buffer[self.valid..]\n }\n /// The valid region of the slab.\n #[inline]\n pub fn valid(&mut self) -> &mut [u8] {\n &mut self.buffer[..self.valid]\n }\n\n #[inline]\n pub fn valid_len(&self) -> usize {\n self.valid\n }\n\n /// Marks the next `bytes` bytes as valid.\n pub fn make_valid(&mut self, bytes: usize) {\n self.valid += bytes;\n }\n /// Extracts the first `bytes` valid bytes.\n pub fn extract(&mut self, bytes: usize) -> Bytes {\n debug_assert!(bytes <= self.valid);\n self.valid -= bytes;\n self.buffer.extract_to(bytes)\n }\n\n pub fn extract_valid(&mut self) -> Option {\n if self.valid > 0 {\n Some(self.extract(self.valid))\n } else {\n None\n }\n }\n\n /// Ensures that `self.empty().len()` is at least `capacity`.\n ///\n /// This method may retire the current buffer if it does not have enough space, in which case\n /// it will copy any remaining contents into a new buffer. If this would not create enough free\n /// space, the shift is increased until it is sufficient.\n pub fn ensure_capacity(&mut self, capacity: usize) {\n\n if self.empty().len() < capacity {\n\n let mut increased_shift = false;\n\n // Increase allocation if copy would be insufficient.\n while self.valid + capacity > (1 << self.shift) {\n self.shift += 1;\n self.stash.clear(); // clear wrongly sized buffers.\n self.in_progress.clear(); // clear wrongly sized buffers.\n increased_shift = true;\n }\n\n // Attempt to reclaim shared slices.\n if self.stash.is_empty() {\n for shared in self.in_progress.iter_mut() {\n if let Some(mut bytes) = shared.take() {\n if bytes.try_regenerate::>() {\n // NOTE: Test should be redundant, but better safe...\n if bytes.len() == (1 << self.shift) {\n self.stash.push(bytes);\n }\n }\n else {\n *shared = Some(bytes);\n }\n }\n }\n self.in_progress.retain(|x| x.is_some());\n }\n\n let new_buffer = self.stash.pop().unwrap_or_else(|| Bytes::from(vec![0; 1 << self.shift].into_boxed_slice()));\n let old_buffer = ::std::mem::replace(&mut self.buffer, new_buffer);\n\n self.buffer[.. self.valid].copy_from_slice(&old_buffer[.. self.valid]);\n if !increased_shift {\n self.in_progress.push(Some(old_buffer));\n }\n }\n }\n}\n\n\nmacro_rules! write_number {\n ($ty:ty, $n:expr, $slab:expr) => ({\n let size = ::std::mem::size_of::<$ty>();\n $slab.ensure_capacity(size);\n let dst = $slab.empty();\n if dst.len() < size {\n return Err(io::Error::from(io::ErrorKind::WriteZero));\n } else {\n unsafe {\n let src = *(&$n.to_le() as *const _ as *const [u8;::std::mem::size_of::<$ty>()]);\n ::std::ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), size);\n }\n $slab.make_valid(size);\n }\n })\n}\n\nimpl BytesSlab {\n pub fn write_u64(&mut self, v: u64) -> Result<(), io::Error> {\n write_number!(u64, v, self);\n Ok(())\n }\n\n pub fn write_u32(&mut self, v: u32) -> Result<(), io::Error> {\n write_number!(u32, v, self);\n Ok(())\n }\n\n pub fn write_u16(&mut self, v: u16) -> Result<(), io::Error> {\n write_number!(u16, v, self);\n Ok(())\n }\n\n pub fn try_read(&mut self, length: usize) -> Option {\n if self.valid < length {\n None\n } else {\n Some(self.extract(length))\n }\n }\n}\n\n\nimpl io::Write for BytesSlab {\n fn write(&mut self, buf: &[u8]) -> Result {\n let length = buf.len();\n self.ensure_capacity(length);\n let empty = self.empty();\n if empty.len() < length {\n Ok(0)\n } else {\n unsafe {\n ::std::ptr::copy_nonoverlapping(buf.as_ptr(), empty.as_mut_ptr(), length);\n }\n self.make_valid(length);\n Ok(length)\n }\n }\n\n #[inline(always)]\n fn flush(&mut self) -> Result<(), io::Error> {\n Ok(())\n }\n}\n\nmacro_rules! read_number {\n ($ty:ty, $src:expr) => ({\n let size = ::std::mem::size_of::<$ty>();\n if $src.len() < size {\n return Err(io::Error::from(io::ErrorKind::UnexpectedEof));\n }\n let r = $src.extract_to(size);\n let mut tmp: $ty = 0;\n unsafe {\n ::std::ptr::copy_nonoverlapping(\n r.as_ptr(),\n &mut tmp as *mut $ty as *mut u8,\n size\n )\n }\n tmp.to_le()\n })\n}\n\nimpl Bytes {\n pub fn read_u64(&mut self) -> Result {\n let r = read_number!(u64, self);\n Ok(r)\n }\n\n pub fn read_u32(&mut self) -> Result {\n let r = read_number!(u32, self);\n Ok(r)\n }\n\n pub fn read_u16(&mut self) -> Result {\n let r = read_number!(u16, self);\n Ok(r)\n }\n}\n\nthread_local! {\n pub static SLAB: RefCell = RefCell::new(BytesSlab::new(20));\n}\n\n#[cfg(test)]\nmod test {\n use crate::common::BytesSlab;\n\n #[test]\n fn test_write_read_number() {\n let mut slab = BytesSlab::new(10);\n slab.write_u64(0).unwrap();\n slab.write_u64(1).unwrap();\n slab.write_u32(2).unwrap();\n slab.write_u32(3).unwrap();\n assert_eq!(slab.valid_len(), 24);\n let mut valid = slab.extract_valid().expect(\"unreachable\");\n assert_eq!(valid.read_u64().unwrap(), 0);\n assert_eq!(valid.read_u64().unwrap(), 1);\n assert_eq!(valid.read_u32().unwrap(), 2);\n assert_eq!(valid.read_u32().unwrap(), 3);\n }\n\n\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134652,"cells":{"blob_id":{"kind":"string","value":"9cf019513cb61c55403234e20863f0db2600328f"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"JCapucho/font-to-mif"},"path":{"kind":"string","value":"/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4166,"string":"4,166"},"score":{"kind":"number","value":2.890625,"string":"2.890625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use ab_glyph::{Font, FontVec};\nuse clap::{App, Arg};\nuse std::{\n fs,\n io::{self, Write},\n ops::Range,\n path::Path,\n};\n\nconst ABOUT: &str = r#\"\nConverts true type fonts (.ttf) and Open type fonts (.otf) to intel quartus Memory Initialization File (.mif)\n\"#;\n\nfn range_parser(range: &str) -> Result, String> {\n let mut chars = range.chars();\n\n if let Some(first) = chars.next() {\n if !first.is_digit(10) {\n return Err(String::from(\"First char must be an integer\"));\n }\n\n let mut start_end = 1;\n let mut end_start = None;\n\n while let Some(c) = chars.next() {\n if c.is_digit(10) {\n start_end += 1\n } else if c == '.' {\n if chars.next() != Some('.') {\n return Err(String::from(\"Expected '.'\"));\n }\n\n if !chars.next().map(|c| c.is_digit(10)).unwrap_or(false) {\n return Err(String::from(\"Character after '.' must be a digit\"));\n }\n\n end_start = Some(start_end + 2);\n\n while let Some(c) = chars.next() {\n if !c.is_digit(10) {\n return Err(String::from(\"Invalid char\"));\n }\n }\n } else {\n return Err(String::from(\"Invalid char\"));\n }\n }\n\n let start = range[..start_end].parse().unwrap();\n\n Ok(if let Some(high_start) = end_start {\n let end = range[high_start..].parse().unwrap();\n\n Range { start, end }\n } else {\n Range {\n start,\n end: start + 1,\n }\n })\n } else {\n Err(String::from(\"Empty string is an invalid range\"))\n }\n}\n\nfn main() -> io::Result<()> {\n let matches = App::new(\"font to intel quartus MIF converter\")\n .version(\"0.1\")\n .author(\"João Capucho \")\n .about(ABOUT)\n .arg(\n Arg::with_name(\"FONT\")\n .help(\"Sets the font file to use\")\n .required(true)\n .index(1),\n )\n .arg(\n Arg::with_name(\"output\")\n .short(\"o\")\n .long(\"out\")\n .value_name(\"FILE\")\n .default_value(\"./font.mif\")\n .help(\"Sets the path to the output file\"),\n )\n .arg(\n Arg::with_name(\"range\")\n .short(\"r\")\n .long(\"range\")\n .value_name(\"RANGE\")\n .default_value(\"0..256\")\n .validator(|value| range_parser(&value).map(|_| ()))\n .help(\"Sets the range of glyphs to process\"),\n )\n .get_matches();\n\n let path = Path::new(matches.value_of(\"FONT\").unwrap());\n let range = range_parser(matches.value_of(\"range\").unwrap()).unwrap();\n\n let font_data = fs::read(path)?;\n\n let font = FontVec::try_from_vec(font_data).unwrap();\n\n let depth = range.len() * 8;\n\n let mut data: Vec = vec![0; depth];\n\n for i in range {\n let glyph = font.glyph_id(From::from(i as u8)).with_scale(8.0);\n\n if let Some(outlined) = font.outline_glyph(glyph) {\n outlined.draw(|x, y, coverage| {\n if coverage != 0.0 {\n data[i * 8 + y as usize] |= 1 << x;\n }\n });\n }\n }\n\n let mut out = fs::OpenOptions::new()\n .write(true)\n .truncate(true)\n .create(true)\n .open(matches.value_of(\"output\").unwrap())?;\n\n writeln!(\n &mut out,\n \"-- {} \\n\",\n path.file_name().unwrap().to_str().unwrap()\n )?;\n writeln!(&mut out, \"DEPTH = {};\", depth)?;\n writeln!(&mut out, \"WIDTH = 8;\")?;\n writeln!(&mut out, \"ADDRESS_RADIX = HEX;\")?;\n writeln!(&mut out, \"DATA_RADIX = HEX;\\n\")?;\n writeln!(&mut out, \"CONTENT\")?;\n writeln!(&mut out, \"BEGIN\")?;\n writeln!(&mut out)?;\n\n for (addr, byte) in data.into_iter().enumerate() {\n writeln!(&mut out, \"{:04X} : {:02X};\", addr * 8, byte)?;\n }\n\n writeln!(&mut out)?;\n writeln!(&mut out, \"END;\")?;\n\n Ok(())\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134653,"cells":{"blob_id":{"kind":"string","value":"1fb14e731d2361a4e84211cf236b51a664168748"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Wojtechnology/chess"},"path":{"kind":"string","value":"/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":13016,"string":"13,016"},"score":{"kind":"number","value":3.046875,"string":"3.046875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::collections::HashMap;\nuse std::fmt;\nuse std::io::{Read, Write};\nuse std::net::{TcpListener, TcpStream};\n\nuse serde::Serialize;\nuse serde_json::json;\n\nmod piece {\n use super::{Board, Location, WalkStrategy};\n\n #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]\n pub enum Type {\n Pawn,\n Bishop,\n Knight,\n Rook,\n Queen,\n King,\n }\n\n #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]\n pub enum Color {\n White,\n Black,\n }\n\n #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]\n pub struct Piece {\n pub tpe: Type,\n pub color: Color,\n }\n\n impl Piece {\n pub fn new(tpe: Type, color: Color) -> Piece {\n Piece {\n tpe: tpe,\n color: color,\n }\n }\n\n pub fn new_opt(tpe: Type, color: Color) -> Option {\n Some(Self::new(tpe, color))\n }\n\n fn strategies_pawn(&self, from: Location) -> Vec {\n match self.color {\n Color::White => {\n if from.y == 1 {\n vec![WalkStrategy::new(0, 1, 2)]\n } else {\n vec![WalkStrategy::new(0, 1, 1)]\n }\n }\n Color::Black => {\n if from.y == 6 {\n vec![WalkStrategy::new(0, -1, 2)]\n } else {\n vec![WalkStrategy::new(0, -1, 1)]\n }\n }\n }\n }\n\n pub fn valid_moves(&self, board: &Board, from: Location) -> Vec {\n let strategies = match self.tpe {\n Type::Pawn => self.strategies_pawn(from),\n Type::Bishop => vec![\n WalkStrategy::new(-1, -1, 7),\n WalkStrategy::new(-1, 1, 7),\n WalkStrategy::new(1, -1, 7),\n WalkStrategy::new(1, 1, 7),\n ],\n Type::Knight => vec![\n WalkStrategy::new(-2, -1, 1),\n WalkStrategy::new(-2, 1, 1),\n WalkStrategy::new(-1, -2, 1),\n WalkStrategy::new(-1, 2, 1),\n WalkStrategy::new(1, -2, 1),\n WalkStrategy::new(1, 2, 1),\n WalkStrategy::new(2, -1, 1),\n WalkStrategy::new(2, 1, 1),\n ],\n Type::Rook => vec![\n WalkStrategy::new(-1, 0, 7),\n WalkStrategy::new(0, -1, 7),\n WalkStrategy::new(0, 1, 7),\n WalkStrategy::new(1, 0, 7),\n ],\n Type::Queen => vec![\n WalkStrategy::new(-1, -1, 7),\n WalkStrategy::new(-1, 1, 7),\n WalkStrategy::new(1, -1, 7),\n WalkStrategy::new(1, 1, 7),\n WalkStrategy::new(-1, 0, 7),\n WalkStrategy::new(0, -1, 7),\n WalkStrategy::new(0, 1, 7),\n WalkStrategy::new(1, 0, 7),\n ],\n Type::King => vec![\n WalkStrategy::new(-1, -1, 1),\n WalkStrategy::new(-1, 1, 1),\n WalkStrategy::new(1, -1, 1),\n WalkStrategy::new(1, 1, 1),\n WalkStrategy::new(-1, 0, 1),\n WalkStrategy::new(0, -1, 1),\n WalkStrategy::new(0, 1, 1),\n WalkStrategy::new(1, 0, 1),\n ],\n };\n let mut moves = Vec::new();\n for strategy in strategies {\n let walk = strategy.to_walk(from);\n for dest in walk {\n if let Some(piece) = board.0[dest.y as usize][dest.x as usize] {\n if piece.color == self.color {\n break;\n }\n }\n moves.push(dest)\n }\n }\n moves\n }\n }\n}\n\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]\nstruct Location {\n x: u8,\n y: u8,\n}\n\nimpl Location {\n pub fn to_string(&self) -> String {\n format!(\"{}{}\", (self.x + 97) as char, self.y + 1)\n }\n}\n\nimpl fmt::Display for Location {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{}\", self.to_string())\n }\n}\n\n#[derive(Debug, Copy, Clone)]\nstruct WalkStrategy {\n dx: i8,\n dy: i8,\n max_steps: u8,\n}\n\nimpl WalkStrategy {\n pub fn new(dx: i8, dy: i8, max_steps: u8) -> WalkStrategy {\n WalkStrategy {\n dx: dx,\n dy: dy,\n max_steps: max_steps,\n }\n }\n\n pub fn to_walk(&self, start: Location) -> Walk {\n Walk {\n dx: self.dx,\n dy: self.dy,\n steps_left: self.max_steps,\n cur: start,\n }\n }\n}\n\nstruct Walk {\n dx: i8,\n dy: i8,\n steps_left: u8,\n cur: Location,\n}\n\nimpl Iterator for Walk {\n type Item = Location;\n\n fn next(&mut self) -> Option {\n if self.steps_left == 0 {\n None\n } else if self.dx < 0 && -self.dx as u8 > self.cur.x {\n None\n } else if self.dx > 0 && self.dx as u8 + self.cur.x >= 8 {\n None\n } else if self.dy < 0 && -self.dy as u8 > self.cur.y {\n None\n } else if self.dy > 0 && self.dy as u8 + self.cur.y >= 8 {\n None\n } else {\n self.steps_left -= 1;\n self.cur.x = (self.cur.x as i8 + self.dx) as u8;\n self.cur.y = (self.cur.y as i8 + self.dy) as u8;\n Some(self.cur)\n }\n }\n}\n\nstruct Board([[Option; 8]; 8]);\n\nimpl Board {\n pub fn new() -> Board {\n use piece::{Color, Piece, Type};\n Board([\n [\n Piece::new_opt(Type::Rook, Color::White),\n Piece::new_opt(Type::Knight, Color::White),\n Piece::new_opt(Type::Bishop, Color::White),\n Piece::new_opt(Type::Queen, Color::White),\n Piece::new_opt(Type::King, Color::White),\n Piece::new_opt(Type::Bishop, Color::White),\n Piece::new_opt(Type::Knight, Color::White),\n Piece::new_opt(Type::Rook, Color::White),\n ],\n [\n Piece::new_opt(Type::Pawn, Color::White),\n Piece::new_opt(Type::Pawn, Color::White),\n Piece::new_opt(Type::Pawn, Color::White),\n Piece::new_opt(Type::Pawn, Color::White),\n Piece::new_opt(Type::Pawn, Color::White),\n Piece::new_opt(Type::Pawn, Color::White),\n Piece::new_opt(Type::Pawn, Color::White),\n Piece::new_opt(Type::Pawn, Color::White),\n ],\n [None, None, None, None, None, None, None, None],\n [None, None, None, None, None, None, None, None],\n [None, None, None, None, None, None, None, None],\n [None, None, None, None, None, None, None, None],\n [\n Piece::new_opt(Type::Pawn, Color::Black),\n Piece::new_opt(Type::Pawn, Color::Black),\n Piece::new_opt(Type::Pawn, Color::Black),\n Piece::new_opt(Type::Pawn, Color::Black),\n Piece::new_opt(Type::Pawn, Color::Black),\n Piece::new_opt(Type::Pawn, Color::Black),\n Piece::new_opt(Type::Pawn, Color::Black),\n Piece::new_opt(Type::Pawn, Color::Black),\n ],\n [\n Piece::new_opt(Type::Rook, Color::Black),\n Piece::new_opt(Type::Knight, Color::Black),\n Piece::new_opt(Type::Bishop, Color::Black),\n Piece::new_opt(Type::Queen, Color::Black),\n Piece::new_opt(Type::King, Color::Black),\n Piece::new_opt(Type::Bishop, Color::Black),\n Piece::new_opt(Type::Knight, Color::Black),\n Piece::new_opt(Type::Rook, Color::Black),\n ],\n ])\n }\n\n pub fn step(&mut self, from: Location, to: Location) -> Result<(), String> {\n let piece = match self.0[from.y as usize][from.x as usize] {\n None => Err(format!(\"No piece at {}\", from)),\n Some(p) => Ok(p),\n }?;\n let valid_moves = piece.valid_moves(self, from);\n let () = if valid_moves.iter().any(|&dest| dest == to) {\n Ok(())\n } else {\n Err(\"Invalid move\".to_string())\n }?;\n self.0[from.y as usize][from.x as usize] = None;\n self.0[to.y as usize][to.x as usize] = Some(piece);\n Ok(())\n }\n}\n\nfn cell_as_str(cell: &Option) -> String {\n use piece::{Color, Piece, Type};\n match cell {\n None => \"\".to_string(),\n Some(Piece { tpe, color }) => {\n let c = match color {\n Color::White => \"w\",\n Color::Black => \"b\",\n };\n let t = match tpe {\n Type::Pawn => \"P\",\n Type::Bishop => \"B\",\n Type::Knight => \"N\",\n Type::Rook => \"R\",\n Type::Queen => \"Q\",\n Type::King => \"K\",\n };\n format!(\"{}{}\", c, t)\n }\n }\n}\n\nfn board_as_str(board: &Board) -> String {\n let mut cells = Vec::with_capacity(64);\n for i in 0..8 {\n for j in 0..8 {\n cells.push(cell_as_str(&board.0[i][j]));\n }\n }\n cells.join(\",\")\n}\n\nfn get_path(mut stream: &TcpStream) -> (String, HashMap) {\n let mut buffer = [0; 1024];\n stream.read(&mut buffer).unwrap();\n let req_str = String::from_utf8_lossy(&buffer[..]);\n let req_fst_line = req_str.split('\\n').next().unwrap();\n let mut req_fst_line_it = req_fst_line.split(' ');\n req_fst_line_it.next().unwrap(); // Method\n let full_path = req_fst_line_it.next().unwrap();\n let mut full_path_it = full_path.split(\"?\");\n let path = full_path_it.next().unwrap().to_string();\n let query_str_it = {\n match full_path_it.next() {\n Some(query_str) => query_str.split(\"&\"),\n None => {\n // Make the split empty\n let mut split = \"\".split(\"&\");\n split.next().unwrap();\n split\n }\n }\n };\n let mut query_args = HashMap::new();\n for query_arg_str in query_str_it {\n let mut query_arg_str_it = query_arg_str.split(\"=\");\n query_args.insert(\n query_arg_str_it.next().unwrap().to_string(),\n query_arg_str_it.collect::>().join(\"=\"),\n );\n }\n (path, query_args)\n}\n\nfn location_from_string(s: &String) -> Location {\n let i = s.parse::().unwrap();\n Location { x: i % 8, y: i / 8 }\n}\n\nfn get_from_to(query_args: HashMap) -> (Location, Location) {\n let from_raw = query_args.get(\"from\").unwrap();\n let to_raw = query_args.get(\"to\").unwrap();\n (location_from_string(from_raw), location_from_string(to_raw))\n}\n\n#[derive(Serialize)]\nstruct ResponseData {\n squares: String,\n}\n\nfn success_res(content: String) -> String {\n format!(\n \"\\\nHTTP/1.1 200 OK\\r\\n\\\nAccess-Control-Allow-Origin: *\\r\\n\\\nContent-Type: application/json\\r\\n\\\nContent-Length: {}\\r\\n\\\n\\r\\n\\\n{}\",\n content.len(),\n content,\n )\n}\n\nfn bad_request_res(err_msg: String) -> String {\n format!(\n \"\\\nHTTP/1.1 400 Bad Request\\r\\n\\\nAccess-Control-Allow-Origin: *\\r\\n\\\nContent-Type: text/plain\\r\\n\\\nContent-Length: {}\\r\\n\\\n\\r\\n\\\n{}\",\n err_msg.len(),\n err_msg,\n )\n}\n\nfn write_board(board: &Board, mut stream: &TcpStream) {\n let data = ResponseData {\n squares: board_as_str(board),\n };\n let body = json!(data).to_string();\n let response = success_res(body);\n stream.write(response.as_bytes()).unwrap();\n}\n\nfn write_err(err_msg: String, mut stream: &TcpStream) {\n let response = bad_request_res(err_msg);\n stream.write(response.as_bytes()).unwrap();\n}\n\nfn main() {\n let mut board = Board::new();\n let listener = TcpListener::bind(\"127.0.0.1:8080\").unwrap();\n\n for stream in listener.incoming() {\n let mut stream = stream.unwrap();\n let (path, query_args) = get_path(&stream);\n println!(\"{}: {:?}\", path, query_args);\n if path.eq(\"/game\") {\n write_board(&board, &stream);\n } else if path.eq(\"/move\") {\n let (from, to) = get_from_to(query_args);\n match board.step(from, to) {\n Ok(()) => write_board(&board, &stream),\n Err(e) => {\n println!(\"Error: {}\", e);\n write_err(e, &stream)\n }\n };\n } else {\n // TODO: 404\n write_err(\"Unknown path\".to_string(), &stream);\n }\n stream.flush().unwrap()\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134654,"cells":{"blob_id":{"kind":"string","value":"69dd6468553a85bcfa57706c7361bb3115801a6d"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"mdaffin/nuc"},"path":{"kind":"string","value":"/src/bin/nuc.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":811,"string":"811"},"score":{"kind":"number","value":2.984375,"string":"2.984375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"extern crate structopt;\n#[macro_use]\nextern crate structopt_derive;\nextern crate nuc;\n\nuse nuc::Number;\nuse structopt::StructOpt;\n\n#[derive(StructOpt, Debug)]\n#[structopt(name = \"nuc\", about = \"Converts numbers form one for to another\")]\nstruct Opt {\n /// Number to convert\n #[structopt(help = \"Input numbers\")]\n input: Vec,\n}\n\nfn main() {\n let opt = Opt::from_args();\n for arg in opt.input {\n let num: Number = match arg.parse() {\n Ok(i) => i,\n Err(e) => {\n println!(\"Failed to parse input '{}': {}\", arg, e);\n std::process::exit(1);\n }\n };\n print!(\"{:>8} \", num);\n print!(\"{:>8} \", num.fmt_signed());\n print!(\"{:>#8x} \", num);\n print!(\"{:>#16b}\", num);\n println!();\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134655,"cells":{"blob_id":{"kind":"string","value":"ab6627ce58ec67aad32c2e9c59fadf1abbefaa83"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"wzhd/rotor"},"path":{"kind":"string","value":"/src/util/cmd.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1162,"string":"1,162"},"score":{"kind":"number","value":2.859375,"string":"2.859375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use super::super::host::UserAtHost;\nuse std::str::FromStr;\nuse structopt::StructOpt;\n\n#[derive(StructOpt, Debug)]\n#[structopt(name = \"rotor\", about = \"Deploying properties to hosts.\")]\npub struct RotorMain {\n #[structopt(subcommand)]\n pub cmd: RotorSub,\n}\n\n#[derive(Debug, StructOpt)]\npub enum RotorSub {\n #[structopt(name = \"list\")]\n /// List configured users at hosts\n List,\n /// Apply configurations for username@hostname locally\n #[structopt(name = \"apply\")]\n Apply {\n #[structopt(parse(try_from_str))]\n user: UserAtHost,\n },\n /// Apply configurations to remote users or hosts via ssh\n #[structopt(name = \"push\")]\n Push { targets: Vec },\n}\n\n#[derive(Debug)]\npub enum PushTarget {\n /// A single user on a single host\n User(UserAtHost),\n /// All users on a host\n Host(String),\n}\n\nimpl FromStr for PushTarget {\n type Err = &'static str;\n\n fn from_str(s: &str) -> Result {\n if !s.contains('@') {\n Ok(PushTarget::Host(s.to_string()))\n } else {\n let u = FromStr::from_str(s)?;\n Ok(PushTarget::User(u))\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134656,"cells":{"blob_id":{"kind":"string","value":"8d76920c11fedc2e7bb55e69be3df7b59a492e4b"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"kellerja/AoC2020"},"path":{"kind":"string","value":"/src/day16/mod.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5789,"string":"5,789"},"score":{"kind":"number","value":2.890625,"string":"2.890625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::fs::File;\nuse std::io::BufReader;\nuse std::io::prelude::*;\nuse std::ops::Range;\nuse std::collections::HashSet;\nuse regex::Regex;\n\nlazy_static! {\n static ref FIELD_RULE_PATTERN: Regex = Regex::new(r\"(?P.+): (?P\\d+)-(?P\\d+) or (?P\\d+)-(?P\\d+)\").unwrap();\n}\n\nstruct TicketField {\n name: String,\n rules: Vec>\n}\n\nimpl TicketField {\n fn parse(input: &str) -> Option {\n FIELD_RULE_PATTERN.captures(input).and_then(|cap| {\n Some(Self {\n name: cap[\"name\"].to_owned(),\n rules: vec![\n Range {start: cap[\"low_start\"].parse().unwrap(), end: cap[\"low_end\"].parse::().unwrap() + 1},\n Range {start: cap[\"high_start\"].parse().unwrap(), end: cap[\"high_end\"].parse::().unwrap() + 1}\n ]\n })\n })\n }\n\n fn is_valid(&self, number: u64) -> bool {\n for rule in &self.rules {\n if rule.contains(&number) {\n return true;\n }\n }\n false\n }\n}\n\n#[derive(Clone)]\nstruct Ticket {\n fields: Vec,\n values: Vec\n}\n\nimpl Ticket {\n fn parse(input: &str) -> Option {\n let input = input.split(\",\");\n let mut values = Vec::new();\n for s in input {\n if let Ok(value) = s.parse() {\n values.push(value);\n } else {\n return None;\n }\n }\n Some(Ticket { fields: Vec::with_capacity(values.len()), values })\n }\n\n fn find_illegal_fields(&self, rules: &Vec) -> Vec {\n if rules.is_empty() {\n return Vec::new();\n }\n self.values.iter()\n .filter(|&num|\n !rules.iter().map(|rule| rule.is_valid(*num)).fold(false, |acc, result| acc || result)\n ).map(|num| *num).collect()\n }\n}\n\nfn get_possible_fields_map(fields: &[TicketField]) -> Vec> {\n let field_names: Vec<&str> = fields.iter().map(|field| field.name.as_str()).collect();\n vec![field_names.clone(); field_names.len()]\n}\n\nfn remove_invalid_possible_fields(possible_fields: &mut Vec>, valid_tickets: &[&Ticket], fields: &[TicketField]) {\n for ticket in valid_tickets {\n for (i, &value) in ticket.values.iter().enumerate() {\n for field in fields {\n if !field.is_valid(value) {\n possible_fields[i].retain(|&name| name != field.name);\n }\n }\n }\n }\n}\n\nfn remove_cerain_fields_from_uncertain_fields(possible_fields: &mut Vec>) {\n let mut handled_fields = HashSet::with_capacity(possible_fields.len());\n loop {\n let certain_fields: HashSet<&str> = possible_fields.iter()\n .filter(|fields| fields.len() == 1)\n .map(|fields| fields.first().unwrap().to_owned()).collect();\n let unhandled_field = certain_fields.difference(&handled_fields).next();\n match unhandled_field {\n None => break,\n Some(unhandled_field) => {\n for fields in possible_fields.iter_mut() {\n if fields.len() == 1 {\n continue;\n }\n fields.retain(|field| field != unhandled_field);\n }\n let unhandled_field = unhandled_field.to_owned();\n handled_fields.insert(unhandled_field);\n }\n }\n }\n}\n\nfn certain_field_map<'a>(possible_fields: &'a Vec>) -> Option> {\n if possible_fields.iter().any(|field| field.len() != 1) {\n return None\n } else {\n Some(possible_fields.iter().map(|field| field.first().unwrap().to_owned()).collect())\n }\n}\n\npub fn solve(input: &File) -> (Option, Option) {\n let input = parse_input(input);\n if let Some((fields, my_ticket, tickets)) = input {\n let mut valid_tickets: Vec<&Ticket> = tickets.iter().filter(|ticket| ticket.find_illegal_fields(&fields).is_empty()).collect();\n valid_tickets.push(&my_ticket);\n let mut possible_field_map = get_possible_fields_map(&fields);\n remove_invalid_possible_fields(&mut possible_field_map, &valid_tickets, &fields);\n remove_cerain_fields_from_uncertain_fields(&mut possible_field_map);\n let field_map = certain_field_map(&possible_field_map);\n\n let departure_fields_product = field_map.and_then(|field_map| {\n let mut result = 1;\n for (i, field) in field_map.iter().enumerate() {\n if field.starts_with(\"departure\") {\n result *= my_ticket.values[i];\n }\n }\n Some(result)\n });\n let invalid_ticket_fields_sum = tickets.iter().map(|ticket| ticket.find_illegal_fields(&fields).iter().sum::()).sum();\n (Some(invalid_ticket_fields_sum), departure_fields_product)\n } else {\n (None, None)\n }\n}\n\nfn parse_input(input: &File) -> Option<(Vec, Ticket, Vec)> {\n let mut lines = BufReader::new(input).lines();\n let mut fields = Vec::new();\n loop {\n let line = lines.next();\n let field = line.and_then(|line| TicketField::parse(&line.unwrap()));\n match field {\n Some(field) => fields.push(field),\n None => break\n }\n };\n lines.next();\n let my_ticket = lines.next().and_then(|line| Ticket::parse(&line.unwrap()));\n lines.next();\n lines.next();\n let tickets: Vec = lines.map(|line| Ticket::parse(&line.unwrap()).unwrap()).collect();\n if fields.is_empty() || my_ticket.is_none() || tickets.is_empty() {\n None\n } else {\n Some((fields, my_ticket.unwrap(), tickets))\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134657,"cells":{"blob_id":{"kind":"string","value":"9dfb91782b25f342c1f51f281268f46d66e7a741"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"whentze/loom"},"path":{"kind":"string","value":"/src/futures/mod.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":959,"string":"959"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"//! Future related synchronization primitives.\n\nmod atomic_task;\n\npub use self::atomic_task::AtomicTask;\npub use self::rt::wait_future as block_on;\n\nuse rt;\n\n/// Mock implementation of `futures::task`.\npub mod task {\n use rt;\n\n /// Mock implementation of `futures::task::Task`.\n #[derive(Debug)]\n pub struct Task {\n thread: rt::thread::Id,\n }\n\n /// Mock implementation of `futures::task::current`.\n pub fn current() -> Task {\n Task {\n thread: rt::thread::Id::current(),\n }\n }\n\n impl Task {\n /// Indicate that the task should attempt to poll its future in a timely fashion.\n pub fn notify(&self) {\n self.thread.future_notify();\n }\n\n /// This function is intended as a performance optimization for structures which store a Task internally.\n pub fn will_notify_current(&self) -> bool {\n self.thread == rt::thread::Id::current()\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134658,"cells":{"blob_id":{"kind":"string","value":"2ee109a255b57bd9d9eb9296e8c17b945ac711e0"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"rm-hull/image-preview"},"path":{"kind":"string","value":"/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1825,"string":"1,825"},"score":{"kind":"number","value":3,"string":"3"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use image::io::Reader as ImageReader;\nuse image::GenericImageView;\nuse std::io::{self, Write};\nuse structopt::StructOpt;\n\nextern crate image_preview;\n\n#[derive(StructOpt)]\nstruct Cli {\n filename: String,\n #[structopt(\n long,\n help = \"When supplied, renders the image in true colour (not supported on all terminals). The default is to use the nearest colour from the 255 indexed colours of the standard ANSI palette.\"\n )]\n true_color: bool,\n #[structopt(\n long,\n help = \"Resize filter used when scaling for the terminal (allowed values: nearest, triangle, catmullrom, gaussian, lanczos3)\",\n default_value = \"lanczos3\"\n )]\n filter_type: String,\n #[structopt(\n long,\n short,\n help = \"When supplied, limits the image with to the number of columns, else probes the terminal to determine the displayable width.\"\n )]\n width: Option,\n}\n\nfn main() {\n let args = Cli::from_args();\n let img = ImageReader::open(args.filename)\n .expect(\"File does not exist\")\n .decode()\n .expect(\"Cannot decode image\");\n let filter_type = image_preview::from_str(&args.filter_type).expect(\"Unsupported filter type\");\n let (width, height) = image_preview::calc_size(&img, args.width).unwrap();\n let resized_img = img.resize(width, height, filter_type);\n\n let pixel_renderer = match args.true_color {\n true => image_preview::true_color,\n false => image_preview::indexed,\n };\n let mut buf = Vec::new();\n for y in (0..resized_img.height() - 1).step_by(2) {\n for x in 0..resized_img.width() {\n buf.write_all(pixel_renderer(&resized_img, x, y).as_bytes())\n .unwrap();\n }\n buf.write_all(b\"\\x1b[m\\n\").unwrap();\n }\n io::stdout().write_all(&buf).unwrap();\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134659,"cells":{"blob_id":{"kind":"string","value":"a20eb7b379ce61003e57c6fc12c171197e59b940"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"linuxdevops-34/aws-apigateway-lambda-authorizer-blueprints"},"path":{"kind":"string","value":"/blueprints/rust/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6162,"string":"6,162"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"#![allow(dead_code)]\n#[macro_use]\nextern crate lambda_runtime as lambda;\n#[macro_use]\nextern crate serde_derive;\n#[macro_use]\nextern crate log;\nextern crate simple_logger;\n\nuse lambda::error::HandlerError;\n\nuse serde_json::json;\nuse std::error::Error;\n\nstatic POLICY_VERSION: &str = \"2012-10-17\"; // override if necessary\n\nfn my_handler(\n event: APIGatewayCustomAuthorizerRequest,\n _ctx: lambda::Context,\n) -> Result {\n info!(\"Client token: {}\", event.authorization_token);\n info!(\"Method ARN: {}\", event.method_arn);\n\n // validate the incoming token\n // and produce the principal user identifier associated with the token\n\n // this could be accomplished in a number of ways:\n // 1. Call out to OAuth provider\n // 2. Decode a JWT token inline\n // 3. Lookup in a self-managed DB\n let principal_id = \"user|a1b2c3d4\";\n\n // you can send a 401 Unauthorized response to the client by failing like so:\n // Err(HandlerError{ msg: \"Unauthorized\".to_string(), backtrace: None });\n\n // if the token is valid, a policy must be generated which will allow or deny access to the client\n\n // if access is denied, the client will recieve a 403 Access Denied response\n // if access is allowed, API Gateway will proceed with the backend integration configured on the method that was called\n\n // this function must generate a policy that is associated with the recognized principal user identifier.\n // depending on your use case, you might store policies in a DB, or generate them on the fly\n\n // keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer)\n // and will apply to subsequent calls to any method/resource in the RestApi\n // made with the same token\n\n //the example policy below denies access to all resources in the RestApi\n let tmp: Vec<&str> = event.method_arn.split(\":\").collect();\n let api_gateway_arn_tmp: Vec<&str> = tmp[5].split(\"/\").collect();\n let aws_account_id = tmp[4];\n let region = tmp[3];\n let rest_api_id = api_gateway_arn_tmp[0];\n let stage = api_gateway_arn_tmp[1];\n\n let policy = APIGatewayPolicyBuilder::new(region, aws_account_id, rest_api_id, stage)\n .deny_all_methods()\n .build();\n\n // new! -- add additional key-value pairs associated with the authenticated principal\n // these are made available by APIGW like so: $context.authorizer.\n // additional context is cached\n Ok(APIGatewayCustomAuthorizerResponse {\n principal_id: principal_id.to_string(),\n policy_document: policy,\n context: json!({\n \"stringKey\": \"stringval\",\n \"numberKey\": 123,\n \"booleanKey\": true\n }),\n })\n}\n\nfn main() -> Result<(), Box> {\n simple_logger::init_with_level(log::Level::Info)?;\n lambda!(my_handler);\n\n Ok(())\n}\n\n#[derive(Serialize, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\nstruct APIGatewayCustomAuthorizerRequest {\n #[serde(rename = \"type\")]\n _type: String,\n authorization_token: String,\n method_arn: String,\n}\n\n#[derive(Serialize, Deserialize)]\n#[allow(non_snake_case)]\nstruct APIGatewayCustomAuthorizerPolicy {\n Version: String,\n Statement: Vec,\n}\n\n#[derive(Serialize, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\nstruct APIGatewayCustomAuthorizerResponse {\n principal_id: String,\n policy_document: APIGatewayCustomAuthorizerPolicy,\n context: serde_json::Value,\n}\n\n#[derive(Serialize, Deserialize)]\n#[allow(non_snake_case)]\nstruct IAMPolicyStatement {\n Action: Vec,\n Effect: Effect,\n Resource: Vec,\n}\n\nstruct APIGatewayPolicyBuilder {\n region: String,\n aws_account_id: String,\n rest_api_id: String,\n stage: String,\n policy: APIGatewayCustomAuthorizerPolicy,\n}\n\n#[derive(Serialize, Deserialize)]\nenum Method {\n #[serde(rename = \"GET\")]\n Get,\n #[serde(rename = \"POST\")]\n Post,\n #[serde(rename = \"*PUT\")]\n Put,\n #[serde(rename = \"DELETE\")]\n Delete,\n #[serde(rename = \"PATCH\")]\n Patch,\n #[serde(rename = \"HEAD\")]\n Head,\n #[serde(rename = \"OPTIONS\")]\n Options,\n #[serde(rename = \"*\")]\n All,\n}\n\n#[derive(Serialize, Deserialize)]\nenum Effect {\n Allow,\n Deny,\n}\n\nimpl APIGatewayPolicyBuilder {\n pub fn new(\n region: &str,\n account_id: &str,\n api_id: &str,\n stage: &str,\n ) -> APIGatewayPolicyBuilder {\n Self {\n region: region.to_string(),\n aws_account_id: account_id.to_string(),\n rest_api_id: api_id.to_string(),\n stage: stage.to_string(),\n policy: APIGatewayCustomAuthorizerPolicy {\n Version: POLICY_VERSION.to_string(),\n Statement: vec![],\n },\n }\n }\n\n pub fn add_method>(\n mut self,\n effect: Effect,\n method: Method,\n resource: T,\n ) -> Self {\n let resource_arn = format!(\n \"arn:aws:execute-api:{}:{}:{}/{}/{}/{}\",\n &self.region,\n &self.aws_account_id,\n &self.rest_api_id,\n &self.stage,\n serde_json::to_string(&method).unwrap(),\n resource.into().trim_start_matches(\"/\")\n );\n\n let stmt = IAMPolicyStatement {\n Effect: effect,\n Action: vec![\"execute-api:Invoke\".to_string()],\n Resource: vec![resource_arn],\n };\n\n self.policy.Statement.push(stmt);\n self\n }\n\n pub fn allow_all_methods(self) -> Self {\n self.add_method(Effect::Allow, Method::All, \"*\")\n }\n\n pub fn deny_all_methods(self) -> Self {\n self.add_method(Effect::Deny, Method::All, \"*\")\n }\n\n pub fn allow_method(self, method: Method, resource: String) -> Self {\n self.add_method(Effect::Allow, method, resource)\n }\n\n pub fn deny_method(self, method: Method, resource: String) -> Self {\n self.add_method(Effect::Deny, method, resource)\n }\n\n // Creates and executes a new child thread.\n pub fn build(self) -> APIGatewayCustomAuthorizerPolicy {\n self.policy\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134660,"cells":{"blob_id":{"kind":"string","value":"f1e4a0c0d05386f7ffb6f6296c7fae4770282033"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"CryZe/romhack-compiler"},"path":{"kind":"string","value":"/backend/src/iso/reader.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4139,"string":"4,139"},"score":{"kind":"number","value":2.734375,"string":"2.734375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use super::virtual_file_system::{Directory, File, Node};\nuse super::{consts::*, FstEntry, FstNodeType};\nuse byteorder::{ByteOrder, BE};\nuse failure::{Error, ResultExt};\nuse std::fs;\nuse std::io::{Read, Result as IOResult};\nuse std::path::Path;\nuse std::str;\n\npub fn load_iso_buf>(path: P) -> IOResult> {\n let mut file = fs::File::open(path)?;\n let len = file.metadata()?.len();\n let mut buf = Vec::with_capacity(len as usize + 1);\n file.read_to_end(&mut buf)?;\n Ok(buf)\n}\n\npub fn load_iso<'a>(buf: &'a [u8]) -> Result, Error> {\n let fst_offset = BE::read_u32(&buf[OFFSET_FST_OFFSET..]) as usize;\n let mut pos = fst_offset;\n let num_entries = BE::read_u32(&buf[fst_offset + 8..]) as usize;\n let string_table_offset = num_entries * 0xC;\n\n let mut fst_entries = Vec::with_capacity(num_entries);\n for _ in 0..num_entries {\n let kind = if buf[pos] == 0 {\n FstNodeType::File\n } else {\n FstNodeType::Directory\n };\n pos += 2;\n\n let cur_pos = pos;\n let string_offset = BE::read_u16(&buf[pos..]) as usize;\n\n pos = string_offset + string_table_offset + fst_offset;\n let mut end = pos;\n while buf[end] != 0 {\n end += 1;\n }\n let relative_file_name =\n str::from_utf8(&buf[pos..end]).context(\"Couldn't parse the relative file name\")?;\n\n pos = cur_pos + 2;\n let file_offset_parent_dir = BE::read_u32(&buf[pos..]) as usize;\n let file_size_next_dir_index = BE::read_u32(&buf[pos + 4..]) as usize;\n pos += 8;\n\n fst_entries.push(FstEntry {\n kind,\n relative_file_name,\n file_offset_parent_dir,\n file_size_next_dir_index,\n file_name_offset: 0,\n });\n }\n\n let mut root_dir = Directory::new(\"root\");\n let mut sys_data = Directory::new(\"&&systemdata\");\n\n sys_data\n .children\n .push(Node::File(File::new(\"iso.hdr\", &buf[..HEADER_LENGTH])));\n\n let dol_offset = BE::read_u32(&buf[OFFSET_DOL_OFFSET..]) as usize;\n\n sys_data.children.push(Node::File(File::new(\n \"AppLoader.ldr\",\n &buf[HEADER_LENGTH..dol_offset],\n )));\n\n sys_data.children.push(Node::File(File::new(\n \"Start.dol\",\n &buf[dol_offset..fst_offset],\n )));\n\n let fst_size = BE::read_u32(&buf[OFFSET_FST_SIZE..]) as usize;\n sys_data.children.push(Node::File(File::new(\n \"Game.toc\",\n &buf[fst_offset..][..fst_size],\n )));\n\n root_dir.children.push(Node::Directory(Box::new(sys_data)));\n\n let mut count = 1;\n\n while count < num_entries {\n let entry = &fst_entries[count];\n if fst_entries[count].kind == FstNodeType::Directory {\n let mut dir = Directory::new(entry.relative_file_name);\n\n while count < entry.file_size_next_dir_index - 1 {\n count = get_dir_structure_recursive(count + 1, &fst_entries, &mut dir, buf);\n }\n\n root_dir.children.push(Node::Directory(Box::new(dir)));\n } else {\n let file = get_file_data(&fst_entries[count], buf);\n root_dir.children.push(Node::File(file));\n }\n count += 1;\n }\n\n Ok(root_dir)\n}\n\nfn get_dir_structure_recursive<'a>(\n mut cur_index: usize,\n fst: &[FstEntry<'a>],\n parent_dir: &mut Directory<'a>,\n buf: &'a [u8],\n) -> usize {\n let entry = &fst[cur_index];\n\n if entry.kind == FstNodeType::Directory {\n let mut dir = Directory::new(entry.relative_file_name);\n\n while cur_index < entry.file_size_next_dir_index - 1 {\n cur_index = get_dir_structure_recursive(cur_index + 1, fst, &mut dir, buf);\n }\n\n parent_dir.children.push(Node::Directory(Box::new(dir)));\n } else {\n let file = get_file_data(entry, buf);\n parent_dir.children.push(Node::File(file));\n }\n\n cur_index\n}\n\nfn get_file_data<'a>(fst_data: &FstEntry<'a>, buf: &'a [u8]) -> File<'a> {\n let data = &buf[fst_data.file_offset_parent_dir..][..fst_data.file_size_next_dir_index];\n File::new(fst_data.relative_file_name, data)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134661,"cells":{"blob_id":{"kind":"string","value":"0ec69a2129085d2ec0096ecb8a909d0af303a9eb"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"dollarkillerx/Re-learning-RUST"},"path":{"kind":"string","value":"/demo12_1/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1396,"string":"1,396"},"score":{"kind":"number","value":3.828125,"string":"3.828125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"// struct Handbag {\n// article: Option>,\n// }\n// impl Handbag {\n// fn new() -> Handbag {\n// Handbag{\n// article:None,\n// }\n// }\n// fn put(&mut self,article: T) {\n// self.article = Some(Box::new(article));\n// }\n// fn take(&mut self) -> Option> {\n// match &self.article {\n// Some(data) => { // data: &Box\n// self.article = None;\n// return Some(*data)\n// },\n// None => None,\n// }\n// }\n// }\n\nuse std::mem::take;\n\nfn main() {\n // let mut handbag = Handbag::new();\n // handbag.put(String::from(\"hello\"));\n // if let Some(article) = handbag.take() {\n // println!(\"data: {}\",article);\n // }\n\n let mut u = User::new();\n u.set_name(String::from(\"acg\"));\n println!(\"name: {}\",u.get_name().unwrap());\n println!(\"name: {}\",u.get_name().unwrap());\n\n println!(\"Hello, world!\");\n}\n\nstruct User {\n name: Option,\n}\nimpl User {\n fn new() -> User {\n User{name:None}\n }\n fn set_name(&mut self,name: String) {\n self.name = Some(name);\n }\n fn get_name(&mut self) -> Option {\n take(&mut self.name)\n // match &self.name {\n // None=>None,\n // Some(name) => {\n // take(name)\n // },\n // }\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134662,"cells":{"blob_id":{"kind":"string","value":"cfe8ce67e3977c8ccb98f3e6db28184566e7f24a"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"lemunozm/ruscii"},"path":{"kind":"string","value":"/examples/space_invaders.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7365,"string":"7,365"},"score":{"kind":"number","value":2.671875,"string":"2.671875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use ruscii::app::{App, State};\nuse ruscii::drawing::Pencil;\nuse ruscii::gui::FPSCounter;\nuse ruscii::keyboard::{Key, KeyEvent};\nuse ruscii::spatial::Vec2;\nuse ruscii::terminal::{Color, Style, Window};\n\nuse rand::{self, prelude::*};\n\nstruct GameState {\n pub dimension: Vec2,\n pub spaceship: Vec2,\n pub spaceship_shots: Vec,\n pub last_shot_frame: usize,\n pub aliens: Vec,\n pub aliens_shots: Vec,\n pub aliens_movement: (i32, bool), //dir, just_down\n pub last_aliens_movement: usize,\n pub last_aliens_shots: usize,\n pub lives: usize,\n pub score: usize,\n}\n\nimpl GameState {\n pub fn new(dimension: Vec2) -> GameState {\n let mut aliens = Vec::new();\n for y in 2..7 {\n for x in 5..dimension.x - 5 {\n if x % 2 != 0 {\n aliens.push(Vec2::xy(x, y));\n }\n }\n }\n GameState {\n dimension,\n spaceship: Vec2::xy(dimension.x / 2, dimension.y - 2),\n spaceship_shots: Vec::new(),\n last_shot_frame: 0,\n aliens,\n aliens_shots: Vec::new(),\n aliens_movement: (1, false),\n last_aliens_movement: 0,\n last_aliens_shots: 0,\n lives: 3,\n score: 0,\n }\n }\n\n pub fn spaceship_move_x(&mut self, displacement: i32) {\n if displacement < 0 && self.spaceship.x != 0\n || displacement > 0 && self.spaceship.x != self.dimension.x\n {\n self.spaceship.x += displacement;\n }\n }\n\n pub fn spaceship_shot(&mut self, shot_frame: usize) {\n if self.last_shot_frame + 15 < shot_frame {\n self.spaceship_shots.push(self.spaceship);\n self.last_shot_frame = shot_frame;\n }\n }\n\n pub fn update(&mut self, frame: usize) {\n let mut partial_score = 0;\n let aliens = &mut self.aliens;\n self.spaceship_shots.retain(|shot| {\n if shot.y == 1 {\n return false;\n }\n let pre_len = aliens.len();\n aliens.retain(|alien| alien != shot);\n let destroyed = aliens.len() != pre_len;\n if destroyed {\n partial_score += 5;\n }\n !destroyed\n });\n self.score += partial_score;\n\n self.spaceship_shots.iter_mut().for_each(|shot| shot.y -= 1);\n\n if self.last_aliens_shots + 5 < frame {\n self.last_aliens_shots = frame;\n for alien in &self.aliens {\n let must_shot = thread_rng().gen_range(0..=200) == 0;\n if must_shot {\n self.aliens_shots.push(*alien);\n }\n }\n\n let bottom_shot_limit = self.dimension.y;\n self.aliens_shots.retain(|shot| shot.y < bottom_shot_limit);\n self.aliens_shots.iter_mut().for_each(|shot| shot.y += 1);\n }\n\n let mut damage = 0;\n let spaceship = &self.spaceship;\n self.aliens_shots.retain(|shot| {\n if shot.y == spaceship.y\n && (shot.x == spaceship.x || shot.x == spaceship.x + 1 || shot.x == spaceship.x - 1)\n {\n damage += 1;\n return false;\n }\n true\n });\n\n self.aliens.iter().for_each(|alien| {\n if alien.y == spaceship.y\n && (alien.x == spaceship.x\n || alien.x == spaceship.x + 1\n || alien.x == spaceship.x - 1)\n {\n damage = 1000;\n }\n });\n\n self.lives = if damage >= self.lives {\n 0\n } else {\n self.lives - damage\n };\n\n if self.aliens.len() > 0 {\n let left = self.aliens.iter().min_by_key(|alien| alien.x).unwrap();\n let right = self.aliens.iter().max_by_key(|alien| alien.x).unwrap();\n if self.last_aliens_movement + 20 < frame {\n self.last_aliens_movement = frame;\n\n if left.x == 0 || right.x == self.dimension.x {\n if self.aliens_movement.1 {\n self.aliens_movement.0 = -self.aliens_movement.0;\n let dir = self.aliens_movement.0;\n self.aliens\n .iter_mut()\n .for_each(|alien| alien.x = alien.x + dir);\n self.aliens_movement.1 = false;\n } else {\n self.aliens.iter_mut().for_each(|alien| alien.y += 1);\n self.aliens_movement.1 = true;\n }\n } else {\n let dir = self.aliens_movement.0;\n self.aliens\n .iter_mut()\n .for_each(|alien| alien.x = alien.x + dir);\n }\n }\n }\n }\n}\n\nfn main() {\n let mut app = App::default();\n let mut state = GameState::new(Vec2::xy(60, 22));\n let mut fps_counter = FPSCounter::default();\n\n app.run(|app_state: &mut State, window: &mut Window| {\n for key_event in app_state.keyboard().last_key_events() {\n match key_event {\n KeyEvent::Pressed(Key::Esc) => app_state.stop(),\n KeyEvent::Pressed(Key::Q) => app_state.stop(),\n _ => (),\n }\n }\n\n for key_down in app_state.keyboard().get_keys_down() {\n match key_down {\n Key::A | Key::H => state.spaceship_move_x(-1),\n Key::D | Key::L => state.spaceship_move_x(1),\n Key::Space => state.spaceship_shot(app_state.step()),\n _ => (),\n }\n }\n\n state.update(app_state.step());\n fps_counter.update();\n\n let win_size = window.size();\n let mut pencil = Pencil::new(window.canvas_mut());\n pencil.draw_text(&format!(\"FPS: {}\", fps_counter.count()), Vec2::xy(1, 0));\n\n if state.aliens.is_empty() || state.lives == 0 {\n let status_msg = if state.lives > 0 {\n \"You win! :D\"\n } else {\n \"You lose :(\"\n };\n let msg = &format!(\"{} - score: {}\", status_msg, state.score);\n pencil.set_origin(win_size / 2 - Vec2::x(msg.len() / 2));\n pencil.draw_text(msg, Vec2::zero());\n return ();\n }\n\n pencil.set_origin((win_size - state.dimension) / 2);\n pencil.draw_text(\n &format!(\"lives: {} - score: {}\", state.lives, state.score),\n Vec2::xy(15, 0),\n );\n pencil.set_foreground(Color::Cyan);\n pencil.draw_char('^', state.spaceship);\n pencil.draw_char('/', state.spaceship - Vec2::x(1));\n pencil.draw_char('\\\\', state.spaceship + Vec2::x(1));\n pencil.draw_char('\\'', state.spaceship + Vec2::y(1));\n\n pencil.set_foreground(Color::Red);\n for shot in &state.aliens_shots {\n pencil.draw_char('|', *shot);\n }\n\n pencil.set_foreground(Color::Green);\n for alien in &state.aliens {\n pencil.draw_char('W', *alien);\n }\n\n pencil.set_foreground(Color::Yellow);\n pencil.set_style(Style::Bold);\n for shot in &state.spaceship_shots {\n pencil.draw_char('|', *shot);\n }\n });\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134663,"cells":{"blob_id":{"kind":"string","value":"b15972d1044b1dc9f5d5f8453ffe6db81aaa46d3"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"goncalopalaio/raytracing_in_rust"},"path":{"kind":"string","value":"/src/raytrace/camera.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2027,"string":"2,027"},"score":{"kind":"number","value":3.0625,"string":"3.0625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use super::ray::Ray;\nuse super::vec::Vec3;\n\nextern crate rand;\nuse rand::Rng;\n\npub fn drand48() -> f32 {\n let random_float: f32 = rand::thread_rng().gen();\n random_float\n}\n\npub struct Camera {\n origin: Vec3,\n lower_left_corner: Vec3,\n vertical: Vec3,\n horizontal: Vec3,\n u: Vec3,\n v: Vec3,\n w: Vec3,\n lens_radius: f32,\n}\nimpl Camera {\n pub fn new(\n look_from: Vec3,\n look_at: Vec3,\n vup: Vec3,\n vfov: f32,\n aspect: f32,\n aperture: f32,\n focus_dist: f32,\n ) -> Self {\n let lens_radius = aperture / 2.0;\n let theta = vfov * std::f32::consts::PI / 180.0;\n let half_height = f32::tan(theta / 2.0);\n let half_width = aspect * half_height;\n let origin = look_from;\n let w = Vec3::make_unit_vector(look_from - look_at);\n let u = Vec3::make_unit_vector(Vec3::cross(vup, w));\n let v = Vec3::cross(w, u);\n let mut lower_left_corner = Vec3::new(-half_width, -half_height, -1.0);\n lower_left_corner =\n origin - half_width * focus_dist * u - half_height * focus_dist * v - focus_dist * w;\n let horizontal = 2.0 * half_width * focus_dist * u;\n let vertical = 2.0 * half_height * focus_dist * v;\n\n Camera {\n origin,\n lower_left_corner,\n horizontal,\n vertical,\n u,\n v,\n w,\n lens_radius,\n }\n }\n\n pub fn get_ray(&self, u: f32, v: f32) -> Ray {\n let rd: Vec3 = self.lens_radius * random_in_unit_sphere();\n let offset = self.u * rd.x() + self.v * rd.y();\n Ray::new(\n self.origin + offset,\n self.lower_left_corner + u * self.horizontal + v * self.vertical - self.origin - offset,\n )\n }\n}\n\nfn random_in_unit_sphere() -> Vec3 {\n let mut p: Vec3;\n while {\n p = 2.0 * Vec3::new(drand48(), drand48(), drand48()) - Vec3::new(1.0, 1.0, 1.0);\n p.squared_length() >= 1.0\n } {}\n return p;\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134664,"cells":{"blob_id":{"kind":"string","value":"3ad9cf2a4da9da9769e70303ba19564d0220c9e7"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"jps580393335/ThermalControl"},"path":{"kind":"string","value":"/dbtest/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":728,"string":"728"},"score":{"kind":"number","value":3.125,"string":"3.125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\nuse postgres::{Client, NoTls};\n\n\nfn main()\n{\n\tlet mut client = Client::connect(\"host=localhost user=postgres\", NoTls).unwrap();\n\n\tclient.batch_execute(\"\n \t\t\t\tCREATE TABLE person (\n \t\t\t\tid SERIAL PRIMARY KEY,\n \t\t\t\tname TEXT NOT NULL,\n \t\t\t\tdata BYTEA\n \t\t\t\t)\n\t\").unwrap();\n\n\tlet name = \"Ferris\";\n\tlet data = None::<&[u8]>;\n\tclient.execute(\n \t\t\t\"INSERT INTO person (name, data) VALUES ($1, $2)\",\n \t\t\t&[&name, &data],\n\t).unwrap();\n\n\tfor row in client.query(\"SELECT id, name, data FROM person\", &[]).unwrap() {\n \t\tlet id: i32 = row.get(0);\n \t\tlet name: &str = row.get(1);\n \t\tlet data: Option<&[u8]> = row.get(2);\n\n \t\tprintln!(\"found person: {} {} {:?}\", id, name, data);\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134665,"cells":{"blob_id":{"kind":"string","value":"ec848088f9da108179f4675907a37d9d00bf0d13"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Jaguar-515/foreman"},"path":{"kind":"string","value":"/src/auth_store.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1749,"string":"1,749"},"score":{"kind":"number","value":2.890625,"string":"2.890625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use std::io;\n\nuse serde::{Deserialize, Serialize};\nuse toml_edit::{value, Document};\n\nuse crate::{fs, paths};\n\npub static DEFAULT_AUTH_CONFIG: &str = include_str!(\"../resources/default-auth.toml\");\n\n/// Contains stored user tokens that Foreman can use to download tools.\n#[derive(Debug, Default, Serialize, Deserialize)]\npub struct AuthStore {\n pub github: Option,\n}\n\nimpl AuthStore {\n pub fn load() -> io::Result {\n log::debug!(\"Loading auth store...\");\n\n match fs::read(paths::auth_store()) {\n Ok(contents) => {\n let store: AuthStore = toml::from_slice(&contents).unwrap();\n\n if store.github.is_some() {\n log::debug!(\"Found GitHub credentials\");\n } else {\n log::debug!(\"Found no credentials\");\n }\n\n Ok(store)\n }\n Err(err) => {\n if err.kind() == io::ErrorKind::NotFound {\n return Ok(AuthStore::default());\n } else {\n return Err(err);\n }\n }\n }\n }\n\n pub fn set_github_token(token: &str) -> io::Result<()> {\n let contents = match fs::read_to_string(paths::auth_store()) {\n Ok(contents) => contents,\n Err(err) => {\n if err.kind() == io::ErrorKind::NotFound {\n DEFAULT_AUTH_CONFIG.to_owned()\n } else {\n return Err(err);\n }\n }\n };\n\n let mut store: Document = contents.parse().unwrap();\n store[\"github\"] = value(token);\n\n let serialized = store.to_string();\n fs::write(paths::auth_store(), serialized)\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134666,"cells":{"blob_id":{"kind":"string","value":"37413ae2a19fdc2faf49581d7a4ee92cf3b5171d"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Hizoul/tetris-link-research"},"path":{"kind":"string","value":"/src/heuristics/tune.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1924,"string":"1,924"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use crate::game_logic::field::{GameField};\r\nuse crate::game_logic::field::helper_structs::{GameRules};\r\nuse crate::game_logic::field::rl::LearnHelper;\r\nuse crate::game_logic::cache::ShapeCache;\r\nuse std::sync::{Arc,RwLock};\r\nuse rayon::prelude::*;\r\n\r\nconst SAMPLE_SIZE: u64 = 500;\r\nconst EVALUATED_PLAYER_NUMBER: i8 = 0;\r\nconst ENEMY_CONFIGS: [(f64, f64, f64, f64); 2] = [\r\n (4.95238700733393,0.115980839099051,0.0603795891552745,19.0148438477953),\r\n (2.29754304265925,0.714950690441259,0.0203784890483687,4.26915982151196)\r\n];\r\n\r\npub fn heuristic_evaluator(connectability_weight: f64, enemy_block_wheight: f64, touching_weight: f64, score_weight: f64) -> u64 {\r\n let mut final_score = 0;\r\n let shape_cache = Arc::new(ShapeCache::new());\r\n let wins_per_config: Vec = ENEMY_CONFIGS.par_iter().map(|weight_configuration| {\r\n let wins: RwLock = RwLock::new(0);\r\n (0..SAMPLE_SIZE).into_par_iter().for_each(|_| {\r\n let mut field = GameField::new_with_cache(2, shape_cache.clone(), GameRules::deterministic());\r\n while !field.game_over {\r\n let play_to_do = if field.current_player == EVALUATED_PLAYER_NUMBER {\r\n field.get_best_heuristic_play_for_params(connectability_weight, enemy_block_wheight, touching_weight, score_weight, true, 0)\r\n } else {\r\n field.get_best_heuristic_play_for_params(weight_configuration.0, weight_configuration.1, weight_configuration.2, weight_configuration.3, true, 0)\r\n };\r\n field.place_block_using_play(play_to_do);\r\n }\r\n if field.get_winning_player() == EVALUATED_PLAYER_NUMBER {\r\n let mut writeable_wins = wins.write().unwrap();\r\n *writeable_wins += 1;\r\n }\r\n });\r\n let readable_wins = wins.read().unwrap();\r\n *readable_wins\r\n }).collect();\r\n for win_amount in wins_per_config {\r\n if win_amount > (SAMPLE_SIZE / 4) {\r\n final_score += win_amount;\r\n }\r\n }\r\n final_score\r\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134667,"cells":{"blob_id":{"kind":"string","value":"de44602ccc26d48adaf913c73304cb953224bf19"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"iCodeIN/lin-rado-turing"},"path":{"kind":"string","value":"/src/types.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8278,"string":"8,278"},"score":{"kind":"number","value":3.25,"string":"3.25"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use crate::program::ProgramParseError;\nuse std::{fmt::Debug, str::FromStr};\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum Direction {\n Left,\n Right,\n}\n\nimpl FromStr for Direction {\n type Err = ProgramParseError;\n\n fn from_str(s: &str) -> Result {\n match s {\n \"L\" => Ok(Self::Left),\n \"R\" => Ok(Self::Right),\n s => Err(ProgramParseError::Error(format!(\n \"Expected 'L' or 'R', found {}\",\n s\n ))),\n }\n }\n}\n\npub trait State: Ord + Eq + FromStr + Copy + Debug {\n const NUM_STATES: usize;\n\n fn initial_state() -> Self;\n\n fn iter_states() -> Box>;\n\n fn halt() -> Self;\n}\n\npub trait Symbol: Ord + Eq + FromStr + Copy + Debug + ToString {\n const NUM: usize;\n\n fn iter_symbols() -> Box>;\n\n fn zero() -> Self;\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]\npub enum TwoState {\n A,\n B,\n H,\n}\n\nimpl FromStr for TwoState {\n type Err = ProgramParseError;\n\n fn from_str(s: &str) -> Result {\n match s {\n \"A\" => Ok(Self::A),\n \"B\" => Ok(Self::B),\n \"H\" => Ok(Self::H),\n a => Err(ProgramParseError::Error(format!(\n \"Expected 'A', 'B', 'H' not {}\",\n a\n ))),\n }\n }\n}\n\nimpl State for TwoState {\n const NUM_STATES: usize = 2;\n\n fn initial_state() -> Self {\n Self::A\n }\n\n fn iter_states() -> Box> {\n Box::new(vec![Self::A, Self::B].into_iter())\n }\n\n fn halt() -> Self {\n Self::H\n }\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]\npub enum ThreeState {\n A,\n B,\n C,\n H,\n}\n\nimpl FromStr for ThreeState {\n type Err = ProgramParseError;\n\n fn from_str(s: &str) -> Result {\n match s {\n \"A\" => Ok(Self::A),\n \"B\" => Ok(Self::B),\n \"C\" => Ok(Self::C),\n \"H\" => Ok(Self::H),\n a => Err(ProgramParseError::Error(format!(\n \"Expected 'A', 'B', 'C', or 'H', found {}\",\n a\n ))),\n }\n }\n}\n\nimpl State for ThreeState {\n const NUM_STATES: usize = 3;\n\n fn initial_state() -> Self {\n Self::A\n }\n\n fn iter_states() -> Box> {\n Box::new(vec![Self::A, Self::B, Self::C].into_iter())\n }\n\n fn halt() -> Self {\n Self::H\n }\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]\npub enum FourState {\n A,\n B,\n C,\n D,\n H,\n}\n\nimpl State for FourState {\n const NUM_STATES: usize = 4;\n\n fn initial_state() -> Self {\n Self::A\n }\n\n fn iter_states() -> Box> {\n Box::new(vec![Self::A, Self::B, Self::C, Self::D].into_iter())\n }\n\n fn halt() -> Self {\n Self::H\n }\n}\n\nimpl FromStr for FourState {\n type Err = ProgramParseError;\n\n fn from_str(s: &str) -> Result {\n match s {\n \"A\" => Ok(Self::A),\n \"B\" => Ok(Self::B),\n \"C\" => Ok(Self::C),\n \"D\" => Ok(Self::D),\n \"H\" => Ok(Self::H),\n a => Err(ProgramParseError::Error(format!(\n \"Expected 'A', 'B', 'C', 'D', 'H', found {}\",\n a\n ))),\n }\n }\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]\npub enum TwoSymbol {\n Zero,\n One,\n}\n\nimpl FromStr for TwoSymbol {\n type Err = ProgramParseError;\n\n fn from_str(s: &str) -> Result {\n match s {\n \"0\" => Ok(Self::Zero),\n \"1\" => Ok(Self::One),\n a => Err(ProgramParseError::Error(format!(\n \"Expected '0' or '1', found {}\",\n a\n ))),\n }\n }\n}\n\nimpl Symbol for TwoSymbol {\n const NUM: usize = 2;\n\n fn iter_symbols() -> Box> {\n Box::new(vec![Self::Zero, Self::One].into_iter())\n }\n\n fn zero() -> Self {\n Self::Zero\n }\n}\n\nimpl ToString for TwoSymbol {\n fn to_string(&self) -> String {\n match self {\n Self::One => \"#\",\n Self::Zero => \"_\",\n }\n .to_owned()\n }\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]\npub enum ThreeSymbol {\n Zero,\n One,\n Two,\n}\n\nimpl Symbol for ThreeSymbol {\n const NUM: usize = 3;\n\n fn iter_symbols() -> Box> {\n Box::new(vec![Self::Zero, Self::One, Self::Two].into_iter())\n }\n\n fn zero() -> Self {\n Self::Zero\n }\n}\n\nimpl ToString for ThreeSymbol {\n fn to_string(&self) -> String {\n match self {\n Self::Zero => \"0\",\n Self::One => \"1\",\n Self::Two => \"2\",\n }\n .to_owned()\n }\n}\n\nimpl FromStr for ThreeSymbol {\n type Err = ProgramParseError;\n\n fn from_str(s: &str) -> Result {\n match s {\n \"0\" => Ok(Self::Zero),\n \"1\" => Ok(Self::One),\n \"2\" => Ok(Self::Two),\n a => Err(ProgramParseError::Error(format!(\n \"Expected '0', '1', or '2', not {}\",\n a\n ))),\n }\n }\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]\npub enum FiveState {\n A,\n B,\n C,\n D,\n E,\n H,\n}\n\nimpl FromStr for FiveState {\n type Err = ProgramParseError;\n\n fn from_str(s: &str) -> Result {\n match s {\n \"A\" => Ok(Self::A),\n \"B\" => Ok(Self::B),\n \"C\" => Ok(Self::C),\n \"D\" => Ok(Self::D),\n \"E\" => Ok(Self::E),\n \"H\" => Ok(Self::H),\n a => Err(ProgramParseError::Error(format!(\n \"Expecting 'A', 'B', 'C', 'D', 'E', or 'H', not {}\",\n a\n ))),\n }\n }\n}\n\nimpl State for FiveState {\n const NUM_STATES: usize = 5;\n\n fn initial_state() -> Self {\n Self::A\n }\n\n fn iter_states() -> Box> {\n Box::new(vec![Self::A, Self::B, Self::C, Self::D, Self::E].into_iter())\n }\n\n fn halt() -> Self {\n Self::H\n }\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]\npub enum SixState {\n A,\n B,\n C,\n D,\n E,\n F,\n H,\n}\n\nimpl FromStr for SixState {\n type Err = ProgramParseError;\n\n fn from_str(s: &str) -> Result {\n match s {\n \"A\" => Ok(Self::A),\n \"B\" => Ok(Self::B),\n \"C\" => Ok(Self::C),\n \"D\" => Ok(Self::D),\n \"E\" => Ok(Self::E),\n \"F\" => Ok(Self::F),\n \"H\" => Ok(Self::H),\n a => Err(ProgramParseError::Error(format!(\n \"Expecting 'A', 'B', 'C', 'D', 'E', or 'H', not {}\",\n a\n ))),\n }\n }\n}\n\nimpl State for SixState {\n const NUM_STATES: usize = 5;\n\n fn initial_state() -> Self {\n Self::A\n }\n\n fn iter_states() -> Box> {\n Box::new(vec![Self::A, Self::B, Self::C, Self::D, Self::E, Self::F].into_iter())\n }\n\n fn halt() -> Self {\n Self::H\n }\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]\npub enum FourSymbol {\n Zero,\n One,\n Two,\n Three,\n}\n\nimpl Symbol for FourSymbol {\n const NUM: usize = 3;\n\n fn iter_symbols() -> Box> {\n Box::new(vec![Self::Zero, Self::One, Self::Two, Self::Three].into_iter())\n }\n\n fn zero() -> Self {\n Self::Zero\n }\n}\n\nimpl FromStr for FourSymbol {\n type Err = ProgramParseError;\n\n fn from_str(s: &str) -> Result {\n match s {\n \"0\" => Ok(Self::Zero),\n \"1\" => Ok(Self::One),\n \"2\" => Ok(Self::Two),\n \"3\" => Ok(Self::Three),\n a => Err(ProgramParseError::Error(format!(\n \"Expected '0', '1', or '2', not {}\",\n a\n ))),\n }\n }\n}\n\nimpl ToString for FourSymbol {\n fn to_string(&self) -> String {\n match self {\n Self::Zero => \"0\",\n Self::One => \"1\",\n Self::Two => \"2\",\n Self::Three => \"3\",\n }\n .to_owned()\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134668,"cells":{"blob_id":{"kind":"string","value":"c7358a6987f53f4e0de4be0d849dbcd306104e2a"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Connicpu/directx-rs"},"path":{"kind":"string","value":"/dcommon/src/idltypes/bstr.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1493,"string":"1,493"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use winapi::shared::wtypes::BSTR;\n\n#[repr(transparent)]\npub struct BStr {\n bstr: BSTR,\n}\n\nimpl BStr {\n pub fn new(s: &str) -> BStr {\n let len = s.encode_utf16().count();\n assert!(len <= std::u32::MAX as usize);\n\n unsafe {\n let bstr = SysAllocStringLen(0 as _, len as u32);\n let slice = std::slice::from_raw_parts_mut(bstr, len);\n\n for (dst, src) in slice.iter_mut().zip(s.encode_utf16()) {\n *dst = src;\n }\n\n BStr { bstr }\n }\n }\n\n pub unsafe fn from_raw(bstr: BSTR) -> Self {\n assert!(!bstr.is_null());\n BStr { bstr }\n }\n\n pub unsafe fn get_raw(&self) -> BSTR {\n self.bstr\n }\n\n pub unsafe fn into_raw(self) -> BSTR {\n let bstr = self.get_raw();\n std::mem::forget(self);\n bstr\n }\n\n pub fn len(&self) -> usize {\n unsafe { SysStringLen(self.bstr) as usize }\n }\n\n pub fn as_slice(&self) -> &[u16] {\n unsafe { std::slice::from_raw_parts(self.bstr, self.len()) }\n }\n}\n\nimpl PartialEq for BStr {\n fn eq(&self, other: &BStr) -> bool {\n self.as_slice() == other.as_slice()\n }\n}\n\nimpl Drop for BStr {\n fn drop(&mut self) {\n unsafe {\n let hr = SysFreeString(self.bstr);\n assert!(hr >= 0);\n }\n }\n}\n\nextern \"system\" {\n fn SysAllocStringLen(str_in: *const u16, ui: u32) -> BSTR;\n fn SysFreeString(b: BSTR) -> i32;\n\n fn SysStringLen(b: BSTR) -> u32;\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134669,"cells":{"blob_id":{"kind":"string","value":"009cca9275888aadfbcf258960fc9adb127afe13"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"yayoc/leetcode"},"path":{"kind":"string","value":"/src/longest_common_prefix.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1771,"string":"1,771"},"score":{"kind":"number","value":3.78125,"string":"3.78125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// Write a function to find the longest common prefix string amongst an array of strings.\n//\n// If there is no common prefix, return an empty string \"\".\n//\n// Example 1:\n//\n// Input: [\"flower\",\"flow\",\"flight\"]\n// Output: \"fl\"\n//\n// Example 2:\n//\n// Input: [\"dog\",\"racecar\",\"car\"]\n// Output: \"\"\n// Explanation: There is no common prefix among the input strings.\n//\n// Note:\n//\n// All given inputs are in lowercase letters a-z.\n\npub struct Solution1;\n\npub trait Solution {\n fn longest_common_prefix(strs: Vec) -> String;\n}\n\nimpl Solution for Solution1 {\n fn longest_common_prefix(strs: Vec) -> String {\n if strs.len() == 0 {\n return String::from(\"\");\n }\n let min_len = strs.iter().map(|s| s.len()).min().unwrap();\n for i in 0..min_len {\n let ch = strs[0].chars().nth(i).unwrap();\n\n for s in &strs {\n if s.chars().nth(i).unwrap() != ch {\n return s[0..i].to_string();\n }\n }\n }\n strs[0][0..min_len].to_string()\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_longest_common_prefix() {\n assert_eq!(\n \"fl\",\n Solution1::longest_common_prefix(vec!(\n String::from(\"flower\"),\n String::from(\"flow\"),\n String::from(\"flight\")\n ))\n );\n assert_eq!(\n \"\",\n Solution1::longest_common_prefix(vec!(\n String::from(\"dog\"),\n String::from(\"racecar\"),\n String::from(\"car\")\n ))\n );\n assert_eq!(\n \"\",\n Solution1::longest_common_prefix(vec!(String::from(\"aca\"), String::from(\"cba\")))\n )\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134670,"cells":{"blob_id":{"kind":"string","value":"08242f971d3f15e9763cc02f6269ceb5dbc2795c"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"poita66/lsd"},"path":{"kind":"string","value":"/src/flags/color.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6993,"string":"6,993"},"score":{"kind":"number","value":3.59375,"string":"3.59375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"//! This module defines the [Color]. To set it up from [ArgMatches], a [Yaml] and its [Default]\n//! value, use its [configure_from](Configurable::configure_from) method.\n\nuse super::Configurable;\n\nuse crate::config_file::Config;\n\nuse clap::ArgMatches;\nuse yaml_rust::Yaml;\n\n/// A collection of flags on how to use colors.\n#[derive(Clone, Debug, Copy, PartialEq, Eq, Default)]\npub struct Color {\n /// When to use color.\n pub when: ColorOption,\n}\n\nimpl Color {\n /// Get a `Color` struct from [ArgMatches], a [Config] or the [Default] values.\n ///\n /// The [ColorOption] is configured with their respective [Configurable] implementation.\n pub fn configure_from(matches: &ArgMatches, config: &Config) -> Self {\n let when = ColorOption::configure_from(matches, config);\n Self { when }\n }\n}\n\n/// The flag showing when to use colors in the output.\n#[derive(Clone, Debug, Copy, PartialEq, Eq)]\npub enum ColorOption {\n Always,\n Auto,\n Never,\n}\n\nimpl ColorOption {\n /// Get a Color value from a [Yaml] string. The [Config] is used to log warnings about wrong\n /// values in a Yaml.\n fn from_yaml_string(value: &str, config: &Config) -> Option {\n match value {\n \"always\" => Some(Self::Always),\n \"auto\" => Some(Self::Auto),\n \"never\" => Some(Self::Never),\n _ => {\n config.print_invalid_value_warning(\"color->when\", &value);\n None\n }\n }\n }\n}\n\nimpl Configurable for ColorOption {\n /// Get a potential `ColorOption` variant from [ArgMatches].\n ///\n /// If the \"classic\" argument is passed, then this returns the [ColorOption::Never] variant in\n /// a [Some]. Otherwise if the argument is passed, this returns the variant corresponding to\n /// its parameter in a [Some]. Otherwise this returns [None].\n fn from_arg_matches(matches: &ArgMatches) -> Option {\n if matches.is_present(\"classic\") {\n Some(Self::Never)\n } else if matches.occurrences_of(\"color\") > 0 {\n match matches.value_of(\"color\") {\n Some(\"always\") => Some(Self::Always),\n Some(\"auto\") => Some(Self::Auto),\n Some(\"never\") => Some(Self::Never),\n _ => panic!(\"This should not be reachable!\"),\n }\n } else {\n None\n }\n }\n\n /// Get a potential `ColorOption` variant from a [Config].\n ///\n /// If the Config's [Yaml] contains a [Boolean](Yaml::Boolean) value pointed to by \"classic\"\n /// and its value is `true`, then this returns the [ColorOption::Never] variant in a [Some].\n /// Otherwise if the Yaml contains a [String](Yaml::String) value pointed to by \"color\" ->\n /// \"when\" and it is one of \"always\", \"auto\" or \"never\", this returns its corresponding variant\n /// in a [Some]. Otherwise this returns [None].\n fn from_config(config: &Config) -> Option {\n if let Some(yaml) = &config.yaml {\n if let Yaml::Boolean(true) = &yaml[\"classic\"] {\n Some(Self::Never)\n } else {\n match &yaml[\"color\"][\"when\"] {\n Yaml::BadValue => None,\n Yaml::String(value) => Self::from_yaml_string(&value, &config),\n _ => {\n config.print_wrong_type_warning(\"color->when\", \"string\");\n None\n }\n }\n }\n } else {\n None\n }\n }\n}\n\n/// The default value for `ColorOption` is [ColorOption::Auto].\nimpl Default for ColorOption {\n fn default() -> Self {\n Self::Auto\n }\n}\n\n#[cfg(test)]\nmod test_color_option {\n use super::ColorOption;\n\n use crate::app;\n use crate::config_file::Config;\n use crate::flags::Configurable;\n\n use yaml_rust::YamlLoader;\n\n #[test]\n fn test_from_arg_matches_none() {\n let argv = vec![\"lsd\"];\n let matches = app::build().get_matches_from_safe(argv).unwrap();\n assert_eq!(None, ColorOption::from_arg_matches(&matches));\n }\n\n #[test]\n fn test_from_arg_matches_always() {\n let argv = vec![\"lsd\", \"--color\", \"always\"];\n let matches = app::build().get_matches_from_safe(argv).unwrap();\n assert_eq!(\n Some(ColorOption::Always),\n ColorOption::from_arg_matches(&matches)\n );\n }\n\n #[test]\n fn test_from_arg_matches_autp() {\n let argv = vec![\"lsd\", \"--color\", \"auto\"];\n let matches = app::build().get_matches_from_safe(argv).unwrap();\n assert_eq!(\n Some(ColorOption::Auto),\n ColorOption::from_arg_matches(&matches)\n );\n }\n\n #[test]\n fn test_from_arg_matches_never() {\n let argv = vec![\"lsd\", \"--color\", \"never\"];\n let matches = app::build().get_matches_from_safe(argv).unwrap();\n assert_eq!(\n Some(ColorOption::Never),\n ColorOption::from_arg_matches(&matches)\n );\n }\n\n #[test]\n fn test_from_arg_matches_classic_mode() {\n let argv = vec![\"lsd\", \"--color\", \"always\", \"--classic\"];\n let matches = app::build().get_matches_from_safe(argv).unwrap();\n assert_eq!(\n Some(ColorOption::Never),\n ColorOption::from_arg_matches(&matches)\n );\n }\n\n #[test]\n fn test_from_config_none() {\n assert_eq!(None, ColorOption::from_config(&Config::with_none()));\n }\n\n #[test]\n fn test_from_config_empty() {\n let yaml_string = \"---\";\n let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone();\n assert_eq!(None, ColorOption::from_config(&Config::with_yaml(yaml)));\n }\n\n #[test]\n fn test_from_config_always() {\n let yaml_string = \"color:\\n when: always\";\n let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone();\n assert_eq!(\n Some(ColorOption::Always),\n ColorOption::from_config(&Config::with_yaml(yaml))\n );\n }\n\n #[test]\n fn test_from_config_auto() {\n let yaml_string = \"color:\\n when: auto\";\n let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone();\n assert_eq!(\n Some(ColorOption::Auto),\n ColorOption::from_config(&Config::with_yaml(yaml))\n );\n }\n\n #[test]\n fn test_from_config_never() {\n let yaml_string = \"color:\\n when: never\";\n let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone();\n assert_eq!(\n Some(ColorOption::Never),\n ColorOption::from_config(&Config::with_yaml(yaml))\n );\n }\n\n #[test]\n fn test_from_config_classic_mode() {\n let yaml_string = \"classic: true\\ncolor:\\n when: always\";\n let yaml = YamlLoader::load_from_str(yaml_string).unwrap()[0].clone();\n assert_eq!(\n Some(ColorOption::Never),\n ColorOption::from_config(&Config::with_yaml(yaml))\n );\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134671,"cells":{"blob_id":{"kind":"string","value":"395be840d336975394316e79b1ca4fd08ee596a4"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"iCodeIN/srv"},"path":{"kind":"string","value":"/src/ui/info.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":20612,"string":"20,612"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use std::{collections::HashMap, fmt, fmt::Write, sync::Arc};\n\nuse screeps_api::websocket::{\n objects::{\n ConstructionSite, Creep, KnownRoomObject, Mineral, Resource, Source, StructureContainer,\n StructureController, StructureExtension, StructureExtractor, StructureKeeperLair,\n StructureLab, StructureLink, StructureNuker, StructureObserver, StructurePortal,\n StructurePowerBank, StructurePowerSpawn, StructureRampart, StructureRoad, StructureSpawn,\n StructureStorage, StructureTerminal, StructureTower, StructureWall, Tombstone,\n },\n resources::ResourceType,\n RoomUserInfo,\n};\n\nuse crate::room::{RoomObjectType, VisualObject};\n\npub fn info(thing: &T, state: &InfoInfo) -> String {\n let mut res = String::new();\n thing\n .fmt(&mut res, state)\n .expect(\"formatting to string should not fail\");\n res\n}\n\n#[derive(Copy, Clone)]\npub struct InfoInfo<'a> {\n game_time: u32,\n users: &'a HashMap>,\n}\n\nimpl<'a> InfoInfo<'a> {\n pub fn new(game_time: u32, users: &'a HashMap>) -> Self {\n InfoInfo { game_time, users }\n }\n\n fn username(&self, id: &str) -> Option<&'a str> {\n self.users\n .get(id)\n .and_then(|i| i.username.as_ref())\n .map(AsRef::as_ref)\n }\n\n fn username_or_fallback<'b>(&self, id: &'b str) -> OptionalUser<'b, 'a> {\n OptionalUser {\n id,\n username: self.username(id),\n }\n }\n}\n\nstruct OptionalUser<'a, 'b> {\n id: &'a str,\n username: Option<&'b str>,\n}\n\nimpl fmt::Display for OptionalUser<'_, '_> {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n match self.username {\n Some(u) => write!(f, \"{}\", u),\n None => write!(f, \"user {}\", self.id),\n }\n }\n}\n\npub trait Info {\n /// Formats self, including a trailing newline\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result;\n}\n\nimpl Info for [T] {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n for obj in self {\n obj.fmt(out, state)?;\n }\n Ok(())\n }\n}\n\nimpl Info for Vec {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n // defer to [T]\n self[..].fmt(out, state)\n }\n}\n\nimpl Info for VisualObject {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n match self {\n VisualObject::InterestingTerrain { ty, .. } => writeln!(out, \"terrain: {}\", ty),\n VisualObject::Flag(f) => writeln!(out, \"flag {}\", f.name),\n VisualObject::RoomObject(obj) => obj.fmt(out, state),\n }\n }\n}\n\nimpl Info for KnownRoomObject {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n match self {\n KnownRoomObject::Source(o) => o.fmt(out, state),\n KnownRoomObject::Mineral(o) => o.fmt(out, state),\n KnownRoomObject::Spawn(o) => o.fmt(out, state),\n KnownRoomObject::Extension(o) => o.fmt(out, state),\n KnownRoomObject::Extractor(o) => o.fmt(out, state),\n KnownRoomObject::Wall(o) => o.fmt(out, state),\n KnownRoomObject::Road(o) => o.fmt(out, state),\n KnownRoomObject::Rampart(o) => o.fmt(out, state),\n KnownRoomObject::KeeperLair(o) => o.fmt(out, state),\n KnownRoomObject::Controller(o) => o.fmt(out, state),\n KnownRoomObject::Portal(o) => o.fmt(out, state),\n KnownRoomObject::Link(o) => o.fmt(out, state),\n KnownRoomObject::Storage(o) => o.fmt(out, state),\n KnownRoomObject::Tower(o) => o.fmt(out, state),\n KnownRoomObject::Observer(o) => o.fmt(out, state),\n KnownRoomObject::PowerBank(o) => o.fmt(out, state),\n KnownRoomObject::PowerSpawn(o) => o.fmt(out, state),\n KnownRoomObject::Lab(o) => o.fmt(out, state),\n KnownRoomObject::Terminal(o) => o.fmt(out, state),\n KnownRoomObject::Container(o) => o.fmt(out, state),\n KnownRoomObject::Nuker(o) => o.fmt(out, state),\n KnownRoomObject::Tombstone(o) => o.fmt(out, state),\n KnownRoomObject::Creep(o) => o.fmt(out, state),\n KnownRoomObject::Resource(o) => o.fmt(out, state),\n KnownRoomObject::ConstructionSite(o) => o.fmt(out, state),\n other => {\n let ty = RoomObjectType::of(&other);\n let ty = string_morph::to_kebab_case(&format!(\"{:?}\", ty));\n writeln!(out, \"{} {}\", ty, other.id())?;\n Ok(())\n }\n }\n }\n}\n\nimpl Info for Source {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n writeln!(out, \"source:\")?;\n fmt_id(out, &self.id)?;\n fmt_energy(out, self.energy, self.energy_capacity as i32)?;\n if self.energy != self.energy_capacity {\n if let Some(gen_time) = self.next_regeneration_time {\n writeln!(out, \" regen in: {}\", gen_time - state.game_time)?;\n }\n }\n Ok(())\n }\n}\n\nimpl Info for Mineral {\n fn fmt(&self, out: &mut W, _state: &InfoInfo) -> fmt::Result {\n writeln!(\n out,\n \"mineral: {} {}\",\n self.mineral_amount,\n kebab_of_debug(self.mineral_type)\n )?;\n fmt_id(out, &self.id)?;\n Ok(())\n }\n}\n\nimpl Info for StructureSpawn {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_user_prefix(out, &self.user, state)?;\n writeln!(out, \"spawn {}:\", self.room)?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n fmt_disabled(out, self.disabled)?;\n fmt_energy(out, self.energy, self.energy_capacity)?;\n Ok(())\n }\n}\n\nimpl Info for StructureExtension {\n fn fmt(&self, out: &mut W, _state: &InfoInfo) -> fmt::Result {\n writeln!(out, \"extension:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n fmt_disabled(out, self.disabled)?;\n fmt_energy(out, self.energy, self.energy_capacity)?;\n Ok(())\n }\n}\n\nimpl Info for StructureExtractor {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_optional_user_prefix(out, &self.user, state)?;\n writeln!(out, \"extractor:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n fmt_disabled(out, self.disabled)?;\n Ok(())\n }\n}\n\nimpl Info for StructureWall {\n fn fmt(&self, out: &mut W, _state: &InfoInfo) -> fmt::Result {\n writeln!(out, \"wall:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits_inf(out, self.hits, self.hits_max)?;\n Ok(())\n }\n}\n\nimpl Info for StructureRoad {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n writeln!(out, \"road:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n writeln!(out, \" decay in: {}\", self.next_decay_time - state.game_time)?;\n Ok(())\n }\n}\n\nimpl Info for StructureRampart {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_user_prefix(out, &self.user, state)?;\n writeln!(out, \"rampart:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits_inf(out, self.hits, self.hits_max)?;\n writeln!(out, \" decay in: {}\", self.next_decay_time - state.game_time)?;\n if self.public {\n writeln!(out, \" --public--\")?;\n } else {\n writeln!(out, \" --private--\")?;\n }\n Ok(())\n }\n}\n\nimpl Info for StructureKeeperLair {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n writeln!(out, \"keeper lair:\")?;\n fmt_id(out, &self.id)?;\n if let Some(spawn_time) = self.next_spawn_time {\n writeln!(out, \" spawning in: {}\", spawn_time - state.game_time)?;\n }\n Ok(())\n }\n}\n\nimpl Info for StructureController {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_optional_user_prefix(out, &self.user, state)?;\n writeln!(out, \"controller:\")?;\n fmt_id(out, &self.id)?;\n if let Some(sign) = &self.sign {\n write!(\n out,\n \"{}\",\n textwrap::indent(&textwrap::fill(&sign.text, 30), \" \")\n )?;\n // TODO: real time?\n writeln!(\n out,\n \" - {} ({} ticks ago)\",\n state.username_or_fallback(&sign.user_id),\n i64::from(state.game_time) - i64::from(sign.game_time_set)\n )?;\n }\n if self.user.is_some() {\n writeln!(out, \" level: {}\", self.level)?;\n if let Some(required) = self.progress_required() {\n let progress_percent =\n (required as f64 - self.progress as f64) / required as f64 * 100.0;\n writeln!(out, \" progress: %{:.2}\", progress_percent)?;\n }\n // TODO: red text for almost downgraded\n if let Some(time) = self.downgrade_time {\n // TODO: see what this data looks like?\n writeln!(out, \" downgrade time: {}\", time)?;\n }\n // TODO: only apply this to owned controllers, maybe?\n writeln!(out, \" safemode:\")?;\n if let Some(end_time) = self.safe_mode {\n if state.game_time < end_time {\n writeln!(out, \" --safe mode active--\")?;\n writeln!(out, \" ends in: {}\", end_time - state.game_time)?;\n }\n }\n writeln!(out, \" available: {}\", self.safe_mode_available)?;\n if self.safe_mode_cooldown > state.game_time {\n writeln!(\n out,\n \" activation cooldown: {}\",\n self.safe_mode_cooldown - state.game_time\n )?;\n }\n }\n if let Some(reservation) = &self.reservation {\n if reservation.end_time > state.game_time {\n writeln!(\n out,\n \" reserved by {}\",\n state.username_or_fallback(&reservation.user)\n )?;\n writeln!(out, \" ends in {}\", reservation.end_time - state.game_time)?;\n }\n }\n Ok(())\n }\n}\n\nimpl Info for StructurePortal {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_id(out, &self.id)?;\n writeln!(\n out,\n \"portal -> {},{} in {}\",\n self.destination.x, self.destination.y, self.destination.room\n )?;\n if let Some(_date) = self.unstable_date {\n // TODO: figure out time formatting\n writeln!(out, \" stable (decay time is in days)\")?;\n writeln!(out, \" (time formatting unimplemented)\")?;\n }\n if let Some(time) = self.decay_time {\n writeln!(out, \" decays in {} ticks\", time - state.game_time)?;\n }\n Ok(())\n }\n}\n\nimpl Info for StructureLink {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_user_prefix(out, &self.user, state)?;\n writeln!(out, \"link:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n fmt_disabled(out, self.disabled)?;\n fmt_energy(out, self.energy, self.energy_capacity)?;\n if self.cooldown != 0 {\n writeln!(out, \" cooldown: {}\", self.cooldown)?;\n }\n Ok(())\n }\n}\n\nimpl Info for StructureStorage {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_user_prefix(out, &self.user, state)?;\n writeln!(out, \"storage:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n fmt_disabled(out, self.disabled)?;\n writeln!(\n out,\n \" capacity: {}/{}\",\n self.resources().map(|(_, amt)| amt).sum::(),\n self.capacity\n )?;\n format_object_contents(out, self.resources())?;\n Ok(())\n }\n}\n\nimpl Info for StructureTower {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_user_prefix(out, &self.user, state)?;\n writeln!(out, \"tower:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n fmt_disabled(out, self.disabled)?;\n fmt_energy(out, self.energy, self.energy_capacity)?;\n Ok(())\n }\n}\n\nimpl Info for StructureObserver {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_user_prefix(out, &self.user, state)?;\n writeln!(out, \"observer:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n fmt_disabled(out, self.disabled)?;\n if let Some(name) = self.observed {\n writeln!(out, \" observing {}\", name)?;\n }\n Ok(())\n }\n}\n\nimpl Info for StructurePowerBank {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n writeln!(out, \"power bank:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n writeln!(out, \" power: {}\", self.power)?;\n writeln!(out, \" decay in: {}\", self.decay_time - state.game_time)?;\n Ok(())\n }\n}\n\nimpl Info for StructurePowerSpawn {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_user_prefix(out, &self.user, state)?;\n writeln!(out, \"power spawn:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n fmt_disabled(out, self.disabled)?;\n fmt_energy(out, self.energy, self.energy_capacity)?;\n writeln!(out, \" power: {}/{}\", self.power, self.power_capacity)?;\n Ok(())\n }\n}\n\nimpl Info for StructureLab {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_user_prefix(out, &self.user, state)?;\n writeln!(out, \"lab:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n fmt_disabled(out, self.disabled)?;\n fmt_energy(out, self.energy, self.energy_capacity)?;\n match self.mineral_type {\n Some(ty) => {\n writeln!(\n out,\n \" {}: {}/{}\",\n kebab_of_debug(ty),\n self.mineral_amount,\n self.mineral_capacity\n )?;\n }\n None => {\n writeln!(\n out,\n \" minerals: {}/{}\",\n self.mineral_amount, self.mineral_capacity\n )?;\n }\n }\n if self.cooldown != 0 {\n writeln!(out, \" cooldown: {}\", self.cooldown)?;\n }\n Ok(())\n }\n}\n\nimpl Info for StructureTerminal {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_user_prefix(out, &self.user, state)?;\n writeln!(out, \"terminal:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n fmt_disabled(out, self.disabled)?;\n writeln!(\n out,\n \" capacity: {}/{}\",\n self.resources().map(|(_, amt)| amt).sum::(),\n self.capacity\n )?;\n format_object_contents(out, self.resources())?;\n Ok(())\n }\n}\n\nimpl Info for StructureContainer {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n writeln!(out, \"container:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n writeln!(out, \" decay in: {}\", self.next_decay_time - state.game_time)?;\n writeln!(\n out,\n \" capacity: {}/{}\",\n self.resources().map(|(_, amt)| amt).sum::(),\n self.capacity\n )?;\n format_object_contents(out, self.resources())?;\n Ok(())\n }\n}\n\nimpl Info for StructureNuker {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_user_prefix(out, &self.user, state)?;\n writeln!(out, \"nuker:\")?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n fmt_disabled(out, self.disabled)?;\n fmt_energy(out, self.energy, self.energy_capacity as i32)?;\n writeln!(out, \" ghodium: {}/{}\", self.ghodium, self.ghodium_capacity)?;\n if self.cooldown_time < state.game_time {\n writeln!(out, \" --ready--\")?;\n } else {\n writeln!(out, \" cooldown: {}\", self.cooldown_time - state.game_time)?;\n }\n Ok(())\n }\n}\n\nimpl Info for Tombstone {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_user_prefix(out, &self.user, state)?;\n writeln!(out, \"tombstone:\")?;\n fmt_id(out, &self.id)?;\n writeln!(out, \" died: {}\", state.game_time - self.death_time)?;\n writeln!(out, \" decay: {}\", self.decay_time - state.game_time)?;\n writeln!(out, \" creep:\")?;\n writeln!(out, \" id: {}\", self.creep_id)?;\n writeln!(out, \" name: {}\", self.creep_name)?;\n writeln!(out, \" ttl: {}\", self.creep_ticks_to_live)?;\n format_object_contents(out, self.resources())?;\n Ok(())\n }\n}\n\nimpl Info for Creep {\n fn fmt(&self, out: &mut W, state: &InfoInfo) -> fmt::Result {\n fmt_user_prefix(out, &self.user, state)?;\n writeln!(out, \"creep {}:\", self.name)?;\n fmt_id(out, &self.id)?;\n fmt_hits(out, self.hits, self.hits_max)?;\n if self.fatigue != 0 {\n writeln!(out, \" fatigue: {}\", self.fatigue)?;\n }\n if let Some(age_time) = self.age_time {\n writeln!(out, \" life: {}\", age_time - state.game_time)?;\n }\n if self.capacity > 0 {\n writeln!(\n out,\n \" capacity: {}/{}\",\n self.carry_contents().map(|(_, amt)| amt).sum::(),\n self.capacity\n )?;\n format_object_contents(out, self.carry_contents())?;\n }\n\n Ok(())\n }\n}\n\nimpl Info for Resource {\n fn fmt(&self, out: &mut W, _state: &InfoInfo) -> fmt::Result {\n writeln!(\n out,\n \"dropped: {} {}\",\n self.amount,\n kebab_of_debug(self.resource_type)\n )?;\n Ok(())\n }\n}\n\nimpl Info for ConstructionSite {\n fn fmt(&self, out: &mut W, _state: &InfoInfo) -> fmt::Result {\n writeln!(\n out,\n \"constructing {}:\",\n kebab_of_debug(&self.structure_type)\n )?;\n writeln!(out, \" progress: {}/{}\", self.progress, self.progress_total)?;\n if let Some(name) = &self.name {\n writeln!(out, \" name: {}\", name)?;\n }\n Ok(())\n }\n}\n\nfn fmt_optional_user_prefix(\n out: &mut W,\n user_id: &Option,\n state: &InfoInfo,\n) -> fmt::Result {\n if let Some(user_id) = user_id {\n fmt_user_prefix(out, user_id, state)?;\n }\n\n Ok(())\n}\n\nfn fmt_user_prefix(out: &mut W, user_id: &str, state: &InfoInfo) -> fmt::Result {\n write!(out, \"[{}] \", state.username_or_fallback(user_id))\n}\n\nfn fmt_id(out: &mut W, id: &str) -> fmt::Result {\n writeln!(out, \" id: {}\", id)\n}\n\nfn fmt_hits(out: &mut W, hits: i32, hits_max: i32) -> fmt::Result {\n writeln!(out, \" hits: {}/{}\", hits, hits_max)\n}\n\nfn fmt_hits_inf(out: &mut W, hits: i32, hits_max: i32) -> fmt::Result {\n if f64::from(hits) > f64::from(hits_max) * 0.9 {\n fmt_hits(out, hits, hits_max)\n } else {\n writeln!(out, \"hits: {}\", hits)\n }\n}\n\nfn fmt_energy(out: &mut W, energy: i32, energy_capacity: i32) -> fmt::Result {\n writeln!(out, \" energy: {}/{}\", energy, energy_capacity)\n}\n\nfn fmt_disabled(out: &mut W, disabled: bool) -> fmt::Result {\n if disabled {\n writeln!(out, \" --disabled--\")?;\n }\n Ok(())\n}\n\nfn kebab_of_debug(item: T) -> String {\n string_morph::to_kebab_case(&format!(\"{:?}\", item))\n}\n\nfn format_object_contents(out: &mut W, contents: T) -> fmt::Result\nwhere\n W: fmt::Write,\n T: Iterator,\n{\n for (ty, amount) in contents {\n if amount > 0 {\n writeln!(out, \" {}: {}\", kebab_of_debug(ty), amount)?;\n }\n }\n Ok(())\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134672,"cells":{"blob_id":{"kind":"string","value":"c03883aed6f89bf5c0a12751f54b21648fe4ce27"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"TurkeyMcMac/vec-rac"},"path":{"kind":"string","value":"/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7676,"string":"7,676"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"extern crate getopts;\nextern crate rayon;\n\nuse getopts::Options;\nuse rayon::{prelude::*, ThreadPoolBuilder};\nuse std::env;\nuse std::iter;\nuse std::process;\nuse std::str::FromStr;\nuse std::sync::mpsc;\nuse std::thread;\nuse std::time::{Duration, SystemTime};\nuse vec_rac::brain::Brain;\nuse vec_rac::racetrack::Racetrack;\nuse vec_rac::rng::Rng;\nuse vec_rac::vector::Vector;\n\nfn options() -> Options {\n let mut opts = Options::new();\n opts.optflag(\"h\", \"help\", \"Print this help information.\");\n opts.optflag(\"v\", \"version\", \"Print version information.\");\n opts.optopt(\n \"\",\n \"view-dist\",\n \"Set how far a racer can see in each cardinal direction. This is a positive integer. The default is 20. This cannot be more than display-dist.\",\n \"DISTANCE\",\n );\n opts.optopt(\n \"\",\n \"display-dist\",\n \"Set how far you can see in each cardinal direction. This is a positive integer. The default is 20. This cannot be less than view-dist.\",\n \"DISTANCE\",\n );\n opts.optopt(\n \"\",\n \"path-radius\",\n \"Set track path radius. This is a positive integer. The default is 4.\",\n \"RADIUS\",\n );\n opts.optopt(\n \"\",\n \"seed\",\n \"Set random seed to use. This is a positive integer. The default is decided randomly.\",\n \"SEED\",\n );\n opts.optopt(\n \"\",\n \"population\",\n \"Set genome population size. This is a positive integer. It may be rounded a bit. The default is 10.\",\n \"SIZE\",\n );\n opts.optopt(\n \"\",\n \"mutation\",\n \"Set mutation rate, a positive decimal. The default is 0.05.\",\n \"RATE\",\n );\n opts.optopt(\n \"\",\n \"testing-threads\",\n \"Set the number of threads to use to continuously test AIs. This is a positive integer. The default is probably the number of cores the computer has.\",\n \"COUNT\",\n );\n opts\n}\n\nfn print_help(opts: &Options) -> String {\n let name = env::args().nth(0).unwrap_or(\"(anonymous)\".to_string());\n format!(\n \"{}\\n\\n{}\\n\",\n opts.short_usage(&name),\n opts.usage(\"Simulate vector racers.\")\n )\n}\n\nfn main() {\n let opts = options();\n let matches = opts.parse(env::args()).unwrap_or_else(|err| {\n eprint!(\"{}\\n\\n{}\", err, print_help(&opts));\n process::exit(1)\n });\n if matches.opt_present(\"help\") {\n print!(\"{}\", print_help(&opts));\n process::exit(0);\n } else if matches.opt_present(\"version\") {\n println!(\"vec-rac version 0.4.2\");\n process::exit(0);\n }\n let view_dist = matches\n .opt_str(\"view-dist\")\n .and_then(|arg| i32::from_str(&arg).ok());\n let display_dist = matches\n .opt_str(\"display-dist\")\n .and_then(|arg| i32::from_str(&arg).ok());\n let (view_dist, display_dist) = match (view_dist, display_dist) {\n (Some(v), Some(d)) => (v, i32::max(v, d)),\n (Some(v), None) => (v, v),\n (None, Some(d)) => (d, d),\n (None, None) => (20, 20),\n };\n let view_dist = i32::max(1, view_dist);\n let display_dist = i32::max(1, display_dist);\n let path_radius = matches\n .opt_str(\"path-radius\")\n .and_then(|arg| i32::from_str(&arg).ok())\n .unwrap_or(4);\n let seed = matches\n .opt_str(\"seed\")\n .and_then(|arg| u64::from_str(&arg).ok())\n .unwrap_or_else(|| {\n // Seed the RNG from the system time now.\n SystemTime::now()\n .duration_since(SystemTime::UNIX_EPOCH)\n .map(|d| d.as_secs())\n .unwrap_or(0)\n });\n let population = matches\n .opt_str(\"population\")\n .and_then(|arg| usize::from_str(&arg).ok())\n .map(|pop| {\n if pop == 0 {\n 2\n } else if pop & 1 == 1 {\n pop + 1\n } else {\n pop\n }\n })\n .unwrap_or(10);\n let mutation = matches\n .opt_str(\"mutation\")\n .and_then(|arg| f64::from_str(&arg).ok())\n .unwrap_or(0.05);\n matches\n .opt_str(\"testing-threads\")\n .and_then(|arg| usize::from_str(&arg).ok())\n .map(|count| {\n ThreadPoolBuilder::new()\n .num_threads(count)\n .build_global()\n .unwrap()\n });\n let mut rng = Rng::with_seed(seed + 17);\n let track_builder = Racetrack::builder().path_radius(path_radius).seed(seed);\n let track = track_builder.clone().view_dist(view_dist).build();\n let mut brains = iter::repeat_with(|| Brain::random(view_dist, &mut rng))\n .take(population)\n .collect::>();\n let mut max_max_score = 0;\n let (tx, rx) = mpsc::channel();\n thread::spawn(move || {\n let displayed_track = track_builder.view_dist(display_dist).build();\n for brain in rx {\n print!(\"\\x07\");\n test_brain(&brain, &displayed_track, true);\n }\n });\n loop {\n let mut results = brains\n .par_iter()\n .map(|brain| (brain.clone(), test_brain(brain, &track, false)))\n .collect::>();\n results.sort_by(|(_, (score_a, time_a)), (_, (score_b, time_b))| {\n score_b.cmp(&score_a).then(time_b.cmp(&time_a))\n });\n results.truncate(population / 2);\n let max_score = (results[0].1).0;\n if max_score > max_max_score {\n max_max_score = max_score;\n tx.send(results[0].0.clone()).unwrap();\n }\n brains.clear();\n for (brain, _) in results.into_iter() {\n brains.push(brain.mutant(&mut rng, mutation));\n brains.push(brain);\n }\n }\n}\n\nfn clear_terminal() {\n print!(\"\\x1b[H\\x1b[J\");\n}\n\nfn draw_track(track: &Racetrack) {\n let view_dist = track.view_dist();\n clear_terminal();\n for y in (-view_dist..=view_dist).rev() {\n for x in -view_dist..=view_dist {\n let pos = Vector::new(x, y);\n let c = if pos == Vector::ORIGIN {\n '@'\n } else if let Some(true) = track.get(pos) {\n '.'\n } else {\n ' '\n };\n print!(\"{}\", c);\n }\n print!(\"\\n\");\n }\n}\n\nfn test_brain(brain: &Brain, track: &Racetrack, show: bool) -> (i32, usize) {\n let mut track = track.clone();\n let mut time = 0usize;\n let mut vel = Vector::ORIGIN;\n let mut pos = Vector::ORIGIN;\n let mut max_score = 0;\n let mut since_improved = 0;\n track.translate(Vector::ORIGIN);\n 'tick_loop: loop {\n vel = vel + brain.compute_accel(vel, &track);\n for pt in Vector::ORIGIN.segment_pts(vel) {\n if let Some(false) = track.get(pt) {\n if show {\n track.translate(pt);\n } else {\n pos = pos + pt;\n }\n break 'tick_loop;\n }\n }\n pos = pos + vel;\n if pos.y > max_score {\n max_score = pos.y;\n since_improved = 0;\n } else if since_improved > 50 {\n break 'tick_loop;\n } else {\n since_improved += 1;\n }\n track.translate(vel);\n time = time.saturating_add(1);\n if show {\n draw_track(&track);\n println!(\"score: {} velocity: {}\", pos.y, vel);\n thread::sleep(Duration::from_millis(50));\n }\n if let Some(false) = track.get(Vector::ORIGIN) {\n break 'tick_loop;\n }\n }\n if show {\n draw_track(&track);\n println!(\"max score: {}\", pos.y);\n thread::sleep(Duration::from_millis(150));\n }\n (pos.y, time)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134673,"cells":{"blob_id":{"kind":"string","value":"4bda801613f5e4aa62d7f43f0c75007b81e18038"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"sergey-melnychuk/parsed"},"path":{"kind":"string","value":"/src/parser.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":11103,"string":"11,103"},"score":{"kind":"number","value":2.84375,"string":"2.84375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"pub use crate::matcher::{Matcher, MatchError, unit};\nuse crate::stream::ByteStream;\nuse std::marker::PhantomData;\n\npub struct Save {\n matcher: M,\n func: F,\n phantom: PhantomData<(T, U)>,\n}\n\nimpl Matcher for Save\nwhere\n M: Matcher<(T, U)>,\n F: Fn(&mut T, U),\n{\n fn do_match(&self, bs: &mut ByteStream) -> Result {\n let (mut t, u) = self.matcher.do_match(bs)?;\n (self.func)(&mut t, u);\n Ok(t)\n }\n}\n\npub struct Skip {\n matcher: M,\n phantom: PhantomData<(T, U)>,\n}\n\nimpl Matcher for Skip\nwhere\n M: Matcher<(T, U)>,\n{\n fn do_match(&self, bs: &mut ByteStream) -> Result {\n let (t, _u) = self.matcher.do_match(bs)?;\n Ok(t)\n }\n}\n\npub trait ParserExt: Sized {\n fn save(self, f: F) -> Save;\n\n fn skip(self) -> Skip;\n}\n\nimpl ParserExt for M where M: Matcher<(T, U)> + Sized {\n fn save(self, f: F) -> Save {\n Save {\n matcher: self,\n func: f,\n phantom: PhantomData::<(T, U)>,\n }\n }\n\n fn skip(self) -> Skip {\n Skip {\n matcher: self,\n phantom: PhantomData::<(T, U)>,\n }\n }\n}\n\npub fn one(b: u8) -> impl Matcher {\n move |bs: &mut ByteStream| {\n let pos = bs.pos();\n bs.next().filter(|x| *x == b).ok_or(MatchError::unexpected(\n pos,\n \"EOF\".to_string(),\n format!(\"byte {}\", b),\n ))\n }\n}\n\npub fn single(chr: char) -> impl Matcher {\n move |bs: &mut ByteStream| {\n let pos = bs.pos();\n bs.next()\n .map(|b| b as char)\n .filter(|c| *c == chr)\n .ok_or(MatchError::unexpected(\n pos,\n \"EOF\".to_string(),\n format!(\"char '{}'\", chr),\n ))\n }\n}\n\npub fn repeat(this: impl Matcher) -> impl Matcher> {\n move |bs: &mut ByteStream| {\n let mut acc: Vec = vec![];\n loop {\n let mark = bs.mark();\n match this.do_match(bs) {\n Err(_) => {\n bs.reset(mark);\n return Ok(acc);\n }\n Ok(t) => acc.push(t),\n }\n }\n }\n}\n\npub fn times(count: usize, this: impl Matcher) -> impl Matcher> {\n move |bs: &mut ByteStream| {\n let mut acc: Vec = vec![];\n let mark = bs.mark();\n loop {\n match this.do_match(bs) {\n Ok(item) => {\n acc.push(item);\n },\n err => {\n bs.reset(mark);\n return err.map(|_| vec![]);\n }\n }\n if acc.len() >= count {\n return Ok(acc);\n }\n }\n }\n}\n\npub fn maybe(this: impl Matcher) -> impl Matcher> {\n move |bs: &mut ByteStream| {\n let mark = bs.mark();\n match this.do_match(bs) {\n Ok(m) => Ok(Some(m)),\n Err(_) => {\n bs.reset(mark);\n Ok(None)\n }\n }\n }\n}\n\npub fn until bool + 'static>(f: F) -> impl Matcher> {\n move |bs: &mut ByteStream| {\n let mut acc = vec![];\n loop {\n let mark = bs.mark();\n match bs.next() {\n Some(b) if f(b) => acc.push(b),\n Some(_) => {\n bs.reset(mark);\n return Ok(acc);\n },\n _ => return Err(MatchError::over_capacity(\n bs.pos(), bs.len(), 1))\n }\n }\n }\n}\n\npub fn before(chr: char) -> impl Matcher> {\n move |bs: &mut ByteStream| {\n let pos = bs.pos();\n bs.find_single(|c| *c == chr as u8)\n .map(|idx| idx - pos)\n .and_then(|len| bs.get(len))\n .ok_or(MatchError::over_capacity(pos, bs.len(), 1))\n }\n}\n\npub fn token() -> impl Matcher {\n before(' ').map(|vec| vec.into_iter().map(|b| b as char).collect::())\n}\n\npub fn exact(slice: &'static [u8]) -> impl Matcher> {\n move |bs: &mut ByteStream| {\n let mark = bs.mark();\n let mut acc = vec![];\n for i in 0..slice.len() {\n let b = slice[i];\n let s = single(b as char);\n match s.do_match(bs) {\n Ok(b) => acc.push(b),\n Err(e) => {\n bs.reset(mark);\n return Err(e);\n }\n }\n }\n\n Ok(acc.into_iter().map(|c| c as u8).collect())\n }\n}\n\npub fn string(s: &'static str) -> impl Matcher {\n move |bs: &mut ByteStream| {\n let m = exact(s.as_bytes());\n let mark = bs.mark();\n match m.do_match(bs) {\n Ok(vec) => Ok(String::from_utf8(vec).unwrap()),\n Err(e) => {\n bs.reset(mark);\n return Err(e);\n }\n }\n }\n}\n\npub fn space() -> impl Matcher> {\n move |bs: &mut ByteStream| {\n let f: fn(u8) -> bool = |b| (b as char).is_whitespace();\n match until(f).do_match(bs) {\n Ok(vec) => Ok(vec.into_iter().map(|b| b as char).collect()),\n Err(e) => Err(e),\n }\n }\n}\n\npub fn bytes(len: usize) -> impl Matcher> {\n move |bs: &mut ByteStream| {\n bs.get(len)\n .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), len))\n }\n}\n\npub fn get_u8() -> impl Matcher {\n move |bs: &mut ByteStream| {\n bs.get_u8()\n .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), 1))\n }\n}\n\npub fn get_u16() -> impl Matcher {\n move |bs: &mut ByteStream| {\n bs.get_u16()\n .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), 2))\n }\n}\n\npub fn get_u32() -> impl Matcher {\n move |bs: &mut ByteStream| {\n bs.get_u32()\n .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), 4))\n }\n}\n\npub fn get_u64() -> impl Matcher {\n move |bs: &mut ByteStream| {\n bs.get_u64()\n .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), 8))\n }\n}\n\npub fn get_16() -> impl Matcher<[u8; 16]> {\n move |bs: &mut ByteStream| {\n bs.get_16()\n .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), 16))\n }\n}\n\npub fn get_32() -> impl Matcher<[u8; 32]> {\n move |bs: &mut ByteStream| {\n bs.get_32()\n .ok_or(MatchError::over_capacity(bs.pos(), bs.len(), 32))\n }\n}\n\npub trait Applicator {\n fn apply(&mut self, parser: impl Matcher) -> Result;\n}\n\nimpl Applicator for ByteStream {\n fn apply(&mut self, parser: impl Matcher) -> Result {\n parser.do_match(self)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn simple() {\n #[derive(Debug, Eq, PartialEq)]\n enum Token {\n KV { k: char, v: char },\n }\n\n struct TokenBuilder {\n k: Option,\n v: Option,\n }\n\n impl TokenBuilder {\n fn zero() -> TokenBuilder {\n TokenBuilder { k: None, v: None }\n }\n }\n\n let mut bs: ByteStream = \"abc\".to_string().into();\n\n let m = unit(|| TokenBuilder::zero())\n .then_map(single('a'), |(tb, a)| TokenBuilder { k: Some(a), ..tb })\n .then_map(single('b'), |(tb, b)| TokenBuilder { v: Some(b), ..tb })\n .map(|tb| Token::KV {\n k: tb.k.unwrap(),\n v: tb.v.unwrap(),\n });\n\n assert_eq!(bs.apply(m).unwrap(), Token::KV { k: 'a', v: 'b' });\n assert_eq!(bs.pos(), 2);\n }\n\n #[test]\n fn list() {\n let mut bs: ByteStream = \"abccc\".to_string().into();\n\n let c = single('c');\n\n let abccc = unit(|| vec![])\n .then_map(single('a'), |(acc, a)| {\n let mut copy = acc.clone();\n copy.push(a);\n copy\n })\n .then_map(single('b'), |(acc, b)| {\n let mut copy = acc.clone();\n copy.push(b);\n copy\n })\n .then_map(repeat(c), |(acc, vec)| {\n let mut copy = acc;\n for item in vec {\n copy.push(item);\n }\n copy\n });\n\n assert_eq!(bs.apply(abccc).unwrap(), vec!['a', 'b', 'c', 'c', 'c']);\n assert_eq!(bs.pos(), 5);\n }\n\n #[test]\n fn until() {\n let mut bs: ByteStream = \"asdasdasdasd1\".to_string().into();\n\n let until1 = unit(|| ())\n .then_map(before('1'), |(_, vec)| {\n vec.into_iter().map(|b| b as char).collect::()\n })\n .then_map(single('1'), |(vec, one)| (vec, one));\n\n assert_eq!(bs.apply(until1).unwrap(), (\"asdasdasdasd\".to_string(), '1'));\n }\n\n #[test]\n fn chunks() {\n let mut bs: ByteStream = \"asdasdqqq123123token1 token2\\n\".to_string().into();\n\n let m = unit(|| vec![])\n .then(exact(\"asd\".as_bytes()))\n .map(|(mut vec, bs)| {\n vec.push(bs.into_iter().map(|b| b as char).collect::());\n vec\n })\n .then(exact(\"asdqqq\".as_bytes()))\n .map(|(mut vec, bs)| {\n vec.push(bs.into_iter().map(|b| b as char).collect::());\n vec\n })\n .then(exact(\"123123\".as_bytes()))\n .map(|(mut vec, bs)| {\n vec.push(bs.into_iter().map(|b| b as char).collect::());\n vec\n })\n .then(token())\n .map(|(mut vec, bs)| {\n vec.push(bs);\n vec\n })\n .then(before('\\n'))\n .map(|(mut vec, bs)| {\n vec.push(bs.into_iter().map(|b| b as char).collect::());\n vec\n });\n\n assert_eq!(\n bs.apply(m).unwrap(),\n vec![\n \"asd\".to_string(),\n \"asdqqq\".to_string(),\n \"123123\".to_string(),\n \"token1\".to_string(),\n \" token2\".to_string(),\n ]\n );\n }\n\n #[test]\n fn test_times_ok() {\n let mut bs = ByteStream::wrap(b\"012301230123\".to_vec());\n\n let m = unit(|| ())\n .then(times(3, exact(b\"0123\")))\n .map(|(_, times)| times);\n\n assert_eq!(\n bs.apply(m).unwrap(),\n vec![\n b\"0123\",\n b\"0123\",\n b\"0123\",\n ]\n );\n }\n\n #[test]\n fn test_times_mismatch() {\n let mut bs = ByteStream::wrap(b\"0123012301AA\".to_vec());\n\n let m = unit(|| vec![])\n .then(times(3, exact(b\"0123\")))\n .save(|vec, times| *vec = times);\n\n assert!(bs.apply(m).is_err());\n }\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134674,"cells":{"blob_id":{"kind":"string","value":"5943c3238ac29ff213eae55862ed5f0474247217"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"pedantic79/Exercism"},"path":{"kind":"string","value":"/rust/atbash-cipher/src/lib.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1917,"string":"1,917"},"score":{"kind":"number","value":3.21875,"string":"3.21875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::iter::{from_fn, once};\n\n/// \"Encipher\" with the Atbash cipher.\npub fn encode(plain: &str) -> String {\n split_from_fn(at_bash(plain))\n}\n\n/// \"Decipher\" with the Atbash cipher.\npub fn decode(cipher: &str) -> String {\n at_bash(cipher).collect()\n}\n\nfn at_bash(s: &str) -> impl Iterator + '_ {\n s.bytes().filter(|c| c.is_ascii_alphanumeric()).map(|c| {\n if c.is_ascii_digit() {\n c\n } else {\n b'a' + b'z' - c.to_ascii_lowercase()\n }\n .into()\n })\n}\n\n/// split_flat_map is public so I can run benchmarks\n/// flat_map 12: 224ns (R²=1.000, 4685942 iterations in 136 samples)\n/// flat_map 48: 625ns (R²=0.994, 1806626 iterations in 126 samples)\n/// flat_map 252: 1us 888ns (R²=0.995, 575638 iterations in 114 samples)\n/// flat_map 1024: 5us 739ns (R²=0.999, 183408 iterations in 102 samples)\npub fn split_flat_map(itr: impl Iterator) -> String {\n itr.enumerate()\n .flat_map(|(idx, c)| {\n if idx % 5 == 0 && idx > 0 {\n Some(' ')\n } else {\n None\n }\n .into_iter()\n .chain(once(c))\n })\n .collect()\n}\n\n/// split_from_fn is public so I can run benchmarks\n/// from_fn 12: 188ns (R²=1.000, 5669992 iterations in 138 samples)\n/// from_fn 48: 441ns (R²=0.996, 2404623 iterations in 129 samples)\n/// from_fn 252: 965ns (R²=1.000, 1121768 iterations in 121 samples)\n/// from_fn 1024: 2us 444ns (R²=1.000, 432483 iterations in 111 samples)\npub fn split_from_fn(iter: impl Iterator) -> String {\n let mut count = 0;\n let mut iter = iter.peekable();\n\n from_fn(|| {\n if count == 5 && iter.peek().is_some() {\n count = 0;\n Some(' ')\n } else {\n count += 1;\n iter.next()\n }\n })\n .collect()\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134675,"cells":{"blob_id":{"kind":"string","value":"3dad82b1b1d08c14f2acd7005d1239265e57863f"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"yangqiong/leetcode"},"path":{"kind":"string","value":"/rust/src/e118_pascals_triangle.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":926,"string":"926"},"score":{"kind":"number","value":3.359375,"string":"3.359375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// https://leetcode.cn/problems/pascals-triangle/\n// 给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。\n\nuse std::result;\n\nstruct Solution {}\n\nimpl Solution {\n pub fn generate(num_rows: i32) -> Vec> {\n let mut result: Vec> = vec![];\n for i in 0..num_rows {\n match i {\n 0 => {\n result.push(vec![1]);\n }\n 1 => {\n result.push(vec![1, 1]);\n }\n _ => {\n let mut nums = vec![1];\n let last_nums = &result[(i - 1) as usize];\n for j in 0..(last_nums.len() - 1) {\n nums.push(last_nums[j] + last_nums[j + 1]);\n }\n nums.push(1);\n result.push(nums)\n }\n }\n }\n result\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134676,"cells":{"blob_id":{"kind":"string","value":"01ce4c055791e08e3e16a0295b69620e39552df5"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"krak3n/Rust101"},"path":{"kind":"string","value":"/constants/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":526,"string":"526"},"score":{"kind":"number","value":3.109375,"string":"3.109375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// must give it a type - no fixed memory address\n// const cannot be muteable\nconst FOO: u8 = 42;\n\n// another way - fixed memory address\nstatic BAR: u8 = 123;\n\n// mutable constants !?\nstatic mut FIZZ: i32 = 345;\n\nfn main() {\n println!(\"{}\", FOO);\n println!(\"{}\", BAR);\n // must be unsafe to use FIZZ because FIZZ is not thread\n // safe since anything at anytime could be reading\n // and writting from it\n unsafe {\n println!(\"{}\", FIZZ);\n FIZZ = 678; // eep\n println!(\"{}\", FIZZ);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134677,"cells":{"blob_id":{"kind":"string","value":"57cdd5339a003dc8f4b153c4f3fb680cb4069e5f"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"divvun/kbdgen"},"path":{"kind":"string","value":"/src/build/windows/klc/ligature.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":810,"string":"810"},"score":{"kind":"number","value":2.875,"string":"2.875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","Apache-2.0","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"Apache-2.0\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use std::fmt::Display;\n\npub struct KlcLigature {\n pub rows: Vec,\n}\n\nimpl Display for KlcLigature {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n if self.rows.is_empty() {\n return Ok(());\n }\n\n f.write_str(\"LIGATURE\\n\\n\")?;\n\n for ligature in &self.rows {\n f.write_fmt(format_args!(\n \"{}\\t{}\",\n ligature.virtual_key, ligature.shift_state\n ))?;\n for utf16 in &ligature.utf16s {\n f.write_fmt(format_args!(\"\\t{:04x}\", utf16))?;\n }\n f.write_str(\"\\n\")?;\n }\n\n f.write_str(\"\\n\")?;\n\n Ok(())\n }\n}\n\npub struct KlcLigatureRow {\n pub virtual_key: String,\n pub shift_state: String,\n pub utf16s: Vec,\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134678,"cells":{"blob_id":{"kind":"string","value":"67d5f79816429a7a2590e5d6776005d1df656372"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"kotlin2018/learn_rust"},"path":{"kind":"string","value":"/tests/chapter_collection.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1684,"string":"1,684"},"score":{"kind":"number","value":4.3125,"string":"4.3125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n#[cfg(test)]\nmod test{\n\n #[derive(Debug,Default)]\n struct Student{\n pub name: Option,\n pub age: Option,\n pub gender: Option,\n }\n\n /// 在循环中使用 Vector (动态数组)\n #[test]\n fn test_vec_mut(){\n let mut students = Vec::::new();\n let mut student_vec = Vec::::new();\n students.push(Student{\n name: Some(\"小明\".to_string()),\n age: Some(18),\n gender: Some(true),\n });\n students.push(Student{\n name: Some(\"小红\".to_string()),\n age: Some(20),\n gender: Some(false),\n });\n /// 这个循环要 消费掉 每个遍历到的元素\n for mut student in students{\n student.name = Some(\"韩信\".to_string());\n student.age = Some(25);\n student.gender = Some(true);\n student_vec.push(student)\n };\n println!(\"student_vec = {:?}\",student_vec);\n }\n\n /// 只有对象的实例是可变的,才能定义它的引用是可变的。(只能获取可变对象的可变引用,不能获取不可变对象的可变引用)\n #[test]\n fn test_borrow_and_borrow_mut(){\n /// 只有对象的实例是可变的,才能定义它的引用是可变的。(只能获取可变对象的可变引用,不能获取不可变对象的可变引用)\n //let student = Student::default();\n //let student_borrow_mut = &mut student;// Error: 只有 Student 的实例 student 是 mut(可变的),才能定义它的引用是可变的\n\n let mut student = Student::default();\n let student_mut = &mut student;\n\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134679,"cells":{"blob_id":{"kind":"string","value":"e80934404a36404e9a431797fae3a96618c0bd20"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"ShadowJonathan/utils"},"path":{"kind":"string","value":"/pkcs8/src/private_key_info.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4126,"string":"4,126"},"score":{"kind":"number","value":2.8125,"string":"2.8125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","Apache-2.0","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"Apache-2.0\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"//! PKCS#8 `PrivateKeyInfo`.\n\nuse core::{convert::TryFrom, fmt};\n\nuse der::{Decodable, Encodable, Message};\n#[cfg(feature = \"pem\")]\nuse {crate::pem, zeroize::Zeroizing};\n#[cfg(feature = \"encryption\")]\nuse {\n crate::EncryptedPrivateKeyDocument,\n rand_core::{CryptoRng, RngCore},\n};\n\n#[cfg(feature = \"alloc\")]\nuse crate::PrivateKeyDocument;\nuse crate::{AlgorithmIdentifier, Error, Result};\n\n/// RFC 5208 designates `0` as the only valid version for PKCS#8 documents\nconst VERSION: u8 = 0;\n\n/// PKCS#8 `PrivateKeyInfo`.\n///\n/// ASN.1 structure containing an [`AlgorithmIdentifier`] and private key\n/// data in an algorithm specific format.\n///\n/// Described in [RFC 5208 Section 5]:\n///\n/// ```text\n/// PrivateKeyInfo ::= SEQUENCE {\n/// version Version,\n/// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,\n/// privateKey PrivateKey,\n/// attributes [0] IMPLICIT Attributes OPTIONAL }\n///\n/// Version ::= INTEGER\n///\n/// PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier\n///\n/// PrivateKey ::= OCTET STRING\n///\n/// Attributes ::= SET OF Attribute\n/// ```\n///\n/// [RFC 5208 Section 5]: https://tools.ietf.org/html/rfc5208#section-5\n#[derive(Clone)]\npub struct PrivateKeyInfo<'a> {\n /// X.509 [`AlgorithmIdentifier`] for the private key type\n pub algorithm: AlgorithmIdentifier<'a>,\n\n /// Private key data\n pub private_key: &'a [u8],\n // TODO(tarcieri): support for `Attributes` (are they used in practice?)\n // PKCS#9 describes the possible attributes: https://tools.ietf.org/html/rfc2985\n // Workaround for stripping attributes: https://stackoverflow.com/a/48039151\n}\n\nimpl<'a> PrivateKeyInfo<'a> {\n /// Encrypt this private key using a symmetric encryption key derived\n /// from the provided password.\n #[cfg(feature = \"encryption\")]\n #[cfg_attr(docsrs, doc(cfg(feature = \"encryption\")))]\n pub fn encrypt(\n &self,\n rng: impl CryptoRng + RngCore,\n password: impl AsRef<[u8]>,\n ) -> Result {\n PrivateKeyDocument::from(self).encrypt(rng, password)\n }\n\n /// Encode this [`PrivateKeyInfo`] as ASN.1 DER.\n #[cfg(feature = \"alloc\")]\n #[cfg_attr(docsrs, doc(cfg(feature = \"alloc\")))]\n pub fn to_der(&self) -> PrivateKeyDocument {\n self.into()\n }\n\n /// Encode this [`PrivateKeyInfo`] as PEM-encoded ASN.1 DER.\n #[cfg(feature = \"pem\")]\n #[cfg_attr(docsrs, doc(cfg(feature = \"pem\")))]\n pub fn to_pem(&self) -> Zeroizing {\n Zeroizing::new(pem::encode(\n self.to_der().as_ref(),\n pem::PRIVATE_KEY_BOUNDARY,\n ))\n }\n}\n\nimpl<'a> TryFrom<&'a [u8]> for PrivateKeyInfo<'a> {\n type Error = Error;\n\n fn try_from(bytes: &'a [u8]) -> Result {\n Ok(Self::from_der(bytes)?)\n }\n}\n\nimpl<'a> TryFrom> for PrivateKeyInfo<'a> {\n type Error = der::Error;\n\n fn try_from(any: der::Any<'a>) -> der::Result> {\n any.sequence(|decoder| {\n // Parse and validate `version` INTEGER.\n if u8::decode(decoder)? != VERSION {\n return Err(der::ErrorKind::Value {\n tag: der::Tag::Integer,\n }\n .into());\n }\n\n let algorithm = decoder.decode()?;\n let private_key = decoder.octet_string()?.into();\n\n Ok(Self {\n algorithm,\n private_key,\n })\n })\n }\n}\n\nimpl<'a> Message<'a> for PrivateKeyInfo<'a> {\n fn fields(&self, f: F) -> der::Result\n where\n F: FnOnce(&[&dyn Encodable]) -> der::Result,\n {\n f(&[\n &VERSION,\n &self.algorithm,\n &der::OctetString::new(self.private_key)?,\n ])\n }\n}\n\nimpl<'a> fmt::Debug for PrivateKeyInfo<'a> {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"PrivateKeyInfo\")\n .field(\"algorithm\", &self.algorithm)\n .finish() // TODO(tarcieri): use `finish_non_exhaustive` when stable\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134680,"cells":{"blob_id":{"kind":"string","value":"28676fefadc8748b3ef84e26b99ab01d966f0c77"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Tarv3/gc_dynamic"},"path":{"kind":"string","value":"/src/evec.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3030,"string":"3,030"},"score":{"kind":"number","value":3.875,"string":"3.875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::mem;\nuse std::ops::{Index, IndexMut};\n\n#[derive(Debug, Clone)]\npub struct Evec {\n pub values: Vec>,\n pub available: Vec,\n}\n\nimpl Evec {\n pub fn new() -> Evec {\n Evec {\n values: Vec::new(),\n available: Vec::new(),\n }\n }\n\n pub fn from(vec: Vec) -> Evec {\n let capacity = vec.capacity();\n let mut values = Vec::with_capacity(capacity);\n\n for value in vec {\n values.push(Some(value));\n }\n\n Evec {\n values,\n available: Vec::with_capacity(capacity),\n }\n }\n\n pub fn from_option_vec(vec: Vec>) -> Evec {\n let mut available = Vec::with_capacity(vec.capacity());\n for (i, value) in vec.iter().enumerate() {\n if value.is_none() {\n available.push(i);\n }\n }\n\n Evec {\n values: vec,\n available,\n }\n }\n\n pub fn next_available(&self) -> usize {\n match self.available.last() {\n Some(index) => *index,\n None => self.values.len()\n }\n }\n\n pub fn with_capacity(capacity: usize) -> Evec {\n Evec {\n values: Vec::with_capacity(capacity),\n available: Vec::with_capacity(capacity),\n }\n }\n\n pub fn push(&mut self, value: T) -> usize {\n match self.available.pop() {\n Some(index) => {\n self.values[index] = Some(value);\n index\n }\n None => {\n let index = self.values.len();\n self.values.push(Some(value));\n index\n }\n }\n }\n\n pub fn remove(&mut self, index: usize) {\n assert!(index < self.values.len());\n if self.values[index].is_some() {\n self.values[index] = None;\n self.available.push(index);\n }\n }\n\n pub fn remove_unused(&mut self) {\n self.available.clear();\n let mut values = Vec::with_capacity(self.values.capacity());\n mem::swap(&mut self.values, &mut values);\n for item in values.into_iter().filter(|item| item.is_some()) {\n self.values.push(item);\n }\n }\n}\n\nimpl Index for Evec {\n type Output = Option;\n\n fn index(&self, index: usize) -> &Option {\n &self.values[index]\n }\n}\n\nimpl IndexMut for Evec {\n fn index_mut(&mut self, index: usize) -> &mut Option {\n &mut self.values[index]\n }\n}\n\n#[cfg(test)]\nmod tests {\n use evec::Evec;\n #[test]\n fn first_tests() {\n let mut evec = Evec::from(vec![1, 2, 3, 4]);\n\n evec.remove(2);\n evec.push(10);\n evec.push(5);\n\n assert_eq!(evec[2], Some(10));\n assert_eq!(evec[4], Some(5));\n }\n\n #[test]\n fn remove_test() {\n let mut evec = Evec::from_option_vec(vec![Some(1), Some(2), None, None, Some(5)]);\n evec.remove_unused();\n\n assert_eq!(evec[2], Some(5));\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134681,"cells":{"blob_id":{"kind":"string","value":"1fad11f86c29e96781dda8a238d2b59e4f7f4e40"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"jordansissel/experiments"},"path":{"kind":"string","value":"/aoc/aoc2022/1/for_loop.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":732,"string":"732"},"score":{"kind":"number","value":3.5,"string":"3.5"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::io;\n\nfn main() {\n let mut elves = vec![];\n let mut count = 0;\n\n for line in io::stdin().lines() {\n if let Err(e) = line {\n println!(\"Error reading line: {}\", e);\n return;\n }\n\n let text = line.unwrap();\n\n if text.is_empty() {\n elves.push(count);\n count = 0;\n continue;\n }\n\n let calories = text.parse::().unwrap();\n count += calories;\n }\n if count > 0 { elves.push(count); }\n\n // Part 1\n let max = elves.iter().max();\n println!(\"Highest single elf: {}\", max.unwrap());\n\n // Part 2\n elves.sort();\n elves.reverse();\n println!(\"Sum of top 3: {}\", elves[0..3].iter().sum::());\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134682,"cells":{"blob_id":{"kind":"string","value":"f4402fc0e9891d79dc0d1e3d0355738e2fd6b85a"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"mosbasik/advent-of-code-2018"},"path":{"kind":"string","value":"/src/bin/day04a.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6210,"string":"6,210"},"score":{"kind":"number","value":3.421875,"string":"3.421875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::collections::HashMap;\nuse std::io::{self, BufRead};\nuse std::iter::Iterator;\n\nextern crate chrono;\nuse chrono::NaiveDateTime;\n\nextern crate unicode_segmentation;\nuse unicode_segmentation::UnicodeSegmentation;\n\nfn main() {\n // make a handle to the standard input of the current process\n let stdin = io::stdin();\n\n // read all of the input into a vector of strings (Vec)\n let input = stdin.lock().lines().map(|line| line.unwrap()).collect();\n\n // feed the Vec into the main logic and print the result\n println!(\"{:}\", answer(input));\n}\n\nfn answer(input: Vec) -> usize {\n // create vector to hold our Log structs\n let mut logs = Vec::new();\n\n // parse a Log struct out of every line of the input\n for line in input.iter() {\n logs.push(parse_log(line));\n }\n\n // sort the Logs from earliest to latest by datetime\n logs.sort_unstable_by(|a, b| a.dt.cmp(&b.dt));\n\n // \"indices\" of a sort to track the current state as we walk through the logs\n let mut guard = None;\n let mut first_sleep_min: Option = None;\n let mut first_wake_min: Option;\n\n // a map of guard IDs to [a map of minutes to counts, where count is the\n // number of times this guard was asleep during this minute]\n let mut asleep = HashMap::new();\n\n // loop over every log entry, choosing a set of operations to perform based\n // on which one of three possible actions this log entry represents\n for log in logs.iter() {\n match log.action {\n // if a guard comes on duty, record his ID\n Action::Start => {\n guard = log.guard;\n }\n // if a guard goes to sleep, record the minute\n Action::Sleep => {\n first_sleep_min = Some(log.dt.format(\"%M\").to_string().parse().unwrap());\n }\n // if a guard wakes up, record the minute. then, for each minute\n // between the time they went to sleep and the time they woke up,\n // increment the appropriate minute counter in the \"asleep\" HashMap\n Action::Wake => {\n first_wake_min = Some(log.dt.format(\"%M\").to_string().parse().unwrap());\n for min in first_sleep_min.unwrap()..first_wake_min.unwrap() {\n let slot = asleep\n .entry(guard.unwrap())\n .or_insert(HashMap::new())\n .entry(min)\n .or_insert(0 as usize);\n *slot += 1;\n }\n // unset the \"going to sleep\" minute for sanity\n first_sleep_min = None;\n }\n }\n }\n\n // find the guard who sleeps the most\n let guard = sleepiest_guard(&asleep);\n // find the minute of the night that guard sleeps the most\n let minute = sleepiest_minute(&asleep, guard);\n // multiply the two together and return the result\n guard * minute\n}\n\nfn sleepiest_guard(asleep: &HashMap>) -> usize {\n asleep\n // make hashmap into an iterator over (k, v) tuples\n .iter()\n // convert to an iterator over (guard, total minutes asleep) tuples\n .map(|(guard, minute_counts)| (*guard, minute_counts.values().sum::()))\n // find the tuple with the highest total minutes asleep\n .max_by_key(|v| v.1)\n .unwrap()\n // return the guard ID of that tuple\n .0\n}\n\nfn sleepiest_minute(asleep: &HashMap>, guard: usize) -> usize {\n match asleep.get(&guard) {\n Some(m) => *(m.iter().max_by_key(|x| x.1).unwrap().0),\n None => panic!(),\n }\n}\n\n#[derive(Debug)]\nenum Action {\n Start,\n Sleep,\n Wake,\n}\n\n#[derive(Debug)]\nstruct Log {\n dt: NaiveDateTime,\n guard: Option,\n action: Action,\n}\n\nfn parse_log(input: &str) -> Log {\n // split input into (roughly) a datetime string and an action string\n let input_tokens = input.split(|c| c == '[' || c == ']').collect::>();\n\n // parse the datetime string into a NaiveDateTime object\n let dt = NaiveDateTime::parse_from_str(input_tokens[1], \"%Y-%m-%d %H:%M\").unwrap();\n\n // split the action string on the unicode word boundaries\n let action_tokens = UnicodeSegmentation::unicode_words(input_tokens[2]).collect::>();\n // use the first word to determine what Action is being taken\n let action = match action_tokens[0] {\n \"Guard\" => Action::Start,\n \"falls\" => Action::Sleep,\n \"wakes\" => Action::Wake,\n _ => panic!(),\n };\n // if the Action is that of a guard starting their shift, get their ID\n // number from the next word\n let guard = match action {\n Action::Start => Some(action_tokens[1].parse().unwrap()),\n _ => None,\n };\n\n // create and return the Log struct\n Log { dt, guard, action }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_1() {\n assert_eq!(\n answer(vec![\n String::from(\"[1518-11-01 00:05] falls asleep\"),\n String::from(\"[1518-11-01 00:25] wakes up\"),\n String::from(\"[1518-11-01 00:30] falls asleep\"),\n String::from(\"[1518-11-01 00:55] wakes up\"),\n String::from(\"[1518-11-01 00:00] Guard #10 begins shift\"),\n String::from(\"[1518-11-01 23:58] Guard #99 begins shift\"),\n String::from(\"[1518-11-02 00:40] falls asleep\"),\n String::from(\"[1518-11-02 00:50] wakes up\"),\n String::from(\"[1518-11-03 00:05] Guard #10 begins shift\"),\n String::from(\"[1518-11-03 00:24] falls asleep\"),\n String::from(\"[1518-11-03 00:29] wakes up\"),\n String::from(\"[1518-11-04 00:02] Guard #99 begins shift\"),\n String::from(\"[1518-11-04 00:36] falls asleep\"),\n String::from(\"[1518-11-04 00:46] wakes up\"),\n String::from(\"[1518-11-05 00:03] Guard #99 begins shift\"),\n String::from(\"[1518-11-05 00:45] falls asleep\"),\n String::from(\"[1518-11-05 00:55] wakes up\"),\n ]),\n 240\n );\n }\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134683,"cells":{"blob_id":{"kind":"string","value":"57291ad6d9558d1f9a3745a8900075f56fe0a46e"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Picahoo/ciruela"},"path":{"kind":"string","value":"/src/client/keys.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3146,"string":"3,146"},"score":{"kind":"number","value":2.78125,"string":"2.78125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","Apache-2.0"],"string":"[\n \"MIT\",\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use std::io::{self, Read};\nuse std::env::{self, home_dir};\nuse std::path::Path;\nuse std::fs::File;\n\nuse failure::{Error, ResultExt};\nuse ssh_keys::PrivateKey;\nuse ssh_keys::openssh::parse_private_key;\n\n\nfn keys_from_file(filename: &Path, allow_non_existent: bool,\n res: &mut Vec)\n -> Result<(), Error>\n{\n let mut f = match File::open(filename) {\n Ok(f) => f,\n Err(ref e)\n if e.kind() == io::ErrorKind::NotFound && allow_non_existent\n => {\n return Ok(());\n }\n Err(e) => return Err(e.into()),\n };\n let mut keybuf = String::with_capacity(1024);\n f.read_to_string(&mut keybuf)?;\n let keys = parse_private_key(&keybuf)?;\n res.extend(keys);\n Ok(())\n}\n\nfn keys_from_env(name: &str, allow_non_existent: bool,\n res: &mut Vec)\n -> Result<(), Error>\n{\n let value = match env::var(name) {\n Ok(x) => x,\n Err(ref e)\n if matches!(e, &env::VarError::NotPresent) && allow_non_existent\n => {\n return Ok(());\n }\n Err(e) => return Err(e.into()),\n };\n let keys = parse_private_key(&value)?;\n res.extend(keys);\n Ok(())\n}\n\npub fn read_keys(identities: &Vec, key_vars: &Vec)\n -> Result, Error>\n{\n let mut private_keys = Vec::new();\n let no_default = identities.len() == 0 &&\n key_vars.len() == 0;\n if no_default {\n keys_from_env(\"CIRUELA_KEY\", true, &mut private_keys)\n .context(format!(\"Can't read env key CIRUELA_KEY\"))?;\n match home_dir() {\n Some(home) => {\n let path = home.join(\".ssh/id_ed25519\");\n keys_from_file(&path, true, &mut private_keys)\n .context(format!(\"Can't read key file {:?}\", path))?;\n let path = home.join(\".ssh/id_ciruela\");\n keys_from_file(&path, true, &mut private_keys)\n .context(format!(\"Can't read key file {:?}\", path))?;\n let path = home.join(\".ciruela/id_ed25519\");\n keys_from_file(&path, true, &mut private_keys)\n .context(format!(\"Can't read key file {:?}\", path))?;\n }\n None if private_keys.len() == 0 => {\n warn!(\"Cannot find home dir. \\\n Use `-i` or `-k` options to specify \\\n identity (private key) explicitly.\");\n }\n None => {} // fine if there is some key, say from env variable\n }\n } else {\n for ident in identities {\n keys_from_file(&Path::new(&ident), false,\n &mut private_keys)\n .context(format!(\"Can't read key file {:?}\", ident))?;\n }\n for name in key_vars {\n keys_from_env(&name, false, &mut private_keys)\n .context(format!(\"Can't read env key {:?}\", name))?;\n }\n };\n eprintln!(\"Ciruela {}: read {} private keys, listing public:\",\n env!(\"CARGO_PKG_VERSION\"), private_keys.len());\n for key in &private_keys {\n eprintln!(\" {}\", key.public_key().to_string());\n }\n return Ok(private_keys)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134684,"cells":{"blob_id":{"kind":"string","value":"38b3211d94766707ae9c5d880ef1c74695d93402"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"OpenTechSchool-Leipzig/volunteero"},"path":{"kind":"string","value":"/heart/src/opportunity.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6951,"string":"6,951"},"score":{"kind":"number","value":3.09375,"string":"3.09375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::convert::TryFrom;\nuse std::convert::TryInto;\n\nuse serde::Serialize;\n\nuse crate::contact::Contact;\nuse crate::contact::ContactOption;\nuse crate::dto::DTO;\nuse crate::geocoder::geocode;\nuse crate::label::Label;\nuse crate::location::{Address, Location};\nuse crate::organisation::Organisation;\nuse crate::repository::Repository;\n\n#[derive(Debug, PartialEq, Serialize, Clone)]\npub struct Opportunity {\n pub job_description: String,\n pub organisation: Organisation,\n pub locations: Vec,\n pub contact: Contact,\n pub labels: Vec