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 |
|---|---|---|---|---|
encode.rs | use super::constants::{CR, DEFAULT_LINE_SIZE, DOT, ESCAPE, LF, NUL};
use super::errors::EncodeError;
use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::Path;
/// Options for encoding.
/// The entry point for encoding a file (part)
/// to a file or (TCP) stream.
#[deriv... |
#[test]
fn encode_options_invalid_end() {
let encode_options = EncodeOptions::new().parts(2).part(1).begin(1);
let vr = encode_options.check_options();
assert!(vr.is_err());
}
#[test]
fn encode_options_invalid_range() {
let encode_options = EncodeOptions::new().par... | {
let encode_options = EncodeOptions::new().parts(2).part(1).end(38400);
let vr = encode_options.check_options();
assert!(vr.is_err());
} | identifier_body |
encode.rs | use super::constants::{CR, DEFAULT_LINE_SIZE, DOT, ESCAPE, LF, NUL};
use super::errors::EncodeError;
use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::Path;
/// Options for encoding.
/// The entry point for encoding a file (part)
/// to a file or (TCP) stream.
#[deriv... |
_ => 1,
};
if col >= line_length {
v.push(CR);
v.push(LF);
col = 0;
}
});
writer.write_all(&v)?;
Ok(col)
}
#[inline(always)]
fn encode_byte(input_byte: u8) -> (u8, u8) {
let mut output = (0, 0);
let output_byte = input_byte.o... | {
v.push(DOT);
2
} | conditional_block |
encode.rs | use super::constants::{CR, DEFAULT_LINE_SIZE, DOT, ESCAPE, LF, NUL};
use super::errors::EncodeError;
use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::Path;
/// Options for encoding.
/// The entry point for encoding a file (part)
/// to a file or (TCP) stream.
#[deriv... | <R, W>(
&self,
input: R,
output: W,
length: u64,
input_filename: &str,
) -> Result<(), EncodeError>
where
R: Read + Seek,
W: Write,
{
let mut rdr = BufReader::new(input);
let mut checksum = crc32fast::Hasher::new();
let mut buff... | encode_stream | identifier_name |
minwinbase.rs | /
/
Licensed
under
the
Apache
License
Version
2
.
0
/
/
<
LICENSE
-
APACHE
or
http
:
/
/
www
.
apache
.
org
/
licenses
/
LICENSE
-
2
.
0
>
or
the
MIT
license
/
/
<
LICENSE
-
MIT
or
http
:
/
/
opensource
.
org
/
licenses
/
MIT
>
at
your
option
.
/
/
All
files
in
the
project
carrying
such
notice
may
not
be
copied
modifie... | REASON_CONTEXT_Reason
{
[
u32
;
4
]
[
u64
;
3
]
Detailed
Detailed_mut
:
REASON_CONTEXT_Detailed
SimpleReasonString
SimpleReasonString_mut
:
LPWSTR
}
}
STRUCT
!
{
struct
REASON_CONTEXT
{
Version
:
ULONG
Flags
:
DWORD
Reason
:
REASON_CONTEXT_Reason
}
}
pub
type
PREASON_CONTEXT
=
*
mut
REASON_CONTEXT
;
pub
const
EXCEPTION... | UNION
!
{
union | random_line_split |
lib.rs | //! A Proxy Connector crate for Hyper based applications
//!
//! # Example
//! ```rust,no_run
//! extern crate hyper;
//! extern crate hyper_proxy;
//! extern crate futures;
//! extern crate tokio_core;
//!
//! use hyper::{Chunk, Client, Request, Method, Uri};
//! use hyper::client::HttpConnector;
//! use hyper::header... | (&self, uri: &Uri) -> Option<&Proxy> {
self.proxies.iter().find(|p| p.intercept.matches(uri))
}
}
impl<C> Service for ProxyConnector<C>
where
C: Service<Request = Uri, Error = io::Error> +'static,
C::Future:'static,
<C::Future as Future>::Item: AsyncRead + AsyncWrite +'static,
{
type Reques... | match_proxy | identifier_name |
lib.rs | //! A Proxy Connector crate for Hyper based applications
//!
//! # Example
//! ```rust,no_run
//! extern crate hyper;
//! extern crate hyper_proxy;
//! extern crate futures;
//! extern crate tokio_core;
//!
//! use hyper::{Chunk, Client, Request, Method, Uri};
//! use hyper::client::HttpConnector;
//! use hyper::header... |
}
impl<F: Fn(&Uri) -> bool + Send + Sync +'static> From<F> for Intercept {
fn from(f: F) -> Intercept {
Intercept::Custom(f.into())
}
}
/// A Proxy strcut
#[derive(Clone, Debug)]
pub struct Proxy {
intercept: Intercept,
headers: Headers,
uri: Uri,
}
impl Proxy {
/// Create a new `Pro... | {
match (self, uri.scheme()) {
(&Intercept::All, _)
| (&Intercept::Http, Some("http"))
| (&Intercept::Https, Some("https")) => true,
(&Intercept::Custom(Custom(ref f)), _) => f(uri),
_ => false,
}
} | identifier_body |
lib.rs | //! A Proxy Connector crate for Hyper based applications
//!
//! # Example
//! ```rust,no_run
//! extern crate hyper;
//! extern crate hyper_proxy;
//! extern crate futures;
//! extern crate tokio_core;
//!
//! use hyper::{Chunk, Client, Request, Method, Uri};
//! use hyper::client::HttpConnector;
//! use hyper::header... | pub struct Proxy {
intercept: Intercept,
headers: Headers,
uri: Uri,
}
impl Proxy {
/// Create a new `Proxy`
pub fn new<I: Into<Intercept>>(intercept: I, uri: Uri) -> Proxy {
Proxy {
intercept: intercept.into(),
uri: uri,
headers: Headers::new(),
... | #[derive(Clone, Debug)] | random_line_split |
mod.rs | //! Metrics
//! ---
//! Contains a set of optimization metrics
//!
//! These are useful for different scorers
extern crate es_data;
extern crate float_ord;
extern crate hashbrown;
use self::es_data::dataset::types::{MetaType, Metadata};
use self::hashbrown::HashMap;
use self::float_ord::FloatOrd;
/// Computes DCG@K ... |
#[inline]
/// Gets relevance for ERR
fn get_relevance(score: f32, score_max: f32) -> f32 {
(2f32.powf(score) - 1.) / 2f32.powf(score_max)
}
/// Computes ERR. Assumes scores are sorted
pub fn get_err(scores: &[f32], k_opt: Option<usize>) -> f32 {
let k = k_opt.unwrap_or(scores.len()).min(scores.len());
le... | {
let size = k.unwrap_or(scores.len()).min(scores.len());
let r_dcg = dcg(scores, size);
// Sort them in ascending order
scores.sort_by_key(|v| FloatOrd(-*v));
let idcg = dcg(scores, size);
if idcg > 0.0 {
r_dcg / idcg
} else {
0.0
}
} | identifier_body |
mod.rs | //! Metrics
//! ---
//! Contains a set of optimization metrics
//!
//! These are useful for different scorers
extern crate es_data;
extern crate float_ord;
extern crate hashbrown;
use self::es_data::dataset::types::{MetaType, Metadata};
use self::hashbrown::HashMap;
use self::float_ord::FloatOrd;
/// Computes DCG@K ... | () {
let mut values = vec![1000.0, 20.0, 100.0];
let quantiles = vec![50];
assert_eq!(get_percentiles(&mut values, &quantiles, None), 100.0);
}
}
| test_get_percentiles | identifier_name |
mod.rs | //! Metrics
//! ---
//! Contains a set of optimization metrics
//!
//! These are useful for different scorers
extern crate es_data;
extern crate float_ord;
extern crate hashbrown;
use self::es_data::dataset::types::{MetaType, Metadata};
use self::hashbrown::HashMap;
use self::float_ord::FloatOrd;
/// Computes DCG@K ... | left * (1. - delta) + right * delta
}
}
/// Compute a set of percentiles and average them
pub fn get_percentiles(
vals: &mut [f32],
percentiles: &[usize],
interpolate_arg_opt: Option<f32>,
) -> f32 {
// Can happen at test time
if vals.is_empty() {
std::f32::NAN
} else {
... | let right = vals[pos.ceil() as usize];
let delta = pos.fract(); | random_line_split |
mod.rs | //! Metrics
//! ---
//! Contains a set of optimization metrics
//!
//! These are useful for different scorers
extern crate es_data;
extern crate float_ord;
extern crate hashbrown;
use self::es_data::dataset::types::{MetaType, Metadata};
use self::hashbrown::HashMap;
use self::float_ord::FloatOrd;
/// Computes DCG@K ... |
for topic in subtopics.iter() {
let counter = weights.entry(*topic).or_insert(0.);
*counter += 1.;
}
for (_, val) in weights.iter_mut() {
*val /= num_examples as f32;
}
weights
}
/// Gets the subtopics. Run this once
/// # Arguments
///
/// * data: Data to get subtopics f... | {
return weights;
} | conditional_block |
utils.rs | use crate::{
acc::{AccPublicKey, AccSecretKey},
chain::{block::Height, object::Object, query::query_param::QueryParam, traits::Num},
};
use anyhow::{ensure, Context, Error, Result};
use howlong::ProcessDuration;
use memmap2::Mmap;
use rand::{CryptoRng, RngCore};
use serde::{Deserialize, Serialize};
use snap::{r... | (path: &Path) -> PathBuf {
path.join("pk")
}
}
pub fn init_tracing_subscriber(directives: &str) -> Result<()> {
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(directives));
tracing_subscriber::fmt()
.with_env_filter(filter)
.try_init()
.map_err... | pk_path | identifier_name |
utils.rs | use crate::{
acc::{AccPublicKey, AccSecretKey},
chain::{block::Height, object::Object, query::query_param::QueryParam, traits::Num},
};
use anyhow::{ensure, Context, Error, Result};
use howlong::ProcessDuration;
use memmap2::Mmap;
use rand::{CryptoRng, RngCore};
use serde::{Deserialize, Serialize};
use snap::{r... | }
}
};
}
pub fn load_query_param_from_file(path: &Path) -> Result<Vec<QueryParam<u32>>> {
let data = fs::read_to_string(path)?;
let query_params: Vec<QueryParam<u32>> = serde_json::from_str(&data)?;
Ok(query_params)
}
// input format: block_id sep [ v_data ] sep { w_data }
// sep =... | static ID_CNT: AtomicU16 = AtomicU16::new(0);
Self(ID_CNT.fetch_add(1, Ordering::SeqCst)) | random_line_split |
utils.rs | use crate::{
acc::{AccPublicKey, AccSecretKey},
chain::{block::Height, object::Object, query::query_param::QueryParam, traits::Num},
};
use anyhow::{ensure, Context, Error, Result};
use howlong::ProcessDuration;
use memmap2::Mmap;
use rand::{CryptoRng, RngCore};
use serde::{Deserialize, Serialize};
use snap::{r... |
fn sk_path(path: &Path) -> PathBuf {
path.join("sk")
}
fn pk_path(path: &Path) -> PathBuf {
path.join("pk")
}
}
pub fn init_tracing_subscriber(directives: &str) -> Result<()> {
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(directives));
trac... | {
let path = path.as_ref();
let sk_file = File::open(Self::sk_path(path))?;
let sk_reader = BufReader::new(sk_file);
let sk: AccSecretKey = bincode::deserialize_from(sk_reader)?;
let pk_file = File::open(Self::pk_path(path))?;
let pk_data = unsafe { Mmap::map(&pk_file) }?... | identifier_body |
utils.rs | use crate::{
acc::{AccPublicKey, AccSecretKey},
chain::{block::Height, object::Object, query::query_param::QueryParam, traits::Num},
};
use anyhow::{ensure, Context, Error, Result};
use howlong::ProcessDuration;
use memmap2::Mmap;
use rand::{CryptoRng, RngCore};
use serde::{Deserialize, Serialize};
use snap::{r... |
let mut split_str = line.splitn(3, |c| c == '[' || c == ']');
let blk_height: Height = Height(
split_str
.next()
.with_context(|| format!("failed to parse line {}", line))?
.trim()
.parse()?,
);
let v_data: Vec<K> =... | {
continue;
} | conditional_block |
huffman.rs | use std::{cmp, io, usize};
use bitstream::BitRead;
use error::{Error, Result};
use util::{self, Bits};
#[derive(Debug)]
pub struct HuffmanDecoder {
lookup_table: LookupTable,
long_codes: Box<[LongCode]>,
max_code_len: usize,
}
impl HuffmanDecoder {
pub fn builder(lookup_table_bits: usize) -> HuffmanD... | };
if is_long_code {
let lc = LongCode {
sort_key: code_straight,
code: code.code,
value: value.value,
len: len,
};
self.long_codes.push(lc);
}
Ok(())
}
pub fn build(mut self) ... | {
let code_straight = try!(self.next_code(len));
let code = code_straight.reverse_bits() >> (32 - len);
let code = Code { code: code, len: len };
let value = CodeValue {
value: value,
len: len,
};
let is_long_code = if !self.lookup_table.is_empty(... | identifier_body |
huffman.rs | use std::{cmp, io, usize};
use bitstream::BitRead;
use error::{Error, Result};
use util::{self, Bits};
#[derive(Debug)]
pub struct HuffmanDecoder {
lookup_table: LookupTable,
long_codes: Box<[LongCode]>,
max_code_len: usize,
}
impl HuffmanDecoder {
pub fn builder(lookup_table_bits: usize) -> HuffmanD... | } | random_line_split | |
huffman.rs | use std::{cmp, io, usize};
use bitstream::BitRead;
use error::{Error, Result};
use util::{self, Bits};
#[derive(Debug)]
pub struct HuffmanDecoder {
lookup_table: LookupTable,
long_codes: Box<[LongCode]>,
max_code_len: usize,
}
impl HuffmanDecoder {
pub fn builder(lookup_table_bits: usize) -> HuffmanD... | {
lookup_table: LookupTable,
long_codes: Vec<LongCode>,
/// Current lowest codes for each code length (length 1 is at index 0).
cur_codes: [Option<u32>; 31],
max_code_len: usize,
}
impl HuffmanDecoderBuilder {
pub fn create_code(&mut self, value: u32, len: usize) -> Result<()> {
let co... | HuffmanDecoderBuilder | identifier_name |
huffman.rs | use std::{cmp, io, usize};
use bitstream::BitRead;
use error::{Error, Result};
use util::{self, Bits};
#[derive(Debug)]
pub struct HuffmanDecoder {
lookup_table: LookupTable,
long_codes: Box<[LongCode]>,
max_code_len: usize,
}
impl HuffmanDecoder {
pub fn builder(lookup_table_bits: usize) -> HuffmanD... |
Ok(code.value)
}
fn find_long_code(&self, bits: u32, len: usize) -> Result<CodeValue> {
// TODO: Use binary search here.
self.long_codes.iter()
.filter(|lc| lc.len <= len &&
lc.code.ls_bits(lc.len) == bits.ls_bits(lc.len))
.next()
.m... | {
return Err(Error::Io(io::Error::new(io::ErrorKind::UnexpectedEof,
"Incomplete Huffman code")));
} | conditional_block |
mod.rs | //! This mod implements `kubernetes_logs` source.
//! The scope of this source is to consume the log files that `kubelet` keeps
//! at `/var/log/pods` at the host of the k8s node when `vector` itself is
//! running inside the cluster as a `DaemonSet`.
#![deny(missing_docs)]
use crate::event::{self, Event};
use crate:... |
/// This function returns the default value for `self_node_name` variable
/// as it should be at the generated config file.
fn default_self_node_name_env_template() -> String {
format!("${{{}}}", SELF_NODE_NAME_ENV_KEY)
}
| {
let mut event = Event::from(line);
// Add source type.
event
.as_mut_log()
.insert(event::log_schema().source_type_key(), COMPONENT_NAME);
// Add file.
event.as_mut_log().insert(FILE_KEY, file);
event
} | identifier_body |
mod.rs | //! This mod implements `kubernetes_logs` source.
//! The scope of this source is to consume the log files that `kubelet` keeps
//! at `/var/log/pods` at the host of the k8s node when `vector` itself is
//! running inside the cluster as a `DaemonSet`.
#![deny(missing_docs)]
use crate::event::{self, Event};
use crate:... | <O>(self, out: O, global_shutdown: ShutdownSignal) -> crate::Result<()>
where
O: Sink<Event> + Send +'static,
<O as Sink<Event>>::Error: std::error::Error,
{
let Self {
client,
self_node_name,
data_dir,
auto_partial_merge,
field... | run | identifier_name |
mod.rs | //! This mod implements `kubernetes_logs` source.
//! The scope of this source is to consume the log files that `kubelet` keeps
//! at `/var/log/pods` at the host of the k8s node when `vector` itself is
//! running inside the cluster as a `DaemonSet`.
#![deny(missing_docs)]
use crate::event::{self, Event};
use crate:... | emit!(KubernetesLogsEventAnnotationFailed { event: &event });
}
event
});
let events = events
.filter_map(move |event| futures::future::ready(parser.transform(event)))
.filter_map(move |event| {
futures::future::ready(partial_... | if annotator.annotate(&mut event, &file).is_none() { | random_line_split |
trace_context.rs | // Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not... | (&self) -> Option<i32> {
self.active_span().map(|span| span.span_id)
}
fn push_active_span(&mut self, span: &SpanObject) -> SpanUid {
let uid = self.generate_span_uid();
self.primary_endpoint_name = span.operation_name.clone();
let mut stack = self.active_span_stack_mut();
... | peek_active_span_id | identifier_name |
trace_context.rs | // Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not... |
}
impl Drop for TracingContext {
/// Convert to segment object, and send to tracer for reporting.
///
/// # Panics
///
/// Panic if tracer is dropped.
fn drop(&mut self) {
self.upgrade_tracer().finalize_context(self)
}
}
/// Cross threads context snapshot.
#[derive(Debug)]
pub str... | {
self.tracer.upgrade().expect("Tracer has dropped")
} | identifier_body |
trace_context.rs | // Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not... | &self.service_instance
}
fn next_span_id(&self) -> i32 {
self.next_span_id
}
#[inline]
fn inc_next_span_id(&mut self) -> i32 {
let span_id = self.next_span_id;
self.next_span_id += 1;
span_id
}
/// The span uid is to identify the [Span] for crate.
... | }
/// Get service instance.
#[inline]
pub fn service_instance(&self) -> &str { | random_line_split |
trace_context.rs | // Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not... |
}
/// Wait all async span dropped which, created by [Span::prepare_for_async].
pub fn wait(self) {
self.wg.clone().wait();
}
/// It converts tracing context into segment object.
/// This conversion should be done before sending segments into OAP.
///
/// Notice: The spans will... | {
self.trace_id = snapshot.trace_id.clone();
let tracer = self.upgrade_tracer();
let segment_ref = SegmentReference {
ref_type: RefType::CrossThread as i32,
trace_id: snapshot.trace_id,
parent_trace_segment_id: snapshot.trace_segment_... | conditional_block |
obj.rs | use std::error::Error;
use std::f32::consts::PI;
use std::ffi::OsStr;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use gleam::gl;
use gleam::gl::types::{GLint, GLsizei};
use image::GenericImageView;
use super::Context;
use error::io_error;
use matr... |
other => {
eprintln!("Unhandled line type: {}", other);
}
}
}
// Push the last group
groups.push(cur_group);
// Average out the center
let center = center * (1.0 / (num_vertices as f32));
println!("Center fo... | {
let face_indices = tokens.map(FaceIndex::from_str).flatten().collect();
cur_group.faces.push(face(face_indices));
} | conditional_block |
obj.rs | use std::error::Error;
use std::f32::consts::PI;
use std::ffi::OsStr;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use gleam::gl;
use gleam::gl::types::{GLint, GLsizei};
use image::GenericImageView;
use super::Context;
use error::io_error;
use matr... | (name: &str) -> Self {
Group {
name: name.into(),
faces: Vec::new(),
}
}
}
struct Material {
/// Ka
ambient_color: Color,
/// Kd
diffuse_color: Color,
/// Ks
specular_color: Color,
/// Ns
specular_exponent: f32,
/// Ni
optical_density:... | new | identifier_name |
obj.rs | use std::error::Error;
use std::f32::consts::PI;
use std::ffi::OsStr;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use gleam::gl;
use gleam::gl::types::{GLint, GLsizei};
use image::GenericImageView;
use super::Context;
use error::io_error;
use matr... | name: name.into(),
faces: Vec::new(),
}
}
}
struct Material {
/// Ka
ambient_color: Color,
/// Kd
diffuse_color: Color,
/// Ks
specular_color: Color,
/// Ns
specular_exponent: f32,
/// Ni
optical_density: f32,
/// d or Tr
transparency:... | random_line_split | |
limit.rs | //! Data structures to help perform rate limiting.
use std::collections::{HashMap, VecDeque};
use std::cmp;
use std::fmt::Debug;
use std::io::{self, Read, Write, ErrorKind};
use std::result::Result;
use bytes::{BytesMut, Buf, BufMut};
use crate::util::RorW;
use self::Status::*;
/// Generic buffer for rate-limiting,... |
fn flush(&mut self) -> io::Result<()> {
match self.wstatus {
SErr =>
// if there was an error, wbuf might not have been consumed, so output error even if wbuf is non-empty
Err(unwrap_err_or(self.inner.write(&mut []), io::Error::new(ErrorKind::Other, "Ok after Err"))),
_ => match self... | {
match self.wstatus {
SOpen => {
// TODO: figure out when it's appropriate to automatically grow the buffer capacity
let remain = self.wbuf.get_demand_remaining();
match remain {
0 => Err(io::Error::new(ErrorKind::WouldBlock, "")),
_ => {
let n = cmp::m... | identifier_body |
limit.rs | //! Data structures to help perform rate limiting.
use std::collections::{HashMap, VecDeque};
use std::cmp;
use std::fmt::Debug;
use std::io::{self, Read, Write, ErrorKind};
use std::result::Result;
use bytes::{BytesMut, Buf, BufMut};
use crate::util::RorW;
use self::Status::*;
/// Generic buffer for rate-limiting,... | pub(crate) inner: T,
}
impl<T> RateLimited<T> {
/** Create a new `RateLimited` with the given initial capacity.
The inner stream must already be in non-blocking mode.
*/
pub fn new_lb(inner: T, init: usize) -> RateLimited<T> {
RateLimited {
inner: inner,
rstatus: SOpen,
rbuf: RLBuf::... | random_line_split | |
limit.rs | //! Data structures to help perform rate limiting.
use std::collections::{HashMap, VecDeque};
use std::cmp;
use std::fmt::Debug;
use std::io::{self, Read, Write, ErrorKind};
use std::result::Result;
use bytes::{BytesMut, Buf, BufMut};
use crate::util::RorW;
use self::Status::*;
/// Generic buffer for rate-limiting,... | (&mut self, buf: &mut [u8]) -> usize {
let to_drain = cmp::min(buf.len(), self.allowance);
self.buf.copy_to_slice(&mut buf[..to_drain]);
self.buf.reserve(to_drain);
self.take_allowance(to_drain);
to_drain
}
fn consume_write<F, E>(&mut self, sz: usize, mut write: F) -> (usize, Option<E>)
where... | consume_read | identifier_name |
de.rs | //! Deserialization support for the `application/x-www-form-urlencoded` format.
use serde::de;
use std::collections::{
HashMap,
};
use std::borrow::Cow;
#[doc(inline)]
pub use serde::de::value::Error;
use serde::de::value::MapDeserializer;
use std::io::Read;
// use url::form_urlencoded::Parse as UrlEncodedParse;... | forward_to_deserialize! {
bool
u8
u16
u32
u64
i8
i16
i32
i64
f32
f64
char
str
string
unit
option
bytes
byte_buf
unit_struct
// seq
seq_fixed_size
... | // visitor.visit_seq(self)
if let Level::Sequence(x) = self.0 {
SeqDeserializer::new(x.into_iter()).deserialize(visitor)
} else {
Err(de::Error::custom("value does not appear to be a sequence"))
}
}
| identifier_body |
de.rs | //! Deserialization support for the `application/x-www-form-urlencoded` format.
use serde::de;
use std::collections::{
HashMap,
};
use std::borrow::Cow;
#[doc(inline)]
pub use serde::de::value::Error;
use serde::de::value::MapDeserializer;
use std::io::Read;
// use url::form_urlencoded::Parse as UrlEncodedParse;... |
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor
{
// visitor.visit_seq(self)
if let Level::Sequence(x) = self.0 {
SeqDeserializer::new(x.into_iter()).deserialize(visitor)
} else {
Err(de::Error::custom("value ... | {
self.deserialize_map(visitor)
} | random_line_split |
de.rs | //! Deserialization support for the `application/x-www-form-urlencoded` format.
use serde::de;
use std::collections::{
HashMap,
};
use std::borrow::Cow;
#[doc(inline)]
pub use serde::de::value::Error;
use serde::de::value::MapDeserializer;
use std::io::Read;
// use url::form_urlencoded::Parse as UrlEncodedParse;... | >(self,
_name: &'static str,
_fields: &'static [&'static str],
visitor: V)
-> Result<V::Value, Self::Error>
where V: de::Visitor
{
visitor.visit_map(self)
}
fn deserialize_seq... | serialize_struct<V | identifier_name |
de.rs | //! Deserialization support for the `application/x-www-form-urlencoded` format.
use serde::de;
use std::collections::{
HashMap,
};
use std::borrow::Cow;
#[doc(inline)]
pub use serde::de::value::Error;
use serde::de::value::MapDeserializer;
use std::io::Read;
// use url::form_urlencoded::Parse as UrlEncodedParse;... | lse {
Err(de::Error::custom("value does not appear to be a map"))
}
}
// _serde::Deserializer::deserialize_struct(deserializer,"A", FIELDS, __Visitor)
fn deserialize_struct<V>(self,
_name: &'static str,
_fields: &'static [&'stati... | Deserializer::with_map(x).deserialize_map(visitor)
} e | conditional_block |
model.rs | use super::{
constants::*, empty_named_tuple, rewrite::Rewrite, sequent::RelSequent, symbol::Symbol, Error,
NamedTuple, Tuple,
};
use crate::chase::{r#impl::basic::BasicWitnessTerm, Model, Observation, E};
use codd::expression as rel_exp;
use itertools::Itertools;
use razor_fol::syntax::Sig;
use std::{collectio... |
if let Some(relation) = self.relations.get(symbol) {
if let Symbol::Equality = symbol {
let to_add = tuples.iter().map(|t| vec![t[1], t[0]]).collect_vec();
tuples.extend(to_add);
};
self.database.insert(relation, tuples).map_err(Error::from)
... | _ => {}
} | random_line_split |
model.rs | use super::{
constants::*, empty_named_tuple, rewrite::Rewrite, sequent::RelSequent, symbol::Symbol, Error,
NamedTuple, Tuple,
};
use crate::chase::{r#impl::basic::BasicWitnessTerm, Model, Observation, E};
use codd::expression as rel_exp;
use itertools::Itertools;
use razor_fol::syntax::Sig;
use std::{collectio... |
// assumes that the witness term is flat
pub(super) fn record(&mut self, witness: BasicWitnessTerm) -> E {
match witness {
BasicWitnessTerm::Elem(e) => e,
_ => self
.rewrites
.get(&witness)
.copied()
.unwrap_or_else(||... | {
let element = E(self.element_index);
self.element_index += 1;
self.rewrites.insert(witness, element);
element
} | identifier_body |
model.rs | use super::{
constants::*, empty_named_tuple, rewrite::Rewrite, sequent::RelSequent, symbol::Symbol, Error,
NamedTuple, Tuple,
};
use crate::chase::{r#impl::basic::BasicWitnessTerm, Model, Observation, E};
use codd::expression as rel_exp;
use itertools::Itertools;
use razor_fol::syntax::Sig;
use std::{collectio... | (&self, element: &E) -> Vec<BasicWitnessTerm> {
self.rewrites
.iter()
.filter(|(_, e)| *e == element)
.map(|(t, _)| t)
.cloned()
.collect()
}
fn element(&self, witness: &BasicWitnessTerm) -> Option<E> {
match witness {
BasicWitn... | witness | identifier_name |
mod.rs | mod graphviz;
pub mod locals;
mod source;
pub use source::initialise_statics;
use rustc_hir::definitions::DefPathData;
use rustc_mir::interpret::{AllocId, Machine, Pointer};
use rustc_target::abi::Size;
use horrorshow::{Raw, Template};
use rocket::response::content::Html;
use crate::step::Breakpoint;
use crate::Pri... | else {
String::new()
}
}
pub fn render_main_window(
pcx: &PrirodaContext<'_, '_>,
display_frame: Option<usize>,
message: String,
) -> Html<String> {
let is_active_stack_frame = match display_frame {
Some(n) => n == Machine::stack(&pcx.ecx).len() - 1,
None => true,
};
... | {
r#"<script>
setInterval(() => {
fetch("/step_count").then((res) => {
if(res.status == 200) {
return res.text();
} else {
throw "";
}
}).then((res) => {
... | conditional_block |
mod.rs | mod graphviz;
pub mod locals;
mod source;
pub use source::initialise_statics;
use rustc_hir::definitions::DefPathData;
use rustc_mir::interpret::{AllocId, Machine, Pointer};
use rustc_target::abi::Size;
use horrorshow::{Raw, Template};
use rocket::response::content::Html;
use crate::step::Breakpoint;
use crate::Pri... | div(id="stack") {
table(border="1") {
@ for (i, &(ref s, ref span, ref def_id)) in stack.iter().enumerate().rev() {
tr {
@ if i == display_frame.unwrap_or(stack.len() - 1) { td { : Raw("→") } } ... | }
div(id="right") {
div {
: format!("Step count: {}", pcx.step_count);
} | random_line_split |
mod.rs | mod graphviz;
pub mod locals;
mod source;
pub use source::initialise_statics;
use rustc_hir::definitions::DefPathData;
use rustc_mir::interpret::{AllocId, Machine, Pointer};
use rustc_target::abi::Size;
use horrorshow::{Raw, Template};
use rocket::response::content::Html;
use crate::step::Breakpoint;
use crate::Pri... | me: String) -> BadRequest<String> {
BadRequest(Some(format!(
"not a number: {:?}",
frame.parse::<usize>().unwrap_err()
)))
}
#[get("/ptr/<alloc_id>/<offset>")]
pub fn ptr(
sender: rocket::State<'_, crate::PrirodaSender>,
alloc_id: u64,
offset: ... | e_invalid(fra | identifier_name |
mod.rs | mod graphviz;
pub mod locals;
mod source;
pub use source::initialise_statics;
use rustc_hir::definitions::DefPathData;
use rustc_mir::interpret::{AllocId, Machine, Pointer};
use rustc_target::abi::Size;
use horrorshow::{Raw, Template};
use rocket::response::content::Html;
use crate::step::Breakpoint;
use crate::Pri... | Html(buf)
}
pub fn refresh_script(pcx: &PrirodaContext<'_, '_>) -> String {
if pcx.config.auto_refresh {
r#"<script>
setInterval(() => {
fetch("/step_count").then((res) => {
if(res.status == 200) {
return res.text();
... | {
let mut buf = String::new();
(horrorshow::html! {
html {
head {
title { : title }
meta(charset = "UTF-8") {}
script(src="/resources/svg-pan-zoom.js") {}
script(src="/resources/zoom_mir.js") {}
: Raw(refresh_scr... | identifier_body |
window_manager.rs | use crate::geometry::{Displacement, Point};
use crate::surface::{Surface, SurfaceExt};
use crate::{
event::{Event, EventOnce},
input::seat::SeatManager,
output_manager::OutputManager,
window::Window,
window_management_policy::WmPolicyManager,
};
use log::{trace, warn};
use std::cell::RefCell;
use std::collect... | // it no longer has focus and the client will repaint accordingly, e.g.
// stop displaying a caret.
let surface = Surface::from_wlr_surface(old_wlr_surface);
surface.set_activated(false);
}
wlr_seat_keyboard_clear_focus(self.seat_manager.raw_seat());
}
}
}
pub(crate) ... | .keyboard_state
.focused_surface;
if !old_wlr_surface.is_null() {
// Deactivate the previously focused window. This lets the client know | random_line_split |
window_manager.rs | use crate::geometry::{Displacement, Point};
use crate::surface::{Surface, SurfaceExt};
use crate::{
event::{Event, EventOnce},
input::seat::SeatManager,
output_manager::OutputManager,
window::Window,
window_management_policy::WmPolicyManager,
};
use log::{trace, warn};
use std::cell::RefCell;
use std::collect... | else {
self.layers.borrow_mut().update(layer, |windows| {
windows.push(window.clone());
})
}
window
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::input::{cursor::CursorManager, event_filter::EventFilterManager};
use crate::output_manager::OutputManager;
use crate::window:... | {
self.layers.borrow_mut().update(layer, |windows| {
windows.insert(0, window.clone());
})
} | conditional_block |
window_manager.rs | use crate::geometry::{Displacement, Point};
use crate::surface::{Surface, SurfaceExt};
use crate::{
event::{Event, EventOnce},
input::seat::SeatManager,
output_manager::OutputManager,
window::Window,
window_management_policy::WmPolicyManager,
};
use log::{trace, warn};
use std::cell::RefCell;
use std::collect... | (&self) -> impl '_ + Iterator<Item = Rc<Window>> {
self.windows().filter(|window| *window.mapped.borrow())
}
pub fn window_at(&self, point: &Point) -> Option<Rc<Window>> {
self
.layers
.borrow()
.all_windows()
// Reverse as windows is from back to front
.rev()
.find(|window| ... | windows_to_render | identifier_name |
lib.rs | //! This crate should eventually represent the structure at this repo:
//!
//! https://github.com/eth2-clients/eth2-testnets/tree/master/nimbus/testnet1
//!
//! It is not accurate at the moment, we include extra files and we also don't support a few
//! others. We are unable to conform to the repo until we have the fol... | else {
// Ensure we can parse the YAML config to a chain spec.
config
.yaml_config
.as_ref()
.unwrap()
.apply_to_chain_spec::<V012LegacyEthSpec>(&E::default_spec())
.unwrap();
}
... | {
// Ensure we can parse the YAML config to a chain spec.
config
.yaml_config
.as_ref()
.unwrap()
.apply_to_chain_spec::<MainnetEthSpec>(&E::default_spec())
.unwrap();
} | conditional_block |
lib.rs | //! This crate should eventually represent the structure at this repo:
//!
//! https://github.com/eth2-clients/eth2-testnets/tree/master/nimbus/testnet1
//!
//! It is not accurate at the moment, we include extra files and we also don't support a few
//! others. We are unable to conform to the repo until we have the fol... | .as_ref()
.ok_or_else(|| "Genesis state is unknown".to_string())?;
BeaconState::from_ssz_bytes(genesis_state_bytes)
.map_err(|e| format!("Genesis state SSZ bytes are invalid: {:?}", e))
}
/// Write the files to the directory.
///
/// Overwrites files if specifi... | /// Attempts to deserialize `self.beacon_state`, returning an error if it's missing or invalid.
pub fn beacon_state<E: EthSpec>(&self) -> Result<BeaconState<E>, String> {
let genesis_state_bytes = self
.genesis_state_bytes | random_line_split |
lib.rs | //! This crate should eventually represent the structure at this repo:
//!
//! https://github.com/eth2-clients/eth2-testnets/tree/master/nimbus/testnet1
//!
//! It is not accurate at the moment, we include extra files and we also don't support a few
//! others. We are unable to conform to the repo until we have the fol... | (&self, base_dir: PathBuf, overwrite: bool) -> Result<(), String> {
if base_dir.exists() &&!overwrite {
return Err("Testnet directory already exists".to_string());
}
self.force_write_to_file(base_dir)
}
/// Write the files to the directory, even if the directory already exi... | write_to_file | identifier_name |
lib.rs | //! This crate should eventually represent the structure at this repo:
//!
//! https://github.com/eth2-clients/eth2-testnets/tree/master/nimbus/testnet1
//!
//! It is not accurate at the moment, we include extra files and we also don't support a few
//! others. We are unable to conform to the repo until we have the fol... |
/// Attempts to deserialize `self.beacon_state`, returning an error if it's missing or invalid.
pub fn beacon_state<E: EthSpec>(&self) -> Result<BeaconState<E>, String> {
let genesis_state_bytes = self
.genesis_state_bytes
.as_ref()
.ok_or_else(|| "Genesis state is unk... | {
self.genesis_state_bytes.is_some()
} | identifier_body |
action.rs | use crate::core::ValueType;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::fmt;
use std::ops::{Neg, Sub};
type SignalType = u8;
const BOUND: SignalType = SignalType::MAX;
const BOUND_FLOAT: f64 = BOUND as f64;
/// Action is basic type of Indicator's signals
///
/// It may be positive \(means ... | (self) -> Option<i8> {
self.into()
}
/// Return an internal representation of the value if signal exists or None if it doesn't.
#[must_use]
pub const fn value(self) -> Option<SignalType> {
match self {
Self::None => None,
Self::Buy(v) | Self::Sell(v) => Some(v),
}
}
/// Checks if there is no signal
... | sign | identifier_name |
action.rs | use crate::core::ValueType;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::fmt;
use std::ops::{Neg, Sub};
type SignalType = u8;
const BOUND: SignalType = SignalType::MAX;
const BOUND_FLOAT: f64 = BOUND as f64;
/// Action is basic type of Indicator's signals
///
/// It may be positive \(means ... | Some(v) => v.into(),
}
}
}
impl From<Action> for Option<i8> {
fn from(value: Action) -> Self {
match value {
Action::None => None,
_ => Some(value.into()),
}
}
}
#[inline]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
fn from_normalized_f64_to_bounded(value: f64) -> Sig... | impl From<Option<i8>> for Action {
fn from(value: Option<i8>) -> Self {
match value {
None => Self::None, | random_line_split |
action.rs | use crate::core::ValueType;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::fmt;
use std::ops::{Neg, Sub};
type SignalType = u8;
const BOUND: SignalType = SignalType::MAX;
const BOUND_FLOAT: f64 = BOUND as f64;
/// Action is basic type of Indicator's signals
///
/// It may be positive \(means ... |
}
impl From<Action> for Option<i8> {
fn from(value: Action) -> Self {
match value {
Action::None => None,
_ => Some(value.into()),
}
}
}
#[inline]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
fn from_normalized_f64_to_bounded(value: f64) -> SignalType {
debug_assert!((0.0.... | {
match value {
None => Self::None,
Some(v) => v.into(),
}
} | identifier_body |
cli.rs | use std::process;
use std::str::FromStr;
use std::string::ToString;
use console::Term;
use structopt::StructOpt;
use crate::bat::assets::HighlightingAssets;
use crate::bat::output::PagingMode;
use crate::config;
use crate::style;
#[derive(StructOpt, Clone, Debug)]
#[structopt(
name = "delta",
about = "A synt... | {
Box,
Plain,
Underline,
}
// TODO: clean up enum parsing and error handling
#[derive(Debug)]
pub enum Error {
SectionStyleParseError,
}
impl FromStr for SectionStyle {
type Err = Error;
fn from_str(s: &str) -> Result<SectionStyle, Error> {
match s.to_lowercase().as_str() {
... | SectionStyle | identifier_name |
cli.rs | use std::process;
use std::str::FromStr;
use std::string::ToString;
use console::Term;
use structopt::StructOpt;
use crate::bat::assets::HighlightingAssets;
use crate::bat::output::PagingMode;
use crate::config;
use crate::style;
#[derive(StructOpt, Clone, Debug)]
#[structopt(
name = "delta",
about = "A synt... | /// be combined with --light and --dark to view the background colors for those modes. It can
/// also be used to experiment with different RGB hex codes by combining this option with
/// --minus-color, --minus-emph-color, --plus-color, --plus-emph-color.
#[structopt(long = "show-background-colors")]
... | /// Show the command-line arguments (RGB hex codes) for the background colors that are in
/// effect. The hex codes are displayed with their associated background color. This option can | random_line_split |
runtime.rs | //! An extension to start the tokio runtime at the appropriate time.
use std::fmt::Debug;
use std::sync::Arc;
use std::time::Duration;
use failure::Error;
use futures::future::{self, Future};
use log::{trace, warn};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use spirit::bodies::InnerBody;
u... | {
/// Use the threadpool runtime.
///
/// The threadpool runtime is the default (both in tokio and spirit).
///
/// This allows you to modify the builder prior to starting it, specifying custom options like
/// number of threads.
ThreadPool(Box<dyn FnMut(&mut runtime::Builder) + Send>),
... | Runtime | identifier_name |
runtime.rs | //! An extension to start the tokio runtime at the appropriate time.
use std::fmt::Debug;
use std::sync::Arc;
use std::time::Duration;
use failure::Error;
use futures::future::{self, Future};
use log::{trace, warn};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use spirit::bodies::InnerBody;
u... | runtime.block_on(fut)?;
runtime.run().map_err(Error::from)
}
Runtime::Custom(mut callback) => callback(Box::new(fut)),
Runtime::__NonExhaustive__ => unreachable!(),
}
}
}
impl<E> Extension<E> for Runtime
where
E: Extensible<Ok = E>,
... | {
let spirit = Arc::clone(spirit);
let fut = future::lazy(move || {
inner.run().map_err(move |e| {
spirit.terminate();
e
})
});
match self {
Runtime::ThreadPool(mut mod_builder) => {
let mut builder = run... | identifier_body |
runtime.rs | //! An extension to start the tokio runtime at the appropriate time.
use std::fmt::Debug;
use std::sync::Arc;
use std::time::Duration;
use failure::Error;
use futures::future::{self, Future};
use log::{trace, warn};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use spirit::bodies::InnerBody;
u... |
/// Maximum number of blocking worker threads.
///
/// These do tasks that take longer time. This includes file IO and CPU intensive tasks.
///
/// If not set, defaults to 100.
///
/// Often, the application doesn't start these threads as they might not always be needed.
#[serde(skip_se... | /// it may make sense to set it lower.
///
/// If not set, the application will start with number of CPUs available in the system.
#[serde(skip_serializing_if = "Option::is_none")]
pub async_threads: Option<usize>, | random_line_split |
init.rs |
use crate::{Error, Result, Logger, LogLevel, netlink, sys};
use crate::cmdline::CmdLine;
use crate::sys::{sethostname, setsid, set_controlling_tty, mount_devtmpfs, mount_tmpfs, mkdir, umount, mount_sysfs, mount_procfs, mount_devpts, chown, chmod, create_directories, mount_overlay, move_mount, pivot_root, mount_9p, mou... |
fn write_xauth(&self) -> io::Result<()> {
let xauth_path = format!("{}/.Xauthority", self.homedir());
let mut randbuf = [0; 16];
let mut file = fs::File::open("/dev/urandom")?;
file.read_exact(&mut randbuf)?;
let mut v: Vec<u8> = Vec::new();
//???
v.exten... | {
let mut octets = ip.octets();
octets[3] = 1;
let gw = Ipv4Addr::from(octets);
let nl = NetlinkSocket::open()?;
if !nl.interface_exists("eth0") {
}
nl.add_ip_address("eth0", ip, 24)?;
nl.set_interface_up("eth0")?;
nl.add_default_route(gw)?;
... | identifier_body |
init.rs |
use crate::{Error, Result, Logger, LogLevel, netlink, sys};
use crate::cmdline::CmdLine;
use crate::sys::{sethostname, setsid, set_controlling_tty, mount_devtmpfs, mount_tmpfs, mkdir, umount, mount_sysfs, mount_procfs, mount_devpts, chown, chmod, create_directories, mount_overlay, move_mount, pivot_root, mount_9p, mou... |
}
pub fn setup_filesystem(&self) -> Result<()> {
sys::set_umask(0o022);
//mount_devtmpfs()?;
mount_tmpfs("/tmp")?;
mkdir("/tmp/sysroot")?;
if self.rootfs.read_only() {
self.setup_readonly_root()?;
} else {
self.setup_writeable_root()?;
... | {
Logger::set_log_level(LogLevel::Info);
} | conditional_block |
init.rs | use crate::{Error, Result, Logger, LogLevel, netlink, sys};
use crate::cmdline::CmdLine;
use crate::sys::{sethostname, setsid, set_controlling_tty, mount_devtmpfs, mount_tmpfs, mkdir, umount, mount_sysfs, mount_procfs, mount_devpts, chown, chmod, create_directories, mount_overlay, move_mount, pivot_root, mount_9p, moun... |
chmod("/dev/wl0", 0o666)?;
let dbus = ServiceLaunch::new("dbus-daemon", "/usr/bin/dbus-daemon")
.base_environment()
.uidgid(1000,1000)
.env("HOME", self.homedir())
.env("NO_AT_BRIDGE", "1")
.env("QT_ACCESSIBILITY", "1")
.env("SHELL", "/... | } | random_line_split |
init.rs |
use crate::{Error, Result, Logger, LogLevel, netlink, sys};
use crate::cmdline::CmdLine;
use crate::sys::{sethostname, setsid, set_controlling_tty, mount_devtmpfs, mount_tmpfs, mkdir, umount, mount_sysfs, mount_procfs, mount_devpts, chown, chmod, create_directories, mount_overlay, move_mount, pivot_root, mount_9p, mou... | (&self) -> Result<()> {
sys::set_umask(0o022);
//mount_devtmpfs()?;
mount_tmpfs("/tmp")?;
mkdir("/tmp/sysroot")?;
if self.rootfs.read_only() {
self.setup_readonly_root()?;
} else {
self.setup_writeable_root()?;
}
fs::write("/etc/hos... | setup_filesystem | identifier_name |
olm_parser.rs | use crate::graph::graph::{Rules, Edges, Graph, Vertices};
use crate::io::{
limit_iter::Limit,
sub_matrix::SubMatrix,
tri_wave::TriWave,
utils::{DiagonalReflection, Reflection, Rotation},
};
use crate::utils::{index_to_coords, is_inside, coords_to_index};
use crate::wfc::collapse;
use bimap::BiMap;
use ... | (
image: RgbImage,
chunk_size: usize,
pixel_aliases: &PixelKeys,
rotate: bool,
reflect_vertical: bool,
reflect_horizontal: bool,
reflect_diagonal: bool,
) -> IndexMap<Chunk, u16> {
sub_images(image, chunk_size)
.map(|sub_image| alias_sub_image(sub_image, pixel_aliases))
.fo... | chunk_image | identifier_name |
olm_parser.rs | use crate::graph::graph::{Rules, Edges, Graph, Vertices};
use crate::io::{
limit_iter::Limit,
sub_matrix::SubMatrix,
tri_wave::TriWave,
utils::{DiagonalReflection, Reflection, Rotation},
};
use crate::utils::{index_to_coords, is_inside, coords_to_index};
use crate::wfc::collapse;
use bimap::BiMap;
use ... |
})
});
rules
})
}
// Create a raw graph for pruning
fn create_raw_graph(all_labels: &MSu16xNU, chunk_size: usize, (height, width): (usize, usize)) -> Graph {
// pixel based graph dimensions
let v_dim_x = (width * chunk_size) - (chunk_size - 1);
l... | {
let mut set = MSu16xNU::empty();
set.insert(other_label, 1);
rules
.entry((*direction, label))
.and_modify(|l| l.add_assign(set))
... | conditional_block |
olm_parser.rs | use crate::graph::graph::{Rules, Edges, Graph, Vertices};
use crate::io::{
limit_iter::Limit,
sub_matrix::SubMatrix,
tri_wave::TriWave,
utils::{DiagonalReflection, Reflection, Rotation},
};
use crate::utils::{index_to_coords, is_inside, coords_to_index};
use crate::wfc::collapse;
use bimap::BiMap;
use ... | })
}
// Create a raw graph for pruning
fn create_raw_graph(all_labels: &MSu16xNU, chunk_size: usize, (height, width): (usize, usize)) -> Graph {
// pixel based graph dimensions
let v_dim_x = (width * chunk_size) - (chunk_size - 1);
let v_dim_y = (height * chunk_size) - (chunk_size - 1);
let ver... | .or_insert(set);
}
})
});
rules | random_line_split |
olm_parser.rs | use crate::graph::graph::{Rules, Edges, Graph, Vertices};
use crate::io::{
limit_iter::Limit,
sub_matrix::SubMatrix,
tri_wave::TriWave,
utils::{DiagonalReflection, Reflection, Rotation},
};
use crate::utils::{index_to_coords, is_inside, coords_to_index};
use crate::wfc::collapse;
use bimap::BiMap;
use ... | .iter()
.for_each(|(chunk, frequency)| {
assert_eq!(chunk_map.get(chunk).unwrap(), frequency);
});
}
#[test]
fn test_subchunk_positions() {
let sub_chunks = vec![
((0, 0), (1, 1), 0),
((0, 0), (2, 1), 1),
((1, 0)... | {
let img = image::open("resources/test/chunk_image_test.png").unwrap().to_rgb8();
let mut pixel_aliases: PixelKeys = BiMap::new();
pixel_aliases.insert(0, Rgb::from([255, 255, 255]));
pixel_aliases.insert(1, Rgb::from([0, 0, 0]));
let chunk_map = chunk_image(img, 2, &pixel_alia... | identifier_body |
wasm.rs | use std::collections::HashMap;
use std::convert::TryFrom;
use crate::error::Error;
/// The allowable types for any real value in wasm (u8 and others are packed)
#[derive(Copy, Clone, PartialEq)]
pub enum PrimitiveType {
I32,
I64,
F32,
F64,
}
impl From<i32> for PrimitiveType {
fn from(_: i32) -> P... | (&self) -> usize {
self.params.len()
}
pub fn params_iter(&self) -> std::slice::Iter<PrimitiveType> {
self.params.iter()
}
}
pub enum Export {
Function(usize),
Table(usize),
Memory(usize),
Global(usize),
}
#[derive(Default)]
pub struct Module {
function_types: Vec<Func... | num_params | identifier_name |
wasm.rs | use std::collections::HashMap;
use std::convert::TryFrom;
use crate::error::Error;
/// The allowable types for any real value in wasm (u8 and others are packed)
#[derive(Copy, Clone, PartialEq)]
pub enum PrimitiveType {
I32,
I64,
F32,
F64,
}
impl From<i32> for PrimitiveType {
fn from(_: i32) -> P... | self.function_types.push(ft);
}
pub fn get_function_type(&self, i: usize) -> FunctionType {
self.function_types[i].clone()
}
pub fn add_function(&mut self, f: Function) {
self.functions.push(f);
}
pub fn add_memory(&mut self, m: Memory) {
self.memory = m;
}... |
pub fn add_function_type(&mut self, ft: FunctionType) { | random_line_split |
wasm.rs | use std::collections::HashMap;
use std::convert::TryFrom;
use crate::error::Error;
/// The allowable types for any real value in wasm (u8 and others are packed)
#[derive(Copy, Clone, PartialEq)]
pub enum PrimitiveType {
I32,
I64,
F32,
F64,
}
impl From<i32> for PrimitiveType {
fn from(_: i32) -> P... |
#[inline]
pub fn as_i64_unchecked(&self) -> i64 {
unsafe { self.v.i64 }
}
#[inline]
pub fn as_f32_unchecked(&self) -> f32 {
unsafe { self.v.f32 }
}
#[inline]
pub fn as_f64_unchecked(&self) -> f64 {
unsafe { self.v.f64 }
}
}
impl From<i32> for Value {
fn ... | {
unsafe { self.v.i32 }
} | identifier_body |
cargo_test.rs | use crate::core::compiler::{Compilation, CompileKind, Doctest, Metadata, Unit, UnitOutput};
use crate::core::shell::Verbosity;
use crate::core::{TargetKind, Workspace};
use crate::ops;
use crate::util::errors::CargoResult;
use crate::util::{add_path_args, CargoTestError, Config, Test};
use cargo_util::{ProcessBuilder, ... | else { doctest };
errors.extend(docerrors);
if errors.is_empty() {
Ok(None)
} else {
Ok(Some(CargoTestError::new(test, errors)))
}
}
pub fn run_benches(
ws: &Workspace<'_>,
options: &TestOptions,
args: &[&str],
) -> CargoResult<Option<CargoTestError>> {
let compilation ... | { test } | conditional_block |
cargo_test.rs | use crate::core::compiler::{Compilation, CompileKind, Doctest, Metadata, Unit, UnitOutput};
use crate::core::shell::Verbosity;
use crate::core::{TargetKind, Workspace};
use crate::ops;
use crate::util::errors::CargoResult;
use crate::util::{add_path_args, CargoTestError, Config, Test};
use cargo_util::{ProcessBuilder, ... | _ => Ok(Some(CargoTestError::new(test, errors))),
}
}
fn compile_tests<'a>(ws: &Workspace<'a>, options: &TestOptions) -> CargoResult<Compilation<'a>> {
let mut compilation = ops::compile(ws, &options.compile_opts)?;
compilation.tests.sort();
Ok(compilation)
}
/// Runs the unit and integration ... | 0 => Ok(None), | random_line_split |
cargo_test.rs | use crate::core::compiler::{Compilation, CompileKind, Doctest, Metadata, Unit, UnitOutput};
use crate::core::shell::Verbosity;
use crate::core::{TargetKind, Workspace};
use crate::ops;
use crate::util::errors::CargoResult;
use crate::util::{add_path_args, CargoTestError, Config, Test};
use cargo_util::{ProcessBuilder, ... | (
ws: &Workspace<'_>,
options: &TestOptions,
test_args: &[&str],
compilation: &Compilation<'_>,
) -> CargoResult<(Test, Vec<ProcessError>)> {
let config = ws.config();
let mut errors = Vec::new();
let doctest_xcompile = config.cli_unstable().doctest_xcompile;
let doctest_in_workspace = c... | run_doc_tests | identifier_name |
lib.rs | 32),
// width and height of character in texture units
tex_size: (f32, f32),
// size of the character in EMs
size: (f32, f32),
// number of EMs between the bottom of the character and the base line of text
height_over_line: f32,
// number of EMs at the left of the character
left_padd... | texture: texture,
character_infos: chr_infos,
em_pixels: em_pixels,
})
}
/// Return the size of an em-unit for the generated font texture.
/// This is needed for a pixel-perfect display: the text geometry is scaled so that
/// 1em == 1 unit. We must scale the... |
Ok(FontTexture { | random_line_split |
lib.rs | ),
// width and height of character in texture units
tex_size: (f32, f32),
// size of the character in EMs
size: (f32, f32),
// number of EMs between the bottom of the character and the base line of text
height_over_line: f32,
// number of EMs at the left of the character
left_paddin... |
/// Return the x-positions (in em-units) of the breaks between characters.
/// When a character starts at n-th byte, then get_char_pos_x()[n] is the x-pos of the character.
/// The last value of the array is the x-pos of the end of the string
pub fn get_char_pos_x(&self) -> &[f32] {
&self.char... | {
let mut text_display = TextDisplay {
context: system.context.clone(),
texture: texture,
vertex_buffer: None,
index_buffer: None,
char_pos_x: vec![],
is_empty: true,
};
text_display.set_text(text);
text_display
... | identifier_body |
lib.rs | ),
// width and height of character in texture units
tex_size: (f32, f32),
// size of the character in EMs
size: (f32, f32),
// number of EMs between the bottom of the character and the base line of text
height_over_line: f32,
// number of EMs at the left of the character
left_paddin... | <F, S:?Sized, M>(text: &TextDisplay<F>, system: &TextSystem, target: &mut S,
matrix: M, color: (f32, f32, f32, f32))
where S: glium::Surface, M: Into<[[f32; 4]; 4]>,
F: Deref<Target=FontTexture>
{
let matrix = matrix.into()... | draw | identifier_name |
lib.rs | ),
// width and height of character in texture units
tex_size: (f32, f32),
// size of the character in EMs
size: (f32, f32),
// number of EMs between the bottom of the character and the base line of text
height_over_line: f32,
// number of EMs at the left of the character
left_paddin... |
}
}
///
/// ## About the matrix
///
/// The matrix must be column-major post-muliplying (which is the usual way to do in OpenGL).
///
/// One unit in height corresponds to a line of text, but the text can go above or under.
/// The bottom of the line is at `0.0`, the top is at `1.0`.
/// You need to adapt your ma... | {
// building the vertex buffer
self.vertex_buffer = Some(glium::VertexBuffer::new(&self.context,
&vertex_buffer_data).unwrap());
// building the index buffer
self.index_buffer = Some(glium::IndexBuffer::new(... | conditional_block |
lib.rs | //! # MCAI Worker SDK
//!
//! This library is an SDK to communicate via message broker with [StepFlow](https://hexdocs.pm/step_flow/readme.html).
//! It's used for every worker as an abstraction.
//! It manage itself requirements, message parsing, direct messaging.
//!
//! ## Worker implementation
//!
//! 1. Create a R... |
Err(message) => {
error!("{:?}", message);
}
}
}
return;
}
loop {
let amqp_uri = get_amqp_uri();
let mut executor = LocalPool::new();
let spawner = executor.spawner();
executor.run_until(async {
let conn = Connection::connect_uri(
amqp_uri,
... | {
job_result.update_execution_duration();
info!(target: &job_result.get_job_id().to_string(), "Process succeeded: {:?}", job_result)
} | conditional_block |
lib.rs | //! # MCAI Worker SDK
//!
//! This library is an SDK to communicate via message broker with [StepFlow](https://hexdocs.pm/step_flow/readme.html).
//! It's used for every worker as an abstraction.
//! It manage itself requirements, message parsing, direct messaging.
//!
//! ## Worker implementation
//!
//! 1. Create a R... | //! // }
//! ```
//!
//! ## Runtime configuration
//!
//! ### AMQP connection
//!
//! | Variable | Description |
//! |-----------------|-------------|
//! | `AMQP_HOSTNAME` | IP or host of AMQP server (default: `localhost`) |
//! | `AMQP_PORT` | AMQP server port (default: `5672`) |
//! | `AMQP_TLS` | en... | //! // mcai_worker_sdk::start_worker(&WORKER_NAME_EVENT); | random_line_split |
lib.rs | //! # MCAI Worker SDK
//!
//! This library is an SDK to communicate via message broker with [StepFlow](https://hexdocs.pm/step_flow/readme.html).
//! It's used for every worker as an abstraction.
//! It manage itself requirements, message parsing, direct messaging.
//!
//! ## Worker implementation
//!
//! 1. Create a R... | (
&mut self,
_job_result: JobResult,
_stream_index: usize,
_frame: ProcessFrame,
) -> Result<ProcessResult> {
Err(MessageError::NotImplemented())
}
#[cfg(feature = "media")]
fn ending_process(&mut self) -> Result<()> {
Ok(())
}
/// Not called when the "media" feature is enabled
f... | process_frame | identifier_name |
lib.rs | //! # MCAI Worker SDK
//!
//! This library is an SDK to communicate via message broker with [StepFlow](https://hexdocs.pm/step_flow/readme.html).
//! It's used for every worker as an abstraction.
//! It manage itself requirements, message parsing, direct messaging.
//!
//! ## Worker implementation
//!
//! 1. Create a R... |
fn get_version(&self) -> semver::Version {
semver::Version::new(1, 2, 3)
}
}
let custom_event = CustomEvent {};
let parameters = CustomParameters {};
let job = job::Job {
job_id: 1234,
parameters: vec![],
};
let job_result = job::JobResult::new(job.job_id);
let result = custom_e... | {
"long description".to_string()
} | identifier_body |
main.rs | /**
shorturl is a web server that can host shortened URLs.
## Example usage
Creating a link:
```
$ curl -X POST 127.0.0.1:8080/tsauvajon -d "https://linkedin.com/in/tsauvajon"
/tsauvajon now redirects to https://linkedin.com/in/tsauvajon
```
Using it redirects us:
```
$ curl 127.0.0.1:8080/tsauvajon -v
* Trying 12... |
#[post("/{id}")]
async fn create_with_id(
db: web::Data<Db>,
payload: web::Payload,
web::Path(id): web::Path<String>,
) -> impl Responder {
let target = match read_target(payload).await {
Ok(target) => target,
Err(err) => return Err(error::ErrorBadRequest(err)),
};
create_shor... | {
if let Err(err) = Url::parse(&target) {
return Err(format!("malformed URL: {}", err));
};
let id = match id {
Some(id) => id,
None => hash(&target),
};
let mut db = db.write().unwrap();
if db.contains_key(&id) {
Err("already registered".to_string())
} else... | identifier_body |
main.rs | /**
shorturl is a web server that can host shortened URLs.
## Example usage
Creating a link:
```
$ curl -X POST 127.0.0.1:8080/tsauvajon -d "https://linkedin.com/in/tsauvajon"
/tsauvajon now redirects to https://linkedin.com/in/tsauvajon
```
Using it redirects us:
```
$ curl 127.0.0.1:8080/tsauvajon -v
* Trying 12... | */
use actix_web::{error, get, post, web, App, HttpResponse, HttpServer, Responder};
use futures::StreamExt;
use std::collections::HashMap;
use std::sync::RwLock;
use url::Url;
const MAX_SIZE: usize = 1_024; // max payload size is 1k
const RANDOM_URL_SIZE: usize = 5; // ramdomly generated URLs are 5 characters long
t... | redirecting to https://linkedin.com/in/tsauvajon...* Closing connection 0
``` | random_line_split |
main.rs | /**
shorturl is a web server that can host shortened URLs.
## Example usage
Creating a link:
```
$ curl -X POST 127.0.0.1:8080/tsauvajon -d "https://linkedin.com/in/tsauvajon"
/tsauvajon now redirects to https://linkedin.com/in/tsauvajon
```
Using it redirects us:
```
$ curl 127.0.0.1:8080/tsauvajon -v
* Trying 12... | (db: web::Data<Db>, web::Path(id): web::Path<String>) -> impl Responder {
match db.read() {
Ok(db) => match db.get(&id) {
None => Err(error::ErrorNotFound("not found")),
Some(url) => Ok(HttpResponse::Found()
.header("Location", url.clone())
.body(format!... | browse | identifier_name |
mod.rs | passphrase = prompt_password(prompt)?;
let confirmed = prompt_password(confirm)?;
// If they match, continue the process
if passphrase.reveal() == confirmed.reveal() {
break;
}
// If they don't match, keep prompting until we hit the sani... | let master_seed = read_or_create_master_seed(recovery_seed.clone(), &wallet_db)?;
let node_identity = match config.wallet.identity_file.as_ref() {
Some(identity_file) => {
warn!(
target: LOG_TARGET,
"Node identity overridden by file {}",
ident... | random_line_split | |
mod.rs | _LIMIT {
return Err(ExitError::new(ExitCode::InputError, "Passphrases don't match!"));
}
println!("Passphrases don't match! Try again.");
}
// Score the passphrase and provide feedback
let weak = display_password_feedback(&passphrase);
// If the ... | tari_splash_screen | identifier_name | |
mod.rs | passphrase = prompt_password(prompt)?;
let confirmed = prompt_password(confirm)?;
// If they match, continue the process
if passphrase.reveal() == confirmed.reveal() {
break;
}
// If they don't match, keep prompting until we hit the sanit... | // NOTE: https://github.com/tari-project/tari/issues/5227
debug!("revalidating all transactions");
if let Err(e) = wallet.transaction_service.revalidate_all_transactions().await {
error!(target: LOG_TARGET, "Failed to revalidate all transactions: {}", e);
}
debug!("r... | {
debug!(target: LOG_TARGET, "Setting base node peer");
let net_address = base_node
.addresses
.best()
.ok_or_else(|| ExitError::new(ExitCode::ConfigError, "Configured base node has no address!"))?;
wallet
.set_base_node_peer(base_node.public_key.clone(), net_address.addres... | identifier_body |
mod.rs | passphrase = prompt_password(prompt)?;
let confirmed = prompt_password(confirm)?;
// If they match, continue the process
if passphrase.reveal() == confirmed.reveal() {
break;
}
// If they don't match, keep prompting until we hit the sanit... | ,
_ => ExitError::new(ExitCode::DatabaseError, "Your password was not changed."),
})
}
/// Populates the PeerConfig struct from:
/// 1. The custom peer in the wallet config if it exists
/// 2. The custom peer in the wallet db if it exists
/// 3. The detected local base node if any
/// 4. The service peers ... | {
ExitError::new(ExitCode::IncorrectOrEmptyPassword, "Your password was not changed.")
} | conditional_block |
pattern.rs | use core::{cmp, fmt, mem, u16, usize};
use alloc::{string::String, vec, vec::Vec};
use crate::packed::api::MatchKind;
/// The type used for representing a pattern identifier.
///
/// We don't use `usize` here because our packed searchers don't scale to
/// huge numbers of patterns, so we keep things a bit smaller.
p... | }
}
return true;
}
// When we have 4 or more bytes to compare, then proceed in chunks of 4
// at a time using unaligned loads.
//
// Also, why do 4 byte loads instead of, say, 8 byte loads? The reason
// is that this particular vers... | {
// Why not just use memcmp for this? Well, memcmp requires calling out
// to libc, and this routine is called in fairly hot code paths. Other
// than just calling out to libc, it also seems to result in worse
// codegen. By rolling our own memcpy in pure Rust, it seems to appear
... | identifier_body |
pattern.rs | use core::{cmp, fmt, mem, u16, usize};
use alloc::{string::String, vec, vec::Vec};
use crate::packed::api::MatchKind;
/// The type used for representing a pattern identifier.
///
/// We don't use `usize` here because our packed searchers don't scale to
/// huge numbers of patterns, so we keep things a bit smaller.
p... | self.i += 1;
Some((id, p))
}
}
/// A pattern that is used in packed searching.
#[derive(Clone)]
pub struct Pattern<'a>(&'a [u8]);
impl<'a> fmt::Debug for Pattern<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Pattern")
.field("lit", &String:... | if self.i >= self.patterns.len() {
return None;
}
let id = self.patterns.order[self.i];
let p = self.patterns.get(id); | random_line_split |
pattern.rs | use core::{cmp, fmt, mem, u16, usize};
use alloc::{string::String, vec, vec::Vec};
use crate::packed::api::MatchKind;
/// The type used for representing a pattern identifier.
///
/// We don't use `usize` here because our packed searchers don't scale to
/// huge numbers of patterns, so we keep things a bit smaller.
p... | (&self) -> usize {
self.minimum_len
}
/// Returns the match semantics used by these patterns.
pub fn match_kind(&self) -> &MatchKind {
&self.kind
}
/// Return the pattern with the given identifier. If such a pattern does
/// not exist, then this panics.
pub fn get(&self, id... | minimum_len | identifier_name |
pattern.rs | use core::{cmp, fmt, mem, u16, usize};
use alloc::{string::String, vec, vec::Vec};
use crate::packed::api::MatchKind;
/// The type used for representing a pattern identifier.
///
/// We don't use `usize` here because our packed searchers don't scale to
/// huge numbers of patterns, so we keep things a bit smaller.
p... |
MatchKind::LeftmostLongest => {
let (order, by_id) = (&mut self.order, &mut self.by_id);
order.sort_by(|&id1, &id2| {
by_id[id1 as usize]
.len()
.cmp(&by_id[id2 as usize].len())
.reverse... | {
self.order.sort();
} | conditional_block |
segment_accountant.rs | Some(new_lsn);
self.state = Active;
}
/// Transitions a segment to being in the Inactive state.
/// Called in:
///
/// PageCache::advance_snapshot for marking when a
/// segment has been completely read
///
/// SegmentAccountant::recover for when
pub fn active_to_inactive(&... | (&mut self, f: &mut File) {
let safety_buffer = self.config.get_io_bufs();
let logical_tail: Vec<(Lsn, LogID)> = self.ordering
.iter()
.rev()
.take(safety_buffer)
.map(|(lsn, lid)| (*lsn, *lid))
.collect();
let mut tear_at = None;
... | clean_tail_tears | identifier_name |
segment_accountant.rs | self.lsn = Some(new_lsn);
self.state = Active;
}
/// Transitions a segment to being in the Inactive state.
/// Called in:
///
/// PageCache::advance_snapshot for marking when a
/// segment has been completely read
///
/// SegmentAccountant::recover for when
pub fn ac... | );
assert_eq!(self.state, Free);
self.present.clear();
self.removed.clear(); | random_line_split | |
segment_accountant.rs | // this is necessary for properly removing the ordering
// info later on, if this segment is found to be empty
// during recovery.
self.segments[idx].lsn = Some(lsn);
}
assert!(!self.ordering.contains_key(&lsn));
self.ordering.insert(lsn, lid);
}
//... | {
self.ordering.remove(&old_lsn);
} | conditional_block | |
history.rs | use super::*;
use std::{
collections::{vec_deque, VecDeque},
fs::File,
io::{self, Write},
io::{BufRead, BufReader, BufWriter},
iter::IntoIterator,
ops::Index,
ops::IndexMut,
path::Path,
//time::Duration,
};
const DEFAULT_MAX_SIZE: usize = 1000;
/// Structure encapsulating command ... | pub fn len(&self) -> usize {
self.buffers.len()
}
/// Is the history empty
pub fn is_empty(&self) -> bool {
self.buffers.is_empty()
}
/// Add a command to the history buffer and remove the oldest commands when the max history
/// size has been met. If writing to the disk is... | #[inline(always)] | random_line_split |
history.rs | use super::*;
use std::{
collections::{vec_deque, VecDeque},
fs::File,
io::{self, Write},
io::{BufRead, BufReader, BufWriter},
iter::IntoIterator,
ops::Index,
ops::IndexMut,
path::Path,
//time::Duration,
};
const DEFAULT_MAX_SIZE: usize = 1000;
/// Structure encapsulating command ... | // Every 30 writes "compact" the history file by writing just in memory history. This
// is to keep the history file clean and at a reasonable size (not much over max
// history size at it's worst).
if self.compaction_writes > 29 {
if ... | {
// buffers[0] is the oldest entry
// the new entry goes to the end
if !self.append_duplicate_entries
&& self.buffers.back().map(|b| b.to_string()) == Some(new_item.to_string())
{
return Ok(());
}
let item_str = String::from(new_item.clone());
... | identifier_body |
history.rs | use super::*;
use std::{
collections::{vec_deque, VecDeque},
fs::File,
io::{self, Write},
io::{BufRead, BufReader, BufWriter},
iter::IntoIterator,
ops::Index,
ops::IndexMut,
path::Path,
//time::Duration,
};
const DEFAULT_MAX_SIZE: usize = 1000;
/// Structure encapsulating command ... | (self) -> Self::IntoIter {
self.buffers.iter()
}
}
impl Index<usize> for History {
type Output = Buffer;
fn index(&self, index: usize) -> &Buffer {
&self.buffers[index]
}
}
impl IndexMut<usize> for History {
fn index_mut(&mut self, index: usize) -> &mut Buffer {
&mut self.... | into_iter | identifier_name |
history.rs | use super::*;
use std::{
collections::{vec_deque, VecDeque},
fs::File,
io::{self, Write},
io::{BufRead, BufReader, BufWriter},
iter::IntoIterator,
ops::Index,
ops::IndexMut,
path::Path,
//time::Duration,
};
const DEFAULT_MAX_SIZE: usize = 1000;
/// Structure encapsulating command ... |
contains &&!starts && tested!= search_term
} else {
false
}
})
.collect();
ret.append(&mut v);
ret
}
pub fn search_index(&self, search_term: &Buffer) -> Vec<usize> {
(0..self.len())
... | {
v.push(*i);
} | conditional_block |
rxcb.rs | //! Objective XCB Wrapper
#![allow(dead_code)]
extern crate univstring; use self::univstring::UnivString;
extern crate xcb;
use self::xcb::ffi::*;
use std::ptr::{null, null_mut};
use std::marker::PhantomData;
use std::io::{Error as IOError, ErrorKind};
#[repr(C)] pub enum WindowIOClass
{
InputOnly = XCB_WINDOW_CLAS... |
}
}
pub type WindowID = xcb_window_t;
pub struct Window(WindowID);
impl Window
{
pub(crate) fn id(&self) -> WindowID { self.0 }
pub fn replace_property<T: PropertyType +?Sized>(&self, con: &Connection, property: Atom, value: &T)
{
value.change_property_of(con, self, property, XCB_PROP_MODE_REPLACE)
}
}
pub tra... | { let p = self.0.data as *mut _; unsafe { xcb_screen_next(&mut self.0); Some(&*p) } } | conditional_block |
rxcb.rs | //! Objective XCB Wrapper
#![allow(dead_code)]
extern crate univstring; use self::univstring::UnivString;
extern crate xcb;
use self::xcb::ffi::*;
use std::ptr::{null, null_mut};
use std::marker::PhantomData;
use std::io::{Error as IOError, ErrorKind};
#[repr(C)] pub enum WindowIOClass
{
InputOnly = XCB_WINDOW_CLAS... | }
}
}
impl<E: PropertyType> PropertyType for [E]
{
const TYPE_ATOM: Atom = E::TYPE_ATOM; const DATA_STRIDE: u32 = E::DATA_STRIDE;
fn change_property_of(&self, con: &Connection, window: &Window, props: Atom, mode: u32)
{
unsafe
{
xcb_change_property(con.0, mode as _, window.0, props, E::TYPE_ATOM, E::DATA_S... | {
unsafe
{
xcb_change_property(con.0, mode as _, window.0, props, XCB_ATOM_ATOM, 32, 1,
self as *const Atom as *const _); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.