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 |
|---|---|---|---|---|
lib.rs | use std::{
alloc,
alloc::Layout,
fmt,
fmt::Debug,
iter::FromIterator,
mem,
ops::{Index, IndexMut},
ptr,
ptr::NonNull,
};
#[cfg(test)]
pub mod test_box;
#[cfg(test)]
pub mod test_i32;
#[cfg(test)]
pub mod test_zst;
pub mod iterator;
use iterator::{BorrowedVectorIterator, BorrowedVectorIteratorMut, VectorIte... |
///Gets a mutable reference to the element at index's position.
///
/// Returns `None` if index is greater than the length of the vector. Has complexity O(1).
pub fn get_mut(&mut self, idx: usize) -> Option<&mut T> {
if idx >= self.size {
return None;
}
//Safety: Index is already checked.
unsafe { self... | {
if idx >= self.size {
return None;
}
//Safety: Index is already checked.
unsafe { self.as_ptr()?.add(idx).as_ref() }
} | identifier_body |
lib.rs | use std::{
alloc,
alloc::Layout,
fmt,
fmt::Debug,
iter::FromIterator,
mem,
ops::{Index, IndexMut},
ptr,
ptr::NonNull,
};
#[cfg(test)]
pub mod test_box;
#[cfg(test)]
pub mod test_i32;
#[cfg(test)]
pub mod test_zst;
pub mod iterator;
use iterator::{BorrowedVectorIterator, BorrowedVectorIteratorMut, VectorIte... | (&mut self, idx: usize, elem: T) {
if idx == self.size {
return self.push(elem);
}
if self.size == self.capacity {
if self.capacity == usize::MAX {
panic!("Overflow");
}
self.reserve(
(self.capacity as f64 * GROWTH_RATE)
.ceil()
.min(usize::MAX as f64) as usize,
);
} else if se... | insert | identifier_name |
lib.rs | use std::{
alloc,
alloc::Layout,
fmt,
fmt::Debug,
iter::FromIterator,
mem,
ops::{Index, IndexMut},
ptr,
ptr::NonNull,
};
#[cfg(test)]
pub mod test_box;
#[cfg(test)]
pub mod test_i32;
#[cfg(test)]
pub mod test_zst;
pub mod iterator;
use iterator::{BorrowedVectorIterator, BorrowedVectorIteratorMut, VectorIte... | }
///Removes any element which does not fulfill the requirement passed.
/// It is recommended to use this over `remove` in a loop due to time
/// complexity and fewer moves.
///
/// Has complexity O(n)
pub fn retain(&mut self, f: fn(&T) -> bool) {
if mem::size_of::<T>() == 0 {
for i in (0..self.size).rev()... |
self.data.map(|p| p.as_ptr())
}
| conditional_block |
lib.rs | use std::{
alloc,
alloc::Layout,
fmt,
fmt::Debug,
iter::FromIterator,
mem,
ops::{Index, IndexMut},
ptr,
ptr::NonNull,
};
#[cfg(test)]
pub mod test_box;
#[cfg(test)]
pub mod test_i32;
#[cfg(test)]
pub mod test_zst;
pub mod iterator;
use iterator::{BorrowedVectorIterator, BorrowedVectorIteratorMut, VectorIte... | self.as_ptr_mut()
.expect("Above assertion failed?")
.add(self.size)
.write(elem)
};
self.size += 1;
}
///Gets a reference to the element at index's position.
///
/// Returns `None` if index is greater than the length of the vector. Has complexity O(1).
pub fn get(&self, idx: usize) -> Option<&... | random_line_split | |
all_phases.rs | use crate::ast2ir;
use crate::emit;
use crate::err::NiceError;
use crate::ir2ast;
use crate::opt;
use crate::opt_ast;
use crate::parse;
use crate::swc_globals;
macro_rules! case {
( $name:ident, $string:expr, @ $expected:literal ) => {
#[test]
fn $name() -> Result<(), NiceError> {
swc_g... | };
"###);
case!(
snudown_js_like2,
r#"
var o, c = {}, s = {};
for (o in c) c.hasOwnProperty(o) && (s[o] = c[o]);
var u = console.log.bind(console), b = console.warn.bind(console);
for (o in s) s.hasOwnProperty(o) && (c[o] = s[o]);
s = null;
var k, v, d, h = 0, w =!1;
k = c.buffer? c... | return z + 2; | random_line_split |
storage.rs | hash_size: None,
chunk_pages: None,
log_bps: dfl_params.log_bps,
mem_avail_err_max: 0.1,
mem_avail_inner_retries: 2,
mem_avail_outer_retries: 2,
first_try: true,
mem_usage: 0,
mem_probe_at: 0,
prev_mem... | <'a>(
&self,
out: &mut Box<dyn Write + 'a>,
rec: &StorageRecord,
res: &StorageResult,
) {
write!(
out,
"Memory offloading: factor={:.3}@{} ",
res.mem_offload_factor, rec.mem.profile
)
.unwrap();
if self.loops > 1 {
... | format_mem_summary | identifier_name |
storage.rs | hash_size: None,
chunk_pages: None,
log_bps: dfl_params.log_bps,
mem_avail_err_max: 0.1,
mem_avail_inner_retries: 2,
mem_avail_outer_retries: 2,
first_try: true,
mem_usage: 0,
mem_probe_at: 0,
prev_me... | continue 'outer;
} else {
continue 'inner;
}
} else {
self.prev_mem_avail = 0;
self.first_try = false;
}
final_mem_probe_periods.push((self.mem... | random_line_split | |
storage.rs | hash_size: None,
chunk_pages: None,
log_bps: dfl_params.log_bps,
mem_avail_err_max: 0.1,
mem_avail_inner_retries: 2,
mem_avail_outer_retries: 2,
first_try: true,
mem_usage: 0,
mem_probe_at: 0,
prev_mem... |
fn run(&mut self, rctx: &mut RunCtx) -> Result<serde_json::Value> {
rctx.set_prep_testfiles()
.disable_zswap()
.start_agent(vec![])?;
// Depending on mem-profile, we might be using a large balloon which
// can push down available memory below workload's memory.low
... | {
HASHD_SYSREQS.clone()
} | identifier_body |
storage.rs | hash_size: None,
chunk_pages: None,
log_bps: dfl_params.log_bps,
mem_avail_err_max: 0.1,
mem_avail_inner_retries: 2,
mem_avail_outer_retries: 2,
first_try: true,
mem_usage: 0,
mem_probe_at: 0,
prev_mem... |
final_mem_probe_periods.push((self.mem_probe_at, unix_now()));
mem_usages.push(self.mem_usage as f64);
mem_sizes.push(mem_size as f64);
info!(
"storage: Supportable memory footprint {}",
format_size(mem_size)
... | {
self.prev_mem_avail = 0;
self.first_try = false;
} | conditional_block |
categorical.rs | //! # One-hot Encoding For [RealNumber](../../math/num/trait.RealNumber.html) Matricies
//! Transform a data [Matrix](../../linalg/trait.BaseMatrix.html) by replacing all categorical variables with their one-hot equivalents
//!
//! Internally OneHotEncoder treats every categorical column as a series and transforms it u... | {
category_mappers: Vec<CategoryMapper<CategoricalFloat>>,
col_idx_categorical: Vec<usize>,
}
impl OneHotEncoder {
/// Create an encoder instance with categories infered from data matrix
pub fn fit<T, M>(data: &M, params: OneHotEncoderParams) -> Result<OneHotEncoder, Failed>
where
T: Categ... | OneHotEncoder | identifier_name |
categorical.rs | //! # One-hot Encoding For [RealNumber](../../math/num/trait.RealNumber.html) Matricies
//! Transform a data [Matrix](../../linalg/trait.BaseMatrix.html) by replacing all categorical variables with their one-hot equivalents
//!
//! Internally OneHotEncoder treats every categorical column as a series and transforms it u... | let repeats = cat_idx.scan(0, |a, v| {
let im = v + 1 - *a;
*a = v;
Some(im)
});
// Calculate the offset to parameter idx due to newly intorduced one-hot vectors
let offset_ = cat_sizes.iter().scan(0, |a, &v| {
*a = *a + v - 1;
Some(*a)
});
let offset = (... | let cat_idx = cat_idxs.iter().copied().chain((num_params..).take(1));
// Offset is constant between two categorical values, here we calculate the number of steps
// that remain constant | random_line_split |
categorical.rs | //! # One-hot Encoding For [RealNumber](../../math/num/trait.RealNumber.html) Matricies
//! Transform a data [Matrix](../../linalg/trait.BaseMatrix.html) by replacing all categorical variables with their one-hot equivalents
//!
//! Internally OneHotEncoder treats every categorical column as a series and transforms it u... |
}
/// Calculate the offset to parameters to due introduction of one-hot encoding
fn find_new_idxs(num_params: usize, cat_sizes: &[usize], cat_idxs: &[usize]) -> Vec<usize> {
// This functions uses iterators and returns a vector.
// In case we get a huge amount of paramenters this might be a problem
// tod... | {
Self {
col_idx_categorical: Some(categorical_params.to_vec()),
infer_categorical: false,
}
} | identifier_body |
view.rs | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::{app::App, geometry::Size};
use failure::Error;
use fidl::endpoints::{create_endpoints, create_proxy, ServerEnd};
use fidl_fuchsia_ui_gfx as gfx... | else {
self.assistant.handle_message(msg);
}
}
}
| {
match view_msg {
ViewMessages::Update => {
self.update();
}
}
} | conditional_block |
view.rs | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::{app::App, geometry::Size};
use failure::Error;
use fidl::endpoints::{create_endpoints, create_proxy, ServerEnd};
use fidl_fuchsia_ui_gfx as gfx... | };
self.assistant
.handle_input_event(&mut context, &event)
.unwrap_or_else(|e| eprintln!("handle_event: {:?}", e));
for msg in context.messages {
self.send_message(&msg);
}
self.upd... | {
events.iter().for_each(|event| match event {
fidl_fuchsia_ui_scenic::Event::Gfx(gfx::Event::Metrics(event)) => {
self.metrics = Size::new(event.metrics.scale_x, event.metrics.scale_y);
self.logical_size = Size::new(
self.physical_size.width * sel... | identifier_body |
view.rs | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::{app::App, geometry::Size};
use failure::Error;
use fidl::endpoints::{create_endpoints, create_proxy, ServerEnd};
use fidl_fuchsia_ui_gfx as gfx... | (
key: ViewKey,
session_listener_request: ServerEnd<SessionListenerMarker>,
) -> Result<(), Error> {
fasync::spawn_local(
session_listener_request
.into_stream()?
.map_ok(move |request| match request {
SessionListenerRequest::OnSc... | setup_session_listener | identifier_name |
view.rs | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::{app::App, geometry::Size};
use failure::Error;
use fidl::endpoints::{create_endpoints, create_proxy, ServerEnd};
use fidl_fuchsia_ui_gfx as gfx... | view_listener,
theirs,
None,
)?;
let (session_listener, session_listener_request) = create_endpoints()?;
let (session_proxy, session_request) = create_proxy()?;
app.scenic.create_session(session_request, Some(session_listener))?;
let session =... | view_token.value, | random_line_split |
main.rs | #[macro_use]
extern crate log;
use std::sync::Arc;
use amethyst::{
assets::{AssetStorage, Loader, PrefabLoader, PrefabLoaderSystem, Processor, RonFormat},
core::{
bundle::SystemBundle,
math::Vector3,
transform::{Transform, TransformBundle},
Float,
},
ecs::{
Disp... | (
&mut self,
texture_path: &str,
ron_path: &str,
world: &mut World,
) -> SpriteSheetHandle {
// Load the sprite sheet necessary to render the graphics.
// The texture is the pixel data
// `sprite_sheet` is the layout of the sprites on the image
// `tex... | load_sprite_sheet | identifier_name |
main.rs | #[macro_use]
extern crate log;
use std::sync::Arc;
use amethyst::{
assets::{AssetStorage, Loader, PrefabLoader, PrefabLoaderSystem, Processor, RonFormat},
core::{
bundle::SystemBundle,
math::Vector3,
transform::{Transform, TransformBundle},
Float,
},
ecs::{
Disp... | .start();
let app_root = application_root_dir()?;
// display configuration
let display_config_path = app_root.join("examples/resources/display_config.ron");
// key bindings
let key_bindings_path = app_root.join("examples/resources/input.ron");
let game_data = GameDataBuilder::default(... | {
//amethyst::start_logger(Default::default());
amethyst::Logger::from_config(Default::default())
.level_for("gfx_backend_vulkan", amethyst::LogLevelFilter::Warn)
.level_for("rendy_factory::factory", amethyst::LogLevelFilter::Warn)
.level_for(
"rendy_memory::allocator::dynami... | identifier_body |
main.rs | #[macro_use]
extern crate log;
use std::sync::Arc;
use amethyst::{
assets::{AssetStorage, Loader, PrefabLoader, PrefabLoaderSystem, Processor, RonFormat},
core::{
bundle::SystemBundle,
math::Vector3,
transform::{Transform, TransformBundle},
Float,
},
ecs::{
Disp... | prelude::*,
renderer::{
formats::texture::ImageFormat,
pass::{DrawDebugLinesDesc, DrawFlat2DDesc},
rendy::{
factory::Factory,
graph::{
render::{RenderGroupDesc, SubpassBuilder},
GraphBuilder,
},
hal::{format:... | System,
SystemData,
WriteStorage,
},
input::{InputBundle, InputHandler, StringBindings}, | random_line_split |
main.rs | #[macro_use]
extern crate log;
use std::sync::Arc;
use amethyst::{
assets::{AssetStorage, Loader, PrefabLoader, PrefabLoaderSystem, Processor, RonFormat},
core::{
bundle::SystemBundle,
math::Vector3,
transform::{Transform, TransformBundle},
Float,
},
ecs::{
Disp... |
Trans::None
}
}
impl<'a, 'b> GameState<'a, 'b> {
fn load_sprite_sheet(
&mut self,
texture_path: &str,
ron_path: &str,
world: &mut World,
) -> SpriteSheetHandle {
// Load the sprite sheet necessary to render the graphics.
// The texture is the pixel ... | {
dispatcher.dispatch(&data.world.res);
} | conditional_block |
lib.rs | //! Ropey is a utf8 text rope for Rust. It is fast, robust, and can handle
//! huge texts and memory-incoherent edits with ease.
//!
//! Ropey's atomic unit of text is Unicode scalar values (or `char`s in Rust)
//! encoded as utf8. All of Ropey's editing and slicing operations are done
//! in terms of char indices, w... | (
f: &mut std::fmt::Formatter<'_>,
start_idx: Option<usize>,
end_idx: Option<usize>,
) -> std::fmt::Result {
match (start_idx, end_idx) {
(None, None) => {
write!(f, "..")
}
(Some(start), None) => {
write!(f, "{}..", start)
}
(None, Some(... | write_range | identifier_name |
lib.rs | //! Ropey is a utf8 text rope for Rust. It is fast, robust, and can handle
//! huge texts and memory-incoherent edits with ease.
//!
//! Ropey's atomic unit of text is Unicode scalar values (or `char`s in Rust)
//! encoded as utf8. All of Ropey's editing and slicing operations are done
//! in terms of char indices, w... |
// Deprecated in std.
fn cause(&self) -> Option<&dyn std::error::Error> {
None
}
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
Error::ByteIndexOutOfBounds(index, len) => {
write!(
... | {
""
} | identifier_body |
lib.rs | //! Ropey is a utf8 text rope for Rust. It is fast, robust, and can handle
//! huge texts and memory-incoherent edits with ease.
//!
//! Ropey's atomic unit of text is Unicode scalar values (or `char`s in Rust)
//! encoded as utf8. All of Ropey's editing and slicing operations are done
//! in terms of char indices, w... | /// Indicates that the passed char index was out of bounds.
///
/// Contains the index attempted and the actual length of the
/// `Rope`/`RopeSlice` in chars, in that order.
CharIndexOutOfBounds(usize, usize),
/// Indicates that the passed line index was out of bounds.
///
/// Contains ... | random_line_split | |
lib.rs | //! Ropey is a utf8 text rope for Rust. It is fast, robust, and can handle
//! huge texts and memory-incoherent edits with ease.
//!
//! Ropey's atomic unit of text is Unicode scalar values (or `char`s in Rust)
//! encoded as utf8. All of Ropey's editing and slicing operations are done
//! in terms of char indices, w... |
}
}
//==============================================================
// Range handling utilities.
#[inline(always)]
pub(crate) fn start_bound_to_num(b: Bound<&usize>) -> Option<usize> {
match b {
Bound::Included(n) => Some(*n),
Bound::Excluded(n) => Some(*n + 1),
Bound::Unbounded => N... | {
write!(f, "{}..{}", start, end)
} | conditional_block |
proto_connection.rs | //! Benchmark the `x11rb_protocol::Connection` type's method, at varying levels of
//! capacity.
use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion};
use std::{
io::{Read, Write},
mem::{replace, size_of},
net::{TcpListener, TcpStream},
thread,
};
use x11rb_protocol::{
... | (i: i32, p: i32) -> i32 {
let mut result = 1;
for _ in 0..p {
result *= i;
}
result
}
fn enqueue_packet_test(c: &mut Criterion) {
// take the cartesian product of the following conditions:
// - the packet is an event, a reply, or an error
// - pending_events and pending_replies are ... | pow | identifier_name |
proto_connection.rs | //! Benchmark the `x11rb_protocol::Connection` type's method, at varying levels of
//! capacity.
use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion};
use std::{
io::{Read, Write},
mem::{replace, size_of},
net::{TcpListener, TcpStream},
thread,
};
use x11rb_protocol::{
... | if left.read(&mut buf).is_err() {
break;
}
}
});
Box::new(right)
}
#[cfg(not(unix))]
{
continue;
... | random_line_split | |
proto_connection.rs | //! Benchmark the `x11rb_protocol::Connection` type's method, at varying levels of
//! capacity.
use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion};
use std::{
io::{Read, Write},
mem::{replace, size_of},
net::{TcpListener, TcpStream},
thread,
};
use x11rb_protocol::{
... | for recv_queue in &[REmpty, RFull] {
let name = format!(
"send_and_receive_request (send {}, recv {})",
match send_queue {
SEmpty => "empty",
SFull => "full",
},
match recv_queue {
... | {
// permutations:
// - send queue is empty or very full
// - receive queue is empty of very full
enum SendQueue {
SEmpty,
SFull,
}
enum RecvQueue {
REmpty,
RFull,
}
use RecvQueue::*;
use SendQueue::*;
let mut group = c.benchmark_group("send_and... | identifier_body |
main.rs | use std::collections::HashMap;
use std::collections::HashSet;
use std::io;
use std::io::Read;
use std::iter::Peekable;
use std::slice::Iter;
#[derive(Clone)]
enum Match {
Literal(char),
Alternation(Vec<Match>),
Concatenation(Vec<Match>),
}
impl std::fmt::Debug for Match {
fn fmt(&self, f: &mut std::fmt::... | element.push(partial);
res.push(Match::Concatenation(element));
}
}
res
}
}
}
}
}
////////////////////////////////////////////////////////////////////////
// ... | {
match m {
Match::Alternation(xs) => {
let mut res = Vec::new();
for alternative in xs.iter() {
res.extend(get_partials(alternative).into_iter());
}
res
}
// A single literal will have no backtrackable parts.
Match::Lit... | identifier_body |
main.rs | use std::collections::HashMap;
use std::collections::HashSet;
use std::io;
use std::io::Read;
use std::iter::Peekable;
use std::slice::Iter;
#[derive(Clone)]
enum Match {
Literal(char),
Alternation(Vec<Match>),
Concatenation(Vec<Match>),
}
impl std::fmt::Debug for Match {
fn fmt(&self, f: &mut std::fmt::... | }
}
}
// Is this an empty match? Used by opt_empties.
fn is_empty(m: &Match) -> bool {
match m {
Match::Literal(_) => false,
Match::Concatenation(xs) => xs.iter().all(is_empty),
Match::Alternation(xs) => xs.len() > 0 && xs.iter().all(is_empty),
}
}
// And this removes alter... | random_line_split | |
main.rs | use std::collections::HashMap;
use std::collections::HashSet;
use std::io;
use std::io::Read;
use std::iter::Peekable;
use std::slice::Iter;
#[derive(Clone)]
enum Match {
Literal(char),
Alternation(Vec<Match>),
Concatenation(Vec<Match>),
}
impl std::fmt::Debug for Match {
fn fmt(&self, f: &mut std::fmt::... | (l: usize, mapping: &HashMap<(i32, i32), usize>) -> usize {
mapping.iter().filter(|(_, l2)| **l2 >= l).count()
}
fn main() {
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer).expect("Read error");
let chars = buffer.replace('^', "").replace('$', "").trim().chars().collect::<Vec<_>... | count_long | identifier_name |
river.rs | #[cfg(test)]
extern crate gag;
use std::rc::{Rc, Weak};
use std::cell::{RefCell, RefMut, Ref};
use tick::Tick;
use salmon::{Salmon, Age, Direction};
use split_custom_escape::HomespringSplit;
use program::Program;
#[derive(Debug, PartialEq, Eq)]
pub enum NodeType {
Other(String),
Hatchery,
HydroPower,
... | InverseLock,
YoungSense,
Switch,
YoungSwitch,
Narrows,
AppendUp,
YoungRangeSense,
Net,
ForceDown,
ForceUp,
Spawn,
PowerInvert,
Current,
Bridge,
Split,
RangeSwitch,
YoungRangeSwitch,
}
impl NodeType {
pub fn from_name(name: &str) -> NodeType {
... | random_line_split | |
river.rs | #[cfg(test)]
extern crate gag;
use std::rc::{Rc, Weak};
use std::cell::{RefCell, RefMut, Ref};
use tick::Tick;
use salmon::{Salmon, Age, Direction};
use split_custom_escape::HomespringSplit;
use program::Program;
#[derive(Debug, PartialEq, Eq)]
pub enum NodeType {
Other(String),
Hatchery,
HydroPower,
... |
pub fn become_watered(&mut self) {
self.watered = true;
}
pub fn is_powered(&self) -> bool {
if self.block_power {
false
} else if self.powered {
true
} else {
self.children.iter().any(|c| {
c.borrow_mut().is_powered()
... | {
use self::NodeType::*;
self.snowy = true;
match self.node_type {
HydroPower => self.destroyed = true,
_ => (),
}
} | identifier_body |
river.rs | #[cfg(test)]
extern crate gag;
use std::rc::{Rc, Weak};
use std::cell::{RefCell, RefMut, Ref};
use tick::Tick;
use salmon::{Salmon, Age, Direction};
use split_custom_escape::HomespringSplit;
use program::Program;
#[derive(Debug, PartialEq, Eq)]
pub enum NodeType {
Other(String),
Hatchery,
HydroPower,
... | (&self, name: &str) -> bool {
let len = self.children.len();
if len > 0 {
match self.borrow_child(0).find_node(name) {
true => return true,
false => (),
}
}
if self.name == name { return true; }
if len > 1 {
for ... | find_node | identifier_name |
main.rs | #![recursion_limit="128"]
#[macro_use]
extern crate yew;
use std::time::Duration;
use std::char;
use yew::html::*;
use yew::services::timeout::TimeoutService;
fn main() {
let model = init_model();
program(model, update, view);
}
struct Model {
input: String,
interval: String,
time: u64,
befunge: Befunge,... | stack: vec![],
output: "".to_string(),
}
}
}
enum Msg {
Input(String),
Interval(String),
Toggle,
Step,
Reset,
Tick,
}
fn update(context: &mut Context<Msg>, model: &mut Model, msg: Msg) {
match msg {
Msg::Input(input) => {
// model.befunge.source = string_to_array(input.as_str... | running: false,
mode: Mode::End, | random_line_split |
main.rs | #![recursion_limit="128"]
#[macro_use]
extern crate yew;
use std::time::Duration;
use std::char;
use yew::html::*;
use yew::services::timeout::TimeoutService;
fn main() {
let model = init_model();
program(model, update, view);
}
struct Model {
input: String,
interval: String,
time: u64,
befunge: Befunge,... | (x: char) -> char {
let ac = x as u32;
if 33 <= ac && ac <= 126 {
x
} else {
char::from_u32(160).unwrap_or(' ')
}
}
fn colorize(source: &Array2d<char>, cursor: (i64, i64)) -> Html<Msg> {
let (cx, cy) = cursor;
html! {
<div>
{
for source.iter().enumerate().map( |(y, row)| {
... | fix_char_width | identifier_name |
main.rs | #![recursion_limit="128"]
#[macro_use]
extern crate yew;
use std::time::Duration;
use std::char;
use yew::html::*;
use yew::services::timeout::TimeoutService;
fn main() |
struct Model {
input: String,
interval: String,
time: u64,
befunge: Befunge,
}
struct Befunge {
source: Array2d<char>,
cursor: (i64, i64),
direction: Direction,
running: bool,
mode: Mode,
stack: Stack,
output: String
}
type Stack = Vec<i64>;
#[derive(Debug)]
enum Mode { StringMode, End, None }... | {
let model = init_model();
program(model, update, view);
} | identifier_body |
section.rs | //! # Section Block
//!
//! _[slack api docs 🔗]_
//!
//! Available in surfaces:
//! - [modals 🔗]
//! - [messages 🔗]
//! - [home tabs 🔗]
//!
//! A `section` is one of the most flexible blocks available -
//! it can be used as a simple text block,
//! in combination with text fields,
//! or side-by-side with any o... | Validate::validate(self)
}
}
/// Section block builder
pub mod build {
use std::marker::PhantomData;
use super::*;
use crate::build::*;
/// Compile-time markers for builder methods
#[allow(non_camel_case_types)]
pub mod method {
/// SectionBuilder.text
#[derive(Clone, Copy, Debug)]
pub ... | #[cfg(feature = "validation")]
#[cfg_attr(docsrs, doc(cfg(feature = "validation")))]
pub fn validate(&self) -> ValidationResult { | random_line_split |
section.rs | //! # Section Block
//!
//! _[slack api docs 🔗]_
//!
//! Available in surfaces:
//! - [modals 🔗]
//! - [messages 🔗]
//! - [home tabs 🔗]
//!
//! A `section` is one of the most flexible blocks available -
//! it can be used as a simple text block,
//! in combination with text fields,
//! or side-by-side with any o... | 10, texts.as_ref()).and(
texts.iter()
.map(|text| {
below_len(
"Section.fields",
2000,
text.as_ref())
... | lds", | identifier_name |
section.rs | //! # Section Block
//!
//! _[slack api docs 🔗]_
//!
//! Available in surfaces:
//! - [modals 🔗]
//! - [messages 🔗]
//! - [home tabs 🔗]
//!
//! A `section` is one of the most flexible blocks available -
//! it can be used as a simple text block,
//! in combination with text fields,
//! or side-by-side with any o... | ique identifier for a block.
///
/// You can use this `block_id` when you receive an interaction payload
/// to [identify the source of the action 🔗].
///
/// If not specified, a `block_id` will be generated.
///
/// Maximum length for this field is 255 characters.
///
/// [identify... | /// A string acting as a un | identifier_body |
install.rs | ERROR: type should be large_string, got " https://bugzilla.redhat.com/show_bug.cgi?id=1905159\n #[allow(clippy::match_bool, clippy::match_single_binding)]\n let sector_size = match is_dasd(device, None)\n .with_context(|| format!(\"checking whether {device} is an IBM DASD disk\"))?\n {\n #[cfg(target_arch = \"s390x\")]\n true => s390x::dasd_try_get_sector_size(device).transpose(),\n _ => None,\n };\n let sector_size = sector_size\n .unwrap_or_else(|| get_sector_size_for_path(Path::new(device)))\n .with_context(|| format!(\"getting sector size of {device}\"))?\n .get();\n\n // Set up DASD. We need to do this before initiating the download\n // because otherwise the download might time out while we're low-level\n // formatting the DASD.\n #[cfg(target_arch = \"s390x\")]\n {\n if is_dasd(device, None)? {\n if!save_partitions.is_empty() {\n // The user requested partition saving, but SavedPartitions\n // doesn't understand DASD VTOCs and won't find any partitions\n // to save.\n bail!(\"saving DASD partitions is not supported\");\n }\n s390x::prepare_dasd(device)?;\n }\n }\n\n // set up image source\n // create location\n let location: Box<dyn ImageLocation> = if let Some(image_file) = &config.image_file {\n Box::new(FileLocation::new(image_file))\n } else if let Some(image_url) = &config.image_url {\n Box::new(UrlLocation::new(image_url, config.fetch_retries))\n } else if config.offline {\n match OsmetLocation::new(config.architecture.as_str(), sector_size)? {\n Some(osmet) => Box::new(osmet),\n None => bail!(\"cannot perform offline install; metadata missing\"),\n }\n } else {\n // For now, using --stream automatically will cause a download. In the future, we could\n // opportunistically use osmet if the version and stream match an osmet file/the live ISO.\n\n let maybe_osmet = match config.stream {\n Some(_) => None,\n None => OsmetLocation::new(config.architecture.as_str(), sector_size)?,\n };\n\n if let Some(osmet) = maybe_osmet {\n Box::new(osmet)\n } else {\n let format = match sector_size {\n 4096 => \"4k.raw.xz\",\n 512 => \"raw.xz\",\n n => {\n // could bail on non-512, but let's be optimistic and just warn but try the regular\n // 512b image\n eprintln!(\n \"Found non-standard sector size {n} for {device}, assuming 512b-compatible\"\n );\n \"raw.xz\"\n }\n };\n Box::new(StreamLocation::new(\n config.stream.as_deref().unwrap_or(\"stable\"),\n config.architecture.as_str(),\n \"metal\",\n format,\n config.stream_base_url.as_ref(),\n config.fetch_retries,\n )?)\n }\n };\n // report it to the user\n eprintln!(\"{location}\");\n // we only support installing from a single artifact\n let mut sources = location.sources()?;\n let mut source = sources.pop().context(\"no artifacts found\")?;\n if!sources.is_empty() {\n bail!(\"found multiple artifacts\");\n }\n if source.signature.is_none() && location.require_signature() {\n if config.insecure {\n eprintln!(\"Signature not found; skipping verification as requested\");\n } else {\n bail!(\"--insecure not specified and signature not found\");\n }\n }\n\n // open output; ensure it's a block device and we have exclusive access\n let mut dest = OpenOptions::new()\n .read(true)\n .write(true)\n .open(device)\n .with_context(|| format!(\"opening {device}\"))?;\n if!dest\n .metadata()\n .with_context(|| format!(\"getting metadata for {device}\"))?\n .file_type()\n .is_block_device()\n {\n bail!(\"{} is not a block device\", device);\n }\n ensure_exclusive_access(device)\n .with_context(|| format!(\"checking for exclusive access to {device}\"))?;\n\n // save partitions that we plan to keep\n let saved = SavedPartitions::new_from_disk(&mut dest, &save_partitions)\n .with_context(|| format!(\"saving partitions from {device}\"))?;\n\n // get reference to partition table\n // For kpartx partitioning, this will conditionally call kpartx -d\n // when dropped\n let mut table = Disk::new(device)?\n .get_partition_table()\n .with_context(|| format!(\"getting partition table for {device}\"))?;\n\n // copy and postprocess disk image\n // On failure, clear and reread the partition table to prevent the disk\n // from accidentally being used.\n dest.rewind().with_context(|| format!(\"seeking {device}\"))?;\n if let Err(err) = write_disk(\n &config,\n &mut source,\n &mut dest,\n &mut *table,\n &saved,\n ignition,\n network_config,\n ) {\n // log the error so the details aren't dropped if we encounter\n // another error during cleanup\n eprintln!(\"\\nError: {err:?}\\n\");\n\n // clean up\n if config.preserve_on_error {\n eprintln!(\"Preserving partition table as requested\");\n if saved.is_saved() {\n // The user asked to preserve the damaged partition table\n // for debugging. We also have saved partitions, and those\n // may or may not be in the damaged table depending where we\n // failed. Preserve the saved partitions by writing them to\n // a file in /tmp and telling the user about it. Hey, it's\n // a debug flag.\n stash_saved_partitions(&mut dest, &saved)?;\n }\n } else {\n reset_partition_table(&config, &mut dest, &mut *table, &saved)?;\n }\n\n // return a generic error so our exit status is right\n bail!(\"install failed\");\n }\n\n // Because grub picks /boot by label and the OS picks /boot, we can end up racing/flapping\n // between picking a /boot partition on startup. So check amount of filesystems labeled 'boot'\n // and warn user if it's not only one\n match get_filesystems_with_label(\"boot\", true) {\n Ok(pts) => {\n if pts.len() > 1 {\n let rootdev = fs::canonicalize(device)\n .unwrap_or_else(|_| PathBuf::from(device))\n .to_string_lossy()\n .to_string();\n let pts = pts\n .iter()\n .filter(|pt|!pt.contains(&rootdev))\n .collect::<Vec<_>>();\n eprintln!(\"\\nNote: detected other devices with a filesystem labeled `boot`:\");\n for pt in pts {\n eprintln!(\" - {pt}\");\n }\n eprintln!(\"The installed OS may not work correctly if there are multiple boot filesystems.\nBefore rebooting, investigate whether these filesystems are needed and consider\nwiping them with `wipefs -a`.\\n\"\n );\n }\n }\n Err(e) => eprintln!(\"checking filesystems labeled 'boot': {e:?}\"),\n }\n\n eprintln!(\"Install complete.\");\n Ok(())\n}\n\nfn parse_partition_filters(labels: &[&str], indexes: &[&str]) -> Result<Vec<PartitionFilter>> {\n use PartitionFilter::*;\n let mut filters: Vec<PartitionFilter> = Vec::new();\n\n // partition label globs\n for glob in labels {\n let filter = Label(\n glob::Pattern::new(glob)\n .with_context(|| format!(\"couldn't parse label glob '{glob}'\"))?,\n );\n filters.push(filter);\n }\n\n // partition index ranges\n let parse_index = |i: &str| -> Result<Option<NonZeroU32>> {\n match i {\n \"\" => Ok(None), // open end of range\n _ => Ok(Some(\n NonZeroU32::new(\n i.parse()\n .with_context(|| format!(\"couldn't parse partition index '{i}'\"))?,\n )\n .context(\"partition index cannot be zero\")?,\n )),\n }\n };\n for range in indexes {\n let parts: Vec<&str> = range.split('-').collect();\n let filter = match parts.len() {\n 1 => Index(parse_index(parts[0])?, parse_index(parts[0])?),\n 2 => Index(parse_index(parts[0])?, parse_index(parts[1])?),\n _ => bail!(\"couldn't parse partition index range '{}'\", range),\n };\n match filter {\n Index(None, None) => bail!(\n \"both ends of partition index range '{}' cannot be open\",\n range\n ),\n Index(Some(x), Some(y)) if x > y => bail!(\n \"start of partition index range '{}' cannot be greater than end\",\n range\n ),\n _ => filters.push(filter),\n };\n }\n Ok(filters)\n}\n\nfn ensure_exclusive_access(device: &str) -> Result<()> {\n let mut parts = Disk::new(device)?.get_busy_partitions()?;\n if parts.is_empty() {\n return Ok(());\n }\n parts.sort_unstable_by_key(|p| p.path.to_string());\n eprintln!(\"Partitions in use on {device}:\");\n for part in parts {\n if let Some(mountpoint) = part.mountpoint.as_ref() {\n eprintln!(\" {} mounted on {}\", part.path, mountpoint);\n }\n if part.swap {\n eprintln!(\" {} is swap device\", part.path);\n }\n for holder in part.get_holders()? {\n eprintln!(\" {} in use by {}\", part.path, holder);\n }\n }\n bail!(\"found busy partitions\");\n}\n\n/// Copy the image source to the target disk and do all post-processing.\n/// If this function fails, the caller should wipe the partition table\n/// to ensure the user doesn't boot from a partially-written disk.\nfn write_disk(\n config: &InstallConfig,\n source: &mut ImageSource,\n dest: &mut File,\n table: &mut dyn PartTable,\n saved: &SavedPartitions,\n ignition: Option<File>,\n network_config: Option<&str>,\n) -> Result<()> {\n let device = config.dest_device.as_deref().expect(\"device missing\");\n\n // Get sector size of destination, for comparing with image\n let sector_size = get_sector_size(dest)?;\n\n // copy the image\n #[allow(clippy::match_bool, clippy::match_single_binding)]\n let image_copy = match is_dasd(device, Some(dest))? {\n #[cfg(target_arch = \"s390x\")]\n true => s390x::image_copy_s390x,\n _ => image_copy_default,\n };\n write_image(\n source,\n dest,\n Path::new(device),\n image_copy,\n true,\n Some(saved),\n Some(sector_size),\n VerifyKeys::Production,\n )?;\n table.reread()?;\n\n // postprocess\n if ignition.is_some()\n || config.firstboot_args.is_some()\n ||!config.append_karg.is_empty()\n ||!config.delete_karg.is_empty()\n || config.platform.is_some()\n ||!config.console.is_empty()\n || network_config.is_some()\n || cfg!(target_arch = \"s390x\")\n {\n let mount = Disk::new(device)?.mount_partition_by_label(\"boot\", mount::MsFlags::empty())?;\n if let Some(ignition) = ignition.as_ref() {\n write_ignition(mount.mountpoint(), &config.ignition_hash, ignition)\n .context(\"writing Ignition configuration\")?;\n }\n if let Some(platform) = config.platform.as_ref() {\n write_platform(mount.mountpoint(), platform).context(\"writing platform ID\")?;\n }\n if config.platform.is_some() ||!config.console.is_empty() {\n write_console(\n mount.mountpoint(),\n config.platform.as_deref(),\n &config.console,\n )\n .context(\"configuring console\")?;\n }\n if let Some(firstboot_args) = config.firstboot_args.as_ref() {\n write_firstboot_kargs(mount.mountpoint(), firstboot_args)\n .context(\"writing firstboot kargs\")?;\n }\n if!config.append_karg.is_empty() ||!config.delete_karg.is_empty() {\n eprintln!(\"Modifying kernel arguments\");\n\n Console::maybe_warn_on_kargs(&config.append_karg, \"--append-karg\", \"--console\");\n visit_bls_entry_options(mount.mountpoint(), |orig_options: &str| {\n KargsEditor::new()\n .append(config.append_karg.as_slice())\n .delete(config.delete_karg.as_slice())\n .maybe_apply_to(orig_options)\n })\n .context(\"deleting and appending kargs\")?;\n }\n if let Some(network_config) = network_config.as_ref() {\n copy_network_config(mount.mountpoint(), network_config)?;\n }\n #[cfg(target_arch = \"s390x\")]\n {\n s390x::zipl(\n mount.mountpoint(),\n None,\n None,\n s390x::ZiplSecexMode::Disable,\n None,\n )?;\n s390x::chreipl(device)?;\n }\n }\n\n // detect any latent write errors\n dest.sync_all().context(\"syncing data to disk\")?;\n\n Ok(())\n}\n\n/// Write the Ignition config.\nfn write_ignition(\n mountpoint: &Path,\n digest_in: &Option<IgnitionHash>,\n mut config_in: &File,\n) -> Result<()> {\n eprintln!(\"Writing Ignition config\");\n\n // Verify configuration digest, if any.\n if let Some(digest) = &digest_in {\n digest\n .validate(&mut config_in)\n .context(\"failed to validate Ignition configuration digest\")?;\n config_in\n .rewind()\n .context(\"rewinding Ignition configuration file\")?;\n };\n\n // make parent directory\n let mut config_dest = mountpoint.to_path_buf();\n config_dest.push(\"ignition\");\n if!config_dest.is_dir() {\n fs::create_dir_all(&config_dest).with_context(|| {\n format!(\n \"creating Ignition config directory {}\",\n config_dest.display()\n )\n })?;\n // Ignition data may contain secrets; restrict to root\n fs::set_permissions(&config_dest, Permissions::from_mode(0o700)).with_context(|| {\n format!(\n \"setting file mode for Ignition directory {}\",\n config_dest.display()\n )\n })?;\n }\n\n // do the copy\n config_dest.push(\"config.ign\");\n let mut config_out = OpenOptions::new()\n .write(true)\n .create_new(true)\n .open(&config_dest)\n .with_context(|| {\n format!(\n \"opening destination Ignition config {}\",\n config_dest.display()\n )\n })?;\n // Ignition config may contain secrets; restrict to root\n fs::set_permissions(&config_dest, Permissions::from_mode(0o600)).with_context(|| {\n format!(\n \"setting file mode for destination Ignition config {}\",\n config_dest.display()\n )\n })?;\n io::copy(&mut config_in, &mut config_out).context(\"writing Ignition config\")?;\n\n Ok(())\n}\n\n/// Write first-boot kernel arguments.\nfn " | (mountpoint: &Path, args: &str) -> Result<()> {
eprintln!("Writing first-boot kernel arguments");
// write the arguments
let mut config_dest = mountpoint.to_path_buf();
config_dest.push("ignition.firstboot");
// if the file doesn't already exist, fail, since our assumptions
// are wrong
let... | write_firstboot_kargs | identifier_name |
install.rs |
// log the error so the details aren't dropped if we encounter
// another error during cleanup
eprintln!("\nError: {err:?}\n");
// clean up
if config.preserve_on_error {
eprintln!("Preserving partition table as requested");
if saved.is_saved() {
... | {
use PartitionFilter::*;
let g = |v| Label(glob::Pattern::new(v).unwrap());
let i = |v| Some(NonZeroU32::new(v).unwrap());
assert_eq!(
parse_partition_filters(&["foo", "z*b?", ""], &["1", "7-7", "2-4", "-3", "4-"])
.unwrap(),
vec![
... | identifier_body | |
install.rs | .collect::<Vec<&str>>(),
&config
.save_partindex
.iter()
.map(|s| s.as_str())
.collect::<Vec<&str>>(),
)?;
// compute sector size
// Uninitialized ECKD DASD's blocksize is 512, but after formatting
// it changes to the recommended 4096
... | .map(|s| s.as_str()) | random_line_split | |
lib.rs | //! The Starling JavaScript runtime.
//!
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
// Annoying warning emitted from the `error_chain!` macro.
#![allow(unused_doc_comment)]
#[macro_use]
extern crate derive_error_chain;
#[macro_use]
... |
}
StarlingMessage::NewTask(task, join_handle) => {
self.tasks.insert(task.id(), task);
self.threads.insert(join_handle.thread().id(), join_handle);
}
}
}
Ok(())
}
}
/// Messages that threads can s... | {
// TODO: notification of shutdown and joining other threads and things.
return Err(error);
} | conditional_block |
lib.rs | //! The Starling JavaScript runtime.
//!
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
// Annoying warning emitted from the `error_chain!` macro.
#![allow(unused_doc_comment)]
#[macro_use]
extern crate derive_error_chain;
#[macro_use]
... |
#[test]
fn task_message_is_send() {
assert_send::<TaskMessage>();
}
}
| {
assert_send::<StarlingMessage>();
} | identifier_body |
lib.rs | //! The Starling JavaScript runtime.
//!
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
// Annoying warning emitted from the `error_chain!` macro.
#![allow(unused_doc_comment)]
#[macro_use]
extern crate derive_error_chain;
#[macro_use]
... | cpu_pool: CpuPool::new(cpu_pool_threads),
sender,
};
Ok(Starling {
handle,
receiver,
tasks,
threads,
})
}
/// Run the main Starling event loop with the specified options.
pub fn run(mut self) -> Result<()> {
... | options: Arc::new(opts),
sync_io_pool: CpuPool::new(sync_io_pool_threads), | random_line_split |
lib.rs | //! The Starling JavaScript runtime.
//!
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
// Annoying warning emitted from the `error_chain!` macro.
#![allow(unused_doc_comment)]
#[macro_use]
extern crate derive_error_chain;
#[macro_use]
... | <T>(&self) -> usize {
let size_of_t = cmp::max(1, mem::size_of::<T>());
let capacity = self.channel_buffer_size / size_of_t;
cmp::max(1, capacity)
}
}
/// The Starling supervisory thread.
///
/// The supervisory thread doesn't do much other than supervise other threads: the IO
/// event loo... | buffer_capacity_for | identifier_name |
random_state.rs | use core::hash::Hash;
cfg_if::cfg_if! {
if #[cfg(any(
all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "aes", not(miri)),
all(any(target_arch = "arm", target_arch = "aarch64"), any(target_feature = "aes", target_feature = "crypto"), not(miri), feature = "stdsimd")
))] {
... | #[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))]
#[test]
fn test_not_pi() {
assert_ne!(PI, get_fixed_seeds()[0]);
}
#[cfg(all(feature = "compile-time-rng", any(not(feature = "runtime-rng"), test)))]
#[test]
fn test_not_pi_const() {
assert_ne... | let a = RandomState::generate_with(1, 2, 3, 4);
let b = RandomState::generate_with(1, 2, 3, 4);
assert_ne!(a.build_hasher().finish(), b.build_hasher().finish());
}
| random_line_split |
random_state.rs | use core::hash::Hash;
cfg_if::cfg_if! {
if #[cfg(any(
all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "aes", not(miri)),
all(any(target_arch = "arm", target_arch = "aarch64"), any(target_feature = "aes", target_feature = "crypto"), not(miri), feature = "stdsimd")
))] {
... | () {
assert_ne!(PI, get_fixed_seeds()[0]);
}
#[cfg(all(not(feature = "runtime-rng"), not(feature = "compile-time-rng")))]
#[test]
fn test_pi() {
assert_eq!(PI, get_fixed_seeds()[0]);
}
#[test]
fn test_with_seeds_const() {
const _CONST_RANDOM_STATE: RandomState = Ran... | test_not_pi_const | identifier_name |
random_state.rs | use core::hash::Hash;
cfg_if::cfg_if! {
if #[cfg(any(
all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "aes", not(miri)),
all(any(target_arch = "arm", target_arch = "aarch64"), any(target_feature = "aes", target_feature = "crypto"), not(miri), feature = "stdsimd")
))] {
... |
}
#[cfg(feature = "specialize")]
impl BuildHasherExt for RandomState {
#[inline]
fn hash_as_u64<T: Hash +?Sized>(&self, value: &T) -> u64 {
let mut hasher = AHasherU64 {
buffer: self.k0,
pad: self.k1,
};
value.hash(&mut hasher);
hasher.finish()
}
... | {
RandomState::hash_one(self, x)
} | identifier_body |
lib.rs | b fn flush(&mut self) -> Result<(), Error> {
if self.bit_count > 0 {
self.buffer <<= 8 - self.bit_count;
let mut buffer = 0;
for i in 0..8 {
buffer <<= 1;
buffer |= (self.buffer >> i) & 1;
}
self.output_vector.push(buff... | */
pu | identifier_name | |
lib.rs | ;
for i in 0..8 {
buffer <<= 1;
buffer |= (self.buffer >> i) & 1;
}
self.output_vector.push(buffer.clone());
if PRINT_DEBUG == true {
println!("push data: {:08b}", self.buffer);
for i in 0..(self.output_vect... | f.crc32, self.hms, self.ymd)
}
}
/*
ファイルの最終更新日時を取得してそれぞれをzipに必要な形式にして返す。
下のurlのヘッダ構造の部分から形式を知った。
https://hgotoh.jp/wiki/doku.php/documents/other/other-017
*/
fn time_data(filename: &str) -> (u16, u16) {
let times;
if let Ok(metadata) = metadata(filename) {
if let Ok(time) = metadata.modified()... | <u8>{
self.push_pk0506();
self.push16(0x0000);
self.push16(0x0000);
self.push16(0x0001);
self.push16(0x0001);
self.push32(header_size);
self.push32(header_start);
self.push16(0x00);
self.buffer
}
/*
cloneの実装を行なっている
*/
pub fn ... | identifier_body |
lib.rs | 0;
for i in 0..8 {
buffer <<= 1;
buffer |= (self.buffer >> i) & 1;
}
self.output_vector.push(buffer.clone());
if PRINT_DEBUG == true {
println!("push data: {:08b}", self.buffer);
for i in 0..(self.output_ve... | pub fn seek_byte(&mut self) -> u8{
self.buffer[self.buf_count]
}
/*
bit_countを進める。bufferの最後まできていた場合には
load_next_byteで次のブロックを読み込む。
*/
pub fn next_byte(&mut self) {
if self.buf_count + 1 < self.buf_size {
self.buf_count += 1;
} else {
let _ =... | */ | random_line_split |
main.rs | // Copyright 2018-2019 Peter Williams <peter@newton.cx>
// Licensed under the MIT License.
//! The main CLI driver logic.
#![deny(missing_docs)]
#![allow(proc_macro_derive_resolution_fallback)]
extern crate app_dirs;
extern crate chrono;
#[macro_use]
extern crate clap; // for arg_enum!
#[macro_use]
extern crate dies... | _n => {
tcprintln!(app.ps, [hl: "Paths::"]);
for p in path_reprs {
tcprintln!(app.ps, (" {}", p));
}
}
}
tcprintln!(app.ps, [hl: "Open-URL:"], (" {}", doc.open_url()));
... | }
match path_reprs.len() {
0 => tcprintln!(app.ps, [hl: "Path:"], (" [none??]")),
1 => tcprintln!(app.ps, [hl: "Path:"], (" {}", path_reprs[0])), | random_line_split |
main.rs | // Copyright 2018-2019 Peter Williams <peter@newton.cx>
// Licensed under the MIT License.
//! The main CLI driver logic.
#![deny(missing_docs)]
#![allow(proc_macro_derive_resolution_fallback)]
extern crate app_dirs;
extern crate chrono;
#[macro_use]
extern crate clap; // for arg_enum!
#[macro_use]
extern crate dies... | (self, app: &mut Application) -> Result<i32> {
app.maybe_sync_all_accounts()?;
let doc = app.get_docs().process_one(self.spec)?;
open_url(doc.open_url())?;
Ok(0)
}
}
/// List recently-used documents.
#[derive(Debug, StructOpt)]
pub struct DrorgRecentOptions {
#[structopt(
... | cli | identifier_name |
finality.rs | // Copyright 2015-2018 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... |
/// Push a hash onto the rolling finality checker (implying `subchain_head` == head.parent)
///
/// Fails if `signer` isn't a member of the active validator set.
/// Returns a list of all newly finalized headers.
// TODO: optimize with smallvec.
pub fn push_hash(&mut self, head: H256, signers:... | {
self.headers.pop_back()
} | identifier_body |
finality.rs | // Copyright 2015-2018 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... | () {
let (signers, key_ids) = get_keys(3);
let mut finality = RollingFinality::blank(signers);
assert!(finality.push_hash(H256::random(), vec![key_ids[0], 0xAA]).is_err());
}
#[test]
fn finalize_multiple() {
let (signers, key_ids) = get_keys(6);
let mut finality = R... | rejects_unknown_signers | identifier_name |
finality.rs | // Copyright 2015-2018 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... | RollingFinality {
headers: VecDeque::new(),
signers: SimpleList::new(signers),
sign_count: HashMap::new(),
last_pushed: None,
}
}
pub fn add_signer(&mut self, signer: PublicKey) {
self.signers.add(signer)
}
pub fn remove_signer(&mut self, signer: &u64) {
self.signers.remov... | /// Create a blank finality checker under the given validator set.
pub fn blank(signers: Vec<PublicKey>) -> Self { | random_line_split |
finality.rs | // Copyright 2015-2018 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... |
for signer in signers.iter() {
*self.sign_count.entry(signer.clone()).or_insert(0) += 1;
}
}
self.headers.push_front((hash, signers));
}
trace!(target: "finality", "Rolling finality state: {:?}", self.headers);
Ok(())
}
/// Clear the finality status, but keeps the validator set.
pub fn ... | {
trace!(target: "finality", "Encountered already finalized block {:?}", hash.clone());
break
} | conditional_block |
ffi.rs | //! Internals of the `libsvm` FFI.
//!
//! Objects whose names start with `Libsvm` are for the most part
//! things that we pass or get directly from `libsvm`, and are highly
//! fragile.
//!
//! Their safe, memory-owning counterparts start with `Svm`.
use std::ffi::CStr;
use std::os::raw::c_char;
use std::slice;
use... |
}
}
/// Fit a `libsvm` model.
pub fn fit<'a, T>(X: &'a T, y: &Array, parameters: &SvmParameter) -> Result<SvmModel, &'static str>
where
T: IndexableMatrix,
&'a T: RowIterable,
{
let problem = SvmProblem::new(X, y);
let libsvm_problem = problem.build_problem();
let libsvm_param = parameters.bu... | {
Err(CStr::from_ptr(message).to_str().unwrap().to_owned())
} | conditional_block |
ffi.rs | //! Internals of the `libsvm` FFI.
//!
//! Objects whose names start with `Libsvm` are for the most part
//! things that we pass or get directly from `libsvm`, and are highly
//! fragile.
//!
//! Their safe, memory-owning counterparts start with `Svm`.
use std::ffi::CStr;
use std::os::raw::c_char;
use std::slice;
use... | cache_size: f64,
eps: f64,
C: f64,
nr_weight: i32,
weight_label: *const i32,
weight: *const f64,
nu: f64,
p: f64,
shrinking: i32,
probability: i32,
}
/// Safe representation of `LibsvmParameter`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SvmParameter {
svm_t... | kernel_type: KernelType,
degree: i32,
gamma: f64,
coef0: f64, | random_line_split |
ffi.rs | //! Internals of the `libsvm` FFI.
//!
//! Objects whose names start with `Libsvm` are for the most part
//! things that we pass or get directly from `libsvm`, and are highly
//! fragile.
//!
//! Their safe, memory-owning counterparts start with `Svm`.
use std::ffi::CStr;
use std::os::raw::c_char;
use std::slice;
use... | <T: NonzeroIterable>(row: T) -> Vec<LibsvmNode> {
let mut nodes = Vec::new();
for (index, value) in row.iter_nonzero() {
nodes.push(LibsvmNode::new(index as i32, value as f64));
}
// Sentinel value for end of row
nodes.push(LibsvmNode::new(-1, 0.0));
nodes
}
impl SvmProblem {
///... | row_to_nodes | identifier_name |
ffi.rs | //! Internals of the `libsvm` FFI.
//!
//! Objects whose names start with `Libsvm` are for the most part
//! things that we pass or get directly from `libsvm`, and are highly
//! fragile.
//!
//! Their safe, memory-owning counterparts start with `Svm`.
use std::ffi::CStr;
use std::os::raw::c_char;
use std::slice;
use... |
/// Returns the unsafe object that can be passed into `libsvm`.
fn build_problem(&self) -> LibsvmProblem {
LibsvmProblem {
l: self.nodes.len() as i32,
y: self.y.as_ptr(),
svm_node: self.node_ptrs.as_ptr(),
}
}
}
/// `libsvm` representation of training p... | {
let mut nodes = Vec::with_capacity(X.rows());
for row in X.iter_rows() {
let row_nodes = row_to_nodes(row);
nodes.push(row_nodes)
}
let node_ptrs = nodes.iter().map(|x| x.as_ptr()).collect::<Vec<_>>();
SvmProblem {
nodes: nodes,
... | identifier_body |
lib.rs | use encoding_rs::{EncoderResult, EUC_KR, SHIFT_JIS, UTF_16LE};
use eztrans_rs::{Container, EzTransLib};
use fxhash::FxHashMap;
use serde_derive::{Deserialize, Serialize};
use std::ffi::CStr;
use std::fs;
use std::path::Path;
use std::ptr::null_mut;
pub struct EzDictItem {
key: String,
value: String,
}
impl Ez... | if!self.sort {
return;
}
self.after_dict
.sort_unstable_by(|l, r| l.key().cmp(r.key()));
}
pub fn sort(&mut self) {
self.sort_after_dict();
self.sort_before_dict();
}
}
mod dict_items {
use super::EzDictItem;
use serde::de::{MapAccess, ... | ;
}
self.before_dict
.sort_unstable_by(|l, r| l.key().cmp(r.key()));
}
pub fn sort_after_dict(&mut self) {
| identifier_body |
lib.rs | use encoding_rs::{EncoderResult, EUC_KR, SHIFT_JIS, UTF_16LE};
use eztrans_rs::{Container, EzTransLib};
use fxhash::FxHashMap;
use serde_derive::{Deserialize, Serialize};
use std::ffi::CStr;
use std::fs;
use std::path::Path;
use std::ptr::null_mut;
pub struct EzDictItem {
key: String,
value: String,
}
impl Ez... | impl EzDict {
pub fn sort_before_dict(&mut self) {
if!self.sort {
return;
}
self.before_dict
.sort_unstable_by(|l, r| l.key().cmp(r.key()));
}
pub fn sort_after_dict(&mut self) {
if!self.sort {
return;
}
self.after_dict
... | random_line_split | |
lib.rs | use encoding_rs::{EncoderResult, EUC_KR, SHIFT_JIS, UTF_16LE};
use eztrans_rs::{Container, EzTransLib};
use fxhash::FxHashMap;
use serde_derive::{Deserialize, Serialize};
use std::ffi::CStr;
use std::fs;
use std::path::Path;
use std::ptr::null_mut;
pub struct EzDictItem {
key: String,
value: String,
}
impl Ez... | t dict = &mut self.dict;
let lib = &self.lib;
let buf = &mut self.encode_buffer;
let str_buf = &mut self.string_buffer;
self.cache.entry(text.into()).or_insert_with(move || {
str_buf.push_str(text);
let mut encoder = SHIFT_JIS.new_encoder();
let mut ... | r {
le | identifier_name |
lib.rs | /// ```
pub fn install() {
BacktracePrinter::default().install(default_output_stream());
}
/// Create the default output stream.
///
/// If stderr is attached to a tty, this is a colorized stderr, else it's
/// a plain (colorless) stderr.
pub fn default_output_stream() -> Box<StandardStream> {
Box::new(Standar... | self, i: usize, out: &mut impl WriteColor, s: &BacktracePrinter) -> IOResult {
let is_dependency_code = self.is_dependency_code();
// Print frame index.
write!(out, "{:>2}: ", i)?;
if s.should_print_addresses() {
if let Some((module_name, module_base)) = self.module_info() ... | int(& | identifier_name |
lib.rs |
/// ```
pub fn install() {
BacktracePrinter::default().install(default_output_stream());
}
/// Create the default output stream.
///
/// If stderr is attached to a tty, this is a colorized stderr, else it's
/// a plain (colorless) stderr.
pub fn default_output_stream() -> Box<StandardStream> {
Box::new(Standa... | "___rust_",
"__pthread",
"_main",
"main",
"__scrt_common_main_seh",
"BaseThreadInitThunk",
"_start",
"__libc_start_main",
"start_thread",
];
// Inspect name.
if let Some(ref name) = self.... | random_line_split | |
lib.rs | /// ```
pub fn install() {
BacktracePrinter::default().install(default_output_stream());
}
/// Create the default output stream.
///
/// If stderr is attached to a tty, this is a colorized stderr, else it's
/// a plain (colorless) stderr.
pub fn default_output_stream() -> Box<StandardStream> {
Box::new(Standar... | lse {
&s.colors.crate_code
})?;
if has_hash_suffix {
write!(out, "{}", &name[..name.len() - 19])?;
if s.strip_function_hash {
writeln!(out)?;
} else {
out.set_color(if is_dependency_code {
&s.colors.depe... | &s.colors.dependency_code
} e | conditional_block |
lib.rs |
/// ```
pub fn install() {
BacktracePrinter::default().install(default_output_stream());
}
/// Create the default output stream.
///
/// If stderr is attached to a tty, this is a colorized stderr, else it's
/// a plain (colorless) stderr.
pub fn default_output_stream() -> Box<StandardStream> {
Box::new(Standa... | /// Alter the color scheme.
///
/// Defaults to `ColorScheme::classic()`.
pub fn color_scheme(mut self, colors: ColorScheme) -> Self {
self.colors = colors;
self
}
/// Controls the "greeting" message of the panic.
///
/// Defaults to `"The application panicked (crashed)"... | Self::default()
}
| identifier_body |
lib.rs | //! Example crate demonstrating how to use nom to parse `/proc/mounts`. Browse crates.io for sys-mount, proc-mounts, and libmount for more stable, usable crates.
// Needed to use traits associated with std::io::BufReader.
use std::io::BufRead;
use std::io::Read;
/// Type-erased errors.
pub type BoxError = std::boxed... | (&'a mut self) -> MountsIteratorMut<'a> {
self.into_iter()
}
}
// Encapsulate individual nom parsers in a private submodule. The `pub(self)` keyword allows the inner method [parsers::parse_line()] to be called by code within this module, but not my users of our crate.
pub(self) mod parsers {
use super::Mount;
... | iter_mut | identifier_name |
lib.rs | //! Example crate demonstrating how to use nom to parse `/proc/mounts`. Browse crates.io for sys-mount, proc-mounts, and libmount for more stable, usable crates.
// Needed to use traits associated with std::io::BufReader.
use std::io::BufRead;
use std::io::Read;
/// Type-erased errors.
pub type BoxError = std::boxed... | } | Mounts::new() | random_line_split |
lib.rs | //! Example crate demonstrating how to use nom to parse `/proc/mounts`. Browse crates.io for sys-mount, proc-mounts, and libmount for more stable, usable crates.
// Needed to use traits associated with std::io::BufReader.
use std::io::BufRead;
use std::io::Read;
/// Type-erased errors.
pub type BoxError = std::boxed... | {
Mounts::new()
} | identifier_body | |
smd.rs | use std::fs::File;
use std::io::{BufReader};
use std::path::PathBuf;
use cgmath::{Matrix4, Deg, Vector4, SquareMatrix, Vector3, Euler, Quaternion, Rotation};
use soto::task::{task_log};
use soto::Error;
use sotolib_fbx::{RawFbx, id_name, friendly_name, ObjectTreeNode};
use sotolib_fbx::animation::{Animation};
use soto... | }
fn calculate_parent_after_rot_translation(fbx: &SimpleFbx, obj: &Object) -> Vector3<f32> {
// First actually get the parent's model data
let parent_obj = if let Some(v) = fbx.parent_of(obj.id) {
if v == 0 {
// At root, no extra translation
return Vector3::new(0.0, 0.0, 0.0)
... | (translation, rotation) | random_line_split |
smd.rs | use std::fs::File;
use std::io::{BufReader};
use std::path::PathBuf;
use cgmath::{Matrix4, Deg, Vector4, SquareMatrix, Vector3, Euler, Quaternion, Rotation};
use soto::task::{task_log};
use soto::Error;
use sotolib_fbx::{RawFbx, id_name, friendly_name, ObjectTreeNode};
use sotolib_fbx::animation::{Animation};
use soto... | (rot_degs: [f32; 3]) -> Matrix4<f32> {
Matrix4::from_angle_z(Deg(rot_degs[2])) *
Matrix4::from_angle_y(Deg(rot_degs[1])) *
Matrix4::from_angle_x(Deg(rot_degs[0]))
}
| euler_rotation_to_matrix | identifier_name |
smd.rs | use std::fs::File;
use std::io::{BufReader};
use std::path::PathBuf;
use cgmath::{Matrix4, Deg, Vector4, SquareMatrix, Vector3, Euler, Quaternion, Rotation};
use soto::task::{task_log};
use soto::Error;
use sotolib_fbx::{RawFbx, id_name, friendly_name, ObjectTreeNode};
use sotolib_fbx::animation::{Animation};
use soto... | ));
let post_rotation = Quaternion::from(Euler::new(
Deg(properties.post_rotation[0]), Deg(properties.post_rotation[1]), Deg(properties.post_rotation[2])
));
let total_rotation = if!flip {
Euler::from(post_rotation.invert() * rotation * pre_rotation)
} else {
Euler::from(pos... | {
let properties = ModelProperties::from_generic(&obj.properties);
// Get the bone's translation
let parent_after_rot_translation = calculate_parent_after_rot_translation(fbx, obj);
let prop_translation: Vector3<_> = properties.translation.into();
let prop_rot_offset: Vector3<_> = properties.rotati... | identifier_body |
smd.rs | use std::fs::File;
use std::io::{BufReader};
use std::path::PathBuf;
use cgmath::{Matrix4, Deg, Vector4, SquareMatrix, Vector3, Euler, Quaternion, Rotation};
use soto::task::{task_log};
use soto::Error;
use sotolib_fbx::{RawFbx, id_name, friendly_name, ObjectTreeNode};
use sotolib_fbx::animation::{Animation};
use soto... | else {
Euler::from(post_rotation.invert() * rotation.invert() * pre_rotation)
};
let rotation = Vector3::new(
total_rotation.x.0,
total_rotation.y.0,
total_rotation.z.0,
);
(translation, rotation)
}
fn calculate_parent_after_rot_translation(fbx: &SimpleFbx, obj: &Objec... | {
Euler::from(post_rotation.invert() * rotation * pre_rotation)
} | conditional_block |
in_memory.rs | // Copyright (c) SimpleStaking, Viable Systems and Tezedge Contributors
// SPDX-License-Identifier: MIT
//! Implementation of an in-memory repository.
use std::{
borrow::Cow,
collections::{hash_map::DefaultHasher, BTreeMap, VecDeque},
hash::Hasher,
mem::size_of,
sync::{atomic::Ordering, Arc},
... | self.free_ids.as_mut()?.pop().ok()
}
pub(crate) fn insert_value_at(
&mut self,
hash_id: HashId,
value: Arc<[u8]>,
) -> Result<(), HashIdError> {
self.values_bytes = self.values_bytes.saturating_add(value.len());
if let Some(old) = self.values.insert_at(hash_i... |
fn get_free_id(&mut self) -> Option<HashId> { | random_line_split |
in_memory.rs | // Copyright (c) SimpleStaking, Viable Systems and Tezedge Contributors
// SPDX-License-Identifier: MIT
//! Implementation of an in-memory repository.
use std::{
borrow::Cow,
collections::{hash_map::DefaultHasher, BTreeMap, VecDeque},
hash::Hasher,
mem::size_of,
sync::{atomic::Ordering, Arc},
... |
pub fn put_context_hash_impl(&mut self, commit_hash_id: HashId) -> Result<(), DBError> {
let commit_hash = self
.hashes
.get_hash(commit_hash_id)?
.ok_or(DBError::MissingObject {
hash_id: commit_hash_id,
})?;
let mut hasher = DefaultHas... | {
let mut hasher = DefaultHasher::new();
hasher.write(context_hash.as_ref());
let hashed = hasher.finish();
self.context_hashes.get(&hashed).cloned()
} | identifier_body |
in_memory.rs | // Copyright (c) SimpleStaking, Viable Systems and Tezedge Contributors
// SPDX-License-Identifier: MIT
//! Implementation of an in-memory repository.
use std::{
borrow::Cow,
collections::{hash_map::DefaultHasher, BTreeMap, VecDeque},
hash::Hasher,
mem::size_of,
sync::{atomic::Ordering, Arc},
... | (&self) -> RepositoryMemoryUsage {
let values_bytes = self.values_bytes;
let values_capacity = self.values.capacity();
let hashes_capacity = self.hashes.capacity();
let total_bytes = values_bytes
.saturating_add(values_capacity * size_of::<Option<Arc<[u8]>>>())
.sat... | get_memory_usage | identifier_name |
lib.rs | #![deny(missing_docs)]
//! An append-only, on-disk key-value index with lockless reads
use std::cell::UnsafeCell;
use std::fs::OpenOptions;
use std::hash::{Hash, Hasher};
use std::io;
use std::marker::PhantomData;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use arrayvec::ArrayVec;
u... |
// Get a mutable reference to the `Entry`,
// locking the corresponding shard.
fn entry_mut(
&self,
lane: usize,
page: usize,
slot: usize,
) -> EntryMut<K, V> {
let shard = (page ^ slot) % NUM_SHARDS;
// Lock the entry for writing
let lock = SHAR... | {
// Get a reference to the `Entry`
let page_ofs = PAGE_SIZE * page;
let slot_ofs = page_ofs + slot * mem::size_of::<Entry<K, V>>();
unsafe {
mem::transmute(
(*self.lanes.get())[lane].as_ptr().offset(slot_ofs as isize),
)
}
} | identifier_body |
lib.rs | #![deny(missing_docs)]
//! An append-only, on-disk key-value index with lockless reads
use std::cell::UnsafeCell;
use std::fs::OpenOptions;
use std::hash::{Hash, Hasher};
use std::io;
use std::marker::PhantomData;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use arrayvec::ArrayVec;
u... | pages: Mutex::new(num_pages as u64),
_marker: PhantomData,
};
// initialize index with at least one page
if num_pages == 0 {
assert_eq!(index.new_page()?, 0);
}
Ok(index)
}
/// Returns how many pages have been allocated so far
pub... | // create the index
let index = Index {
lanes: UnsafeCell::new(lanes),
path: PathBuf::from(path.as_ref()), | random_line_split |
lib.rs | #![deny(missing_docs)]
//! An append-only, on-disk key-value index with lockless reads
use std::cell::UnsafeCell;
use std::fs::OpenOptions;
use std::hash::{Hash, Hasher};
use std::io;
use std::marker::PhantomData;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use arrayvec::ArrayVec;
u... | (&self) -> &Self::Target {
&self.entry
}
}
impl<'a, K, V> DerefMut for EntryMut<'a, K, V> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.entry
}
}
impl<K: Hash, V: Hash> Entry<K, V> {
fn new(key: K, val: V) -> Self {
let kv_checksum = hash_val(&key).wrapping_add(has... | deref | identifier_name |
fmt.rs | // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
//! This module provides file formatting utilities using
//! [`dprint-plugin-typescript`](https://github.com/dprint/dprint-plugin-typescript).
//!
//! At the moment it is only consumed using CLI but in
//! the future it can be easily extended t... | () -> dprint_plugin_json::configuration::Configuration {
dprint_plugin_json::configuration::ConfigurationBuilder::new()
.deno()
.build()
}
struct FileContents {
text: String,
had_bom: bool,
}
fn read_file_contents(file_path: &Path) -> Result<FileContents, AnyError> {
let file_bytes = fs::read(&file_path... | get_json_config | identifier_name |
fmt.rs | // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
//! This module provides file formatting utilities using
//! [`dprint-plugin-typescript`](https://github.com/dprint/dprint-plugin-typescript).
//!
//! At the moment it is only consumed using CLI but in
//! the future it can be easily extended t... |
}
Ok(())
}
fn files_str(len: usize) -> &'static str {
if len <= 1 {
"file"
} else {
"files"
}
}
fn get_typescript_config(
) -> dprint_plugin_typescript::configuration::Configuration {
dprint_plugin_typescript::configuration::ConfigurationBuilder::new()
.deno()
.build()
}
fn get_markdown_co... | {
return Err(generic_error(e));
} | conditional_block |
fmt.rs | // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
//! This module provides file formatting utilities using
//! [`dprint-plugin-typescript`](https://github.com/dprint/dprint-plugin-typescript).
//!
//! At the moment it is only consumed using CLI but in
//! the future it can be easily extended t... | /// Formats markdown (using https://github.com/dprint/dprint-plugin-markdown) and its code blocks
/// (ts/tsx, js/jsx).
fn format_markdown(
file_text: &str,
ts_config: dprint_plugin_typescript::configuration::Configuration,
) -> Result<String, String> {
let md_config = get_markdown_config();
dprint_plugin_markd... |
Ok(())
}
| random_line_split |
fmt.rs | // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
//! This module provides file formatting utilities using
//! [`dprint-plugin-typescript`](https://github.com/dprint/dprint-plugin-typescript).
//!
//! At the moment it is only consumed using CLI but in
//! the future it can be easily extended t... |
fn write_file_contents(
file_path: &Path,
file_contents: FileContents,
) -> Result<(), AnyError> {
let file_text = if file_contents.had_bom {
// add back the BOM
format!("{}{}", BOM_CHAR, file_contents.text)
} else {
file_contents.text
};
Ok(fs::write(file_path, file_text)?)
}
pub async fn r... | {
let file_bytes = fs::read(&file_path)?;
let charset = text_encoding::detect_charset(&file_bytes);
let file_text = text_encoding::convert_to_utf8(&file_bytes, charset)?;
let had_bom = file_text.starts_with(BOM_CHAR);
let text = if had_bom {
// remove the BOM
String::from(&file_text[BOM_CHAR.len_utf8(... | identifier_body |
global_stats.rs | current = kitchen_sink.total_year_downloads(current_year)?;
}
let n = current[day.ordinal0() as usize];
match day.weekday() {
// this sucks a bit due to mon/fri being UTC, and overlapping with the weekend
// in the rest of the world.
W... | ,
pub title: String,
pub label: String,
pub font_size: f64,
/// SVG fill
pub color: String,
pub count: u32,
pub weight: f64,
pub bounds: treemap::Rect,
pub sub: Vec<TreeBox>,
}
impl TreeBox {
pub fn line_y(&self, nth: usize) -> f64 {
self.bounds.y + 1. + self.font_size *... | ategory | identifier_name |
global_stats.rs | current = kitchen_sink.total_year_downloads(current_year)?;
}
let n = current[day.ordinal0() as usize];
match day.weekday() {
// this sucks a bit due to mon/fri being UTC, and overlapping with the weekend
// in the rest of the world.
W... | cat("database-implementations", &mut roots).label = "Database".into();
get_cat("simulation", &mut roots).label = "Sim".into();
get_cat("caching", &mut roots).label = "Cache".into();
get_cat("config", &mut roots).label = "Config".into();
get_cat("os", &mut roots).label = "OS".into();
get_cat("interna... | at: CATEGORIES.root.values().next().unwrap(),
title: String::new(),
label: String::new(),
font_size: 0.,
color: String::new(),
count: 0,
weight: 0.,
bounds: Rect::new(),
sub,
}
}
// names don't fit
get_ | identifier_body |
global_stats.rs | current = kitchen_sink.total_year_downloads(current_year)?;
}
let n = current[day.ordinal0() as usize];
match day.weekday() {
// this sucks a bit due to mon/fri being UTC, and overlapping with the weekend
// in the rest of the world.
... | }
postprocess_treebox_items(&mut items_flattened);
Ok(items_flattened)
}
fn postprocess_treebox_items(items: &mut Vec<TreeBox>) {
let colors = [
[0xff, 0xf1, 0xe6],
[0xe2, 0xec, 0xe9],
[0xDC, 0xED, 0xC1],
[0xcd, 0xda, 0xfd],
[0xbe, 0xe1, 0xe6],
[0xfd, 0... | items_flattened.append(&mut parent.sub); | random_line_split |
global_stats.rs | current = kitchen_sink.total_year_downloads(current_year)?;
}
let n = current[day.ordinal0() as usize];
match day.weekday() {
// this sucks a bit due to mon/fri being UTC, and overlapping with the weekend
// in the rest of the world.
W... | let hs_deps2 = Histogram {
max: hs_deps1.max,
buckets: hs_deps1.buckets.split_off(10),
bucket_labels: hs_deps1.bucket_labels.split_off(10),
};
let rev_deps = kitchen_sink.crates_io_all_rev_deps_counts().await?;
let mut hs_rev_deps = Histogram::new(rev_deps, true,
&[0,1,2... | to_string()});
| conditional_block |
mod.rs | mod field_names_encoder;
use self::field_names_encoder::FieldNamesEncoder;
use csv::{self, Result};
use rustc_serialize::Encodable;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::marker::PhantomData;
use std::path::Path;
/// A CSV writer that automatically writes the headers.
///
/// This writer provid... |
// Write row.
let mut erecord = csv::Encoded::new();
row.encode(&mut erecord)?;
self.csv.write(erecord.unwrap().into_iter())
}
/// Flushes the underlying buffer.
pub fn flush(&mut self) -> Result<()> {
self.csv.flush()
}
}
#[cfg(test)]
mod tests {
use super... | {
let mut field_names_encoder = FieldNamesEncoder::new();
row.encode(&mut field_names_encoder)?;
self.csv.write(field_names_encoder.into_field_names().into_iter())?;
self.first_row = false;
} | conditional_block |
mod.rs | mod field_names_encoder;
use self::field_names_encoder::FieldNamesEncoder;
use csv::{self, Result};
use rustc_serialize::Encodable;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::marker::PhantomData;
use std::path::Path;
/// A CSV writer that automatically writes the headers.
///
/// This writer provid... | () {
let mut w = Writer::from_memory();
let s1 = SimpleStruct { a: 0, b: 1 };
w.encode(s1).unwrap();
let s2 = SimpleStruct { a: 3, b: 4 };
w.encode(s2).unwrap();
assert_eq!(w.as_string(), "a,b\n0,1\n3,4\n");
}
#[test]
fn test_tuple_of_structs() {
let ... | test_struct | identifier_name |
mod.rs | mod field_names_encoder;
use self::field_names_encoder::FieldNamesEncoder;
use csv::{self, Result};
use rustc_serialize::Encodable;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::marker::PhantomData;
use std::path::Path;
/// A CSV writer that automatically writes the headers.
///
/// This writer provid... | /// ),
/// (
/// Part1 { count: Count(9), animal: "platypus" },
/// Part2 { group: Group::Mammal, description: None },
/// ),
/// ];
///
/// let mut wtr = typed_csv::Writer::from_memory();
/// for record in records.into_iter() {
/// wtr.encode(reco... | random_line_split | |
mod.rs | mod field_names_encoder;
use self::field_names_encoder::FieldNamesEncoder;
use csv::{self, Result};
use rustc_serialize::Encodable;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::marker::PhantomData;
use std::path::Path;
/// A CSV writer that automatically writes the headers.
///
/// This writer provid... |
}
impl<W: Write, E: Encodable> Writer<W, E> {
/// Writes a record by encoding any `Encodable` value.
///
/// When the first record is encoded, the headers (the field names in the
/// struct) are written prior to encoding the record.
///
/// The type that is being encoded into should correspond... | {
self.csv.into_bytes()
} | identifier_body |
http_ece.rs | use base64::{self, URL_SAFE_NO_PAD};
use crate::error::WebPushError;
use crate::message::WebPushPayload;
use ring::rand::SecureRandom;
use ring::{aead::{self, BoundKey}, agreement, hkdf, rand};
use crate::vapid::VapidSignature;
pub enum ContentEncoding {
AesGcm,
Aes128Gcm,
}
pub struct HttpEce<'a> {
peer_... | }
pub fn generate_headers(
&self,
public_key: &'a [u8],
salt: &'a [u8],
) -> Vec<(&'static str, String)> {
let mut crypto_headers = Vec::new();
let mut crypto_key = format!("dh={}", base64::encode_config(public_key, URL_SAFE_NO_PAD));
if let Some(ref signat... | random_line_split | |
http_ece.rs | use base64::{self, URL_SAFE_NO_PAD};
use crate::error::WebPushError;
use crate::message::WebPushPayload;
use ring::rand::SecureRandom;
use ring::{aead::{self, BoundKey}, agreement, hkdf, rand};
use crate::vapid::VapidSignature;
pub enum ContentEncoding {
AesGcm,
Aes128Gcm,
}
pub struct HttpEce<'a> {
peer_... | () {
// writes the padding count in the beginning, zeroes, content and again space for the encryption tag
let content = "naukio";
let mut output = [0u8; 30];
front_pad(content.as_bytes(), &mut output);
assert_eq!(
vec![0, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0... | test_front_pad | identifier_name |
http_ece.rs | use base64::{self, URL_SAFE_NO_PAD};
use crate::error::WebPushError;
use crate::message::WebPushPayload;
use ring::rand::SecureRandom;
use ring::{aead::{self, BoundKey}, agreement, hkdf, rand};
use crate::vapid::VapidSignature;
pub enum ContentEncoding {
AesGcm,
Aes128Gcm,
}
pub struct HttpEce<'a> {
peer_... |
/// The aesgcm encrypted content-encoding, draft 3.
pub fn aes_gcm(
&self,
shared_secret: &'a [u8],
as_public_key: &'a [u8],
salt_bytes: &'a [u8],
payload: &'a mut Vec<u8>,
) -> Result<(), WebPushError> {
let mut context = Vec::with_capacity(140);
c... | {
let mut crypto_headers = Vec::new();
let mut crypto_key = format!("dh={}", base64::encode_config(public_key, URL_SAFE_NO_PAD));
if let Some(ref signature) = self.vapid_signature {
crypto_key = format!("{}; p256ecdsa={}", crypto_key, signature.auth_k);
let sig_s: Stri... | identifier_body |
http_ece.rs | use base64::{self, URL_SAFE_NO_PAD};
use crate::error::WebPushError;
use crate::message::WebPushPayload;
use ring::rand::SecureRandom;
use ring::{aead::{self, BoundKey}, agreement, hkdf, rand};
use crate::vapid::VapidSignature;
pub enum ContentEncoding {
AesGcm,
Aes128Gcm,
}
pub struct HttpEce<'a> {
peer_... |
let private_key =
agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &self.rng)?;
let public_key = private_key.compute_public_key()?;
let mut salt_bytes = [0u8; 16];
self.rng.fill(&mut salt_bytes)?;
let peer_public_key = agreement::UnparsedPublicKey::n... | {
return Err(WebPushError::PayloadTooLarge);
} | conditional_block |
read_pool.rs | // Copyright 2020 EinsteinDB Project Authors. Licensed under Apache-2.0.
use futures::channel::oneshot;
use futures::future::TryFutureExt;
use prometheus::IntGauge;
use std::future::Future;
use std::sync::{Arc, Mutex};
use thiserror::Error;
use yatp::pool::Remote;
use yatp::queue::Extras;
use yatp::task::future::Task... |
ReadPoolHandle::Yatp {
remote,
running_tasks,
max_tasks,
..
} => {
let running_tasks = running_tasks.clone();
// Note that the running task number limit is not strict.
// If several ta... | {
let pool = match priority {
CommandPri::High => read_pool_high,
CommandPri::Normal => read_pool_normal,
CommandPri::Low => read_pool_low,
};
pool.spawn(f)?;
} | conditional_block |
read_pool.rs | // Copyright 2020 EinsteinDB Project Authors. Licensed under Apache-2.0.
use futures::channel::oneshot;
use futures::future::TryFutureExt;
use prometheus::IntGauge;
use std::future::Future;
use std::sync::{Arc, Mutex};
use thiserror::Error;
use yatp::pool::Remote;
use yatp::queue::Extras;
use yatp::task::future::Task... | remote: pool.remote().clone(),
running_tasks: running_tasks.clone(),
max_tasks: *max_tasks,
pool_size: *pool_size,
},
}
}
}
#[derive(Clone)]
pub enum ReadPoolHandle {
FuturePools {
read_pool_high: FuturePool,
re... | pool,
running_tasks,
max_tasks,
pool_size,
} => ReadPoolHandle::Yatp { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.