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 |
|---|---|---|---|---|
members.rs | use db::Conn;
use errors::Result;
use models::{Member, MemberChangeset};
use schema::members;
use std::ops::Deref;
use rocket::Route;
use rocket_contrib::Json;
use diesel;
use diesel::prelude::*;
pub fn routes() -> Vec<Route> {
routes![index, update]
}
#[get("/", format = "application/json")]
fn | (conn: Conn) -> Result<Json<Vec<Member>>> {
let members = members::dsl::members.load(conn.deref())?;
Ok(Json(members))
}
#[patch("/<id>", format = "application/json", data = "<member_changeset>")]
fn update(id: i32, member_changeset: Json<MemberChangeset>, conn: Conn) -> Result<Json<Member>> {
let member:... | index | identifier_name |
members.rs | use db::Conn;
use errors::Result;
use models::{Member, MemberChangeset};
use schema::members;
use std::ops::Deref;
use rocket::Route;
use rocket_contrib::Json;
use diesel;
use diesel::prelude::*;
pub fn routes() -> Vec<Route> {
routes![index, update]
}
#[get("/", format = "application/json")]
fn index(conn: Con... |
#[test]
fn test_update() {
let pool = default_pool();
let app = app(pool.clone());
let conn = pool.get().unwrap();
let new_team = NewTeam::new(5.0);
let team = diesel::insert(&new_team)
.into(teams::table)
.get_result::<Team>(conn.deref())
... | random_line_split | |
members.rs | use db::Conn;
use errors::Result;
use models::{Member, MemberChangeset};
use schema::members;
use std::ops::Deref;
use rocket::Route;
use rocket_contrib::Json;
use diesel;
use diesel::prelude::*;
pub fn routes() -> Vec<Route> {
routes![index, update]
}
#[get("/", format = "application/json")]
fn index(conn: Con... |
#[test]
fn test_update() {
let pool = default_pool();
let app = app(pool.clone());
let conn = pool.get().unwrap();
let new_team = NewTeam::new(5.0);
let team = diesel::insert(&new_team)
.into(teams::table)
.get_result::<Team>(conn.deref())
... | {
let app = app(default_pool());
let client = Client::new(app).unwrap();
let response = client
.get("/members")
.header(ContentType::JSON)
.dispatch();
assert_eq!(response.status(), Status::Ok);
} | identifier_body |
flags.rs | use std;
use libc::c_int;
/// Rust alternative to Qt's `QFlags` types.
///
/// `Flags<E>` is an OR-combination of integer values of the enum type `E`.
#[derive(Clone, Copy)]
pub struct Flags<E: FlaggableEnum> {
value: c_int,
_phantom_data: std::marker::PhantomData<E>,
}
impl<E: FlaggableEnum> Flags<E> {
/// Co... |
}
impl<T: FlaggableEnum> Default for Flags<T> {
fn default() -> Self {
Flags {
value: 0,
_phantom_data: std::marker::PhantomData,
}
}
}
| {
write!(f, "Flags<{}>({})", T::enum_name(), self.value)
} | identifier_body |
flags.rs | use std;
use libc::c_int;
/// Rust alternative to Qt's `QFlags` types.
///
/// `Flags<E>` is an OR-combination of integer values of the enum type `E`.
#[derive(Clone, Copy)]
pub struct Flags<E: FlaggableEnum> {
value: c_int,
_phantom_data: std::marker::PhantomData<E>,
}
impl<E: FlaggableEnum> Flags<E> {
/// Co... | (value: E) -> Self {
Self::from_int(value.to_flag_value())
}
/// Converts `Flags` to integer.
pub fn to_int(self) -> c_int {
self.value
}
/// Returns `true` if `flag` is enabled in `self`.
pub fn test_flag(self, flag: E) -> bool {
self.value & flag.to_flag_value()!= 0
}
/// Returns `true` if... | from_enum | identifier_name |
flags.rs | use std;
use libc::c_int;
/// Rust alternative to Qt's `QFlags` types.
///
/// `Flags<E>` is an OR-combination of integer values of the enum type `E`.
#[derive(Clone, Copy)]
pub struct Flags<E: FlaggableEnum> {
value: c_int,
_phantom_data: std::marker::PhantomData<E>,
}
impl<E: FlaggableEnum> Flags<E> {
/// Co... | /// Trait representing types that can be converted to `Flags`.
pub trait EnumOrFlags<T: FlaggableEnum> {
fn to_flags(self) -> Flags<T>;
}
// TODO: use Into and From traits instead
impl<T: FlaggableEnum> EnumOrFlags<T> for Flags<T>
where T: Clone
{
fn to_flags(self) -> Flags<T> {
self.clone()
}
}
impl<T: F... | random_line_split | |
scopes.rs | use {ast, typeinf, util};
use core::{Src, CompletionType, Session};
#[cfg(test)] use core;
use std::iter::Iterator;
use std::path::Path;
use std::str::from_utf8;
use util::char_at;
fn find_close<'a, A>(iter: A, open: u8, close: u8, level_end: u32) -> Option<usize> where A: Iterator<Item=&'a u8> {
let mut levels =... | assert_eq!(4, get_start_of_pattern("bla, ast::PatTup(ref tuple_elements) => {",36));
}
pub fn expand_search_expr(msrc: &str, point: usize) -> (usize, usize) {
let start = get_start_of_search_expr(msrc, point);
(start, util::find_ident_end(msrc, point))
}
#[test]
fn expand_search_expr_finds_ident() {
a... | assert_eq!(4, get_start_of_pattern("foo, Some(a) =>",13));
}
#[test]
fn get_start_of_pattern_handles_variant2() { | random_line_split |
scopes.rs | use {ast, typeinf, util};
use core::{Src, CompletionType, Session};
#[cfg(test)] use core;
use std::iter::Iterator;
use std::path::Path;
use std::str::from_utf8;
use util::char_at;
fn find_close<'a, A>(iter: A, open: u8, close: u8, level_end: u32) -> Option<usize> where A: Iterator<Item=&'a u8> {
let mut levels =... |
pub fn get_local_module_path(msrc: Src, point: usize) -> Vec<String> {
let mut v = Vec::new();
get_local_module_path_(msrc, point, &mut v);
v
}
fn get_local_module_path_(msrc: Src, point: usize, out: &mut Vec<String>) {
for (start, end) in msrc.iter_stmts() {
if start < point && end > point {... | {
// iterate the scope to find the start of the statement
let scopestart = scope_start(msrc, point);
msrc.from(scopestart).iter_stmts()
.find(|&(_, end)| scopestart + end > point)
.map(|(start, _)| scopestart + start)
} | identifier_body |
scopes.rs | use {ast, typeinf, util};
use core::{Src, CompletionType, Session};
#[cfg(test)] use core;
use std::iter::Iterator;
use std::path::Path;
use std::str::from_utf8;
use util::char_at;
fn find_close<'a, A>(iter: A, open: u8, close: u8, level_end: u32) -> Option<usize> where A: Iterator<Item=&'a u8> {
let mut levels =... | () {
assert_eq!((0, 20), expand_search_expr("yeah::blah.foo().bar", 18))
}
#[test]
fn expand_search_expr_handles_inline_closures() {
assert_eq!((0, 24), expand_search_expr("yeah::blah.foo(||{}).bar", 22))
}
#[test]
fn expand_search_expr_handles_a_function_arg() {
assert_eq!((5, 25), expand_search_expr("myf... | expand_search_expr_handles_chained_calls | identifier_name |
mod.rs | use sea_canal::Analyzer;
use sea_canal::Pattern;
use sea_canal::PatternElem::*;
#[test]
fn meta_find_any_pattern() {
let slice = &[1, 2, 4, 7, 11];
let analyzer = Analyzer::with_meta(slice);
assert_eq!(Some(pat!(Meta(pat!(Plus(1), Plus(2), Plus(3), Plus(4))))), analyzer.find_any_pattern(1));
}
#[test]
fn... | assert_eq!(Some(pat!(Meta(pat!(Plus(1), Mult(2), Plus(3), Mult(4))), Const(10))), analyzer.find_any_pattern(4));
} | let analyzer = Analyzer::with_meta(slice);
assert_eq!(None, analyzer.find_any_pattern(1)); | random_line_split |
mod.rs | use sea_canal::Analyzer;
use sea_canal::Pattern;
use sea_canal::PatternElem::*;
#[test]
fn meta_find_any_pattern() {
let slice = &[1, 2, 4, 7, 11];
let analyzer = Analyzer::with_meta(slice);
assert_eq!(Some(pat!(Meta(pat!(Plus(1), Plus(2), Plus(3), Plus(4))))), analyzer.find_any_pattern(1));
}
#[test]
fn... | () {
let slice = &[10, 11, 10, 20, 10, 13, 10, 40];
let analyzer = Analyzer::with_meta(slice);
assert_eq!(None, analyzer.find_any_pattern(1));
assert_eq!(Some(pat!(Meta(pat!(Plus(1), Mult(2), Plus(3), Mult(4))), Const(10))), analyzer.find_any_pattern(4));
}
| mixed_operand_meta_pattern | identifier_name |
mod.rs | use sea_canal::Analyzer;
use sea_canal::Pattern;
use sea_canal::PatternElem::*;
#[test]
fn meta_find_any_pattern() {
let slice = &[1, 2, 4, 7, 11];
let analyzer = Analyzer::with_meta(slice);
assert_eq!(Some(pat!(Meta(pat!(Plus(1), Plus(2), Plus(3), Plus(4))))), analyzer.find_any_pattern(1));
}
#[test]
fn... | {
let slice = &[10, 11, 10, 20, 10, 13, 10, 40];
let analyzer = Analyzer::with_meta(slice);
assert_eq!(None, analyzer.find_any_pattern(1));
assert_eq!(Some(pat!(Meta(pat!(Plus(1), Mult(2), Plus(3), Mult(4))), Const(10))), analyzer.find_any_pattern(4));
} | identifier_body | |
multi_product.rs | #![cfg(feature = "use_std")]
use crate::size_hint;
use crate::Itertools;
#[derive(Clone)]
/// An iterator adaptor that iterates over the cartesian product of
/// multiple iterators of type `I`.
///
/// An iterator element type is `Vec<I>`.
///
/// See [`.multi_cartesian_product()`](../trait.Itertools.html#method.mult... |
}
impl<I> Iterator for MultiProduct<I>
where I: Iterator + Clone,
I::Item: Clone
{
type Item = Vec<I::Item>;
fn next(&mut self) -> Option<Self::Item> {
if MultiProduct::iterate_last(
&mut self.0,
MultiProductIterState::StartOfIter
) {
Some(sel... | {
self.cur.is_some()
} | identifier_body |
multi_product.rs | #![cfg(feature = "use_std")]
use crate::size_hint;
use crate::Itertools;
#[derive(Clone)]
/// An iterator adaptor that iterates over the cartesian product of
/// multiple iterators of type `I`.
///
/// An iterator element type is `Vec<I>`.
///
/// See [`.multi_cartesian_product()`](../trait.Itertools.html#method.mult... | self.0.iter().map(|multi_iter| {
multi_iter.cur.clone().unwrap()
}).collect()
}
/// Returns true if iteration has started and has not yet finished; false
/// otherwise.
fn in_progress(&self) -> bool {
if let Some(last) = self.0.last() {
last.in_progress()... |
/// Returns the unwrapped value of the next iteration.
fn curr_iterator(&self) -> Vec<I::Item> { | random_line_split |
multi_product.rs | #![cfg(feature = "use_std")]
use crate::size_hint;
use crate::Itertools;
#[derive(Clone)]
/// An iterator adaptor that iterates over the cartesian product of
/// multiple iterators of type `I`.
///
/// An iterator element type is `Vec<I>`.
///
/// See [`.multi_cartesian_product()`](../trait.Itertools.html#method.mult... | (&mut self) {
self.cur = self.iter.next();
}
/// Reset the managed iterator.
fn reset(&mut self) {
self.iter = self.iter_orig.clone();
}
/// Returns true if the current iterator has been started and has not yet
/// finished; false otherwise.
fn in_progress(&self) -> bool {
... | iterate | identifier_name |
multi_product.rs | #![cfg(feature = "use_std")]
use crate::size_hint;
use crate::Itertools;
#[derive(Clone)]
/// An iterator adaptor that iterates over the cartesian product of
/// multiple iterators of type `I`.
///
/// An iterator element type is `Vec<I>`.
///
/// See [`.multi_cartesian_product()`](../trait.Itertools.html#method.mult... |
if last.in_progress() {
true
} else if MultiProduct::iterate_last(rest, state) {
last.reset();
last.iterate();
// If iterator is None twice consecutively, then iterator is
// empty; whole product is empty.
... | {
last.iterate();
} | conditional_block |
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/. */
#[macro_use]
extern crate serde;
use euclid::default::{Point2D, Rect, Size2D};
use malloc_size_of_derive::Malloc... |
let origin = Point2D::new(origin.x as u64, origin.y as u64);
Rect::new(origin, size)
.intersection(&Rect::from_size(surface))
.filter(|rect|!rect.is_empty())
}
| {
size.height = size.height.saturating_sub(-origin.y as u64);
origin.y = 0;
} | conditional_block |
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/. */
#[macro_use]
extern crate serde;
use euclid::default::{Point2D, Rect, Size2D};
use malloc_size_of_derive::Malloc... | .filter(|rect|!rect.is_empty())
} | random_line_split | |
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/. */
#[macro_use]
extern crate serde;
use euclid::default::{Point2D, Rect, Size2D};
use malloc_size_of_derive::Malloc... | (a: u8, b: u8) -> u8 {
return (a as u32 * b as u32 / 255) as u8;
}
pub fn clip(
mut origin: Point2D<i32>,
mut size: Size2D<u64>,
surface: Size2D<u64>,
) -> Option<Rect<u64>> {
if origin.x < 0 {
size.width = size.width.saturating_sub(-origin.x as u64);
origin.x = 0;
}
if orig... | multiply_u8_color | 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/. */
#[macro_use]
extern crate serde;
use euclid::default::{Point2D, Rect, Size2D};
use malloc_size_of_derive::Malloc... |
pub fn clip(
mut origin: Point2D<i32>,
mut size: Size2D<u64>,
surface: Size2D<u64>,
) -> Option<Rect<u64>> {
if origin.x < 0 {
size.width = size.width.saturating_sub(-origin.x as u64);
origin.x = 0;
}
if origin.y < 0 {
size.height = size.height.saturating_sub(-origin.y ... | {
return (a as u32 * b as u32 / 255) as u8;
} | identifier_body |
unique-object-move.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 struct UvEventLoop {
uvio: isize
}
impl EventLoop for UvEventLoop { }
pub fn main() {
let loop_: Box<EventLoop> = box UvEventLoop { uvio: 0 } as Box<EventLoop>;
let _loop2_ = loop_;
}
| {} | identifier_body |
unique-object-move.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 trait EventLoop { fn foo(&self) {} }
pub struct UvEventLoop {
uvio: isize
}
impl EventLoop for UvEventLoop { }
pub fn main() {
let loop_: Box<EventLoop> = box UvEventLoop { uvio: 0 } as Box<EventLoop>;
let _loop2_ = loop_;
} | #![feature(box_syntax)] | random_line_split |
unique-object-move.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 ... | {
uvio: isize
}
impl EventLoop for UvEventLoop { }
pub fn main() {
let loop_: Box<EventLoop> = box UvEventLoop { uvio: 0 } as Box<EventLoop>;
let _loop2_ = loop_;
}
| UvEventLoop | identifier_name |
outline.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
| additional_methods=[Method("outline_has_nonzero_width", "bool")]) %>
// TODO(pcwalton): `invert`
${helpers.predefined_type("outline-color", "CSSColor", "::cssparser::Color::CurrentColor",
animatable=True)}
<%helpers:longhand name="outline-style" need_clone="True" ani... | <% data.new_style_struct("Outline",
inherited=False, | random_line_split |
outline.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Out... | (&self, context: &Context) -> computed_value::T {
self.0.to_computed_value(context)
}
}
</%helpers:longhand>
// The -moz-outline-radius-* properties are non-standard and not on a standards track.
// TODO: Should they animate?
% for corner in ["topleft", "topright", "bottomright", "bottomleft"]:... | to_computed_value | identifier_name |
outline.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Out... |
}
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
specified::parse_border_width(input).map(SpecifiedValue)
}
impl HasViewportPercentage for SpecifiedValue {
fn has_viewport_percentage(&self) -> bool {
let &SpecifiedValue(length) =... | {
self.0.to_css(dest)
} | identifier_body |
htmltitleelement.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::codegen::Bindings::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... | }
}
impl VirtualMethods for HTMLTitleElement {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn children_changed(&self, mutation: &ChildrenMutation) {
if let So... | random_line_split | |
htmltitleelement.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::codegen::Bindings::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... |
}
fn bind_to_tree(&self, is_in_doc: bool) {
let node = NodeCast::from_ref(self);
if is_in_doc {
let document = node.owner_doc();
document.r().title_changed();
}
}
}
| {
node.owner_doc().title_changed();
} | conditional_block |
htmltitleelement.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::codegen::Bindings::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... | (&self) -> DOMString {
let node = NodeCast::from_ref(self);
let mut content = String::new();
for child in node.children() {
let text: Option<&Text> = TextCast::to_ref(child.r());
match text {
Some(text) => content.push_str(&CharacterDataCast::from_ref(text... | Text | identifier_name |
htmltitleelement.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::codegen::Bindings::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... |
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTitleElement> {
let element = HTMLTitleElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTitl... | {
HTMLTitleElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTitleElement, localName, prefix, document)
}
} | identifier_body |
emoji.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... | // please edit https://github.com/slack-rs/slack-rs-api/tree/master/codegen
//
//=============================================================================
pub use crate::mod_types::emoji_types::*;
use crate::sync::requests::SlackWebRequestSender;
/// Lists custom emoji for a team.
///
/// Wraps https://api.slack.... | random_line_split | |
emoji.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... | <R>(client: &R, token: &str) -> Result<ListResponse, ListError<R::Error>>
where
R: SlackWebRequestSender,
{
let params = &[("token", token)];
let url = crate::get_slack_url_for_method("emoji.list");
client
.send(&url, ¶ms[..])
.map_err(ListError::Client)
.and_then(|result| {
... | list | identifier_name |
emoji.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... | {
let params = &[("token", token)];
let url = crate::get_slack_url_for_method("emoji.list");
client
.send(&url, ¶ms[..])
.map_err(ListError::Client)
.and_then(|result| {
serde_json::from_str::<ListResponse>(&result)
.map_err(|e| ListError::MalformedRes... | identifier_body | |
build.rs | use std::env;
use std::fs;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use protobuf_codegen::Codegen;
use protobuf_test_common::build::*;
use protobuf_test_common::print_rerun_if_changed_recursively;
fn copy_test<P1: AsRef<Path>, P2: AsRef<Path>>(src: P1, dst: P2) {
eprintln!("copy {:?} to {:?}", ... | () {
env_logger::init();
clean_old_files();
generate_pb_rs();
}
| main | identifier_name |
build.rs | use std::env;
use std::fs;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use protobuf_codegen::Codegen;
use protobuf_test_common::build::*;
use protobuf_test_common::print_rerun_if_changed_recursively;
fn copy_test<P1: AsRef<Path>, P2: AsRef<Path>>(src: P1, dst: P2) {
eprintln!("copy {:?} to {:?}", ... | .run_from_script();
}
fn generate_pb_rs() {
print_rerun_if_changed_recursively("../../test-crates/protobuf-test");
copy_tests("src/v2");
gen_in_dir("src/v2", "src/v2");
copy_tests("src/v3");
gen_in_dir("src/v3", "src/v3");
copy_tests("src/common/v2");
gen_in_dir("src/common/v2", "... | .pure()
.out_dir(dir)
.input("../../test-crates/protobuf-test/src/include_generated/v2.proto")
.input("../../test-crates/protobuf-test/src/include_generated/v3.proto")
.include("../../test-crates/protobuf-test/src/include_generated") | random_line_split |
wait_delete.rs | // Copyright 2019 Guanhao Yin <sopium@mysterious.site>
// This file is part of TiTun.
// TiTun 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 la... | let _ = ready.send(());
let buf = vec![0u8; 1024];
let mut stream = inotify.event_stream(buf).context("event_stream")?;
loop {
let event = stream.next().await.unwrap().context("next")?;
if event.mask == EventMask::DELETE && event.name.as_ref() == Some(&file_name) {
break;
... | .context("add_watch")?; | random_line_split |
wait_delete.rs | // Copyright 2019 Guanhao Yin <sopium@mysterious.site>
// This file is part of TiTun.
// TiTun 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 la... | (p: &Path, ready: Sender<()>) -> anyhow::Result<()> {
// Use inotify on linux.
use anyhow::Context;
use futures::StreamExt;
use inotify::{EventMask, Inotify, WatchMask};
let file_name = p.file_name().unwrap().into();
let parent_dir = p.parent().unwrap();
let mut inotify = Inotify::init().co... | wait_delete | identifier_name |
wait_delete.rs | // Copyright 2019 Guanhao Yin <sopium@mysterious.site>
// This file is part of TiTun.
// TiTun 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 la... |
}
if!found {
break;
}
std::thread::sleep(std::time::Duration::from_secs(2));
}
tx.send(Ok(())).unwrap();
});
rx.await.unwrap()
}
#[cfg(target_os = "linux")]
pub async fn wait_delete(p: &Path, ready: Sender<()>) -> anyhow::Result<... | {
found = true;
break;
} | conditional_block |
wait_delete.rs | // Copyright 2019 Guanhao Yin <sopium@mysterious.site>
// This file is part of TiTun.
// TiTun 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 la... | }
Ok(())
}
#[cfg(test)]
mod tests {
// XXX: On mips/mipsel, `INotify::init` (`inotify_init1`) returns an
// `EINVAL` error *in CI*. Ignore the test for now.
#[cfg(not(target_arch = "mips"))]
#[tokio::test]
async fn test_wait_delete() {
use super::*;
use nix::unistd::{mkstem... | {
// Use inotify on linux.
use anyhow::Context;
use futures::StreamExt;
use inotify::{EventMask, Inotify, WatchMask};
let file_name = p.file_name().unwrap().into();
let parent_dir = p.parent().unwrap();
let mut inotify = Inotify::init().context("init")?;
inotify
.add_watch(paren... | identifier_body |
util.rs | // Copyright 2012-2015 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-MI... |
pub fn logv(config: &Config, s: String) {
debug!("{}", s);
if config.verbose { println!("{}", s); }
}
| { ";" } | identifier_body |
util.rs | // Copyright 2012-2015 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-MI... | (config: &Config, s: String) {
debug!("{}", s);
if config.verbose { println!("{}", s); }
}
| logv | identifier_name |
util.rs | // Copyright 2012-2015 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-MI... | Err(..) => path.to_string()
}
}
pub fn lib_path_env_var() -> &'static str { "PATH" }
fn path_div() -> &'static str { ";" }
pub fn logv(config: &Config, s: String) {
debug!("{}", s);
if config.verbose { println!("{}", s); }
} | // maintain the current value while adding our own
match env::var(lib_path_env_var()) {
Ok(curr) => {
format!("{}{}{}", path, path_div(), curr)
} | random_line_split |
libclarity.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program 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... |
format!(
"{} {} ({}:{}{}, {} build, {} [{}])",
pkg_name,
pkg_version,
&git_branch,
git_commit,
git_tree_clean,
BUILD_TYPE,
std::env::consts::OS,
std::env::consts::ARCH
)
} | random_line_split | |
libclarity.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program 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... | (pkg_name: &str, pkg_version: &str) -> String {
let git_branch = GIT_BRANCH.unwrap_or("");
let git_commit = GIT_COMMIT.unwrap_or("");
let git_tree_clean = GIT_TREE_CLEAN.unwrap_or("");
format!(
"{} {} ({}:{}{}, {} build, {} [{}])",
pkg_name,
pkg_version,
&git_branch,
... | version_string | identifier_name |
libclarity.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program 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... | {
let git_branch = GIT_BRANCH.unwrap_or("");
let git_commit = GIT_COMMIT.unwrap_or("");
let git_tree_clean = GIT_TREE_CLEAN.unwrap_or("");
format!(
"{} {} ({}:{}{}, {} build, {} [{}])",
pkg_name,
pkg_version,
&git_branch,
git_commit,
git_tree_clean,
... | identifier_body | |
aal.rs | // #[macro_use] extern crate lazy_static;
extern crate docopt;
extern crate raal;
extern crate serde_json;
extern crate shellexpand;
use docopt::Docopt;
use raal::ec2_instances::{AshufInfo, read_without_cache, read_via_cache, instances_matching_regex};
use raal::config::read_config;
const USAGE: &'static str = "
Que... | .get(&env_name.to_string())
.unwrap()
.account_id
.clone();
let aws_region = config.environments
.get(&env_name.to_string())
.unwrap()
.region
.clone();
let all_instances = match bypass_cache {
true => {
if debug {
prin... | {
let version = "0.1.0".to_owned();
let parsed_cmdline = Docopt::new(USAGE)
.and_then(|d| d.version(Some(version)).parse())
.unwrap_or_else(|e| e.exit());
let pattern = parsed_cmdline.get_str("<pattern>").to_string();
let debug = false;
// if debug {
// println!("Command line... | identifier_body |
aal.rs | // #[macro_use] extern crate lazy_static;
extern crate docopt;
extern crate raal;
extern crate serde_json;
extern crate shellexpand;
use docopt::Docopt;
use raal::ec2_instances::{AshufInfo, read_without_cache, read_via_cache, instances_matching_regex};
use raal::config::read_config;
const USAGE: &'static str = "
Que... | () {
let version = "0.1.0".to_owned();
let parsed_cmdline = Docopt::new(USAGE)
.and_then(|d| d.version(Some(version)).parse())
.unwrap_or_else(|e| e.exit());
let pattern = parsed_cmdline.get_str("<pattern>").to_string();
let debug = false;
// if debug {
// println!("Command lin... | main | identifier_name |
aal.rs | // #[macro_use] extern crate lazy_static;
extern crate docopt;
extern crate raal;
extern crate serde_json;
extern crate shellexpand;
use docopt::Docopt;
use raal::ec2_instances::{AshufInfo, read_without_cache, read_via_cache, instances_matching_regex};
use raal::config::read_config;
const USAGE: &'static str = "
Que... | let pattern = parsed_cmdline.get_str("<pattern>").to_string();
let debug = false;
// if debug {
// println!("Command line parsed to {:?}", parsed_cmdline);
// println!("Pattern is {:?}", pattern);
// };
let env_name = parsed_cmdline.get_str("-n");
let bypass_cache = parsed_cmdli... | let version = "0.1.0".to_owned();
let parsed_cmdline = Docopt::new(USAGE)
.and_then(|d| d.version(Some(version)).parse())
.unwrap_or_else(|e| e.exit()); | random_line_split |
union_fields_1_0.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
pub struct __BindgenUnionField<T>(::std::marker::PhantomData<T>);
impl<T> __BindgenUnionField<T> {
#[inline]
pub fn new() -> Self {
__BindgenUnionField(::std::marker::PhantomData)
}
#... | (&self) -> Self {
Self::new()
}
}
impl<T> ::std::marker::Copy for __BindgenUnionField<T> {}
impl<T> ::std::fmt::Debug for __BindgenUnionField<T> {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_str("__BindgenUnionField")
}
}
impl<T> ::std::hash::Hash for... | clone | identifier_name |
union_fields_1_0.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
pub struct __BindgenUnionField<T>(::std::marker::PhantomData<T>);
impl<T> __BindgenUnionField<T> {
#[inline]
pub fn new() -> Self {
__BindgenUnionField(::std::marker::PhantomData)
}
#... |
}
| {
*self
} | identifier_body |
union_fields_1_0.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
pub struct __BindgenUnionField<T>(::std::marker::PhantomData<T>);
impl<T> __BindgenUnionField<T> {
#[inline]
pub fn new() -> Self {
__BindgenUnionField(::std::marker::PhantomData)
}
#... | }
impl<T> ::std::hash::Hash for __BindgenUnionField<T> {
fn hash<H: ::std::hash::Hasher>(&self, _state: &mut H) {}
}
impl<T> ::std::cmp::PartialEq for __BindgenUnionField<T> {
fn eq(&self, _other: &__BindgenUnionField<T>) -> bool {
true
}
}
impl<T> ::std::cmp::Eq for __BindgenUnionField<T> {}
#[repr... | } | random_line_split |
method-ambig-two-traits-cross-crate.rs | // Copyright 2012-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-MI... | () { 1u.me(); } //~ ERROR E0034
| main | identifier_name |
method-ambig-two-traits-cross-crate.rs | // Copyright 2012-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-MI... | fn main() { 1u.me(); } //~ ERROR E0034 | fn me(&self) -> uint;
}
impl me2 for uint { fn me(&self) -> uint { *self } } | random_line_split |
method-ambig-two-traits-cross-crate.rs | // Copyright 2012-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-MI... | //~ ERROR E0034
| { 1u.me(); } | identifier_body |
x86.rs | #[repr(C)]
#[derive(Copy)]
pub struct netent {
pub n_name: *mut ::schar_t,
pub n_aliases: *mut *mut ::schar_t,
pub n_addrtype: ::int_t,
pub n_net: ::stdint::uint32_t,
}
new!(netent);
#[repr(C)]
#[derive(Copy)]
pub struct hostent {
pub h_name: *mut ::schar_t,
pub h_aliases: *mut *mut ::schar_t,
... | {
pub ai_flags: ::int_t,
pub ai_family: ::int_t,
pub ai_socktype: ::int_t,
pub ai_protocol: ::int_t,
pub ai_addrlen: ::sys::socket::socklen_t,
pub ai_addr: *mut ::sys::socket::sockaddr,
pub ai_canonname: *mut ::schar_t,
pub ai_next: *mut addrinfo,
}
new!(addrinfo);
pub const IPPORT_RESE... | addrinfo | identifier_name |
x86.rs | #[repr(C)]
#[derive(Copy)]
pub struct netent {
pub n_name: *mut ::schar_t,
pub n_aliases: *mut *mut ::schar_t,
pub n_addrtype: ::int_t,
pub n_net: ::stdint::uint32_t,
}
new!(netent);
#[repr(C)]
#[derive(Copy)]
pub struct hostent {
pub h_name: *mut ::schar_t,
pub h_aliases: *mut *mut ::schar_t,
... | pub const EAI_SYSTEM: ::int_t = 11;
pub const EAI_OVERFLOW: ::int_t = 12; | pub const EAI_SOCKTYPE: ::int_t = 7; | random_line_split |
function-prologue-stepping-regular.rs | // Copyright 2013-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-MI... | // lldb-command:breakpoint set --name assignment
// lldb-command:breakpoint set --name function_call
// lldb-command:breakpoint set --name identifier
// lldb-command:breakpoint set --name return_expr
// lldb-command:breakpoint set --name arithmetic_expr
// lldb-command:breakpoint set --name if_expr
// lldb-command:brea... | // lldb-command:breakpoint set --name non_immediate_args
// lldb-command:breakpoint set --name binding | random_line_split |
function-prologue-stepping-regular.rs | // Copyright 2013-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-MI... | (x: u64, y: u64, z: f64) -> u64 {
x
}
fn return_expr(x: u64, y: u64, z: f64) -> u64 {
return x;
}
fn arithmetic_expr(x: u64, y: u64, z: f64) -> u64 {
x + y
}
fn if_expr(x: u64, y: u64, z: f64) -> u64 {
if x + y < 1000 {
x
} else {
y
}
}
fn while_expr(mut x: u64, y: u64, z: u6... | identifier | identifier_name |
function-prologue-stepping-regular.rs | // Copyright 2013-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-MI... |
}
fn while_expr(mut x: u64, y: u64, z: u64) -> u64 {
while x + y < 1000 {
x += z
}
return x;
}
fn loop_expr(mut x: u64, y: u64, z: u64) -> u64 {
loop {
x += z;
if x + y > 1000 {
return x;
}
}
}
fn main() {
immediate_args(1, true, 2.5);
non_im... | {
y
} | conditional_block |
mod.rs | //! A module that provides an interface for torrent clients
mod deluge;
mod transmission;
pub use self::deluge::Deluge;
pub use self::transmission::Transmission;
use self::transmission::{ArgGet, DeleteLocalData, TorrentSelect, TorrentStatus as TStatus};
use std::fmt::Debug;
pub type Result<T> = std::result::Result<... | /// Starts a list of torrents.
fn start(&self, _: &[String]) -> Result<()>;
/// Stop a list of torrents.
fn stop(&self, _: &[String]) -> Result<()>;
/// Remove a list of torrents from client.
///
/// If the second parameter is true, then it also removes local data.
fn remove(&self, _: &[... | /// A trait for any object that will represent a torrent client.
pub trait TorrentClient: Debug {
fn url(&self) -> &str;
/// Returns a list of all torrents in the client.
fn list(&self) -> Result<Vec<Torrent>>; | random_line_split |
mod.rs | //! A module that provides an interface for torrent clients
mod deluge;
mod transmission;
pub use self::deluge::Deluge;
pub use self::transmission::Transmission;
use self::transmission::{ArgGet, DeleteLocalData, TorrentSelect, TorrentStatus as TStatus};
use std::fmt::Debug;
pub type Result<T> = std::result::Result<... | {
Seeding,
Stopped,
Other,
}
impl From<i16> for TorrentStatus {
fn from(status: i16) -> Self {
match status {
0 => TorrentStatus::Seeding,
1 => TorrentStatus::Stopped,
_ => TorrentStatus::Other,
}
}
}
/// A trait for any object that will represe... | TorrentStatus | identifier_name |
mod.rs | //! A module that provides an interface for torrent clients
mod deluge;
mod transmission;
pub use self::deluge::Deluge;
pub use self::transmission::Transmission;
use self::transmission::{ArgGet, DeleteLocalData, TorrentSelect, TorrentStatus as TStatus};
use std::fmt::Debug;
pub type Result<T> = std::result::Result<... |
fn start(&self, _hashes: &[String]) -> Result<()> {
unimplemented!();
}
fn stop(&self, _hashes: &[String]) -> Result<()> {
unimplemented!();
}
fn remove(&self, _hashes: &[String], _delete: bool) -> Result<()> {
unimplemented!();
}
}
| {
unimplemented!();
} | identifier_body |
main.rs | fn _12_1(){
println!("guide 12-1");
let a = [1i32, 2i32, 3i32];
let mut m = [2i32, 3i32, 4i32];
if false {
println!("{:?} {:?}", a, m);
}
let b = [0i32; 20]; // shorthand for array of 20 elements all initialized to 0
println!("{:?}", b);
m = [5i32, 6i32, 7i32];
println!("{:?}... | {
println!("guide 12");
_12_1();
_12_2();
_12_3();
} | identifier_body | |
main.rs | fn _12_1(){
println!("guide 12-1");
let a = [1i32, 2i32, 3i32];
let mut m = [2i32, 3i32, 4i32];
if false {
println!("{:?} {:?}", a, m);
}
| println!("{:?}", m);
for i in m.iter() {
println!("elem {}", i);
}
let names = ["Emilija", "Anzelika"];
println!("{} -> {}", names[1], names[0]);
}
fn _12_2(){
println!("guide 12-2");
let mut v = vec![1i32, 2, 3];
v.push(4);
println!("{:?}, len is {}", v, v.len());
}
fn ... | let b = [0i32; 20]; // shorthand for array of 20 elements all initialized to 0
println!("{:?}", b);
m = [5i32, 6i32, 7i32]; | random_line_split |
main.rs | fn _12_1(){
println!("guide 12-1");
let a = [1i32, 2i32, 3i32];
let mut m = [2i32, 3i32, 4i32];
if false |
let b = [0i32; 20]; // shorthand for array of 20 elements all initialized to 0
println!("{:?}", b);
m = [5i32, 6i32, 7i32];
println!("{:?}", m);
for i in m.iter() {
println!("elem {}", i);
}
let names = ["Emilija", "Anzelika"];
println!("{} -> {}", names[1], names[0]);
}
fn ... | {
println!("{:?} {:?}", a, m);
} | conditional_block |
main.rs | fn | (){
println!("guide 12-1");
let a = [1i32, 2i32, 3i32];
let mut m = [2i32, 3i32, 4i32];
if false {
println!("{:?} {:?}", a, m);
}
let b = [0i32; 20]; // shorthand for array of 20 elements all initialized to 0
println!("{:?}", b);
m = [5i32, 6i32, 7i32];
println!("{:?}", m);
... | _12_1 | identifier_name |
resolve.rs | use super::encode::Metadata;
use crate::core::dependency::DepKind;
use crate::core::interning::InternedString;
use crate::core::{Dependency, PackageId, PackageIdSpec, Summary, Target};
use crate::util::errors::CargoResult;
use crate::util::Graph;
use std::borrow::Borrow;
use std::cmp;
use std::collections::{HashMap, Ha... | ;
let crate_name = to_target.crate_name();
let mut names = deps.iter().map(|d| {
d.explicit_name_in_toml()
.map(|s| s.as_str().replace("-", "_"))
.unwrap_or_else(|| crate_name.clone())
});
let name = names.next().unwrap_or_else(|| crate_name.clo... | {
self.dependencies_listed(from, to)
} | conditional_block |
resolve.rs | use super::encode::Metadata;
use crate::core::dependency::DepKind;
use crate::core::interning::InternedString;
use crate::core::{Dependency, PackageId, PackageIdSpec, Summary, Target};
use crate::util::errors::CargoResult;
use crate::util::Graph;
use std::borrow::Borrow;
use std::cmp;
use std::collections::{HashMap, Ha... | &self.version
}
pub fn summary(&self, pkg_id: PackageId) -> &Summary {
&self.summaries[&pkg_id]
}
}
impl PartialEq for Resolve {
fn eq(&self, other: &Resolve) -> bool {
macro_rules! compare {
($($fields:ident)* | $($ignored:ident)*) => {
let Resolve ... | /// file.
pub fn version(&self) -> &ResolveVersion { | random_line_split |
resolve.rs | use super::encode::Metadata;
use crate::core::dependency::DepKind;
use crate::core::interning::InternedString;
use crate::core::{Dependency, PackageId, PackageIdSpec, Summary, Target};
use crate::util::errors::CargoResult;
use crate::util::Graph;
use std::borrow::Borrow;
use std::cmp;
use std::collections::{HashMap, Ha... | {
/// Historical baseline for when this abstraction was added.
V1,
/// A more compact format, more amenable to avoiding source-control merge
/// conflicts. The `dependencies` arrays are compressed and checksums are
/// listed inline. Introduced in 2019 in version 1.38. New lockfiles use
/// V2 ... | ResolveVersion | identifier_name |
resolve.rs | use super::encode::Metadata;
use crate::core::dependency::DepKind;
use crate::core::interning::InternedString;
use crate::core::{Dependency, PackageId, PackageIdSpec, Summary, Target};
use crate::util::errors::CargoResult;
use crate::util::Graph;
use std::borrow::Borrow;
use std::cmp;
use std::collections::{HashMap, Ha... |
pub fn features(&self, pkg: PackageId) -> &[InternedString] {
self.features.get(&pkg).unwrap_or(&self.empty_features)
}
/// This is only here for legacy support, it will be removed when
/// switching to the new feature resolver.
pub fn features_clone(&self) -> HashMap<PackageId, Vec<Inter... | {
&self.replacements
} | identifier_body |
clusters.rs | use maud::{html, Markup, PreEscaped};
use rocket::State;
use cache::{BrokerCache, Cache, TopicCache};
use metadata::ClusterId;
use web_server::view::layout;
fn cluster_pane_layout(
cluster_id: &ClusterId,
brokers: usize,
topics: usize,
) -> PreEscaped<String> {
let link = format!("/clusters/{}/", clus... | {
let mut cluster_ids = cache.brokers.keys();
cluster_ids.sort();
let content = html! {
@for cluster_id in &cluster_ids {
(cluster_pane(cluster_id, &cache.brokers, &cache.topics))
}
};
layout::page("Clusters", content)
} | identifier_body | |
clusters.rs | use maud::{html, Markup, PreEscaped};
use rocket::State;
use cache::{BrokerCache, Cache, TopicCache};
use metadata::ClusterId;
use web_server::view::layout;
fn cluster_pane_layout(
cluster_id: &ClusterId,
brokers: usize,
topics: usize,
) -> PreEscaped<String> {
let link = format!("/clusters/{}/", clus... | (cache: State<Cache>) -> Markup {
let mut cluster_ids = cache.brokers.keys();
cluster_ids.sort();
let content = html! {
@for cluster_id in &cluster_ids {
(cluster_pane(cluster_id, &cache.brokers, &cache.topics))
}
};
layout::page("Clusters", content)
}
| clusters_page | identifier_name |
clusters.rs | use maud::{html, Markup, PreEscaped};
use rocket::State;
use cache::{BrokerCache, Cache, TopicCache};
use metadata::ClusterId;
use web_server::view::layout;
fn cluster_pane_layout(
cluster_id: &ClusterId,
brokers: usize,
topics: usize,
) -> PreEscaped<String> {
let link = format!("/clusters/{}/", clus... | topic_cache: &TopicCache,
) -> PreEscaped<String> {
let broker_count = broker_cache.get(cluster_id).unwrap_or_default().len();
let topics_count = topic_cache.count(|&(ref c, _)| c == cluster_id);
cluster_pane_layout(cluster_id, broker_count, topics_count)
}
#[get("/clusters")]
pub fn clusters_page(cach... | }
fn cluster_pane(
cluster_id: &ClusterId,
broker_cache: &BrokerCache, | random_line_split |
tests.rs | use super::*;
use std::cell::Cell;
#[test]
fn allocator_param() {
use crate::alloc::AllocError;
// Writing a test of integration between third-party
// allocators and `RawVec` is a little tricky because the `RawVec`
// API does not expose fallible allocation methods, so we
// cannot check what hap... | (&self, ptr: NonNull<u8>, layout: Layout) {
unsafe { Global.deallocate(ptr, layout) }
}
}
let a = BoundedAlloc { fuel: Cell::new(500) };
let mut v: RawVec<u8, _> = RawVec::with_capacity_in(50, a);
assert_eq!(v.alloc.fuel.get(), 450);
v.reserve(50, 150); // (causes a realloc, thu... | deallocate | identifier_name |
tests.rs | use super::*;
use std::cell::Cell;
#[test]
fn allocator_param() {
use crate::alloc::AllocError;
// Writing a test of integration between third-party
// allocators and `RawVec` is a little tricky because the `RawVec`
// API does not expose fallible allocation methods, so we
// cannot check what hap... |
err @ Err(_) => err,
}
}
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
unsafe { Global.deallocate(ptr, layout) }
}
}
let a = BoundedAlloc { fuel: Cell::new(500) };
let mut v: RawVec<u8, _> = RawVec::with_capacity_in(50, a);
... | {
self.fuel.set(self.fuel.get() - size);
ok
} | conditional_block |
tests.rs | use super::*;
use std::cell::Cell;
#[test]
fn allocator_param() {
use crate::alloc::AllocError;
// Writing a test of integration between third-party
// allocators and `RawVec` is a little tricky because the `RawVec`
// API does not expose fallible allocation methods, so we
// cannot check what hap... |
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
unsafe { Global.deallocate(ptr, layout) }
}
}
let a = BoundedAlloc { fuel: Cell::new(500) };
let mut v: RawVec<u8, _> = RawVec::with_capacity_in(50, a);
assert_eq!(v.alloc.fuel.get(), 450);
v.reserve(50, 15... | {
let size = layout.size();
if size > self.fuel.get() {
return Err(AllocError);
}
match Global.allocate(layout) {
ok @ Ok(_) => {
self.fuel.set(self.fuel.get() - size);
ok
}
... | identifier_body |
tests.rs | use super::*;
use std::cell::Cell;
#[test]
fn allocator_param() {
use crate::alloc::AllocError;
// Writing a test of integration between third-party
// allocators and `RawVec` is a little tricky because the `RawVec`
// API does not expose fallible allocation methods, so we
// cannot check what hap... | v.reserve(0, 9);
assert_eq!(9, v.capacity());
}
{
let mut v: RawVec<u32> = RawVec::new();
v.reserve(0, 7);
assert_eq!(7, v.capacity());
// 97 is more than double of 7, so `reserve` should work
// like `reserve_exact`.
v.reserve(7, 90);
ass... | // First, `reserve` allocates like `reserve_exact`. | random_line_split |
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 http://mozilla.org/MPL/2.0/. */
#![cfg_attr(feature = "unstable", feature(core_intrinsics))]
#![cfg_attr(feature = "unstable", feature(on_unimplem... |
#[allow(unsafe_code)]
unsafe extern "C" fn is_dom_object(obj: *mut JSObject) -> bool {
!obj.is_null() && (is_platform_object(obj) || is_dom_proxy(obj))
}
#[allow(unsafe_code)]
pub fn init() {
unsafe {
proxyhandler::init();
// Create the global vtables used by the (generated) DOM
// bind... | {
// Spawn the service worker manager passing the constellation sender
ServiceWorkerManager::spawn_manager(sw_senders);
} | 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 http://mozilla.org/MPL/2.0/. */
#![cfg_attr(feature = "unstable", feature(core_intrinsics))]
#![cfg_attr(feature = "unstable", feature(on_unimplem... | () {}
pub fn init_service_workers(sw_senders: SWManagerSenders) {
// Spawn the service worker manager passing the constellation sender
ServiceWorkerManager::spawn_manager(sw_senders);
}
#[allow(unsafe_code)]
unsafe extern "C" fn is_dom_object(obj: *mut JSObject) -> bool {
!obj.is_null() && (is_platform_objec... | perform_platform_specific_initialization | 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 http://mozilla.org/MPL/2.0/. */
#![cfg_attr(feature = "unstable", feature(core_intrinsics))]
#![cfg_attr(feature = "unstable", feature(on_unimplem... | // we have more than enough
return;
}
rlim.rlim_cur = match rlim.rlim_max {
libc::RLIM_INFINITY => MAX_FILE_LIMIT,
_ => {
if rlim.rlim_max < MAX_FILE_LIMIT {
... | 0 => {
if rlim.rlim_cur >= MAX_FILE_LIMIT { | random_line_split |
main.rs | #![feature(vec_resize)]
use std::iter::repeat;
use std::collections::VecDeque;
use std::collections::BinaryHeap;
use std::cmp::Ordering;
fn max(a: u32, b: u32) -> u32 { if a > b { a } else { b } }
#[derive(Clone)]
struct Edge {
vertex: u32,
weight: f32,
}
impl Edge {
pub fn new(vertex_: u32, weight_: f3... | pub fn bfs(&self, src: u32) {
let mut queue: VecDeque<u32> = VecDeque::new();
let len = self.nodes.len();
let mut visited = vec!(false ; len);
queue.push_front(src);
while let Some(current) = queue.pop_back() {
if!visited[current as usize] {
... | random_line_split | |
main.rs | #![feature(vec_resize)]
use std::iter::repeat;
use std::collections::VecDeque;
use std::collections::BinaryHeap;
use std::cmp::Ordering;
fn max(a: u32, b: u32) -> u32 { if a > b { a } else | }
#[derive(Clone)]
struct Edge {
vertex: u32,
weight: f32,
}
impl Edge {
pub fn new(vertex_: u32, weight_: f32) -> Edge {
Edge{vertex: vertex_, weight: weight_,}
}
}
impl Ord for Edge {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).unwrap()
}
}
impl Eq fo... | { b } | conditional_block |
main.rs | #![feature(vec_resize)]
use std::iter::repeat;
use std::collections::VecDeque;
use std::collections::BinaryHeap;
use std::cmp::Ordering;
fn max(a: u32, b: u32) -> u32 { if a > b { a } else { b } }
#[derive(Clone)]
struct Edge {
vertex: u32,
weight: f32,
}
impl Edge {
pub fn new(vertex_: u32, weight_: f3... |
}
struct Graph {
nodes: Vec<Vec<Edge>>,
}
impl Graph {
pub fn new() -> Graph { Graph{nodes: Vec::new(),} }
pub fn add_edge(&mut self, src: u32, dst: u32, weight: f32) {
let len = self.nodes.len();
if (max(src, dst)) > len as u32 {
let new_len = (max(src, dst) + 1) as usize;
... | {
(self.weight, &self.vertex) == (other.weight, &other.vertex)
} | identifier_body |
main.rs | #![feature(vec_resize)]
use std::iter::repeat;
use std::collections::VecDeque;
use std::collections::BinaryHeap;
use std::cmp::Ordering;
fn max(a: u32, b: u32) -> u32 { if a > b { a } else { b } }
#[derive(Clone)]
struct Edge {
vertex: u32,
weight: f32,
}
impl Edge {
pub fn new(vertex_: u32, weight_: f3... | (&self, src: u32) {
let mut stack: Vec<u32> = Vec::new();
let len = self.nodes.len() as usize;
let mut visited = vec!(false ; len);
stack.push(src);
while let Some(current) = stack.pop() {
if!visited[current as usize] {
println!("current: {}"... | dfs | identifier_name |
condexpr.rs | /*
* Copyright (c) 2017 Christoph Heiss
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, pub... | Some(var) => (!var.value.is_empty()).to_exec_result(),
None => match env::var(&args[1]) {
Ok(var) => (!var.is_empty()).to_exec_result(),
Err(_) => ExecResult::failure(),
... | {
if args.len() == 1 {
return ExecResult::failure();
}
let args = &args[..args.len()-1];
match args[0].as_ref() {
"-a" => Path::new(&args[1]).exists().to_exec_result(),
"-d" => Path::new(&args[1]).is_dir().to_exec_result(),
... | identifier_body |
condexpr.rs | /*
* Copyright (c) 2017 Christoph Heiss
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, pub... | None => match env::var(&args[1]) {
Ok(var) => (!var.is_empty()).to_exec_result(),
Err(_) => ExecResult::failure(),
},
}
},
... | },
"-n" => (!args[1].is_empty()).to_exec_result(),
"-v" => {
match state.var(&args[1]) {
Some(var) => (!var.value.is_empty()).to_exec_result(), | random_line_split |
condexpr.rs | /*
* Copyright (c) 2017 Christoph Heiss
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, pub... | (state: &mut State, args: &[String]) -> ExecResult {
if args.len() == 1 {
return ExecResult::failure();
}
let args = &args[..args.len()-1];
match args[0].as_ref() {
"-a" => Path::new(&args[1]).exists().to_exec_result(),
"-d" => Path::new(... | exec | identifier_name |
mod.rs | #![ warn( missing_docs ) ]
#![ warn( missing_debug_implementations ) ]
// #![ feature( type_name_of_val ) ]
// #![ feature( trace_macros ) ]
//!
//! Former - variation of builder pattern.
//!
//! # Sample
//! ```
//! use former::Former;
//!
//! #[derive( Debug, PartialEq, Former )]
//! pub struct Structure1
//! {
//! ... | pub use former_meta as derive;
pub use derive::Former as Former; | random_line_split | |
probe.rs | use std::os;
use std::io::fs::PathExtensions;
pub struct ProbeResult {
pub cert_file: Option<Path>,
pub cert_dir: Option<Path>,
}
/// Probe the system for the directory in which CA certificates should likely be
/// found.
///
/// This will only search known system locations.
pub fn find_certs_dirs() -> Vec<Pa... | () {
let ProbeResult { cert_file, cert_dir } = probe();
match cert_file {
Some(path) => put("SSL_CERT_FILE", path),
None => {}
}
match cert_dir {
Some(path) => put("SSL_CERT_DIR", path),
None => {}
}
fn put(var: &str, path: Path) {
// Don't stomp over wha... | init_ssl_cert_env_vars | identifier_name |
probe.rs | use std::os;
use std::io::fs::PathExtensions;
pub struct ProbeResult {
pub cert_file: Option<Path>,
pub cert_dir: Option<Path>,
}
/// Probe the system for the directory in which CA certificates should likely be
/// found.
///
/// This will only search known system locations.
pub fn find_certs_dirs() -> Vec<Pa... |
pub fn init_ssl_cert_env_vars() {
let ProbeResult { cert_file, cert_dir } = probe();
match cert_file {
Some(path) => put("SSL_CERT_FILE", path),
None => {}
}
match cert_dir {
Some(path) => put("SSL_CERT_DIR", path),
None => {}
}
fn put(var: &str, path: Path) {
... | {
// see http://gagravarr.org/writing/openssl-certs/others.shtml
[
"/var/ssl",
"/usr/share/ssl",
"/usr/local/ssl",
"/usr/local/openssl",
"/usr/local/share",
"/usr/lib/ssl",
"/usr/ssl",
"/etc/openssl",
"/etc/pki/tls",
"/etc/ssl",
... | identifier_body |
probe.rs | use std::os;
use std::io::fs::PathExtensions;
pub struct ProbeResult {
pub cert_file: Option<Path>,
pub cert_dir: Option<Path>, | /// Probe the system for the directory in which CA certificates should likely be
/// found.
///
/// This will only search known system locations.
pub fn find_certs_dirs() -> Vec<Path> {
// see http://gagravarr.org/writing/openssl-certs/others.shtml
[
"/var/ssl",
"/usr/share/ssl",
"/usr/l... | }
| random_line_split |
response_parameters.rs | use serde::de::{Deserialize, Deserializer, Error};
use crate::types::*;
/// All API responses are from this type. Mostly used internal.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum ResponseWrapper<T> {
/// Request was successful.
Success {
/// Response result.
result:... | /// Request was unsuccessful.
Error {
/// Human-readable description of the result.
description: String,
/// Contains information about why a request was unsuccessful.
parameters: Option<ResponseParameters>,
},
}
impl<'de, T: Deserialize<'de>> Deserialize<'de> for ResponseWr... | random_line_split | |
response_parameters.rs | use serde::de::{Deserialize, Deserializer, Error};
use crate::types::*;
/// All API responses are from this type. Mostly used internal.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum ResponseWrapper<T> {
/// Request was successful.
Success {
/// Response result.
result:... | <T> {
/// If ‘ok’ equals true, the request was successful.
ok: bool,
/// Human-readable description of the result.
description: Option<String>,
/// Result of the query.
result: Option<T>,
/// Information about why a request was unsuccessful.
parameters: Option<ResponseParameters>,
}
///... | RawResponse | identifier_name |
blocks.rs | // Copyright 2015, 2016 Ethcore (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 later version.... | (amount: u64) {
let mut canon_chain = ChainGenerator::default();
let mut finalizer = BlockFinalizer::default();
let genesis = canon_chain.generate(&mut finalizer).unwrap();
let db_cfg = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let orig_path = RandomTempPath::create_dir();
let new_path = RandomTempPath::c... | chunk_and_restore | identifier_name |
blocks.rs | // Copyright 2015, 2016 Ethcore (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 later version.... |
#[test]
fn chunk_and_restore_40k() { chunk_and_restore(40000) }
#[test]
fn checks_flag() {
use ::rlp::{RlpStream, Stream};
use util::H256;
let mut stream = RlpStream::new_list(5);
stream.append(&100u64)
.append(&H256::default())
.append(&(!0u64));
stream.append_empty_data().append_empty_data();
let gen... | { chunk_and_restore(500) } | identifier_body |
blocks.rs | // Copyright 2015, 2016 Ethcore (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 later version.... | fn checks_flag() {
use ::rlp::{RlpStream, Stream};
use util::H256;
let mut stream = RlpStream::new_list(5);
stream.append(&100u64)
.append(&H256::default())
.append(&(!0u64));
stream.append_empty_data().append_empty_data();
let genesis = {
let mut canon_chain = ChainGenerator::default();
let mut final... | #[test] | random_line_split |
main.rs | /*
Copyright © 2021 Alastair Feille
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/.
SPDX-License-Identifier: MPL-2.0
*/
use std::{env,
fs,
... | )
{
let session_time = Local::now();
let mut fallback_mode = false;
ctrlc::set_handler(|| ()).expect("Error setting Ctrl-C handler");
loop
{
let cwd: String = env::current_dir().map(|p| {
// Attempt to canonicalize the path else return "???"
... | ain( | identifier_name |
main.rs | /*
Copyright © 2021 Alastair Feille
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/.
SPDX-License-Identifier: MPL-2.0
*/
use std::{env,
fs,
... | whoami::hostname(),
cwd);
io::stdout().flush().expect("failed to print prompt");
// Read in line
let mut line = String::new();
io::stdin().read_line(&mut line)
.expect("failed to read from stdin");
let original_line = line.clone()... |
let session_time = Local::now();
let mut fallback_mode = false;
ctrlc::set_handler(|| ()).expect("Error setting Ctrl-C handler");
loop
{
let cwd: String = env::current_dir().map(|p| {
// Attempt to canonicalize the path else return "???"
... | identifier_body |
main.rs | /*
Copyright © 2021 Alastair Feille
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/.
SPDX-License-Identifier: MPL-2.0
*/
use std::{env,
fs,
... | ).to_string();
(&"bash",
vec!["-c".to_string(),
format!("shopt -s expand_aliases\n{}\n{}", aliases, line)])
}
else
{
let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
... | ])
.output()
.expect("failed to load aliases")
.stdout, | random_line_split |
raw.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 crate::common::*;
use crate::user;
use chrono;
use serde::Deserialize;
use super::DMEntities;
#[derive(Debug, ... | ///The screen name of the user who received the DM.
pub recipient_screen_name: String,
///The ID of the user who received the DM.
pub recipient_id: u64,
///Full information for the user who received the DM.
pub recipient: Box<user::TwitterUser>,
} | ///Full information of the user who sent the DM.
pub sender: Box<user::TwitterUser>, | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.