Dataset Viewer
Auto-converted to Parquet Duplicate
content
stringlengths
40
17.4k
id
int64
0
236
fn connection() -> OciConnection { let database_url = database_url_from_env("OCI_DATABASE_URL"); OciConnection::establish(&database_url).unwrap() }
0
pub unsafe extern "C" fn kdb2_firstkey() -> datum { let mut item: datum = datum{dptr: 0 as *mut libc::c_char, dsize: 0,}; if __cur_db.is_null() { no_open_db(); item.dptr = 0 as *mut libc::c_char; item.dsize = 0 as libc::c_int; return item } return kdb2_dbm_firstkey(__cur_db); }
1
pub fn argument_error(name: &str, required: usize, passed: usize) -> Error { anyhow!( "Function '{}' required {} argument(s), but passed {}", name, required, passed ) }
2
pub fn pyclass(attr: TokenStream, item: TokenStream) -> TokenStream { let attr = parse_macro_input!(attr); let item = parse_macro_input!(item); derive_impl::pyclass(attr, item).into() }
3
fn create_mesh_buffer_verts( chunk: &Chunk, device: &wgpu::Device, queue: &wgpu::Queue, ) -> MeshBufferVerts { // Calculate total length of buffer e.g. a full chunk of different voxels. This way a new buffer only has to be created when the voxel capacity is changed. let verts = Mesh::verts(chunk); let vert_len = verts.len(); let single_cube_verts = Mesh::cube_verts().len(); let single_cube_color_verts = (single_cube_verts / 3) * std::mem::size_of::<PaletteIndexType>(); // One PaletteIndexType per 3 verts let max_voxels = { let (x, y, z) = chunk.capacity(); x * y * z }; let max_buf_size = (single_cube_verts + single_cube_color_verts) * max_voxels * std::mem::size_of::<f32>(); let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: None, mapped_at_creation: false, size: max_buf_size as u64, usage: wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST, }); if vert_len > 0 { queue.write_buffer(&buffer, 0, bytemuck::cast_slice(&verts)); } MeshBufferVerts { buffer, vert_len, max_capacity: chunk.capacity(), } }
4
pub fn clone(_meta: TokenStream, input: TokenStream) -> TokenStream { // parse the input stream into our async function let func = syn::parse_macro_input!(input as syn::ItemFn); // get attributes (docstrings/examples) for our function let attrs = &func.attrs; // get visibility of function let vis = &func.vis; // get the name of our function let name = &func.sig.ident; // get the name of our cloned function let sync_name = syn::Ident::new(&format!("{}_blocking", name), name.span()); // get information on the generics to pass let generics = &func.sig.generics; // get the arguments for our function let args = &func.sig.inputs; // get our output let output = &func.sig.output; // get the block of instrutions that are going to be called let block = &func.block; // cast back to a token stream let output = quote!{ // iterate and add all of our attributes #(#attrs)* // conditionally add tokio::main if the sync feature is enabled #vis async fn #name #generics(#args) #output { #block } // iterate and add all of our attributes #(#attrs)* // conditionally add tokio::main if the sync feature is enabled #[cfg_attr(feature = "sync", tokio::main)] #vis async fn #sync_name #generics(#args) #output { #block } }; output.into() }
5
pub(crate) fn build_query_string(request: &Request, ruma_api: &TokenStream) -> TokenStream { let ruma_serde = quote! { #ruma_api::exports::ruma_serde }; if let Some(field) = request.query_map_field() { let field_name = field.ident.as_ref().expect("expected field to have identifier"); quote!({ // This function exists so that the compiler will throw an // error when the type of the field with the query_map // attribute doesn't implement IntoIterator<Item = (String, String)> // // This is necessary because the ruma_serde::urlencoded::to_string // call will result in a runtime error when the type cannot be // encoded as a list key-value pairs (?key1=value1&key2=value2) // // By asserting that it implements the iterator trait, we can // ensure that it won't fail. fn assert_trait_impl<T>(_: &T) where T: ::std::iter::IntoIterator<Item = (::std::string::String, ::std::string::String)>, {} let request_query = RequestQuery(self.#field_name); assert_trait_impl(&request_query.0); format_args!( "?{}", #ruma_serde::urlencoded::to_string(request_query)? ) }) } else if request.has_query_fields() { let request_query_init_fields = request.request_query_init_fields(); quote!({ let request_query = RequestQuery { #request_query_init_fields }; format_args!( "?{}", #ruma_serde::urlencoded::to_string(request_query)? ) }) } else { quote! { "" } } }
6
pub fn skia_rectangle_f32_top(rectangle_ptr: *mut ValueBox<Rect>) -> scalar { rectangle_ptr.with_not_null_return(0.0, |rectangle| rectangle.top()) }
7
fn build_url(host: &str, page: Option<i32>) -> String { match page { Some(p) => format!( "https://api.binaryedge.io/v2/query/domains/subdomain/{}?page={}", host, p ), None => format!( "https://api.binaryedge.io/v2/query/domains/subdomain/{}", host ), } }
8
pub fn import_ruma_api() -> TokenStream { if let Ok(FoundCrate::Name(possibly_renamed)) = crate_name("ruma-api") { let import = Ident::new(&possibly_renamed, Span::call_site()); quote! { ::#import } } else if let Ok(FoundCrate::Name(possibly_renamed)) = crate_name("ruma") { let import = Ident::new(&possibly_renamed, Span::call_site()); quote! { ::#import::api } } else { quote! { ::ruma_api } } }
9
pub fn generate(graphics: &Graphics) -> String { let mut document = "".to_owned(); document.push_str(SVG_OPEN); document.push_str("\n"); let graphics_result = gen_graphics(graphics, 1); document.push_str(&graphics_result); document.push_str(SVG_CLOSE); document }
10
pub fn caml_pasta_fq_div(x: ocaml::Pointer<CamlFq>, y: ocaml::Pointer<CamlFq>) -> CamlFq { CamlFq(x.as_ref().0 / y.as_ref().0) }
11
fn subst_op(ctx: &Closure, id: &str, fix: &Imm, o: &Op) -> Op { use crate::lambdal::Op::*; match o { Op2(op, e1, e2) => { let e1 = Box::new(subst_op(ctx, id, fix, e1)); let e2 = Box::new(subst_op(ctx, id, fix, e2)); Op2(*op, e1, e2) } MkArray(sz, n) => { let sz = Box::new(subst_imm(ctx, id, fix, sz)); let n = Box::new(subst_imm(ctx, id, fix, n)); MkArray(sz, n) } GetArray(iid, idx) => { let iid = Box::new(subst_imm(ctx, id, fix, iid)); let idx = Box::new(subst_imm(ctx, id, fix, idx)); GetArray(iid, idx) } SetArray(iid, idx, v) => { let iid = Box::new(subst_imm(ctx, id, fix, iid)); let idx = Box::new(subst_imm(ctx, id, fix, idx)); let v = Box::new(subst_imm(ctx, id, fix, v)); SetArray(iid, idx, v) } Imm(imm) => Imm(subst_imm(ctx, id, fix, imm)), } }
12
pub const fn create_default_audio_stream(stream_type: AudioStreamType) -> AudioStream { AudioStream { stream_type: stream_type, source: AudioSettingSource::User, user_volume_level: DEFAULT_VOLUME_LEVEL, user_volume_muted: DEFAULT_VOLUME_MUTED, } }
13
fn system_call(message: SystemCall) -> SystemCall { let addr = task_buffer_addr(); unsafe { let buffer = &mut *(addr as *mut TaskBuffer); buffer.call = Some(message); system_call_raw(); buffer.call.take().unwrap() } }
14
pub fn debug_time<T>(label: impl AsRef<str>, cb: impl FnOnce() -> T) -> T { let label = label.as_ref(); let t0 = std::time::Instant::now(); debug_log(format!("Starting {}...", label)); let ret = cb(); debug_log(format!("Finished {}: {:?}", label, t0.elapsed())); return ret; }
15
fn unit(num: u32, capitalise: bool) -> String { match num { 0 if capitalise => "No more bottles".to_string(), 0 => "no more bottles".to_string(), 1 => "1 bottle".to_string(), _ => num.to_string() + " bottles", } }
16
fn parse_stars(line: &str) -> Star { let u_pos = &line[10..]; let mut pos_parts = u_pos[0..u_pos.find(">").unwrap()].split(","); let u_vel = line.split("velocity=<").nth(1).unwrap(); let mut vel_parts = u_vel[0..u_vel.find(">").unwrap()].split(","); return Star { position: Point { x: pos_parts.next().unwrap().replace(" ", "").parse().unwrap(), y: pos_parts.next().unwrap().replace(" ", "").parse().unwrap(), }, velocity: Point { x: vel_parts.next().unwrap().replace(" ", "").parse().unwrap(), y: vel_parts.next().unwrap().replace(" ", "").parse().unwrap(), }, }; }
17
pub fn unary_num(t_unary: Token, n_simple_numeric: Node) -> Node { let mut numeric_value = if let Node::Int(int_value) = n_simple_numeric { int_value } else { panic!(); }; if let Token::T_UNARY_NUM(polarty) = t_unary { match polarty.as_ref() { "+" => (), "-" => { numeric_value = 0 - numeric_value; }, _ => { panic!(); } } } else { panic!(); } return Node::Int(numeric_value); }
18
pub fn star2(lines: &Vec<String>) -> String { let days = initialize(lines); let mut guard_map = HashMap::new(); for day in days { guard_map.entry(day.guard_id) .or_insert(vec![]) .push(day); } let mut max_guard_asleep_per_minute = vec![(0, None); 60]; for &guard_id in guard_map.keys() { let mut guard_asleep_by_minute = vec![0; 60]; for day in &guard_map[&guard_id] { for minute in 0..60 { guard_asleep_by_minute[minute] += i32::from(!day.minutes[minute]); } } for minute in 0..60 { if max_guard_asleep_per_minute[minute].0 < guard_asleep_by_minute[minute] { max_guard_asleep_per_minute[minute] = (guard_asleep_by_minute[minute], Some(guard_id)); } } } if let Some((max_minute, (_, Some(max_guard_id)))) = max_guard_asleep_per_minute.iter().enumerate().max_by_key(|(_, (times, _))| times) { return (max_minute as i32 * max_guard_id) .to_string(); } panic!("No maximum found: Invalid input!"); }
19
fn tab_base_template<A>(state: &State, tab: &Tab, mixin: A) -> Dom where A: FnOnce(DomBuilder<HtmlElement>) -> DomBuilder<HtmlElement> { html!("div", { .class([ &*ROW_STYLE, &*TAB_STYLE, //&*MENU_ITEM_STYLE, ]) .cursor!(state.is_dragging(), intern("pointer")) .class_signal(&*TAB_UNLOADED_STYLE, and(tab.is_unloaded(), not(state.is_tab_hovered(&tab)))) .class_signal(&*TAB_FOCUSED_STYLE, tab.is_focused()) .apply(mixin) }) }
20
pub fn crate_inherent_impls(tcx: TyCtxt<'_>, (): ()) -> CrateInherentImpls { let mut collect = InherentCollect { tcx, impls_map: Default::default() }; for id in tcx.hir().items() { collect.check_item(id); } collect.impls_map }
21
fn get_common_chars(box_one: &String, box_two: &String) -> String { box_one.chars() .zip(box_two.chars()) .filter(|ch| ch.0 == ch.1) .map(|ch| ch.0) .collect() }
22
fn delete(task: Event, mut todays_list: List) -> List { todays_list.retain(|x| x.2 != task.2); todays_list }
23
fn parseLightInfo(reader: &mut BufReader<&File>, buf: &mut String, lights: &mut Vec<Light>) -> Model { let mut light = Light { lightType: "" as str, radius: 0.0, period: 0, position: Vec3f::new(0.0, 0.0, 0.0), Color: Vec3f::new(0.0, 0.0, 0.0), }; //Firstly, read the LigthType reader.read_line(buf); let lightType: &str = buf.trim().clone(); let mut key = ""; let mut radius = ""; let mut period = 0; if lightType == "o" || lightType == "l" { let mut infoIndex = 0; reader.read_line(buf); let mut split_info = buf.split(" "); key = split_info.next().unwrap().parse().unwrap(); radius = split_info.next().unwrap().parse().unwrap(); period = split_info.next().unwrap().parse().unwrap(); } let mut infoIndex = 0; while infoIndex < 2 { //Then, read the position and Color Info split_info = buf.split(" "); let mut fieldInfo = 0; reader.read_line(buf); let mut split_info = buf.split(" "); key = split_info.next().unwrap().parse().unwrap(); if infoIndex == 1 { light.position = Vec3f::new( x: split_info.next().unwrap().parse().unwrap(), y: split_info.next().unwrap().parse().unwrap(), z: split_info.next().unwrap().parse().unwrap(), ) } else { light.Color = Vec3f::new( x: split_info.next().unwrap().parse().unwrap(), y: split_info.next().unwrap().parse().unwrap(), z: split_info.next().unwrap().parse().unwrap(), ) } infoIndex += 1 } //Finally, we only need to read an empty line to finish the model parsing process reader.read_line(buf); lights.push(light); }
24
fn current_manifest_path() -> ManifestResult { let locate_result = Command::new("cargo").arg("locate-project").output(); let output = match locate_result { Ok(out) => out, Err(e) => { print!("Failure: {:?}", e); panic!("Cargo failure to target project via locate-project") } }; if !output.status.success() { return Err(ManifestLoadError::CargoLoadFailure); } #[derive(Deserialize)] struct Data { root: String, } let stdout = String::from_utf8(output.stdout).unwrap(); let decoded: Data = serde_json::from_str(&stdout).unwrap(); let path = Path::new(&decoded.root).to_owned(); // debug!("manifest: {:?}", path); Ok(path) }
25
pub fn formatted_now() -> String { let system_time = SystemTime::now(); let date_time: DateTime<Utc> = system_time.into(); date_time.format("%d/%m/%Y %T").to_string() }
26
fn docker_metric_entry_from_two_stats(time_diff: Duration, first: InstantDockerContainerMetricEntry, second: InstantDockerContainerMetricEntry) -> DockerContainerMetricEntry { let diff = time_diff.num_milliseconds() as f64 / 1000.0; // seconds DockerContainerMetricEntry { name: second.name, state: second.state, cpu_usage: ((second.cpu_usage - first.cpu_usage) as f64 / (second.system_cpu_usage - first.system_cpu_usage) as f64) / diff, memory_usage: second.memory_usage, memory_cache: second.memory_cache, network_tx: (second.network_tx - first.network_tx) as f64 / diff, network_rx: (second.network_rx - first.network_rx) as f64 / diff } }
27
pub fn get_temp_folder() -> PathBuf { let temp_dir = mktemp::Temp::new_dir().unwrap(); let path = temp_dir.to_path_buf(); temp_dir.release(); path }
28
fn build_user(email: String, username: String) -> User{ User{ // Using the Field Init Shorthand when Variables and Fields Have the Same Name email, username, active: true, sign_in_count: 1 } }
29
pub fn format_memory_usage(bytes: usize) -> String { format!("{:12}", bytes >> 20) // MB }
30
pub fn calendar(year: Year) -> Calendar{ let mut cal = Calendar::new(); let tz_offset = FixedOffset::east(1 * 60*60); //TODO: Actually depends on daylight saving time (DST) ("sommartid/vintertid") for each date, but it should not matter because there are no events which depends on time. Also, I mix UTC and this timezone everywhere ///////////////////////////////////////////////////////////////// // Easter related days if let Some(easter) = påskdagen(year){ (try{cal.push(Event::new() .summary("Skärtorsdagen") .all_day(Date::<FixedOffset>::from_utc(date_of_last_weekday(Weekday::Thu,easter)?,tz_offset)) .add_multi_property("CATEGORIES","INOFFICIALHOLIDAY") //TODO: HOLIDAY fram till och med år 1772 .description("\"Thursday of mysteries\"") .done() )}): Option<_>; //Källor: https://www.riksdagen.se/sv/dokument-lagar/dokument/svensk-forfattningssamling/lag-1989253-om-allmanna-helgdagar_sfs-1989-253 (try{cal.push(Event::new() .summary("Långfredagen") .all_day(Date::<FixedOffset>::from_utc(date_of_last_weekday(Weekday::Fri,easter)?,tz_offset)) .add_multi_property("CATEGORIES","HOLIDAY") .done() )}): Option<_>; (try{cal.push(Event::new() .summary("Påskafton") .all_day(Date::<FixedOffset>::from_utc(easter.pred_opt()?,tz_offset)) .add_multi_property("CATEGORIES","INOFFICIALHOLIDAY") .description("Jesu uppståndelse") .done() )}): Option<_>; //Källor: https://www.riksdagen.se/sv/dokument-lagar/dokument/svensk-forfattningssamling/lag-1989253-om-allmanna-helgdagar_sfs-1989-253 (try{cal.push(Event::new() .summary("Påskdagen") .all_day(Date::<FixedOffset>::from_utc(easter,tz_offset)) .add_multi_property("CATEGORIES","HOLIDAY") .add_multi_property("CATEGORIES","FLAGDAY") .description("Jesu uppståndelse") .done() )}): Option<_>; //Källor: https://www.riksdagen.se/sv/dokument-lagar/dokument/svensk-forfattningssamling/lag-1989253-om-allmanna-helgdagar_sfs-1989-253 (try{cal.push(Event::new() .summary("Annandag påsk") .all_day(Date::<FixedOffset>::from_utc(easter.succ_opt()?,tz_offset)) .add_multi_property("CATEGORIES","HOLIDAY") .done() )}): Option<_>; //Källor: https://www.riksdagen.se/sv/dokument-lagar/dokument/svensk-forfattningssamling/lag-1989253-om-allmanna-helgdagar_sfs-1989-253 (try{cal.push(Event::new() .summary("Kristi himmelsfärdsdag") .all_day(Date::<FixedOffset>::from_utc(date_of_next_weekday(Weekday::Thu,easter.checked_add_signed(Duration::weeks(5))?)?,tz_offset)) .add_multi_property("CATEGORIES","HOLIDAY") .done() )}): Option<_>; (try{cal.push(Event::new() .summary("Pingstafton") .all_day(Date::<FixedOffset>::from_utc(date_of_next_weekday(Weekday::Sun,easter.checked_add_signed(Duration::weeks(6))?)?.pred_opt()?,tz_offset)) .add_multi_property("CATEGORIES","INOFFICIALHOLIDAY") .done() )}): Option<_>; //Källor: https://www.riksdagen.se/sv/dokument-lagar/dokument/svensk-forfattningssamling/lag-1989253-om-allmanna-helgdagar_sfs-1989-253 (try{cal.push(Event::new() .summary("Pingstdagen") .all_day(Date::<FixedOffset>::from_utc(date_of_next_weekday(Weekday::Sun,easter.checked_add_signed(Duration::weeks(6))?)?,tz_offset)) .add_multi_property("CATEGORIES","HOLIDAY") .add_multi_property("CATEGORIES","FLAGDAY") .done() )}): Option<_>; } ///////////////////////////////////////////////////////////////// // Officially recognized days //Källor: https://www.riksdagen.se/sv/dokument-lagar/dokument/svensk-forfattningssamling/lag-1989253-om-allmanna-helgdagar_sfs-1989-253 cal.push(Event::new() .summary("Nyårsdagen") .all_day(Utc.ymd(year,01,01)) .add_multi_property("CATEGORIES","HOLIDAY") .add_multi_property("CATEGORIES","FLAGDAY") .done() ); cal.push(Event::new() .summary("Trettondagsafton") .all_day(Utc.ymd(year,01,05)) .add_multi_property("CATEGORIES","INOFFICIALHOLIDAY") .done() ); //Källor: https://www.riksdagen.se/sv/dokument-lagar/dokument/svensk-forfattningssamling/lag-1989253-om-allmanna-helgdagar_sfs-1989-253 cal.push(Event::new() .summary("Trettondedag jul") .all_day(Utc.ymd(year,01,06)) .add_multi_property("CATEGORIES","HOLIDAY") .description("\"Epifania\"/\"Theofania\", en högtid kopplat till kristendomen.") .done() ); cal.push(Event::new() .summary("Tjugondedag jul") .all_day(Utc.ymd(year,01,13)) .description("Slutet på julhögtiden. \"Kasta ut granen och plocka undan juldekorationerna\"-dagen.") .done() ); if year >= 1992{cal.push(Event::new() .summary("Samernas nationaldag") .all_day(Utc.ymd(year,02,06)) .description("Datumet valdes till minne av det första samiska landsmötet.") .done() );} if year >= 1956{cal.push(Event::new() .summary("Alla hjärtans dag") .all_day(Utc.ymd(year,02,14)) .done() );} if year >= 1684{cal.push(Event::new() .summary("Våffeldagen") .all_day(Utc.ymd(year,03,25)) .description("Tidigare \"Jungfru Marie bebådelsedag\"/\"Vårfrudagen\" som har blivit till \"Våffeldagen\", en dag man äter våfflor.") .done() );} cal.push(Event::new() .summary("Första april") .all_day(Utc.ymd(year,04,01)) .done() ); cal.push(Event::new() .summary("Valborgsmässoafton") .all_day(Utc.ymd(year,04,30)) .add_multi_property("CATEGORIES","INOFFICIALHOLIDAY") .description("\"Saint Walpurgis night\"/\"Sankt Walpurgisnacht\"/\"Valborg\", en högtid vars ursprung är från Tyskland, men som nu har koppling med heliga Valborg.") .done() ); cal.push(Event::new() .summary("Första maj / Arbetarrörelsens dag") .all_day(Utc.ymd(year,05,01)) .add_multi_property("CATEGORIES","INOFFICIALHOLIDAY") .add_multi_property("CATEGORIES","FLAGDAY") .done() ); if year >= 2008{cal.push(Event::new() .summary("Veterandagen") .all_day(Utc.ymd(year,05,29)) .description("Till minne av krigsveteranger. Datumet står för grundandet av United Nations Truce Supervision Organization (UNTSO) som iakttog vapenvilan efter FN:s första fredsbevarande uppdrag vid 1948 års arabisk-israeliska krig.") .add_multi_property("CATEGORIES","FLAGDAY") .done() );} //Källor: https://www.riksdagen.se/sv/dokument-lagar/dokument/svensk-forfattningssamling/lag-1989253-om-allmanna-helgdagar_sfs-1989-253 if year >= 1983{cal.push(Event::new() .summary("Sveriges nationaldag") .all_day(Utc.ymd(year,06,06)) .add_multi_property("CATEGORIES","HOLIDAY") .add_multi_property("CATEGORIES","FLAGDAY") .description("Tidigare \"Svenska flaggans dag\". Det är kopplat till att Gustav Vasa valdes till kung 1523 och bröt Kalmarunionen, men även till \"1809 års regeringsform\" som skrevs på 1809.") .done() );} //Källor: https://www.riksdagen.se/sv/dokument-lagar/dokument/svensk-forfattningssamling/lag-1989253-om-allmanna-helgdagar_sfs-1989-253 if let Some(midsommardagen) = midsommardagen(year){ (try{cal.push(Event::new() .summary("Midsommarafton") .all_day(Date::<FixedOffset>::from_utc(midsommardagen.pred_opt()?,tz_offset)) .add_multi_property("CATEGORIES","INOFFICIALHOLIDAY") .location("Sverige") .description("En högtid kopplat till men som inte nödvändigtvis faller på sommarsolståndet. Fredagen efter eller på 19:e juni.") .done() )}): Option<_>; (try{cal.push(Event::new() .summary("Midsommardagen") .all_day(Date::<FixedOffset>::from_utc(midsommardagen,tz_offset)) .add_multi_property("CATEGORIES","HOLIDAY") .add_multi_property("CATEGORIES","FLAGDAY") .location("Sverige") .description("En högtid kopplat till men som inte nödvändigtvis faller på sommarsolståndet. Lördagen efter eller på 20:e juni.") .done() )}): Option<_>; } if year >= 1947{cal.push(Event::new() .summary("FN-dagen") .all_day(Utc.ymd(year,10,24)) .description("Datumet står för när FN-stadgan trädde i kraft 1945.") .add_multi_property("CATEGORIES","FLAGDAY") .done() );} cal.push(Event::new() .summary("Halloween") .all_day(Utc.ymd(year,10,31)) .description("\"All hallows evening\", en högtid som sägs komma från vikningar till engelsktalande öar och tillbaka.") .done() ); cal.push(Event::new() .summary("Allhelgonadagen") .all_day(Utc.ymd(year,11,01)) .description("Den gamla \"Alla helgons dag\" som har samma datum varje år.") .done() ); //Källor: https://www.riksdagen.se/sv/dokument-lagar/dokument/svensk-forfattningssamling/lag-1989253-om-allmanna-helgdagar_sfs-1989-253 (try{cal.push(Event::new() .summary("Alla helgons dag") .all_day(Date::<FixedOffset>::from_utc(allahelgonsdag(year)?,tz_offset)) .add_multi_property("CATEGORIES","HOLIDAY") .location("Sverige") .done() )}): Option<_>; cal.push(Event::new() .summary("Gustav Adolfsdagen") .all_day(Utc.ymd(year,11,06)) .description("Datumet står för när Kung Gustav II Adolf dog 1632.") .add_multi_property("CATEGORIES","FLAGDAY") .done() ); cal.push(Event::new() .summary("Mårtensafton / Mårten Gås") .all_day(Utc.ymd(year,11,10)) .done() ); if year >= 1896{cal.push(Event::new() .summary("Nobeldagen") .all_day(Utc.ymd(year,12,10)) .description("Datumet står för när Alfred Nobel dog 1896. Det är också under detta datum som nobelprisen delas ut.") .add_multi_property("CATEGORIES","FLAGDAY") .done() );} if year >= 1900{cal.push(Event::new() .summary("Lucia") .all_day(Utc.ymd(year,12,13)) .done() );} if year >= 0{ if let Some(fjärde_advent) = date_of_last_weekday_or_today(Weekday::Sun,NaiveDate::from_ymd(year,12,24)){ (try{cal.push(Event::new() .summary("Fjärde advent") .all_day(Date::<FixedOffset>::from_utc(fjärde_advent,tz_offset)) .done() )}): Option<_>; (try{cal.push(Event::new() .summary("Tredje advent") .all_day(Date::<FixedOffset>::from_utc(fjärde_advent.checked_add_signed(Duration::weeks(-1))?,tz_offset)) .done() )}): Option<_>; (try{cal.push(Event::new() .summary("Andra advent") .all_day(Date::<FixedOffset>::from_utc(fjärde_advent.checked_add_signed(Duration::weeks(-2))?,tz_offset)) .done() )}): Option<_>; (try{cal.push(Event::new() .summary("Första advent") .all_day(Date::<FixedOffset>::from_utc(fjärde_advent.checked_add_signed(Duration::weeks(-3))?,tz_offset)) .done() )}): Option<_>; } cal.push(Event::new() .summary("Julafton") .all_day(Utc.ymd(year,12,24)) .add_multi_property("CATEGORIES","INOFFICIALHOLIDAY") .done() ); //Källor: https://www.riksdagen.se/sv/dokument-lagar/dokument/svensk-forfattningssamling/lag-1989253-om-allmanna-helgdagar_sfs-1989-253 cal.push(Event::new() .summary("Juldagen") .all_day(Utc.ymd(year,12,25)) .add_multi_property("CATEGORIES","HOLIDAY") .add_multi_property("CATEGORIES","FLAGDAY") .done() ); //Källor: https://www.riksdagen.se/sv/dokument-lagar/dokument/svensk-forfattningssamling/lag-1989253-om-allmanna-helgdagar_sfs-1989-253 cal.push(Event::new() .summary("Annandag jul") .all_day(Utc.ymd(year,12,26)) .add_multi_property("CATEGORIES","HOLIDAY") .done() ); } cal.push(Event::new() .summary("Nyårsafton") .all_day(Utc.ymd(year,12,31)) .add_multi_property("CATEGORIES","INOFFICIALHOLIDAY") .done() ); ///////////////////////////////////////////////////////////////// // Other days //Källor: https://www.internationalwomensday.com/About if year >= 1909{cal.push(Event::new() .summary("Internationella kvinnodagen") .all_day(Utc.ymd(year,03,08)) .done() );} //Källor: https://www.piday.org/ , https://en.wikipedia.org/wiki/Pi_Day if year >= 1988{cal.push(Event::new() .summary("Pidagen (π)") .all_day(Utc.ymd(year,03,14)) .done() );} //Källor: https://en.wikipedia.org/wiki/White_Day , http://iroha-japan.net/iroha/A01_event/06_wd.html if year >= 1978{cal.push(Event::new() .summary("Vita dagen") .location("Japan") .all_day(Utc.ymd(year,03,14)) .done() );} (try{cal.push(Event::new() .summary("Sommartid (UTC+1 → UTC+2)") .location("Sverige") .all_day(Date::<FixedOffset>::from_utc(sommartid(year)?,tz_offset)) .description("Sommartid (Daylight Saving Time, DST) upphör. Klockan flyttas en timme fram. Sverige byter tidszon från CET/UTC+1 (Central European Time) till EET/UTC+2 (Eastern European Time).") .done() )}): Option<_>; //Källor: https://en.wikipedia.org/wiki/Black_Day_(South_Korea) , https://ko.wikipedia.org/wiki/%EB%B8%94%EB%9E%99%EB%8D%B0%EC%9D%B4 if year >= 1990{cal.push(Event::new() .summary("Svarta dagen") .location("Sydkorea") .all_day(Utc.ymd(year,04,14)) .done() );} //Källor: http://svenskafriluftsdagen.se/om-dagen/ if year >= 2014{cal.push(Event::new() .summary("Svenska friluftsdagen") .location("Sverige") .all_day(Utc.ymd(year,04,29)) .done() );} //Källor: https://www.starwars.com/star-wars-day , https://en.wikipedia.org/wiki/Star_Wars_Day if year >= 2011{cal.push(Event::new() .summary("Star Wars-dagen") .all_day(Utc.ymd(year,05,04)) .description("\"May the fourth be with you\"") .done() );} //Källor: https://sv.wikipedia.org/wiki/Mors_dag if year >= 1905{(try{cal.push(Event::new() .summary("Mors dag") .all_day(Date::<FixedOffset>::from_utc(date_of_last_weekday_of_month(Weekday::Sun,year,05)?,tz_offset)) .done() )}): Option<_>;} cal.push(Event::new() .summary("Sommarsolståndet") .location("Jorden") .start_date(Utc.ymd(year,06,20)) .end_date (Utc.ymd(year,06,22)) .done() ); //Källor: https://worldemojiday.com/ if year >= 2014{cal.push(Event::new() .summary("Emojidagen") .all_day(Utc.ymd(year,07,17)) .description("Stiftats av hemsidan \"Emojipedia\".") .done() );} //Källor: https://www.nordiskamuseet.se/aretsdagar/surstrommingspremiaren if year >= 1940{(try{cal.push(Event::new() .summary("Surströmmingspremiären") .all_day(Date::<FixedOffset>::from_utc(date_of_first_weekday_of_month(Weekday::Thu,year,08)?.checked_add_signed(Duration::weeks(2))?,tz_offset)) .done() )}): Option<_>;} //Källor: https://www.raa.se/evenemang-och-upplevelser/arkeologidagen/ if year >= 2001{(try{cal.push(Event::new() .summary("Arkeologidagen") .all_day(Date::<FixedOffset>::from_utc(date_of_last_weekday_of_month(Weekday::Sun,year,08)?,tz_offset)) .done() )}): Option<_>;} //Källor: https://geologinsdag.nu/om-oss/ if year >= 2001{(try{cal.push(Event::new() .summary("Geologins dag") .all_day(Date::<FixedOffset>::from_utc(date_of_first_weekday_of_month(Weekday::Sat,year,09)?.checked_add_signed(Duration::weeks(1))?,tz_offset)) .done() )}): Option<_>;} //Källor: https://sv.wikipedia.org/wiki/Internationella_barndagen#Sverige if year >= 1999{(try{cal.push(Event::new() .summary("Internationella barndagen") .location("Sverige") .all_day(Date::<FixedOffset>::from_utc(date_of_last_weekday_of_month(Weekday::Mon,year,10)?,tz_offset)) .done() )}): Option<_>;} (try{cal.push(Event::new() .summary("Vintertid (UTC+2 → UTC+1)") .location("Sverige") .all_day(Date::<FixedOffset>::from_utc(vintertid(year)?,tz_offset)) .description("Sommartid (Daylight Saving Time, DST) upphör. Klockan flyttas en timme tillbaka. Sverige byter tidszon från EET/UTC+2 (Eastern European Time) till CET/UTC+1 (Central European Time).") .done() )}): Option<_>; //Källor: https://worldvegetarianday.navs-online.org/about/about-wvd/ if year >= 1977{cal.push(Event::new() .summary("Vegetariska världsdagen") .all_day(Utc.ymd(year,10,01)) .description("\"World Vegetarian Day\".") .done() );} //Källor: https://www.worldanimalday.org.uk/about_us , https://web.archive.org/web/20121007012833/http://www.djurensratt.se/djurens-dag if year >= 1931{cal.push(Event::new() .summary("Djurens dag") .all_day(Utc.ymd(year,10,04)) .description("\"World Animal Day\".") .done() );} //Källor: http://kanelbullensdag.se/sa-har-firar-vi-kanelbullens-dag/ , http://kanelbullensdag.se/ if year >= 1999{cal.push(Event::new() .summary("Kanelbullens dag") .location("Sverige") .all_day(Utc.ymd(year,10,04)) .done() );} //Källor: https://sv.wikipedia.org/wiki/Fars_dag if year >= 1910{(try{cal.push(Event::new() .summary("Fars dag") .all_day(Date::<FixedOffset>::from_utc(date_of_last_weekday_of_month(Weekday::Sun,year,11)?.checked_add_signed(Duration::weeks(1))?,tz_offset)) .done() )}): Option<_>;} //Källor: https://sv.wikipedia.org/wiki/Black_Friday if year >= 2010{(try{cal.push(Event::new() .summary("Black Friday") .all_day(Date::<FixedOffset>::from_utc(thanksgiving(year)?.succ_opt()?,tz_offset)) .done() )}): Option<_>;} //Källor: http://webarchive.loc.gov/all/20121224030153/http://www.worldveganmonth.net/ if year >= 1994{cal.push(Event::new() .summary("Internationella vegandagen") .all_day(Utc.ymd(year,11,01)) .description("\"World Vegan Month\".") .done() );} //Källor: http://internationalmensday.com/founders-statement/ if year >= 1999{cal.push(Event::new() .summary("Internationella mansdagen") .all_day(Utc.ymd(year,11,19)) .done() );} //Källor: https://unicef.se/barnkonventionen/barnkonventionens-dag , https://sv.wikipedia.org/wiki/Barnens_dag if year >= 1989{cal.push(Event::new() .summary("Barnens dag") .all_day(Utc.ymd(year,11,20)) .description("Födelsedagen av FN:s konvention om barnets rättighter") .done() );} cal.push(Event::new() .summary("Vintersolståndet") .location("Jorden") .start_date(Utc.ymd(year,12,20)) .end_date (Utc.ymd(year,12,23)) .done() ); cal }
31
pub fn get_path_in_temp(file_path: &str) -> PathBuf { let mut path = get_temp_folder(); path.push(&file_path); path }
32
fn read_time() -> Time { read_line().trim().parse().unwrap() }
33
unsafe fn replace<T, R>(v: &mut T, change: impl FnOnce(T) -> (T, R)) -> R { let value = ptr::read(v); let (new_value, ret) = change(value); ptr::write(v, new_value); ret }
34
async fn index(schema: web::Data<MessageSchema>, req: HttpRequest, gql_request: Request) -> Response { let token = req .headers() .get("Authorization") .and_then(|value| value.to_str().map(|s| MyToken(s.to_string())).ok()); let mut request = gql_request.into_inner(); if let Some(token) = token { request = request.data(token); } schema.execute(request).await.into() }
35
fn to_rust_varstr(s: &str) -> String { use inflector::cases::snakecase::to_snake_case; let s = to_snake_case(s); fixup(s) }
36
pub fn assignable(node: Node) -> Node { println!("DEBUGGING node::assignable: {:?}", node); match node { Node::Ident(ident) => { // name, = *node // @parser.static_env.declare(name) // // node.updated(:lVasgn) // TODO handle appending nodes list // TODO handle static_env return Node::LVasgn(ident, vec![]); }, _ => { panic!("node::assignable: UNIMPL branch"); } } }
37
pub fn pystruct_sequence_try_from_object(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input); derive_impl::pystruct_sequence_try_from_object(input).into() }
38
fn rules<'r, 'p: 'r, 's: 'r>( s: &mut Solver<'r>, inputs: &'p [TensorProxy], outputs: &'p [TensorProxy], ) -> InferenceResult { check_input_arity(&inputs, 1)?; check_output_arity(&outputs, 1)?; s.equals(&outputs[0].datum_type, &inputs[0].datum_type)?; s.equals(&outputs[0].rank, &inputs[0].rank)?; s.equals(&outputs[0].shape[0], &inputs[0].shape[0])?; s.equals(&outputs[0].shape[1], &inputs[0].shape[1])?; s.given(&inputs[0].rank, move |s, rank| { for i in 2..rank { s.equals(&outputs[0].shape[i as usize], TDim::from(1))?; } Ok(()) }) }
39
pub fn number(n: i64) -> Value { Rc::new(RefCell::new(V { val: Value_::Number(n), computed: true, })) }
40
pub fn digamma<F : special::Gamma>(f: F) -> F { f.digamma() }
41
fn load_descriptor() -> Config { descriptor::load_internal_descriptors(true, false, None) }
42
fn env_var<K: AsRef<std::ffi::OsStr>>(key: K) -> String { env::var(&key).expect(&format!("Unable to find env var {:?}", key.as_ref())) }
43
pub fn global_rng() -> GlobalRng { GLOBAL_RNG_STATE.clone() }
44
fn cef_dir() -> PathBuf { PathBuf::from(env_var("CEF_DIR")) }
45
fn load_histograms() -> Loaded { let mut hist = Histogram::new_with_max(TRACKABLE_MAX, SIGFIG).unwrap(); let mut scaled_hist = Histogram::new_with_bounds(1000, TRACKABLE_MAX * SCALEF, SIGFIG).unwrap(); let mut raw = Histogram::new_with_max(TRACKABLE_MAX, SIGFIG).unwrap(); let mut scaled_raw = Histogram::new_with_bounds(1000, TRACKABLE_MAX * SCALEF, SIGFIG).unwrap(); // Log hypothetical scenario: 100 seconds of "perfect" 1msec results, sampled // 100 times per second (10,000 results), followed by a 100 second pause with a single (100 // second) recorded result. Recording is done indicating an expected EINTERVAL between samples // of 10 msec: for _ in 0..10_000 { let v = 1_000; // 1ms hist.record_correct(v, EINTERVAL).unwrap(); scaled_hist .record_correct(v * SCALEF, EINTERVAL * SCALEF) .unwrap(); raw += v; scaled_raw += v * SCALEF; } let v = 100_000_000; hist.record_correct(v, EINTERVAL).unwrap(); scaled_hist .record_correct(v * SCALEF, EINTERVAL * SCALEF) .unwrap(); raw += v; scaled_raw += v * SCALEF; let post = raw.clone_correct(EINTERVAL); let scaled_post = scaled_raw.clone_correct(EINTERVAL * SCALEF); Loaded { hist, scaled_hist, raw, scaled_raw, post, scaled_post, } }
46
pub fn greet(text: &str) -> String { text.to_string() }
47
pub(crate) fn iced_to_op_access(value: iced_x86_rust::OpAccess) -> OpAccess { // SAFETY: the enums are exactly identical unsafe { std::mem::transmute(value as u8) } }
48
fn gen_graphics(graphics: &Graphics, indent_level: usize) -> String { let mut document = "".to_owned(); for node in graphics.get_nodes() { let xml_element = element(node, indent_level); let indent_chars = " ".repeat(indent_level * INDENT_SIZE); document.push_str(&indent_chars); document.push_str(&xml_element); document.push_str("\n"); } document }
49
pub fn create_file_in_temp(file_name: &str, content: &str) -> PathBuf { let path = get_path_in_temp(&file_name); let mut file = File::create(&path).unwrap(); file.write_all(content.as_bytes()) .expect(&format!("cannot write to file {:?}", path)); path }
50
fn tab_favicon<A>(tab: &Tab, mixin: A) -> Dom where A: FnOnce(DomBuilder<HtmlElement>) -> DomBuilder<HtmlElement> { let favicon_url = tab.favicon_url.clone(); lazy_static! { static ref LOADING_URL: Arc<String> = Arc::new(intern("icons/firefox/tab-loading.png").to_string()); } html!("img", { .class(&*TAB_FAVICON_STYLE) /*.class([ &*TAB_FAVICON_STYLE, &*ICON_STYLE, ])*/ //.class_signal(&*TAB_FAVICON_STYLE_UNLOADED, tab.is_unloaded()) .attribute_signal("src", tab.is_loading() // TODO make this more efficient somehow ? .switch(move |is_loading| -> Box<dyn Signal<Item = Option<Arc<String>>> + Unpin> { if is_loading { Box::new(always(Some(LOADING_URL.clone()))) } else { Box::new(favicon_url.signal_cloned()) } }) .map(|x| { RefFn::new(x, move |x| { x.as_ref().map(|x| x.as_str()).unwrap_or(intern(DEFAULT_FAVICON)) }) })) .apply(mixin) }) }
51
fn content(content: ElementContent, indent_level: usize) -> String { use ElementContent::*; match content { Empty => "".to_owned(), Text(t) => t, Elements(e) => gen_graphics(e.as_ref(), indent_level), } }
52
pub fn clamp<T: Ord> (x: T, a: T, b: T) -> T { match (x.cmp(&a), x.cmp(&b)) { (Ordering::Less, _) => a, (_, Ordering::Greater) => b, _ => x, } }
53
pub fn caml_pasta_fq_sub(x: ocaml::Pointer<CamlFq>, y: ocaml::Pointer<CamlFq>) -> CamlFq { CamlFq(x.as_ref().0 - y.as_ref().0) }
54
pub fn py_freeze(input: TokenStream) -> TokenStream { derive_impl::py_freeze(input.into(), &Compiler).into() }
55
pub(crate) fn make_entity_builder( main: &ECS, components: &[Component], generics: &GenericOutput, ) -> TokenStream { let name = main.as_entity_builder_ident(); let fields = components.iter().map(|comp| { let name = comp.as_ident(); let ty = comp.as_ty(); quote::quote! { #name: Option<#ty> } }); let fields_default = components.iter().map(|comp| { let name = comp.as_ident(); quote::quote! { #name: None } }); let setters_fn = components.iter().map(|comp| { let name = comp.as_ident(); let name_add = comp.as_add_ident(); let name_del = comp.as_del_ident(); let ty = comp.as_ty(); let doc_str = format!( "Adds the component '{}' of type [`{}`] to the entity", comp.name, comp.path ); let doc_del = format!( "Removes the component '{}' of type [`{}`] to the entity", comp.name, comp.path ); quote::quote! { #[doc = #doc_str] pub fn #name(mut self, value: #ty) -> Self { self.#name = Some(value); self } #[doc = #doc_str] pub fn #name_add(&mut self, value: #ty) -> &mut Self { self.#name = Some(value); self } #[doc = #doc_del] pub fn #name_del(&mut self) -> &mut Self { self.#name = None; self } } }); let component_generics = &generics.components; quote::quote! { pub struct #name#component_generics { entity: ::secs::Entity, #(#fields,)* } impl#component_generics #name#component_generics { fn new(entity: ::secs::Entity) -> Self { Self { entity, #(#fields_default,)* } } pub fn entity(&self) -> ::secs::Entity { self.entity } #(#setters_fn)* } } }
56
fn system_call_put_payload<T: Any>(message: SystemCall, payload: T) -> SystemCall { use core::mem::{size_of}; let addr = task_buffer_addr(); unsafe { let buffer = &mut *(addr as *mut TaskBuffer); buffer.call = Some(message); buffer.payload_length = size_of::<T>(); let payload_addr = &mut buffer.payload_data as *mut _ as *mut T; let payload_data = &mut *payload_addr; *payload_data = payload; system_call_raw(); buffer.call.take().unwrap() } }
57
pub fn interpret(expr: &Expr) -> Value { let ctx: Closure = HashMap::new(); eval(&ctx, expr) }
58
pub fn caml_pasta_fq_size() -> CamlBigInteger256 { Fq_params::MODULUS.into() }
59
pub fn create_file<P>(path: P) -> File where P: AsRef<Path> { match File::create(&path) { Err(_) => { println!("cannot create file: {:?}", path.as_ref()); exit(1) } Ok(file) => file, } }
60
pub fn caml_pasta_fq_square(x: ocaml::Pointer<CamlFq>) -> CamlFq { CamlFq(x.as_ref().0.square()) }
61
fn part1(filename: &Path) -> String { Snafu::from( iter_lines(filename) .map(Snafu::from) .map::<isize, _>(Snafu::into) .sum::<isize>(), ) .to_string() }
62
pub fn create_insert(run: Run) -> Insert { Insert(docx_rs::Insert::new(run.take())) }
63
fn mock<T>() -> T { unimplemented!() }
64
pub fn b(b: BuiltIn) -> Value { Rc::new(RefCell::new(V { val: Value_::BuiltIn(b), computed: true, })) }
65
pub fn ln<F : Float>(f: F) -> F { f.ln() }
66
pub fn fatal_error() -> Error { anyhow!("Fatal error!") }
67
pub fn new_cube() -> Tess { let vertices: &[([f32; 3], [f32; 3], [f32; 2])] = &[ // front face ([ 1., -1., 1.], [ 0., 0., 1.], [1., 0.]), // 0 ([ 1., 1., 1.], [ 0., 0., 1.], [1., 1.]), ([-1., -1., 1.], [ 0., 0., 1.], [0., 0.]), ([-1., 1., 1.], [ 0., 0., 1.], [0., 1.]), // back face ([ 1., -1., -1.], [ 0., 0., -1.], [1., 0.]), // 4 ([ 1., 1., -1.], [ 0., 0., -1.], [1., 1.]), ([-1., -1., -1.], [ 0., 0., -1.], [0., 0.]), ([-1., 1., -1.], [ 0., 0., -1.], [0., 1.]), // left face ([-1., -1., 1.], [-1., 0., 0.], [1., 0.]), // 8 ([-1., 1., 1.], [-1., 0., 0.], [1., 1.]), ([-1., -1., -1.], [-1., 0., 0.], [0., 0.]), ([-1., 1., -1.], [-1., 0., 0.], [0., 1.]), // right face ([ 1., -1., -1.], [ 1., 0., 0.], [1., 0.]), // 12 ([ 1., 1., -1.], [ 1., 0., 0.], [1., 1.]), ([ 1., -1., 1.], [ 1., 0., 0.], [0., 0.]), ([ 1., 1., 1.], [ 1., 0., 0.], [0., 1.]), // top face ([ 1., 1., 1.], [ 0., 1., 0.], [1., 0.]), // 16 ([ 1., 1., -1.], [ 0., 1., 0.], [1., 1.]), ([-1., 1., 1.], [ 0., 1., 0.], [0., 0.]), ([-1., 1., -1.], [ 0., 1., 0.], [0., 1.]), // bottom face ([ 1., -1., -1.], [ 0., -1., 0.], [1., 0.]), // 20 ([ 1., -1., 1.], [ 0., -1., 0.], [1., 1.]), ([-1., -1., -1.], [ 0., -1., 0.], [0., 0.]), ([-1., -1., 1.], [ 0., -1., 0.], [0., 1.]), ]; let indices: &[u32] = &[ 0, 1, 2, 2, 1, 3, // front face 4, 5, 6, 6, 5, 7, // back face 8, 9, 10, 10, 9, 11, // left face 12, 13, 14, 14, 13, 15, // right face 16, 17, 18, 18, 17, 19, // top face 20, 21, 22, 22, 21, 23, // bottom face ]; Tess::new(Mode::Triangle, TessVertices::Fill(vertices), indices) }
68
fn subst_imm(ctx: &Closure, id: &str, fix: &Imm, i: &Imm) -> Imm { use crate::lambdal::Imm::*; match i { Bool(b) => Bool(*b), Int(n) => Int(*n), Var(x) => { if x == id { fix.clone() } else { Var(x.clone()) } } Fun(vid, e) => { let e = Box::new(subst_expr(ctx, id, fix, e)); Fun(vid.clone(), e) } Fix(vid, e) => { let e = Box::new(subst_expr(ctx, id, fix, e)); Fix(vid.clone(), e) } V | Star => unreachable!("ν or ★ encountered during subst"), } }
69
fn bindgen_prop(header: fuzzers::HeaderC) -> TestResult { match run_predicate_script(header) { Ok(o) => TestResult::from_bool(o.status.success()), Err(e) => { println!("{:?}", e); TestResult::from_bool(false) } } }
70
pub fn caml_pasta_fq_random() -> CamlFq { let fq: Fq = UniformRand::rand(&mut rand::thread_rng()); CamlFq(fq) }
71
pub fn sing(high: u32, low: u32) -> String { (low..(high + 1)) .rev() .map(|x| verse(x)) .collect::<Vec<String>>() .join("\n") }
72
pub fn verse(num: u32) -> String { let prefix = format!("{} of beer on the wall, \ {} of beer.\n", unit(num, true), unit(num, false)); let suffix = match num { 0 => { "Go to the store and buy some more, \ 99 bottles of beer on the wall.\n" .to_string() } _ => { format!("Take {} down and pass it around, \ {} of beer on the wall.\n", determiner(num), unit(num - 1, false)) } }; prefix + &suffix }
73
fn rdin() -> String{ let mut reader = String::new(); std::io::stdin().read_line(&mut reader).unwrap(); reader = removed(reader.to_lowercase()); // Changes everything to lowercase so it is not a case sensetive program. println!(); return reader; }
74
pub fn assign(lhs_node: Node, token: Token, rhs_node: Node) -> Node { match lhs_node { Node::LVasgn(var_str, mut nodes) => { nodes.push(rhs_node); return Node::LVasgn(var_str, nodes); }, _ => { panic!("node::assign UNIMPL"); } } }
75
pub fn smart_to_total_words() -> TotalWords { let mut words_vec: Vec<Words> = Vec::new(); for i in 1..22 { let words = smart_to_words(i); words_vec.push(words); } TotalWords::new(words_vec) }
76
fn random_with_rng<N, T: Rng>(a: N, b: N, rng: &mut T) -> N where N: SampleUniform + SampleBorrow<N> + Ord + Sized, { match a.cmp(&b) { Ordering::Greater => { let simpler = Uniform::new_inclusive(b, a); simpler.sample(rng) } Ordering::Equal => a, Ordering::Less => { let simpler = Uniform::new_inclusive(a, b); simpler.sample(rng) } } }
77
pub(crate) fn assignment_expression(i: Input) -> NodeResult { alt(( single::single_assignment_expression, abbreviated::abbreviated_assignment_expression, assignment_with_rescue_modifier, ))(i) }
78
fn reflect(v: &Vec3, n: &Vec3) -> Vec3 { *v - *n * 2.0 * dot(v, n) }
79
pub(crate) fn create_array_iterator_prototype(agent: &Agent) -> Value { let proto = Value::new_object(agent.intrinsics.iterator_prototype.clone()); proto .set( agent, ObjectKey::from("next"), Value::new_builtin_function(agent, next, false), ) .unwrap(); proto }
80
fn get_comments_progress_bar( total_bytes: u64, statistics: &Arc<Statistics>, show_annotated: bool, ) -> Progress { Progress::new( move |statistics| { let num_downloaded = statistics.num_downloaded(); let num_annotated = statistics.num_annotated(); ( num_downloaded as u64, format!( "{} {}{}", num_downloaded.to_string().bold(), "comments".dimmed(), if show_annotated { format!(" [{} {}]", num_annotated, "annotated".dimmed()) } else { "".into() } ), ) }, &statistics, Some(total_bytes), ProgressOptions { bytes_units: false }, ) }
81
fn fake_private_key() -> Bip32PrivateKey { Bip32PrivateKey::from_bytes( &[0xb8, 0xf2, 0xbe, 0xce, 0x9b, 0xdf, 0xe2, 0xb0, 0x28, 0x2f, 0x5b, 0xad, 0x70, 0x55, 0x62, 0xac, 0x99, 0x6e, 0xfb, 0x6a, 0xf9, 0x6b, 0x64, 0x8f, 0x44, 0x45, 0xec, 0x44, 0xf4, 0x7a, 0xd9, 0x5c, 0x10, 0xe3, 0xd7, 0x2f, 0x26, 0xed, 0x07, 0x54, 0x22, 0xa3, 0x6e, 0xd8, 0x58, 0x5c, 0x74, 0x5a, 0x0e, 0x11, 0x50, 0xbc, 0xce, 0xba, 0x23, 0x57, 0xd0, 0x58, 0x63, 0x69, 0x91, 0xf3, 0x8a, 0x37, 0x91, 0xe2, 0x48, 0xde, 0x50, 0x9c, 0x07, 0x0d, 0x81, 0x2a, 0xb2, 0xfd, 0xa5, 0x78, 0x60, 0xac, 0x87, 0x6b, 0xc4, 0x89, 0x19, 0x2c, 0x1e, 0xf4, 0xce, 0x25, 0x3c, 0x19, 0x7e, 0xe2, 0x19, 0xa4] ).unwrap() }
82
pub unsafe extern "C" fn kdb2_fetch(mut key: datum) -> datum { let mut item: datum = datum{dptr: 0 as *mut libc::c_char, dsize: 0,}; if __cur_db.is_null() { no_open_db(); item.dptr = 0 as *mut libc::c_char; item.dsize = 0 as libc::c_int; return item } return kdb2_dbm_fetch(__cur_db, key); }
83
pub fn format_pbs_duration(duration: &Duration) -> String { format_duration(duration) }
84
pub fn wrap(_meta: TokenStream, input: TokenStream) -> TokenStream { // parse the input stream into our async function let func = syn::parse_macro_input!(input as syn::ItemFn); // get attributes (docstrings/examples) for our function let attrs = &func.attrs; // get visibility of function let vis = &func.vis; // get the name of our function let name = &func.sig.ident; // get information on the generics to pass let generics = &func.sig.generics; // get the arguments for our function let args = &func.sig.inputs; // get our output let output = &func.sig.output; // get the block of instrutions that are going to be called let block = &func.block; // cast back to a token stream let output = quote!{ // iterate and add all of our attributes #(#attrs)* // conditionally add tokio::main if the sync feature is enabled #[cfg_attr(feature = "sync", tokio::main)] #vis async fn #name #generics(#args) #output { #block } }; output.into() }
85
pub fn derive_encode(input: TokenStream) -> TokenStream { // Construct a string representation of the type definition let s = input.to_string(); // Parse the string representation let ast = syn::parse_derive_input(&s).unwrap(); // Build the impl let gen = impl_encode(&ast); // Return the generated impl gen.parse().unwrap() }
86
pub fn create_default_modified_timestamps() -> ModifiedTimestamps { let mut timestamps = HashMap::new(); let stream_types = [ AudioStreamType::Background, AudioStreamType::Media, AudioStreamType::Interruption, AudioStreamType::SystemAgent, AudioStreamType::Communication, ]; for stream_type in stream_types.iter() { timestamps.insert(*stream_type, default_time().to_string()); } timestamps }
87
fn to_rust_typestr(s: &str) -> String { use inflector::cases::pascalcase::to_pascal_case; let s = to_pascal_case(s); fixup(s) }
88
pub fn ap(f: Value, arg: Value) -> Value { Rc::new(RefCell::new(V { val: Value_::Apply(f, arg), computed: false, })) }
89
fn mac_to_string(mac: Option<MacAddr>) -> String { match mac { Some(m) => m.to_string(), None => "Unknown mac address".to_string(), } }
90
pub(crate) fn extract_request_query(request: &Request, ruma_api: &TokenStream) -> TokenStream { let ruma_serde = quote! { #ruma_api::exports::ruma_serde }; if request.query_map_field().is_some() { quote! { let request_query = #ruma_api::try_deserialize!( request, #ruma_serde::urlencoded::from_str( &request.uri().query().unwrap_or("") ), ); } } else if request.has_query_fields() { quote! { let request_query: <RequestQuery as #ruma_serde::Outgoing>::Incoming = #ruma_api::try_deserialize!( request, #ruma_serde::urlencoded::from_str( &request.uri().query().unwrap_or("") ), ); } } else { TokenStream::new() } }
91
const fn null_ble_gatt_svc_def() -> ble_gatt_svc_def { return ble_gatt_svc_def { type_: BLE_GATT_SVC_TYPE_END as u8, uuid: ptr::null(), includes: ptr::null_mut(), characteristics: ptr::null(), }; }
92
fn solve() -> String { compute(1000).to_string() }
93
pub fn caml_pasta_fq_deep_copy(x: CamlFq) -> CamlFq { x }
94
fn element(node: &GraphicNode, indent_level: usize) -> String { let name = node.get_name(); let attrs = gen_attributes(node.get_attributes()); let mut content = content(node.get_content(), indent_level + 1); if content != "" { let indent_chars = " ".repeat(indent_level * INDENT_SIZE); content = format!("\n{}{}", content, indent_chars); } match attrs { Some(a) => format!("<{} {}>{}</{}>", name, a, content, name), None => format!("<{}>{}</{}>", name, content, name) } }
95
pub fn string_compose(parts: Node) -> Node { if is_collapse_string_parts(&parts) {} // TODO DUMMY if let Node::Str(string_value) = parts { return Node::Str(string_value); } if let Node::Nodes(str_nodes) = parts { if let Node::Str(str_value) = (*str_nodes.get(0).unwrap()).clone() { return Node::Str(str_value); } } panic!("string_compose UNIMPL"); }
96
fn calculate_metrics(ref_cluster:&ClusterResults, query_clusters: &Vec<&ClusterResults>) -> ExperimentResults{ let mut stability_results = Array2::<f64>::zeros(( ref_cluster.grouped_barcodes.len() ,query_clusters.len() )); let mut purity_results = Array2::<f64>::zeros(( ref_cluster.grouped_barcodes.len() ,query_clusters.len() )); for (i, cluster) in ref_cluster.grouped_barcodes.values().enumerate(){ for (j, experiment) in query_clusters.iter().enumerate() { let mut stab = stability_k(&cluster, &experiment) / experiment.h_tot ; if stab.is_nan(){// cant compare a naturally occuring NAN to f64::NAN stab = 1.0; } stability_results[[i, j]]= stab ; purity_results[[i,j]] = purity_k(&cluster, &experiment.grouped_barcodes) } } let stability_scores = stability_results.rows().into_iter().map(|x| 1.0 - x.mean().unwrap()).collect::<Vec<f64>>(); let purity_scores = purity_results.rows().into_iter().map( |x| { let mut v = x.to_vec(); v.retain(|x| *x != f64::NAN); // in purity_k f64::NAN is explicitly returned, so this works. Consider changing for conistency return vmean(v) } ).collect::<Vec<f64>>(); let cluster_ids: Vec<i64> = ref_cluster.grouped_barcodes.keys().cloned().collect::<Vec<i64>>() ; let exp_param = ref_cluster.exp_name.clone(); return ExperimentResults{ exp_param,cluster_ids, stability_scores, purity_scores } }
97
pub(crate) fn build_request_body(request: &Request, ruma_api: &TokenStream) -> TokenStream { let serde_json = quote! { #ruma_api::exports::serde_json }; if let Some(field) = request.newtype_raw_body_field() { let field_name = field.ident.as_ref().expect("expected field to have an identifier"); quote!(self.#field_name) } else if request.has_body_fields() || request.newtype_body_field().is_some() { let request_body_initializers = if let Some(field) = request.newtype_body_field() { let field_name = field.ident.as_ref().expect("expected field to have an identifier"); quote! { (self.#field_name) } } else { let initializers = request.request_body_init_fields(); quote! { { #initializers } } }; quote! { { let request_body = RequestBody #request_body_initializers; #serde_json::to_vec(&request_body)? } } } else { quote!(Vec::new()) } }
98
fn removed(mut string: String) -> String { if let Some('\n')=string.chars().next_back() { string.pop(); } if let Some('\r')=string.chars().next_back() { string.pop(); } string }
99
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
2