file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
nist-spce.rs
//! Testing energy computation for SPC/E water using data from //! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-9%C3%A5-cutoff //! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-10å-cutoff extern crate lumol; ext...
// Lumol, an extensible molecular simulation engine // Copyright (C) 2015-2016 G. Fraux — BSD license
random_line_split
nist-spce.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) 2015-2016 G. Fraux — BSD license //! Testing energy computation for SPC/E water using data from //! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-9%C3%A5-cutoff //! https://www.nist.gov/mml/csd/che...
#[test] fn nist3() { let system = get_system("spce-3.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.71488e6; assert!(f64::abs((energy - expected)/expected) < 1e-3); } #[test] fn nist4() { let system = get_system("spce-4.xy...
let system = get_system("spce-2.xyz", 9.0); let energy = system.potential_energy() / K_BOLTZMANN; let expected = -1.06602e6; assert!(f64::abs((energy - expected)/expected) < 1e-3); }
identifier_body
vec-to_str.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { assert_eq!((~[0, 1]).to_str(), ~"[0, 1]"); assert_eq!((&[1, 2]).to_str(), ~"[1, 2]"); assert_eq!((@[2, 3]).to_str(), ~"[2, 3]"); let foo = ~[3, 4]; let bar = &[4, 5]; let baz = @[5, 6]; assert_eq!(foo.to_str(), ~"[3, 4]"); assert_eq!(bar.to_str(), ~"[4, 5]"); assert_eq!(baz.to...
main
identifier_name
vec-to_str.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
assert_eq!(foo.to_str(), ~"[3, 4]"); assert_eq!(bar.to_str(), ~"[4, 5]"); assert_eq!(baz.to_str(), ~"[5, 6]"); }
assert_eq!((@[2, 3]).to_str(), ~"[2, 3]"); let foo = ~[3, 4]; let bar = &[4, 5]; let baz = @[5, 6];
random_line_split
vec-to_str.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ assert_eq!((~[0, 1]).to_str(), ~"[0, 1]"); assert_eq!((&[1, 2]).to_str(), ~"[1, 2]"); assert_eq!((@[2, 3]).to_str(), ~"[2, 3]"); let foo = ~[3, 4]; let bar = &[4, 5]; let baz = @[5, 6]; assert_eq!(foo.to_str(), ~"[3, 4]"); assert_eq!(bar.to_str(), ~"[4, 5]"); assert_eq!(baz.to_st...
identifier_body
events.rs
//! (De)serializable types for the events in the [Matrix](https://matrix.org) specification. //! These types are used by other Ruma crates. //! //! All data exchanged over Matrix is expressed as an event. //! Different event types represent different actions, such as joining a room or sending a message. //! Events are ...
/ Marker trait for the content of an ephemeral room event. pub trait EphemeralRoomEventContent: EventContent {} /// Marker trait for the content of a global account data event. pub trait GlobalAccountDataEventContent: EventContent {} /// Marker trait for the content of a room account data event. pub trait RoomAccount...
T::from_parts(event_type, self.json()) } } //
identifier_body
events.rs
//! (De)serializable types for the events in the [Matrix](https://matrix.org) specification. //! These types are used by other Ruma crates. //! //! All data exchanged over Matrix is expressed as an event. //! Different event types represent different actions, such as joining a room or sending a message. //! Events are ...
// Global account data event kind. GlobalAccountData, /// Room account data event kind. RoomAccountData, /// Ephemeral room event kind. EphemeralRoomData, /// Message-like event kind. /// /// Since redacted / non-redacted message-like events are used in the same places but have //...
d { /
identifier_name
events.rs
//! (De)serializable types for the events in the [Matrix](https://matrix.org) specification. //! These types are used by other Ruma crates. //! //! All data exchanged over Matrix is expressed as an event. //! Different event types represent different actions, such as joining a room or sending a message. //! Events are ...
//! Ok(SyncMessageLikeEvent { //! content: ReactionEventContent { //! relates_to: RelatesTo::Annotation { key,.. }, //! }, //! .. //! }) if key == "👍" //! ); //! ``` //! //! # Serialization and deserialization //! //! All concrete event types in this module can be serialized ...
//! // but could be deserialized from a `Raw<_>` that has failed to deserialize. //! matches::assert_matches!( //! serde_json::from_value::<SyncMessageLikeEvent<ReactionEventContent>>(json),
random_line_split
into.rs
use std::iter; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{parse::Result, DeriveInput}; use crate::utils::{add_extra_generic_param, AttrParams, MultiFieldData, State}; /// Provides the hook to expand `#[derive(Into)]` into an implementation of `Into` pub fn expand(input: &DeriveInput, trait...
}; let additional_types = variant_info.additional_types(ref_type); for explicit_type in iter::once(None).chain(additional_types.iter().map(Some)) { let into_types: Vec<_> = field_types .iter() .map(|field_type| { // No, `.unwrap_or()...
let (impl_generics, _, _) = if ref_type.is_ref() { generics_impl = add_extra_generic_param(&input.generics, lifetime); generics_impl.split_for_impl() } else { input.generics.split_for_impl()
random_line_split
into.rs
use std::iter; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{parse::Result, DeriveInput}; use crate::utils::{add_extra_generic_param, AttrParams, MultiFieldData, State}; /// Provides the hook to expand `#[derive(Into)]` into an implementation of `Into` pub fn
(input: &DeriveInput, trait_name: &'static str) -> Result<TokenStream> { let state = State::with_attr_params( input, trait_name, quote!(::core::convert), trait_name.to_lowercase(), AttrParams { enum_: vec!["ignore", "owned", "ref", "ref_mut"], variant:...
expand
identifier_name
into.rs
use std::iter; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{parse::Result, DeriveInput}; use crate::utils::{add_extra_generic_param, AttrParams, MultiFieldData, State}; /// Provides the hook to expand `#[derive(Into)]` into an implementation of `Into` pub fn expand(input: &DeriveInput, trait...
let mut tokens = TokenStream::new(); for ref_type in variant_info.ref_types() { let reference = ref_type.reference(); let lifetime = ref_type.lifetime(); let reference_with_lifetime = ref_type.reference_with_lifetime(); let generics_impl; let (_, ty_generics, where_cla...
{ let state = State::with_attr_params( input, trait_name, quote!(::core::convert), trait_name.to_lowercase(), AttrParams { enum_: vec!["ignore", "owned", "ref", "ref_mut"], variant: vec!["ignore", "owned", "ref", "ref_mut"], struct_: vec!["...
identifier_body
into.rs
use std::iter; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{parse::Result, DeriveInput}; use crate::utils::{add_extra_generic_param, AttrParams, MultiFieldData, State}; /// Provides the hook to expand `#[derive(Into)]` into an implementation of `Into` pub fn expand(input: &DeriveInput, trait...
}); (quote! { #[automatically_derived] impl#impl_generics ::core::convert::From<#reference_with_lifetime #input_type#ty_generics> for (#(#into_types),*) #where_clause { #[inline] fn from(original: #ref...
{ quote! { #reference original.#field_ident } }
conditional_block
traits.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
{ let pointer_size = self.pointer_size(); self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?; let alloc = self.memory.get(vtable.alloc_id)?; let size = alloc.read_ptr_sized(self, vtable.offset(pointer_size, self)?)? .to_bits(pointer_size)? as u64;...
identifier_body
traits.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} self.memory.mark_immutable(vtable.alloc_id)?; assert!(self.vtables.insert((ty, poly_trait_ref), vtable.alloc_id).is_none()); Ok(vtable) } /// Return the drop fn instance as well as the actual dynamic type pub fn read_drop_type_from_vtable( &self, vtable:...
{ let instance = self.resolve(def_id, substs)?; let fn_ptr = self.memory.create_fn_alloc(instance).with_default_tag(); let method_ptr = vtable.offset(ptr_size * (3 + i as u64), self)?; self.memory .get_mut(method_ptr.alloc_id)? ...
conditional_block
traits.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
) -> EvalResult<'tcx, (Size, Align)> { let pointer_size = self.pointer_size(); self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?; let alloc = self.memory.get(vtable.alloc_id)?; let size = alloc.read_ptr_sized(self, vtable.offset(pointer_size, self)?)? ...
pub fn read_size_and_align_from_vtable( &self, vtable: Pointer<M::PointerTag>,
random_line_split
traits.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
( &mut self, ty: Ty<'tcx>, poly_trait_ref: ty::PolyExistentialTraitRef<'tcx>, ) -> EvalResult<'tcx, Pointer<M::PointerTag>> { trace!("get_vtable(trait_ref={:?})", poly_trait_ref); let (ty, poly_trait_ref) = self.tcx.erase_regions(&(ty, poly_trait_ref)); if let Some(...
get_vtable
identifier_name
associated-types-simple.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} struct Struct { x: isize, } impl Get for Struct { type Value = isize; fn get(&self) -> &isize { &self.x } } fn main() { let s = Struct { x: 100, }; assert_eq!(*s.get(), 100); }
trait Get { type Value; fn get(&self) -> &<Self as Get>::Value;
random_line_split
associated-types-simple.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) -> &isize { &self.x } } fn main() { let s = Struct { x: 100, }; assert_eq!(*s.get(), 100); }
get
identifier_name
associated-types-simple.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} fn main() { let s = Struct { x: 100, }; assert_eq!(*s.get(), 100); }
{ &self.x }
identifier_body
tasks.rs
use chrono::{Duration, Local}; use postgres::GenericConnection as PostgresConnection; use redis::Connection as RedisConnection; use timer::{Guard, Timer}; use db::{PostgresPool, RedisPool}; use library::streak::Streak; pub struct TaskRunner { timer: Timer, pg_pool: PostgresPool, redis_pool: RedisPool, } ...
(pg_pool: PostgresPool, redis_pool: RedisPool) -> TaskRunner { TaskRunner { timer: Timer::new(), pg_pool: pg_pool, redis_pool: redis_pool, } } pub fn run(&self) -> Vec<Guard> { let mut guards = Vec::<Guard>::new(); guards.push({ le...
new
identifier_name
tasks.rs
use chrono::{Duration, Local}; use postgres::GenericConnection as PostgresConnection; use redis::Connection as RedisConnection; use timer::{Guard, Timer}; use db::{PostgresPool, RedisPool}; use library::streak::Streak; pub struct TaskRunner { timer: Timer, pg_pool: PostgresPool,
macro_rules! get_conn { ($pool:ident) => { match $pool.get() { Ok(conn) => conn, Err(err) => { error!("Failed to get pooled connection: {}", err); return; } } } } impl TaskRunner { pub fn new(pg_pool: PostgresPool, redis_po...
redis_pool: RedisPool, }
random_line_split
tasks.rs
use chrono::{Duration, Local}; use postgres::GenericConnection as PostgresConnection; use redis::Connection as RedisConnection; use timer::{Guard, Timer}; use db::{PostgresPool, RedisPool}; use library::streak::Streak; pub struct TaskRunner { timer: Timer, pg_pool: PostgresPool, redis_pool: RedisPool, } ...
}; if let Err(err) = streak.save(rds) { error!("Failed to save streak: {}", err); } else { trace!("Streak updated: {:?}", streak); } }
{ error!("Failed to calculate streak: {}", err); return; }
conditional_block
tasks.rs
use chrono::{Duration, Local}; use postgres::GenericConnection as PostgresConnection; use redis::Connection as RedisConnection; use timer::{Guard, Timer}; use db::{PostgresPool, RedisPool}; use library::streak::Streak; pub struct TaskRunner { timer: Timer, pg_pool: PostgresPool, redis_pool: RedisPool, } ...
} fn update_streak(pg: &PostgresConnection, rds: &RedisConnection) { let streak = match Streak::calculate(pg) { Ok(streak) => streak, Err(err) => { error!("Failed to calculate streak: {}", err); return; } }; if let Err(err) = streak.save(rds) { error...
{ let mut guards = Vec::<Guard>::new(); guards.push({ let pg_pool = self.pg_pool.clone(); let redis_pool = self.redis_pool.clone(); self.timer.schedule(Local::now(), Some(Duration::days(1)), move || { let pg_conn = get_conn!(pg_pool); l...
identifier_body
struct-destructuring-cross-crate.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { let x = struct_destructuring_cross_crate::S { x: 1, y: 2 }; let struct_destructuring_cross_crate::S { x: a, y: b } = x; assert_eq!(a, 1); assert_eq!(b, 2); }
random_line_split
struct-destructuring-cross-crate.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x = struct_destructuring_cross_crate::S { x: 1, y: 2 }; let struct_destructuring_cross_crate::S { x: a, y: b } = x; assert_eq!(a, 1); assert_eq!(b, 2); }
main
identifier_name
struct-destructuring-cross-crate.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = struct_destructuring_cross_crate::S { x: 1, y: 2 }; let struct_destructuring_cross_crate::S { x: a, y: b } = x; assert_eq!(a, 1); assert_eq!(b, 2); }
identifier_body
browsingcontext.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use d...
(cx: *mut JSContext, proxy: HandleObject, id: HandleId, bp: *mut bool) -> bool { let window = GetSubframeWindow(cx, proxy, id); if window.is_some() { *bp = true; return true; } rooted!(in...
has
identifier_name
browsingcontext.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use d...
} } pub fn set_reflow_status(&self, status: bool) -> bool { let old = self.needs_reflow.get(); self.needs_reflow.set(status); old } pub fn pipeline(&self) -> PipelineId { self.id } pub fn push_child_context(&self, context: &BrowsingContext) { s...
{ self.children .borrow_mut() .iter_mut() .filter_map(|context| context.remove(id)) .next() }
conditional_block
browsingcontext.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use d...
pub fn active_document(&self) -> Root<Document> { Root::from_ref(&self.history.borrow()[self.active_index.get()].document) } pub fn maybe_active_document(&self) -> Option<Root<Document>> { self.history.borrow().get(self.active_index.get()).map(|entry| { Root::from_ref(&*entry....
{ let mut history = self.history.borrow_mut(); // Clear all session history entries after the active index history.drain((self.active_index.get() + 1)..); history.push(SessionHistoryEntry::new(document, document.url().clone(), document.Title())); self.active_index.set(self.active...
identifier_body
browsingcontext.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use d...
use dom::bindings::utils::WindowProxyHandler; use dom::bindings::utils::get_array_index_from_id; use dom::document::Document; use dom::element::Element; use dom::window::Window; use js::JSCLASS_IS_GLOBAL; use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy}; use js::glue::{GetProxyPrivate, SetProxyExtr...
use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor}; use dom::bindings::reflector::{Reflectable, MutReflectable, Reflector}; use dom::bindings::str::DOMString; use dom::bindings::trace::JSTraceable;
random_line_split
delete_machine.rs
use std::os::unix::fs::PermissionsExt; use pidfile_rs::{ Pidfile, PidfileError, }; use eyre::{ eyre, Result, // Context as _, }; use crate::machine::Machine; use crate::config::MachineConfig; #[xactor::message(result = "Result<()>")] pub struct DeleteMachine; #[async_trait::async_trait] impl xact...
attempts += 1; if attempts >= 10 { break } // Attempt to lock the pidfile let pid_file = MachineConfig::pid_file_path(&self.id); let lock_result = Pidfile::new( &pid_file, std::fs::Permissions::from...
{ // Delete the machine foreign keys in the database sqlx::query!( r#" DELETE FROM machine_print_queues WHERE machine_id = $1 "#, self.id, ) .fetch_optional(&self.db) .await?; // Delete the machi...
identifier_body
delete_machine.rs
use std::os::unix::fs::PermissionsExt; use pidfile_rs::{ Pidfile, PidfileError, }; use eyre::{ eyre, Result, // Context as _, }; use crate::machine::Machine; use crate::config::MachineConfig; #[xactor::message(result = "Result<()>")] pub struct DeleteMachine; #[async_trait::async_trait] impl xact...
) .fetch_optional(&self.db) .await?; // Delete the machine config let config_path = crate::paths::etc_common().join(format!("machine-{}.toml", self.id)); let _ = std::fs::remove_file(config_path); let mut attempted_sig_int = false; let mut attempts...
WHERE machine_id = $1 "#, self.id,
random_line_split
delete_machine.rs
use std::os::unix::fs::PermissionsExt; use pidfile_rs::{ Pidfile, PidfileError, }; use eyre::{ eyre, Result, // Context as _, }; use crate::machine::Machine; use crate::config::MachineConfig; #[xactor::message(result = "Result<()>")] pub struct DeleteMachine; #[async_trait::async_trait] impl xact...
}; async_std::task::sleep(std::time::Duration::from_millis(10)).await; } ctx.stop(Some(eyre!("Unable to kill pid for deleted machine ID: {}", self.id))); Ok(()) } }
{ // Other weirdness - let's try again in a little bit }
conditional_block
delete_machine.rs
use std::os::unix::fs::PermissionsExt; use pidfile_rs::{ Pidfile, PidfileError, }; use eyre::{ eyre, Result, // Context as _, }; use crate::machine::Machine; use crate::config::MachineConfig; #[xactor::message(result = "Result<()>")] pub struct
; #[async_trait::async_trait] impl xactor::Handler<DeleteMachine> for Machine { async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: DeleteMachine) -> Result<()> { // Delete the machine foreign keys in the database sqlx::query!( r#" DELETE FROM machine_print...
DeleteMachine
identifier_name
no_0350_intersection_of_two_arrays_ii.rs
struct Solution; impl Solution { pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32>
意理解错了 // 这个解法求的是连续出现的,题目是可以不连续的,而且顺序也无关。 pub fn intersect_failed(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> { // 练习下动态规划 let (m, n) = (nums1.len(), nums2.len()); let mut dp = vec![vec![0; n + 1]; m + 1]; let mut max_len = 0; let mut pos = (0, 0); for i in (0.....
{ // key => num, value => 出现的次数 let mut map = std::collections::HashMap::with_capacity(nums1.len()); for num in nums1 { let v = map.entry(num).or_insert(0); *v += 1; } let mut ans = Vec::new(); for num in nums2 { if let Some(count) = ma...
identifier_body
no_0350_intersection_of_two_arrays_ii.rs
struct Solution; impl Solution { pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> { // key => num, value => 出现的次数 let mut map = std::collections::HashMap::with_capacity(nums1.len()); for num in nums1 { let v = map.entry(num).or_insert(0); *v += 1; ...
if nums1[i] == nums2[j] { dp[i][j] = dp[i + 1][j + 1] + 1; } else { dp[i][j] = 0; } if max_len <= dp[i][j] { max_len = dp[i][j]; pos = (i, j); } } ...
for i in (0..m).rev() { for j in (0..n).rev() {
random_line_split
no_0350_intersection_of_two_arrays_ii.rs
struct Solution; impl Solution { pub fn
(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> { // key => num, value => 出现的次数 let mut map = std::collections::HashMap::with_capacity(nums1.len()); for num in nums1 { let v = map.entry(num).or_insert(0); *v += 1; } let mut ans = Vec::new(); for num...
intersect
identifier_name
no_0350_intersection_of_two_arrays_ii.rs
struct Solution; impl Solution { pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> { // key => num, value => 出现的次数 let mut map = std::collections::HashMap::with_capacity(nums1.len()); for num in nums1 { let v = map.entry(num).or_insert(0); *v += 1; ...
pos = (i, j); } } } nums1 .get(pos.0..(pos.0 + max_len)) .map(|x| x.iter().map(|x| *x).collect()) .unwrap_or(Vec::new()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_intersect1() { let mut res = Sol...
max_len = dp[i][j];
conditional_block
config.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use serde::{Deserialize, Serialize}; use tikv_util::config::ReadableDuration; #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(default)] #[serde(rename_all = "kebab-case")] pub struct Config { pub max_batch_size: Option<usize>, ...
() -> Config { Config { max_batch_size: None, pool_size: 2, reschedule_duration: ReadableDuration::secs(5), low_priority_pool_size: 1, } } }
default
identifier_name
config.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use serde::{Deserialize, Serialize}; use tikv_util::config::ReadableDuration; #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(default)] #[serde(rename_all = "kebab-case")] pub struct Config { pub max_batch_size: Option<usize>, ...
}
random_line_split
operator-overloading.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl ops::Index<bool,int> for Point { fn index(&self, +x: &bool) -> int { if *x { self.x } else { self.y } } } impl cmp::Eq for Point { fn eq(&self, other: &Point) -> bool { (*self).x == (*other).x && (*self).y == (*other).y } fn ne(&self, other: &Point) -> bool {!(*self).eq(oth...
{ Point {x: !self.x, y: !self.y } }
identifier_body
operator-overloading.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { self.y } } } impl cmp::Eq for Point { fn eq(&self, other: &Point) -> bool { (*self).x == (*other).x && (*self).y == (*other).y } fn ne(&self, other: &Point) -> bool {!(*self).eq(other) } } pub fn main() { let mut p = Point {x: 10, y: 20}; p += Point {x: 101, y: 102}; p = p ...
{ self.x }
conditional_block
operator-overloading.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) -> Point { Point {x:!self.x, y:!self.y } } } impl ops::Index<bool,int> for Point { fn index(&self, +x: &bool) -> int { if *x { self.x } else { self.y } } } impl cmp::Eq for Point { fn eq(&self, other: &Point) -> bool { (*self).x == (*other).x && (*self).y == (*other).y ...
not
identifier_name
operator-overloading.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let q =!p; assert!(q.x ==!(p.x)); assert!(q.y ==!(p.y)); // Issue #1733 let result: ~fn(int) = |_|(); result(p[true]); }
p = p - Point {x: 100, y: 100}; assert!(p + Point {x: 5, y: 5} == Point {x: 16, y: 27}); assert!(-p == Point {x: -11, y: -22}); assert!(p[true] == 11); assert!(p[false] == 22);
random_line_split
tac_code.rs
use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Result; use super::{ function_attributes::FunctionAttribute, types::Type, node_info::{ DeclarationInfo, FunctionInfo }, }; use std::rc::Rc; #[derive(Clone, Debug, PartialEq)] pub enum Statement { Assignment{ operator: Optio...
(&self, formatter: &mut Formatter) -> Result { write!(formatter, "{}", match *self { Operator::Plus => "+".to_string(), Operator::Minus => "-".to_string(), Operator::Multiply => "*".to_string(), Operator::Divide => "/".to_string(), Operator::Modu...
fmt
identifier_name
tac_code.rs
use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Result; use super::{ function_attributes::FunctionAttribute, types::Type, node_info::{ DeclarationInfo, FunctionInfo }, }; use std::rc::Rc; #[derive(Clone, Debug, PartialEq)] pub enum Statement { Assignment{ operator: Optio...
fn fmt(&self, formatter: &mut Formatter) -> Result { write!(formatter, "{}", match *self { Statement::Assignment{ref operator, ref destination, ref left_operand, ref right_operand} => format!("{}= {}{}{}", opt_to_str(destination), ...
} impl Display for Statement {
random_line_split
tac_code.rs
use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Result; use super::{ function_attributes::FunctionAttribute, types::Type, node_info::{ DeclarationInfo, FunctionInfo }, }; use std::rc::Rc; #[derive(Clone, Debug, PartialEq)] pub enum Statement { Assignment{ operator: Optio...
"<initialized {} value>", t), }) } } impl Display for Operator { fn fmt(&self, formatter: &mut Formatter) -> Result { write!(formatter, "{}", match *self { Operator::Plus => "+".to_string(), Operator::Minus => "-".to_string(), Opera...
{ write!(formatter, "{}", match *self { Operand::ArrayIndex { id, ref index_operand, ref variable_info} => { format!("{}_{}[{}]", variable_info.name, id, index_operand) }, Operand::ArraySlice{ id, ref start_operand, ref end_operand, ref variable_info} => ...
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use egl::egl::EGLContext; use egl::egl::EGLDisplay; use egl::egl::EGLSurface; use egl::egl::MakeCurrent; use egl:...
(&self, _contents: String) {} fn on_devtools_started(&self, port: Result<u16, ()>) { match port { Ok(p) => info!("Devtools Server running on port {}", p), Err(()) => error!("Error running Devtools server"), } } } pub struct ServoInstance { scroll_state: ScrollState,...
set_clipboard_contents
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use egl::egl::EGLContext; use egl::egl::EGLDisplay; use egl::egl::EGLSurface; use egl::egl::MakeCurrent; use egl:...
fn set_clipboard_contents(&self, _contents: String) {} fn on_devtools_started(&self, port: Result<u16, ()>) { match port { Ok(p) => info!("Devtools Server running on port {}", p), Err(()) => error!("Error running Devtools server"), } } } pub struct ServoInstance {...
{ None }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use egl::egl::EGLContext; use egl::egl::EGLDisplay; use egl::egl::EGLSurface; use egl::egl::MakeCurrent; use egl:...
let service = Box::new(service); let heartbeat = Box::new(heartbeat); VRInitOptions::VRService(service, heartbeat) } else { VRInitOptions::None }; let xr_discovery: Option<Box<dyn webxr_api::Discovery>> = if!landscape { let discovery = MagicLeapDiscovery::new(ctxt, g...
let vr_init = if !landscape { let name = String::from("Magic Leap VR Display"); let (service, heartbeat) = MagicLeapVRService::new(name, ctxt, gl.gl_wrapper.clone()) .expect("Failed to create VR service");
random_line_split
tips.rs
/// Utilties for loading remote FROG tips. use futures::{Future, Stream}; use errors::*; use hyper::{self, Method, Request}; use hyper::header::ContentType; use hyper_tls; use tokio_core::reactor::Core;
/// A tip, as received from the server. These are the public API fields. #[allow(dead_code)] #[derive(Clone, Serialize, Deserialize, Debug)] pub struct Tip { pub number: TipNum, pub tip: String, } /// A croak is normally precisely 50 tips, but serde_json can't handle encoding and decoding /// fixed-sized arra...
use serde_json; use std::io; /// A tip number, as received from the server. I doubt we'll overflow. type TipNum = u64;
random_line_split
tips.rs
/// Utilties for loading remote FROG tips. use futures::{Future, Stream}; use errors::*; use hyper::{self, Method, Request}; use hyper::header::ContentType; use hyper_tls; use tokio_core::reactor::Core; use serde_json; use std::io; /// A tip number, as received from the server. I doubt we'll overflow. type TipNum = u...
{ pub number: TipNum, pub tip: String, } /// A croak is normally precisely 50 tips, but serde_json can't handle encoding and decoding /// fixed-sized arrays, so this contains a vector of tips. #[derive(Serialize, Deserialize, Debug)] pub struct Croak { pub tips: Vec<Tip>, } /// Return a `Result` with a `...
Tip
identifier_name
block_sync.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
self.blocks.insert_headers(headers); trace!(target: "sync", "Inserted {} headers", count); }, _ => trace!(target: "sync", "Unexpected headers({})", headers.len()), } Ok(DownloadAction::None) } /// Called by peer once it has new block bodies pub fn import_bodies(&mut self, _io: &mut SyncIo, r: &U...
{ trace!(target: "sync", "No useful headers"); return Err(BlockDownloaderImportError::Useless); }
conditional_block
block_sync.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
}; // Perform basic block verification if!Block::is_good(&block) { debug!(target: "sync", "Bad block rlp {:?} : {:?}", h, block); bad = true; break; } if self.target_hash.as_ref().map_or(false, |t| t == &h) { self.state = State::Complete; trace!(target: "sync", "Sync target reached"...
let block = block_and_receipts.block; let receipts = block_and_receipts.receipts; let (h, number, parent) = { let header = BlockView::new(&block).header_view(); (header.sha3(), header.number(), header.parent_hash())
random_line_split
block_sync.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
self.reset(); } else { let n = start - min(self.retract_step, start); self.retract_step *= 2; match io.chain().block_hash(BlockId::Number(n)) { Some(h) => { self.last_imported_block = n; self.last_imported_hash = h; trace!(target: "sync", "Searching common hea...
{ self.state = State::ChainHead; trace!(target: "sync", "Starting round (last imported count = {:?}, last started = {}, block = {:?}", self.imported_this_round, self.last_round_start, self.last_imported_block); // Check if need to retract to find the common block. The problem is that the peers still return header...
identifier_body
block_sync.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
{ /// No active downloads. Idle, /// Downloading subchain heads ChainHead, /// Downloading blocks Blocks, /// Download is complete Complete, } /// Data that needs to be requested from a peer. pub enum BlockRequest { Headers { start: H256, count: u64, skip: u64, }, Bodies { hashes: Vec<H256>, }, R...
State
identifier_name
char_class.rs
// Copyright 2014 Strahinja Val Markovic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
let chars = toU32Vector( &contents ); let mut char_class = CharClass { single_chars: Vec::new(), ranges: Vec::new() }; let mut index = 0; loop { match rangeAtIndex( index, &chars ) { Some( range ) => { char_class.ranges.push( range ); ...
{ match ( chars.get( index ), chars.get( index + 1 ), chars.get( index + 2 ) ) { ( Some( char1 ), Some( char2 ), Some( char3 ) ) if *char2 == '-' as u32 => Some( ( *char1, *char3 ) ), _ => None } }
identifier_body
char_class.rs
// Copyright 2014 Strahinja Val Markovic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
() { assert!( charClassMatch( class!( "a" ), b"a" ) ); assert!( charClassMatch( class!( "abcdef" ), b"e" ) ); assert!( charClassMatch( class!( "a-z" ), b"a" ) ); assert!( charClassMatch( class!( "a-z" ), b"c" ) ); assert!( charClassMatch( class!( "a-z" ), b"z" ) ); ...
CharClass_Match
identifier_name
char_class.rs
// Copyright 2014 Strahinja Val Markovic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
_ => None } } } impl Expression for CharClass { fn apply<'a>( &self, parse_state: &ParseState<'a> ) -> Option< ParseResult<'a> > { self.applyToUtf8( parse_state ).or( self.applyToBytes( parse_state ) ) } } #[cfg(test)] mod tests { use base; use base::{Node, Data, ParseResult, Expressi...
{ parse_state.offsetToResult( parse_state.offset + 1 ) }
conditional_block
char_class.rs
// Copyright 2014 Strahinja Val Markovic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
assert!( charClassMatch( class!( "a-zA-Z-" ), b"z" ) ); assert!( charClassMatch( class!( "aa-zA-Z-0" ), b"0" ) ); assert!( charClassMatch( class!( "a-cdefgh-k" ), b"e" ) ); assert!( charClassMatch( class!( "---" ), b"-" ) ); assert!( charClassMatch( class!( "a-a" ), b"a" ) ); } ...
assert!( charClassMatch( class!( "-" ), b"-" ) ); assert!( charClassMatch( class!( "a-" ), b"-" ) ); assert!( charClassMatch( class!( "-a" ), b"-" ) ); assert!( charClassMatch( class!( "a-zA-Z-" ), b"-" ) ); assert!( charClassMatch( class!( "aa-zA-Z-a" ), b"-" ) );
random_line_split
issue-3953.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ if Lol(2) == Lol(4) { println!("2 == 4"); } else { println!("2 != 4"); } }
identifier_body
issue-3953.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
{ println!("2 != 4"); }
conditional_block
issue-3953.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self, other: &Lol) -> bool { **self == **other } } fn main() { if Lol(2) == Lol(4) { println!("2 == 4"); } else { println!("2!= 4"); } }
ne
identifier_name
issue-3953.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-tidy-linelength use std::cmp::PartialEq; trait Hahaha: PartialEq + PartialEq { //~^ ERROR trait `PartialEq` already appears in the list of bounds } struct Lol(isize); impl Hahaha for Lol { } impl Par...
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
gate.rs
// ignore-arm // ignore-aarch64 // ignore-wasm // ignore-emscripten // ignore-mips // ignore-mips64 // ignore-powerpc // ignore-powerpc64 // ignore-powerpc64le // ignore-riscv64 // ignore-sparc // ignore-sparc64 // ignore-s390x // gate-test-sse4a_target_feature // gate-test-powerpc_target_feature // gate-test-avx512_ta...
fn main() {}
{}
identifier_body
gate.rs
// ignore-arm // ignore-aarch64 // ignore-wasm // ignore-emscripten // ignore-mips // ignore-mips64 // ignore-powerpc // ignore-powerpc64 // ignore-powerpc64le
// gate-test-powerpc_target_feature // gate-test-avx512_target_feature // gate-test-tbm_target_feature // gate-test-arm_target_feature // gate-test-aarch64_target_feature // gate-test-hexagon_target_feature // gate-test-mips_target_feature // gate-test-wasm_target_feature // gate-test-adx_target_feature // gate-test-cm...
// ignore-riscv64 // ignore-sparc // ignore-sparc64 // ignore-s390x // gate-test-sse4a_target_feature
random_line_split
gate.rs
// ignore-arm // ignore-aarch64 // ignore-wasm // ignore-emscripten // ignore-mips // ignore-mips64 // ignore-powerpc // ignore-powerpc64 // ignore-powerpc64le // ignore-riscv64 // ignore-sparc // ignore-sparc64 // ignore-s390x // gate-test-sse4a_target_feature // gate-test-powerpc_target_feature // gate-test-avx512_ta...
() {} fn main() {}
foo
identifier_name
values.rs
use num::FromPrimitive; pub const FALSE: u8 = 0; pub const TRUE: u8 = 1; /// This gets added to the trainer class when setting CURRENT_OPPONENT pub const TRAINER_TAG: u8 = 0xC8; /// Any tile that has a value above this is a menu tile and therefore should be drawn on top of /// sprites. pub const MAX_MAP_TILE: u8 = 0...
pub const RYHDON: u8 = 0x01; pub const WEEDLE: u8 = 0x70; } pub mod status { pub const NONE : u8 = 0; pub const POISON : u8 = 3; pub const BURN : u8 = 4; pub const FREEZE : u8 = 5; pub const PARALYZE: u8 = 6; pub const SLEEP : u8 = 7; } pub mod types { pub const NORMAL :...
pub mod pokeid { // TODO: Add more pokemon
random_line_split
values.rs
use num::FromPrimitive; pub const FALSE: u8 = 0; pub const TRUE: u8 = 1; /// This gets added to the trainer class when setting CURRENT_OPPONENT pub const TRAINER_TAG: u8 = 0xC8; /// Any tile that has a value above this is a menu tile and therefore should be drawn on top of /// sprites. pub const MAX_MAP_TILE: u8 = 0...
(n: i64) -> Option<Direction> { match n { 0x0 => Some(Direction::Down), 0x4 => Some(Direction::Up), 0x8 => Some(Direction::Left), 0xC => Some(Direction::Right), _ => None, } } fn from_u64(n: u64) -> Option<Direction> { From...
from_i64
identifier_name
htmlparagraphelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLParagraphElementBinding; use crate::dom::bindings::root::DomRoot...
}
{ Node::reflect_node( Box::new(HTMLParagraphElement::new_inherited( local_name, prefix, document, )), document, HTMLParagraphElementBinding::Wrap, ) }
identifier_body
htmlparagraphelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLParagraphElementBinding; use crate::dom::bindings::root::DomRoot...
( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLParagraphElement> { Node::reflect_node( Box::new(HTMLParagraphElement::new_inherited( local_name, prefix, document, )), document, HTM...
new
identifier_name
htmlparagraphelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLParagraphElementBinding; use crate::dom::bindings::root::DomRoot...
document: &Document, ) -> HTMLParagraphElement { HTMLParagraphElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document...
impl HTMLParagraphElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>,
random_line_split
lib.rs
//! `xxcalc` is a crate which provides an embeddable floating-point //! polynomial calculator and linear solver. //! //! You can use `xxcalc` to embed mathematical expression evaluator //! in your own programs. By default the calculator provides addition `+`, //! subtraction `-`, multiplication `*`, division `/` and ex...
/// List of tokens with their position. /// /// Tokens are represented as space-efficient continous vector /// of tuples consisting of position in a input string and a /// corresponding Token. pub type TokenList = Vec<(usize, Token)>; /// Vector of unique identifiers. /// /// `Token::Identifier` stores just a location...
random_line_split
lib.rs
//! `xxcalc` is a crate which provides an embeddable floating-point //! polynomial calculator and linear solver. //! //! You can use `xxcalc` to embed mathematical expression evaluator //! in your own programs. By default the calculator provides addition `+`, //! subtraction `-`, multiplication `*`, division `/` and ex...
{ /// Encountered an operator, a constant or a function with no meaning /// to the evaluator. Most probably such symbol must be registered /// beforehand. The identifier is a first argument, while its position /// is the last one. UnknownSymbol(String, usize), /// Number of provided arguments for a functi...
EvaluationError
identifier_name
dependency_format.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(sess: &session::Session, cnum: ast::CrateNum, link: cstore::LinkagePreference, m: &mut FnvHashMap<ast::CrateNum, cstore::LinkagePreference>) { match m.get(&cnum) { Some(&link2) => { // If the linkages differ, then we'd have two copies of the library ...
add_library
identifier_name
dependency_format.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} None => { m.insert(cnum, link); } } } fn attempt_static(sess: &session::Session) -> Option<DependencyList> { let crates = sess.cstore.get_used_crates(cstore::RequireStatic); if crates.iter().by_ref().all(|&(_, ref p)| p.is_some()) { Some(crates.into_iter().map(|_| Some(cstore::Req...
}
random_line_split
dependency_format.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
None => {} } sess.cstore.iter_crate_data(|cnum, data| { let src = sess.cstore.get_used_crate_source(cnum).unwrap(); if src.rlib.is_some() { return } sess.err(&format!("dependency `{}` not found in rlib format", ...
{ match ty { // If the global prefer_dynamic switch is turned off, first attempt // static linkage (this can fail). config::CrateTypeExecutable if !sess.opts.cg.prefer_dynamic => { match attempt_static(sess) { Some(v) => return v, None => {} ...
identifier_body
simple.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn maybe_yield(self: Box<SimpleTask>, _cur_task: Box<Task>) { fail!() } fn spawn_sibling(self: Box<SimpleTask>, _cur_task: Box<Task>, _opts: TaskOpts, _f: proc():Send) { fail!() } fn local_io<'a>(&'a mut self) -> Option<rtio::LocalI...
{ fail!() }
identifier_body
simple.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
struct SimpleTask { lock: NativeMutex, awoken: bool, } impl Runtime for SimpleTask { // Implement the simple tasks of descheduling and rescheduling, but only in // a simple number of cases. fn deschedule(mut self: Box<SimpleTask>, times: uint, mut cur_task: Box<...
use std::rt::rtio; use std::rt::task::{Task, BlockedTask, TaskOpts};
random_line_split
simple.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(self: Box<SimpleTask>) -> Box<Any> { fail!() } } pub fn task() -> Box<Task> { let mut task = box Task::new(); task.put_runtime(box SimpleTask { lock: unsafe {NativeMutex::new()}, awoken: false, }); return task; }
wrap
identifier_name
circle_queue.rs
#[derive(Debug)] struct CircleQueue { queue: Vec<i32>, head: i32, tail: i32, n: i32, } impl CircleQueue { fn new(n: i32) -> Self { CircleQueue { queue: vec![-1; n as usize], head: 0, tail: 0, n: n, } } fn enqueue(&mut self, nu...
let shift = self.queue[self.head as usize]; self.head = (self.head + 1) % self.n; shift } fn print_all(&self) { let mut s = String::from(""); for i in self.head..self.tail { s.push(self.queue[i as usize] as u8 as char); s.push_str("->"); ...
{ return -1; }
conditional_block
circle_queue.rs
#[derive(Debug)] struct CircleQueue { queue: Vec<i32>, head: i32, tail: i32, n: i32, } impl CircleQueue { fn new(n: i32) -> Self { CircleQueue { queue: vec![-1; n as usize], head: 0, tail: 0, n: n, } } fn enqueue(&mut self, nu...
s.push_str("->"); } println!("{:?}", s); } } fn main() { let mut queue = CircleQueue::new(10); queue.enqueue(2); queue.enqueue(2); queue.enqueue(2); queue.enqueue(2); queue.dequeue(); queue.dequeue(); queue.enqueue(4); queue.dequeue(); queue.print...
random_line_split
circle_queue.rs
#[derive(Debug)] struct CircleQueue { queue: Vec<i32>, head: i32, tail: i32, n: i32, } impl CircleQueue { fn new(n: i32) -> Self { CircleQueue { queue: vec![-1; n as usize], head: 0, tail: 0, n: n, } } fn enqueue(&mut self, nu...
fn print_all(&self) { let mut s = String::from(""); for i in self.head..self.tail { s.push(self.queue[i as usize] as u8 as char); s.push_str("->"); } println!("{:?}", s); } } fn main() { let mut queue = CircleQueue::new(10); queue.enqueue(2); ...
{ if self.head == self.tail { return -1; } let shift = self.queue[self.head as usize]; self.head = (self.head + 1) % self.n; shift }
identifier_body
circle_queue.rs
#[derive(Debug)] struct CircleQueue { queue: Vec<i32>, head: i32, tail: i32, n: i32, } impl CircleQueue { fn new(n: i32) -> Self { CircleQueue { queue: vec![-1; n as usize], head: 0, tail: 0, n: n, } } fn enqueue(&mut self, nu...
() { let mut queue = CircleQueue::new(10); queue.enqueue(2); queue.enqueue(2); queue.enqueue(2); queue.enqueue(2); queue.dequeue(); queue.dequeue(); queue.enqueue(4); queue.dequeue(); queue.print_all(); }
main
identifier_name
op.rs
#[derive(Debug, PartialEq)] pub enum InfixOp { // A + B Add, // A - B Sub, // A / B Div, // A * B Mul, // A % B Mod, // A ^ B Pow, // A equals B (traditionally A == B) Equ, // A < B Lt, // A <= B Lte, // A > B Gt, // A >= B Gte, } ...
{ // -A Negate, // not A (traditionally!A) Not }
UnaryOp
identifier_name
op.rs
#[derive(Debug, PartialEq)] pub enum InfixOp { // A + B Add, // A - B Sub, // A / B Div, // A * B Mul, // A % B Mod,
// A ^ B Pow, // A equals B (traditionally A == B) Equ, // A < B Lt, // A <= B Lte, // A > B Gt, // A >= B Gte, } impl InfixOp { pub fn get_precedence(&self) -> u8 { // Precedence(High -> Low): // 9. () | []. // 8. not | negate // 7. *...
random_line_split
union_find.rs
pub struct UnionFind { parents: Vec<usize>, ranks: Vec<u64> } impl UnionFind { pub fn new(size: usize) -> UnionFind { UnionFind { parents: (0..size).map(|i| i).collect(), ranks: (0..size).map(|_| 0).collect() } } pub fn find(&mut self, x: usize) -> usize { ...
assert!(uf.find(2)!= uf.find(6)); } }
assert!(uf.find(3) == uf.find(8)); assert!(uf.find(3) != uf.find(6));
random_line_split
union_find.rs
pub struct UnionFind { parents: Vec<usize>, ranks: Vec<u64> } impl UnionFind { pub fn new(size: usize) -> UnionFind { UnionFind { parents: (0..size).map(|i| i).collect(), ranks: (0..size).map(|_| 0).collect() } } pub fn find(&mut self, x: usize) -> usize { ...
}
{ let mut uf = UnionFind::new(10); uf.union(3, 5); uf.union(7, 8); uf.union(7, 9); uf.union(5, 9); assert!(uf.find(3) == uf.find(8)); assert!(uf.find(3) != uf.find(6)); assert!(uf.find(2) != uf.find(6)); }
identifier_body
union_find.rs
pub struct UnionFind { parents: Vec<usize>, ranks: Vec<u64> } impl UnionFind { pub fn
(size: usize) -> UnionFind { UnionFind { parents: (0..size).map(|i| i).collect(), ranks: (0..size).map(|_| 0).collect() } } pub fn find(&mut self, x: usize) -> usize { let parent = self.parents[x]; if parent!= x { self.parents[x] = self.find(...
new
identifier_name
detect.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
unsafe { *buffer = ptr::null(); *buffer_len = 0; } return 0; } #[no_mangle] pub extern "C" fn rs_smb_tx_match_dce_opnum(tx: &mut SMBTransaction, dce_data: &mut DCEOpnumData) -> u8 { SCLogDebug!("rs_sm...
{ match tx.type_data { Some(SMBTransactionTypeData::DCERPC(ref x)) => { let vref = if direction == STREAM_TOSERVER { &x.stub_data_ts } else { &x.stub_data_tc }; if vref.len() > 0 { unsafe { *b...
identifier_body
detect.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
if range.range1 == x.opnum as u32 { return 1; } else if range.range1 <= x.opnum as u32 && range.range2 >= x.opnum as u32 { return 1; } } } } ...
if range.range2 == DETECT_DCE_OPNUM_RANGE_UNINITIALIZED {
random_line_split
detect.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
(tx: &mut SMBTransaction, dce_data: &mut DCEOpnumData) -> u8 { SCLogDebug!("rs_smb_tx_get_dce_opnum: start"); match tx.type_data { Some(SMBTransactionTypeData::DCERPC(ref x)) => { if x.req_cmd == 1 { // REQ...
rs_smb_tx_match_dce_opnum
identifier_name
cht.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITH...
// This file is part of Parity.
random_line_split
cht.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
/// Check a proof for a CHT. /// Given a set of a trie nodes, a number to query, and a trie root, /// verify the given trie branch and extract the canonical hash and total difficulty. // TODO: better support for partially-checked queries. pub fn check_proof(proof: &[Bytes], num: u64, root: H256) -> Option<(H256, U256...
{ let mut v = Vec::with_capacity(SIZE as usize); let start_num = start_number(cht_num) as usize; for (i, (h, td)) in iterable.into_iter().take(SIZE as usize).enumerate() { v.push((key!(i + start_num).to_vec(), val!(h, td).to_vec())) } if v.len() == SIZE as usize { Some(::util::triehash::trie_root(v)) } else...
identifier_body
cht.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
() { assert!(::cht::block_to_cht_number(0).is_none()); assert_eq!(::cht::block_to_cht_number(1).unwrap(), 0); assert_eq!(::cht::block_to_cht_number(::cht::SIZE + 1).unwrap(), 1); assert_eq!(::cht::block_to_cht_number(::cht::SIZE).unwrap(), 0); } #[test] fn start_number() { assert_eq!(::cht::start_number(0...
block_to_cht_number
identifier_name
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, Program}; use graphql_syntax::parse_executable; ...
Ok(result.join("\n\n")) }
{ let ast = parse_executable( fixture.content, SourceLocationKey::standalone(fixture.file_name), ) .unwrap(); let schema = get_test_schema(); let ir = build(&schema, &ast.definitions).unwrap(); let program = Program::from_definitions(Arc::clone(&schema), ir); let next_program...
identifier_body
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, Program}; use graphql_syntax::parse_executable; ...
(fixture: &Fixture<'_>) -> Result<String, String> { let ast = parse_executable( fixture.content, SourceLocationKey::standalone(fixture.file_name), ) .unwrap(); let schema = get_test_schema(); let ir = build(&schema, &ast.definitions).unwrap(); let program = Program::from_definitio...
transform_fixture
identifier_name
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, Program}; use graphql_syntax::parse_executable; ...
.chain( next_program .operations() .map(|def| print_operation(&schema, &def, JsModuleFormat::Haste)), ) .collect::<Vec<_>>(); result.sort_unstable(); Ok(result.join("\n\n")) }
.fragments() .map(|def| print_fragment(&schema, &def, JsModuleFormat::Haste))
random_line_split
all.rs
use std::collections::HashMap; use protobuf::descriptor::FileDescriptorProto; use protobuf::reflect::FileDescriptor; use protobuf_parse::ProtoPath; use protobuf_parse::ProtoPathBuf; use crate::compiler_plugin; use crate::customize::ctx::CustomizeElemCtx; use crate::customize::CustomizeCallback; use crate::gen::file::...
( file_descriptors: &[FileDescriptorProto], parser: &str, files_to_generate: &[ProtoPathBuf], customize: &Customize, customize_callback: &dyn CustomizeCallback, ) -> anyhow::Result<Vec<compiler_plugin::GenResult>> { let file_descriptors = FileDescriptor::new_dynamic_fds(file_descriptors.to_vec()...
gen_all
identifier_name
all.rs
use std::collections::HashMap; use protobuf::descriptor::FileDescriptorProto; use protobuf::reflect::FileDescriptor; use protobuf_parse::ProtoPath; use protobuf_parse::ProtoPathBuf; use crate::compiler_plugin; use crate::customize::ctx::CustomizeElemCtx; use crate::customize::CustomizeCallback; use crate::gen::file::...
Ok(results) }
{ results.push(gen_mod_rs(&mods)); }
conditional_block