file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
android_calls.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Formatter for Android contacts2.db database events."""
from plaso.lib import eventdata
class AndroidCallFormatter(eventdata.ConditionalEventFormatter):
| """Formatter for Android call history events."""
DATA_TYPE = 'android:event:call'
FORMAT_STRING_PIECES = [
u'{call_type}',
u'Number: {number}',
u'Name: {name}',
u'Duration: {duration} seconds']
FORMAT_STRING_SHORT_PIECES = [u'{call_type} Call']
SOURCE_LONG = 'Android Call History'
SOURCE_SHORT = 'LOG' | identifier_body | |
android_calls.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and | # limitations under the License.
"""Formatter for Android contacts2.db database events."""
from plaso.lib import eventdata
class AndroidCallFormatter(eventdata.ConditionalEventFormatter):
"""Formatter for Android call history events."""
DATA_TYPE = 'android:event:call'
FORMAT_STRING_PIECES = [
u'{call_type}',
u'Number: {number}',
u'Name: {name}',
u'Duration: {duration} seconds']
FORMAT_STRING_SHORT_PIECES = [u'{call_type} Call']
SOURCE_LONG = 'Android Call History'
SOURCE_SHORT = 'LOG' | random_line_split | |
android_calls.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Formatter for Android contacts2.db database events."""
from plaso.lib import eventdata
class | (eventdata.ConditionalEventFormatter):
"""Formatter for Android call history events."""
DATA_TYPE = 'android:event:call'
FORMAT_STRING_PIECES = [
u'{call_type}',
u'Number: {number}',
u'Name: {name}',
u'Duration: {duration} seconds']
FORMAT_STRING_SHORT_PIECES = [u'{call_type} Call']
SOURCE_LONG = 'Android Call History'
SOURCE_SHORT = 'LOG'
| AndroidCallFormatter | identifier_name |
atmega16hvb.js | module.exports = {
"name": "ATmega16HVB",
"timeout": 200,
"stabDelay": 100,
"cmdexeDelay": 25,
"syncLoops": 32,
"byteDelay": 0,
"pollIndex": 3,
"pollValue": 83,
"preDelay": 1,
"postDelay": 1,
"pgmEnable": [172, 83, 0, 0],
"erase": {
"cmd": [172, 128, 0, 0],
"delay": 45,
"pollMethod": 1
},
"flash": {
"write": [64, 76, 0],
"read": [32, 0, 0],
"mode": 65,
"blockSize": 128,
"delay": 10,
"poll2": 0,
"poll1": 0,
"size": 16384,
"pageSize": 128, | "write": [193, 194, 0],
"read": [160, 0, 0],
"mode": 65,
"blockSize": 4,
"delay": 10,
"poll2": 0,
"poll1": 0,
"size": 512,
"pageSize": 4,
"pages": 128,
"addressOffset": 0
},
"sig": [30, 148, 13],
"signature": {
"size": 3,
"startAddress": 0,
"read": [48, 0, 0, 0]
},
"fuses": {
"startAddress": 0,
"write": {
"low": [172, 160, 0, 0],
"high": [172, 168, 0, 0]
},
"read": {
"low": [80, 0, 0, 0],
"high": [88, 8, 0, 0]
}
}
} | "pages": 128,
"addressOffset": null
},
"eeprom": { | random_line_split |
text_expression_methods.rs | use crate::dsl;
use crate::expression::grouped::Grouped;
use crate::expression::operators::{Concat, Like, NotLike};
use crate::expression::{AsExpression, Expression};
use crate::sql_types::{Nullable, SqlType, Text};
/// Methods present on text expressions
pub trait TextExpressionMethods: Expression + Sized {
/// Concatenates two strings using the `||` operator.
///
/// # Example
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// #
/// # table! {
/// # users {
/// # id -> Integer,
/// # name -> VarChar,
/// # hair_color -> Nullable<Text>,
/// # }
/// # }
/// #
/// # fn main() {
/// # use self::users::dsl::*;
/// # use diesel::insert_into;
/// #
/// # let connection = connection_no_data();
/// # connection.execute("CREATE TABLE users (
/// # id INTEGER PRIMARY KEY,
/// # name VARCHAR(255) NOT NULL,
/// # hair_color VARCHAR(255)
/// # )").unwrap();
/// #
/// # insert_into(users)
/// # .values(&vec![
/// # (id.eq(1), name.eq("Sean"), hair_color.eq(Some("Green"))),
/// # (id.eq(2), name.eq("Tess"), hair_color.eq(None)),
/// # ])
/// # .execute(&connection)
/// # .unwrap();
/// #
/// let names = users.select(name.concat(" the Greatest")).load(&connection);
/// let expected_names = vec![
/// "Sean the Greatest".to_string(),
/// "Tess the Greatest".to_string(),
/// ];
/// assert_eq!(Ok(expected_names), names);
///
/// // If the value is nullable, the output will be nullable
/// let names = users.select(hair_color.concat("ish")).load(&connection);
/// let expected_names = vec![
/// Some("Greenish".to_string()),
/// None,
/// ];
/// assert_eq!(Ok(expected_names), names);
/// # }
/// ```
fn concat<T>(self, other: T) -> dsl::Concat<Self, T>
where
Self::SqlType: SqlType,
T: AsExpression<Self::SqlType>,
{
Grouped(Concat::new(self, other.as_expression()))
}
/// Returns a SQL `LIKE` expression
///
/// This method is case insensitive for SQLite and MySQL.
/// On PostgreSQL, `LIKE` is case sensitive. You may use
/// [`ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.ilike)
/// for case insensitive comparison on PostgreSQL.
///
/// # Examples
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// #
/// # fn main() {
/// # run_test().unwrap();
/// # }
/// #
/// # fn run_test() -> QueryResult<()> {
/// # use schema::users::dsl::*;
/// # let connection = establish_connection();
/// #
/// let starts_with_s = users
/// .select(name)
/// .filter(name.like("S%"))
/// .load::<String>(&connection)?;
/// assert_eq!(vec!["Sean"], starts_with_s);
/// # Ok(())
/// # }
/// ```
fn like<T>(self, other: T) -> dsl::Like<Self, T>
where
Self::SqlType: SqlType,
T: AsExpression<Self::SqlType>,
|
/// Returns a SQL `NOT LIKE` expression
///
/// This method is case insensitive for SQLite and MySQL.
/// On PostgreSQL `NOT LIKE` is case sensitive. You may use
/// [`not_ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.not_ilike)
/// for case insensitive comparison on PostgreSQL.
///
/// # Examples
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// #
/// # fn main() {
/// # run_test().unwrap();
/// # }
/// #
/// # fn run_test() -> QueryResult<()> {
/// # use schema::users::dsl::*;
/// # let connection = establish_connection();
/// #
/// let doesnt_start_with_s = users
/// .select(name)
/// .filter(name.not_like("S%"))
/// .load::<String>(&connection)?;
/// assert_eq!(vec!["Tess"], doesnt_start_with_s);
/// # Ok(())
/// # }
/// ```
fn not_like<T>(self, other: T) -> dsl::NotLike<Self, T>
where
Self::SqlType: SqlType,
T: AsExpression<Self::SqlType>,
{
Grouped(NotLike::new(self, other.as_expression()))
}
}
#[doc(hidden)]
/// Marker trait used to implement `TextExpressionMethods` on the appropriate
/// types. Once coherence takes associated types into account, we can remove
/// this trait.
pub trait TextOrNullableText {}
impl TextOrNullableText for Text {}
impl TextOrNullableText for Nullable<Text> {}
impl<T> TextExpressionMethods for T
where
T: Expression,
T::SqlType: TextOrNullableText,
{
}
| {
Grouped(Like::new(self, other.as_expression()))
} | identifier_body |
text_expression_methods.rs | use crate::dsl;
use crate::expression::grouped::Grouped;
use crate::expression::operators::{Concat, Like, NotLike};
use crate::expression::{AsExpression, Expression};
use crate::sql_types::{Nullable, SqlType, Text};
/// Methods present on text expressions
pub trait TextExpressionMethods: Expression + Sized {
/// Concatenates two strings using the `||` operator.
///
/// # Example
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// #
/// # table! {
/// # users {
/// # id -> Integer,
/// # name -> VarChar,
/// # hair_color -> Nullable<Text>,
/// # }
/// # }
/// #
/// # fn main() {
/// # use self::users::dsl::*;
/// # use diesel::insert_into;
/// #
/// # let connection = connection_no_data();
/// # connection.execute("CREATE TABLE users (
/// # id INTEGER PRIMARY KEY,
/// # name VARCHAR(255) NOT NULL,
/// # hair_color VARCHAR(255) | /// #
/// # insert_into(users)
/// # .values(&vec![
/// # (id.eq(1), name.eq("Sean"), hair_color.eq(Some("Green"))),
/// # (id.eq(2), name.eq("Tess"), hair_color.eq(None)),
/// # ])
/// # .execute(&connection)
/// # .unwrap();
/// #
/// let names = users.select(name.concat(" the Greatest")).load(&connection);
/// let expected_names = vec![
/// "Sean the Greatest".to_string(),
/// "Tess the Greatest".to_string(),
/// ];
/// assert_eq!(Ok(expected_names), names);
///
/// // If the value is nullable, the output will be nullable
/// let names = users.select(hair_color.concat("ish")).load(&connection);
/// let expected_names = vec![
/// Some("Greenish".to_string()),
/// None,
/// ];
/// assert_eq!(Ok(expected_names), names);
/// # }
/// ```
fn concat<T>(self, other: T) -> dsl::Concat<Self, T>
where
Self::SqlType: SqlType,
T: AsExpression<Self::SqlType>,
{
Grouped(Concat::new(self, other.as_expression()))
}
/// Returns a SQL `LIKE` expression
///
/// This method is case insensitive for SQLite and MySQL.
/// On PostgreSQL, `LIKE` is case sensitive. You may use
/// [`ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.ilike)
/// for case insensitive comparison on PostgreSQL.
///
/// # Examples
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// #
/// # fn main() {
/// # run_test().unwrap();
/// # }
/// #
/// # fn run_test() -> QueryResult<()> {
/// # use schema::users::dsl::*;
/// # let connection = establish_connection();
/// #
/// let starts_with_s = users
/// .select(name)
/// .filter(name.like("S%"))
/// .load::<String>(&connection)?;
/// assert_eq!(vec!["Sean"], starts_with_s);
/// # Ok(())
/// # }
/// ```
fn like<T>(self, other: T) -> dsl::Like<Self, T>
where
Self::SqlType: SqlType,
T: AsExpression<Self::SqlType>,
{
Grouped(Like::new(self, other.as_expression()))
}
/// Returns a SQL `NOT LIKE` expression
///
/// This method is case insensitive for SQLite and MySQL.
/// On PostgreSQL `NOT LIKE` is case sensitive. You may use
/// [`not_ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.not_ilike)
/// for case insensitive comparison on PostgreSQL.
///
/// # Examples
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// #
/// # fn main() {
/// # run_test().unwrap();
/// # }
/// #
/// # fn run_test() -> QueryResult<()> {
/// # use schema::users::dsl::*;
/// # let connection = establish_connection();
/// #
/// let doesnt_start_with_s = users
/// .select(name)
/// .filter(name.not_like("S%"))
/// .load::<String>(&connection)?;
/// assert_eq!(vec!["Tess"], doesnt_start_with_s);
/// # Ok(())
/// # }
/// ```
fn not_like<T>(self, other: T) -> dsl::NotLike<Self, T>
where
Self::SqlType: SqlType,
T: AsExpression<Self::SqlType>,
{
Grouped(NotLike::new(self, other.as_expression()))
}
}
#[doc(hidden)]
/// Marker trait used to implement `TextExpressionMethods` on the appropriate
/// types. Once coherence takes associated types into account, we can remove
/// this trait.
pub trait TextOrNullableText {}
impl TextOrNullableText for Text {}
impl TextOrNullableText for Nullable<Text> {}
impl<T> TextExpressionMethods for T
where
T: Expression,
T::SqlType: TextOrNullableText,
{
} | /// # )").unwrap(); | random_line_split |
text_expression_methods.rs | use crate::dsl;
use crate::expression::grouped::Grouped;
use crate::expression::operators::{Concat, Like, NotLike};
use crate::expression::{AsExpression, Expression};
use crate::sql_types::{Nullable, SqlType, Text};
/// Methods present on text expressions
pub trait TextExpressionMethods: Expression + Sized {
/// Concatenates two strings using the `||` operator.
///
/// # Example
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// #
/// # table! {
/// # users {
/// # id -> Integer,
/// # name -> VarChar,
/// # hair_color -> Nullable<Text>,
/// # }
/// # }
/// #
/// # fn main() {
/// # use self::users::dsl::*;
/// # use diesel::insert_into;
/// #
/// # let connection = connection_no_data();
/// # connection.execute("CREATE TABLE users (
/// # id INTEGER PRIMARY KEY,
/// # name VARCHAR(255) NOT NULL,
/// # hair_color VARCHAR(255)
/// # )").unwrap();
/// #
/// # insert_into(users)
/// # .values(&vec![
/// # (id.eq(1), name.eq("Sean"), hair_color.eq(Some("Green"))),
/// # (id.eq(2), name.eq("Tess"), hair_color.eq(None)),
/// # ])
/// # .execute(&connection)
/// # .unwrap();
/// #
/// let names = users.select(name.concat(" the Greatest")).load(&connection);
/// let expected_names = vec![
/// "Sean the Greatest".to_string(),
/// "Tess the Greatest".to_string(),
/// ];
/// assert_eq!(Ok(expected_names), names);
///
/// // If the value is nullable, the output will be nullable
/// let names = users.select(hair_color.concat("ish")).load(&connection);
/// let expected_names = vec![
/// Some("Greenish".to_string()),
/// None,
/// ];
/// assert_eq!(Ok(expected_names), names);
/// # }
/// ```
fn concat<T>(self, other: T) -> dsl::Concat<Self, T>
where
Self::SqlType: SqlType,
T: AsExpression<Self::SqlType>,
{
Grouped(Concat::new(self, other.as_expression()))
}
/// Returns a SQL `LIKE` expression
///
/// This method is case insensitive for SQLite and MySQL.
/// On PostgreSQL, `LIKE` is case sensitive. You may use
/// [`ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.ilike)
/// for case insensitive comparison on PostgreSQL.
///
/// # Examples
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// #
/// # fn main() {
/// # run_test().unwrap();
/// # }
/// #
/// # fn run_test() -> QueryResult<()> {
/// # use schema::users::dsl::*;
/// # let connection = establish_connection();
/// #
/// let starts_with_s = users
/// .select(name)
/// .filter(name.like("S%"))
/// .load::<String>(&connection)?;
/// assert_eq!(vec!["Sean"], starts_with_s);
/// # Ok(())
/// # }
/// ```
fn | <T>(self, other: T) -> dsl::Like<Self, T>
where
Self::SqlType: SqlType,
T: AsExpression<Self::SqlType>,
{
Grouped(Like::new(self, other.as_expression()))
}
/// Returns a SQL `NOT LIKE` expression
///
/// This method is case insensitive for SQLite and MySQL.
/// On PostgreSQL `NOT LIKE` is case sensitive. You may use
/// [`not_ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.not_ilike)
/// for case insensitive comparison on PostgreSQL.
///
/// # Examples
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// #
/// # fn main() {
/// # run_test().unwrap();
/// # }
/// #
/// # fn run_test() -> QueryResult<()> {
/// # use schema::users::dsl::*;
/// # let connection = establish_connection();
/// #
/// let doesnt_start_with_s = users
/// .select(name)
/// .filter(name.not_like("S%"))
/// .load::<String>(&connection)?;
/// assert_eq!(vec!["Tess"], doesnt_start_with_s);
/// # Ok(())
/// # }
/// ```
fn not_like<T>(self, other: T) -> dsl::NotLike<Self, T>
where
Self::SqlType: SqlType,
T: AsExpression<Self::SqlType>,
{
Grouped(NotLike::new(self, other.as_expression()))
}
}
#[doc(hidden)]
/// Marker trait used to implement `TextExpressionMethods` on the appropriate
/// types. Once coherence takes associated types into account, we can remove
/// this trait.
pub trait TextOrNullableText {}
impl TextOrNullableText for Text {}
impl TextOrNullableText for Nullable<Text> {}
impl<T> TextExpressionMethods for T
where
T: Expression,
T::SqlType: TextOrNullableText,
{
}
| like | identifier_name |
response.rs | use std::borrow::Cow;
use std::sync::RwLock;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::path::Path;
use serialize::Encodable;
use hyper::status::StatusCode;
use hyper::server::Response as HyperResponse;
use hyper::header::{
Headers, Date, HttpDate, Server, ContentType, ContentLength, Header, HeaderFormat
};
use hyper::net::{Fresh, Streaming};
use time;
use mimes::MediaType;
use mustache;
use mustache::Template;
use std::io::{self, Read, Write, copy};
use std::fs::File;
use std::any::Any;
use {NickelError, Halt, MiddlewareResult, Responder};
use modifier::Modifier;
pub type TemplateCache = RwLock<HashMap<String, Template>>;
///A container for the response
pub struct Response<'a, T: 'static + Any = Fresh> {
///the original `hyper::server::Response`
origin: HyperResponse<'a, T>,
templates: &'a TemplateCache
}
impl<'a> Response<'a, Fresh> {
pub fn from_internal<'c, 'd>(response: HyperResponse<'c, Fresh>,
templates: &'c TemplateCache)
-> Response<'c, Fresh> {
Response {
origin: response,
templates: templates
}
}
/// Get a mutable reference to the status.
pub fn status_mut(&mut self) -> &mut StatusCode {
self.origin.status_mut()
}
/// Get a mutable reference to the Headers.
pub fn headers_mut(&mut self) -> &mut Headers {
self.origin.headers_mut()
}
/// Modify the response with the provided data.
///
/// # Examples
/// ```{rust}
/// extern crate hyper;
/// #[macro_use] extern crate nickel;
///
/// use nickel::{Nickel, HttpRouter, MediaType};
/// use nickel::status::StatusCode;
/// use hyper::header::Location;
///
/// fn main() {
/// let mut server = Nickel::new();
/// server.get("/a", middleware! { |_, mut res|
/// // set the Status
/// res.set(StatusCode::PermanentRedirect)
/// // update a Header value
/// .set(Location("http://nickel.rs".into()));
///
/// ""
/// });
///
/// server.get("/b", middleware! { |_, mut res|
/// // setting the content type
/// res.set(MediaType::Json);
///
/// "{'foo': 'bar'}"
/// });
///
/// // ...
/// }
/// ```
pub fn set<T: Modifier<Response<'a>>>(&mut self, attribute: T) -> &mut Response<'a> {
attribute.modify(self);
self
}
/// Writes a response
///
/// # Examples
/// ```{rust}
/// use nickel::{Request, Response, MiddlewareResult};
///
/// # #[allow(dead_code)]
/// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> {
/// res.send("hello world")
/// }
/// ```
#[inline]
pub fn send<T: Responder>(self, data: T) -> MiddlewareResult<'a> {
data.respond(self)
}
/// Writes a file to the output.
///
/// # Examples
/// ```{rust}
/// use nickel::{Request, Response, MiddlewareResult};
/// use std::path::Path;
///
/// # #[allow(dead_code)]
/// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> {
/// let favicon = Path::new("/assets/favicon.ico");
/// res.send_file(favicon)
/// }
/// ```
pub fn send_file(mut self, path: &Path) -> MiddlewareResult<'a> {
// Chunk the response
self.origin.headers_mut().remove::<ContentLength>();
// Determine content type by file extension or default to binary
let mime = mime_from_filename(path).unwrap_or(MediaType::Bin);
self.set(mime);
| File::open(path).map_err(|e| format!("Failed to send file '{:?}': {}",
path, e))
});
let mut stream = try!(self.start());
match copy(&mut file, &mut stream) {
Ok(_) => Ok(Halt(stream)),
Err(e) => stream.bail(format!("Failed to send file: {}", e))
}
}
// TODO: This needs to be more sophisticated to return the correct headers
// not just "some headers" :)
//
// Also, it should only set them if not already set.
fn set_fallback_headers(&mut self) {
self.set_header_fallback(|| Date(HttpDate(time::now_utc())));
self.set_header_fallback(|| Server("Nickel".to_string()));
self.set_header_fallback(|| ContentType(MediaType::Html.into()));
}
/// Return an error with the appropriate status code for error handlers to
/// provide output for.
pub fn error<T>(self, status: StatusCode, message: T) -> MiddlewareResult<'a>
where T: Into<Cow<'static, str>> {
Err(NickelError::new(self, message, status))
}
/// Sets the header if not already set.
///
/// If the header is not set then `f` will be called.
/// Renders the given template bound with the given data.
///
/// # Examples
/// ```{rust}
/// #[macro_use] extern crate nickel;
/// extern crate hyper;
///
/// use nickel::{Nickel, HttpRouter, MediaType};
/// use hyper::header::ContentType;
///
/// # #[allow(unreachable_code)]
/// fn main() {
/// let mut server = Nickel::new();
/// server.get("/", middleware! { |_, mut res|
/// res.set(MediaType::Html);
/// res.set_header_fallback(|| {
/// panic!("Should not get called");
/// ContentType(MediaType::Txt.into())
/// });
///
/// "<h1>Hello World</h1>"
/// });
///
/// // ...
/// }
/// ```
pub fn set_header_fallback<F, H>(&mut self, f: F)
where H: Header + HeaderFormat, F: FnOnce() -> H {
let headers = self.origin.headers_mut();
if !headers.has::<H>() { headers.set(f()) }
}
/// Renders the given template bound with the given data.
///
/// # Examples
/// ```{rust}
/// use std::collections::HashMap;
/// use nickel::{Request, Response, MiddlewareResult};
///
/// # #[allow(dead_code)]
/// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> {
/// let mut data = HashMap::new();
/// data.insert("name", "user");
/// res.render("examples/assets/template.tpl", &data)
/// }
/// ```
pub fn render<T, P>(self, path: P, data: &T) -> MiddlewareResult<'a>
where T: Encodable, P: AsRef<str> + Into<String> {
fn render<'a, T>(res: Response<'a>, template: &Template, data: &T)
-> MiddlewareResult<'a> where T: Encodable {
let mut stream = try!(res.start());
match template.render(&mut stream, data) {
Ok(()) => Ok(Halt(stream)),
Err(e) => stream.bail(format!("Problem rendering template: {:?}", e))
}
}
// Fast path doesn't need writer lock
if let Some(t) = self.templates.read().unwrap().get(path.as_ref()) {
return render(self, t, data);
}
// We didn't find the template, get writers lock
let mut templates = self.templates.write().unwrap();
// Additional clone required for now as the entry api doesn't give us a key ref
let path = path.into();
// Search again incase there was a race to compile the template
let template = match templates.entry(path.clone()) {
Vacant(entry) => {
let template = try_with!(self, {
mustache::compile_path(&path)
.map_err(|e| format!("Failed to compile template '{}': {:?}",
path, e))
});
entry.insert(template)
},
Occupied(entry) => entry.into_mut()
};
render(self, template, data)
}
pub fn start(mut self) -> Result<Response<'a, Streaming>, NickelError<'a>> {
self.set_fallback_headers();
let Response { origin, templates } = self;
match origin.start() {
Ok(origin) => Ok(Response { origin: origin, templates: templates }),
Err(e) =>
unsafe {
Err(NickelError::without_response(format!("Failed to start response: {}", e)))
}
}
}
}
impl<'a, 'b> Write for Response<'a, Streaming> {
#[inline(always)]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.origin.write(buf)
}
#[inline(always)]
fn flush(&mut self) -> io::Result<()> {
self.origin.flush()
}
}
impl<'a, 'b> Response<'a, Streaming> {
/// In the case of an unrecoverable error while a stream is already in
/// progress, there is no standard way to signal to the client that an
/// error has occurred. `bail` will drop the connection and log an error
/// message.
pub fn bail<T>(self, message: T) -> MiddlewareResult<'a>
where T: Into<Cow<'static, str>> {
let _ = self.end();
unsafe { Err(NickelError::without_response(message)) }
}
/// Flushes all writing of a response to the client.
pub fn end(self) -> io::Result<()> {
self.origin.end()
}
}
impl <'a, T: 'static + Any> Response<'a, T> {
/// The status of this response.
pub fn status(&self) -> StatusCode {
self.origin.status()
}
/// The headers of this response.
pub fn headers(&self) -> &Headers {
self.origin.headers()
}
}
fn mime_from_filename<P: AsRef<Path>>(path: P) -> Option<MediaType> {
path.as_ref()
.extension()
.and_then(|os| os.to_str())
// Lookup mime from file extension
.and_then(|s| s.parse().ok())
}
#[test]
fn matches_content_type () {
assert_eq!(Some(MediaType::Txt), mime_from_filename("test.txt"));
assert_eq!(Some(MediaType::Json), mime_from_filename("test.json"));
assert_eq!(Some(MediaType::Bin), mime_from_filename("test.bin"));
}
mod modifier_impls {
use hyper::header::*;
use hyper::status::StatusCode;
use modifier::Modifier;
use {Response, MediaType};
impl<'a> Modifier<Response<'a>> for StatusCode {
fn modify(self, res: &mut Response<'a>) {
*res.status_mut() = self
}
}
impl<'a> Modifier<Response<'a>> for MediaType {
fn modify(self, res: &mut Response<'a>) {
ContentType(self.into()).modify(res)
}
}
macro_rules! header_modifiers {
($($t:ty),+) => (
$(
impl<'a> Modifier<Response<'a>> for $t {
fn modify(self, res: &mut Response<'a>) {
res.headers_mut().set(self)
}
}
)+
)
}
header_modifiers! {
Accept,
AccessControlAllowHeaders,
AccessControlAllowMethods,
AccessControlAllowOrigin,
AccessControlMaxAge,
AccessControlRequestHeaders,
AccessControlRequestMethod,
AcceptCharset,
AcceptEncoding,
AcceptLanguage,
AcceptRanges,
Allow,
Authorization<Basic>,
Authorization<String>,
CacheControl,
Cookie,
Connection,
ContentEncoding,
ContentLanguage,
ContentLength,
ContentType,
Date,
ETag,
Expect,
Expires,
From,
Host,
IfMatch,
IfModifiedSince,
IfNoneMatch,
IfRange,
IfUnmodifiedSince,
LastModified,
Location,
Pragma,
Referer,
Server,
SetCookie,
TransferEncoding,
Upgrade,
UserAgent,
Vary
}
} | let mut file = try_with!(self, { | random_line_split |
response.rs | use std::borrow::Cow;
use std::sync::RwLock;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::path::Path;
use serialize::Encodable;
use hyper::status::StatusCode;
use hyper::server::Response as HyperResponse;
use hyper::header::{
Headers, Date, HttpDate, Server, ContentType, ContentLength, Header, HeaderFormat
};
use hyper::net::{Fresh, Streaming};
use time;
use mimes::MediaType;
use mustache;
use mustache::Template;
use std::io::{self, Read, Write, copy};
use std::fs::File;
use std::any::Any;
use {NickelError, Halt, MiddlewareResult, Responder};
use modifier::Modifier;
pub type TemplateCache = RwLock<HashMap<String, Template>>;
///A container for the response
pub struct | <'a, T: 'static + Any = Fresh> {
///the original `hyper::server::Response`
origin: HyperResponse<'a, T>,
templates: &'a TemplateCache
}
impl<'a> Response<'a, Fresh> {
pub fn from_internal<'c, 'd>(response: HyperResponse<'c, Fresh>,
templates: &'c TemplateCache)
-> Response<'c, Fresh> {
Response {
origin: response,
templates: templates
}
}
/// Get a mutable reference to the status.
pub fn status_mut(&mut self) -> &mut StatusCode {
self.origin.status_mut()
}
/// Get a mutable reference to the Headers.
pub fn headers_mut(&mut self) -> &mut Headers {
self.origin.headers_mut()
}
/// Modify the response with the provided data.
///
/// # Examples
/// ```{rust}
/// extern crate hyper;
/// #[macro_use] extern crate nickel;
///
/// use nickel::{Nickel, HttpRouter, MediaType};
/// use nickel::status::StatusCode;
/// use hyper::header::Location;
///
/// fn main() {
/// let mut server = Nickel::new();
/// server.get("/a", middleware! { |_, mut res|
/// // set the Status
/// res.set(StatusCode::PermanentRedirect)
/// // update a Header value
/// .set(Location("http://nickel.rs".into()));
///
/// ""
/// });
///
/// server.get("/b", middleware! { |_, mut res|
/// // setting the content type
/// res.set(MediaType::Json);
///
/// "{'foo': 'bar'}"
/// });
///
/// // ...
/// }
/// ```
pub fn set<T: Modifier<Response<'a>>>(&mut self, attribute: T) -> &mut Response<'a> {
attribute.modify(self);
self
}
/// Writes a response
///
/// # Examples
/// ```{rust}
/// use nickel::{Request, Response, MiddlewareResult};
///
/// # #[allow(dead_code)]
/// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> {
/// res.send("hello world")
/// }
/// ```
#[inline]
pub fn send<T: Responder>(self, data: T) -> MiddlewareResult<'a> {
data.respond(self)
}
/// Writes a file to the output.
///
/// # Examples
/// ```{rust}
/// use nickel::{Request, Response, MiddlewareResult};
/// use std::path::Path;
///
/// # #[allow(dead_code)]
/// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> {
/// let favicon = Path::new("/assets/favicon.ico");
/// res.send_file(favicon)
/// }
/// ```
pub fn send_file(mut self, path: &Path) -> MiddlewareResult<'a> {
// Chunk the response
self.origin.headers_mut().remove::<ContentLength>();
// Determine content type by file extension or default to binary
let mime = mime_from_filename(path).unwrap_or(MediaType::Bin);
self.set(mime);
let mut file = try_with!(self, {
File::open(path).map_err(|e| format!("Failed to send file '{:?}': {}",
path, e))
});
let mut stream = try!(self.start());
match copy(&mut file, &mut stream) {
Ok(_) => Ok(Halt(stream)),
Err(e) => stream.bail(format!("Failed to send file: {}", e))
}
}
// TODO: This needs to be more sophisticated to return the correct headers
// not just "some headers" :)
//
// Also, it should only set them if not already set.
fn set_fallback_headers(&mut self) {
self.set_header_fallback(|| Date(HttpDate(time::now_utc())));
self.set_header_fallback(|| Server("Nickel".to_string()));
self.set_header_fallback(|| ContentType(MediaType::Html.into()));
}
/// Return an error with the appropriate status code for error handlers to
/// provide output for.
pub fn error<T>(self, status: StatusCode, message: T) -> MiddlewareResult<'a>
where T: Into<Cow<'static, str>> {
Err(NickelError::new(self, message, status))
}
/// Sets the header if not already set.
///
/// If the header is not set then `f` will be called.
/// Renders the given template bound with the given data.
///
/// # Examples
/// ```{rust}
/// #[macro_use] extern crate nickel;
/// extern crate hyper;
///
/// use nickel::{Nickel, HttpRouter, MediaType};
/// use hyper::header::ContentType;
///
/// # #[allow(unreachable_code)]
/// fn main() {
/// let mut server = Nickel::new();
/// server.get("/", middleware! { |_, mut res|
/// res.set(MediaType::Html);
/// res.set_header_fallback(|| {
/// panic!("Should not get called");
/// ContentType(MediaType::Txt.into())
/// });
///
/// "<h1>Hello World</h1>"
/// });
///
/// // ...
/// }
/// ```
pub fn set_header_fallback<F, H>(&mut self, f: F)
where H: Header + HeaderFormat, F: FnOnce() -> H {
let headers = self.origin.headers_mut();
if !headers.has::<H>() { headers.set(f()) }
}
/// Renders the given template bound with the given data.
///
/// # Examples
/// ```{rust}
/// use std::collections::HashMap;
/// use nickel::{Request, Response, MiddlewareResult};
///
/// # #[allow(dead_code)]
/// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> {
/// let mut data = HashMap::new();
/// data.insert("name", "user");
/// res.render("examples/assets/template.tpl", &data)
/// }
/// ```
pub fn render<T, P>(self, path: P, data: &T) -> MiddlewareResult<'a>
where T: Encodable, P: AsRef<str> + Into<String> {
fn render<'a, T>(res: Response<'a>, template: &Template, data: &T)
-> MiddlewareResult<'a> where T: Encodable {
let mut stream = try!(res.start());
match template.render(&mut stream, data) {
Ok(()) => Ok(Halt(stream)),
Err(e) => stream.bail(format!("Problem rendering template: {:?}", e))
}
}
// Fast path doesn't need writer lock
if let Some(t) = self.templates.read().unwrap().get(path.as_ref()) {
return render(self, t, data);
}
// We didn't find the template, get writers lock
let mut templates = self.templates.write().unwrap();
// Additional clone required for now as the entry api doesn't give us a key ref
let path = path.into();
// Search again incase there was a race to compile the template
let template = match templates.entry(path.clone()) {
Vacant(entry) => {
let template = try_with!(self, {
mustache::compile_path(&path)
.map_err(|e| format!("Failed to compile template '{}': {:?}",
path, e))
});
entry.insert(template)
},
Occupied(entry) => entry.into_mut()
};
render(self, template, data)
}
pub fn start(mut self) -> Result<Response<'a, Streaming>, NickelError<'a>> {
self.set_fallback_headers();
let Response { origin, templates } = self;
match origin.start() {
Ok(origin) => Ok(Response { origin: origin, templates: templates }),
Err(e) =>
unsafe {
Err(NickelError::without_response(format!("Failed to start response: {}", e)))
}
}
}
}
impl<'a, 'b> Write for Response<'a, Streaming> {
#[inline(always)]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.origin.write(buf)
}
#[inline(always)]
fn flush(&mut self) -> io::Result<()> {
self.origin.flush()
}
}
impl<'a, 'b> Response<'a, Streaming> {
/// In the case of an unrecoverable error while a stream is already in
/// progress, there is no standard way to signal to the client that an
/// error has occurred. `bail` will drop the connection and log an error
/// message.
pub fn bail<T>(self, message: T) -> MiddlewareResult<'a>
where T: Into<Cow<'static, str>> {
let _ = self.end();
unsafe { Err(NickelError::without_response(message)) }
}
/// Flushes all writing of a response to the client.
pub fn end(self) -> io::Result<()> {
self.origin.end()
}
}
impl <'a, T: 'static + Any> Response<'a, T> {
/// The status of this response.
pub fn status(&self) -> StatusCode {
self.origin.status()
}
/// The headers of this response.
pub fn headers(&self) -> &Headers {
self.origin.headers()
}
}
fn mime_from_filename<P: AsRef<Path>>(path: P) -> Option<MediaType> {
path.as_ref()
.extension()
.and_then(|os| os.to_str())
// Lookup mime from file extension
.and_then(|s| s.parse().ok())
}
#[test]
fn matches_content_type () {
assert_eq!(Some(MediaType::Txt), mime_from_filename("test.txt"));
assert_eq!(Some(MediaType::Json), mime_from_filename("test.json"));
assert_eq!(Some(MediaType::Bin), mime_from_filename("test.bin"));
}
mod modifier_impls {
use hyper::header::*;
use hyper::status::StatusCode;
use modifier::Modifier;
use {Response, MediaType};
impl<'a> Modifier<Response<'a>> for StatusCode {
fn modify(self, res: &mut Response<'a>) {
*res.status_mut() = self
}
}
impl<'a> Modifier<Response<'a>> for MediaType {
fn modify(self, res: &mut Response<'a>) {
ContentType(self.into()).modify(res)
}
}
macro_rules! header_modifiers {
($($t:ty),+) => (
$(
impl<'a> Modifier<Response<'a>> for $t {
fn modify(self, res: &mut Response<'a>) {
res.headers_mut().set(self)
}
}
)+
)
}
header_modifiers! {
Accept,
AccessControlAllowHeaders,
AccessControlAllowMethods,
AccessControlAllowOrigin,
AccessControlMaxAge,
AccessControlRequestHeaders,
AccessControlRequestMethod,
AcceptCharset,
AcceptEncoding,
AcceptLanguage,
AcceptRanges,
Allow,
Authorization<Basic>,
Authorization<String>,
CacheControl,
Cookie,
Connection,
ContentEncoding,
ContentLanguage,
ContentLength,
ContentType,
Date,
ETag,
Expect,
Expires,
From,
Host,
IfMatch,
IfModifiedSince,
IfNoneMatch,
IfRange,
IfUnmodifiedSince,
LastModified,
Location,
Pragma,
Referer,
Server,
SetCookie,
TransferEncoding,
Upgrade,
UserAgent,
Vary
}
}
| Response | identifier_name |
response.rs | use std::borrow::Cow;
use std::sync::RwLock;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::path::Path;
use serialize::Encodable;
use hyper::status::StatusCode;
use hyper::server::Response as HyperResponse;
use hyper::header::{
Headers, Date, HttpDate, Server, ContentType, ContentLength, Header, HeaderFormat
};
use hyper::net::{Fresh, Streaming};
use time;
use mimes::MediaType;
use mustache;
use mustache::Template;
use std::io::{self, Read, Write, copy};
use std::fs::File;
use std::any::Any;
use {NickelError, Halt, MiddlewareResult, Responder};
use modifier::Modifier;
pub type TemplateCache = RwLock<HashMap<String, Template>>;
///A container for the response
pub struct Response<'a, T: 'static + Any = Fresh> {
///the original `hyper::server::Response`
origin: HyperResponse<'a, T>,
templates: &'a TemplateCache
}
impl<'a> Response<'a, Fresh> {
pub fn from_internal<'c, 'd>(response: HyperResponse<'c, Fresh>,
templates: &'c TemplateCache)
-> Response<'c, Fresh> {
Response {
origin: response,
templates: templates
}
}
/// Get a mutable reference to the status.
pub fn status_mut(&mut self) -> &mut StatusCode {
self.origin.status_mut()
}
/// Get a mutable reference to the Headers.
pub fn headers_mut(&mut self) -> &mut Headers {
self.origin.headers_mut()
}
/// Modify the response with the provided data.
///
/// # Examples
/// ```{rust}
/// extern crate hyper;
/// #[macro_use] extern crate nickel;
///
/// use nickel::{Nickel, HttpRouter, MediaType};
/// use nickel::status::StatusCode;
/// use hyper::header::Location;
///
/// fn main() {
/// let mut server = Nickel::new();
/// server.get("/a", middleware! { |_, mut res|
/// // set the Status
/// res.set(StatusCode::PermanentRedirect)
/// // update a Header value
/// .set(Location("http://nickel.rs".into()));
///
/// ""
/// });
///
/// server.get("/b", middleware! { |_, mut res|
/// // setting the content type
/// res.set(MediaType::Json);
///
/// "{'foo': 'bar'}"
/// });
///
/// // ...
/// }
/// ```
pub fn set<T: Modifier<Response<'a>>>(&mut self, attribute: T) -> &mut Response<'a> {
attribute.modify(self);
self
}
/// Writes a response
///
/// # Examples
/// ```{rust}
/// use nickel::{Request, Response, MiddlewareResult};
///
/// # #[allow(dead_code)]
/// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> {
/// res.send("hello world")
/// }
/// ```
#[inline]
pub fn send<T: Responder>(self, data: T) -> MiddlewareResult<'a> {
data.respond(self)
}
/// Writes a file to the output.
///
/// # Examples
/// ```{rust}
/// use nickel::{Request, Response, MiddlewareResult};
/// use std::path::Path;
///
/// # #[allow(dead_code)]
/// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> {
/// let favicon = Path::new("/assets/favicon.ico");
/// res.send_file(favicon)
/// }
/// ```
pub fn send_file(mut self, path: &Path) -> MiddlewareResult<'a> {
// Chunk the response
self.origin.headers_mut().remove::<ContentLength>();
// Determine content type by file extension or default to binary
let mime = mime_from_filename(path).unwrap_or(MediaType::Bin);
self.set(mime);
let mut file = try_with!(self, {
File::open(path).map_err(|e| format!("Failed to send file '{:?}': {}",
path, e))
});
let mut stream = try!(self.start());
match copy(&mut file, &mut stream) {
Ok(_) => Ok(Halt(stream)),
Err(e) => stream.bail(format!("Failed to send file: {}", e))
}
}
// TODO: This needs to be more sophisticated to return the correct headers
// not just "some headers" :)
//
// Also, it should only set them if not already set.
fn set_fallback_headers(&mut self) {
self.set_header_fallback(|| Date(HttpDate(time::now_utc())));
self.set_header_fallback(|| Server("Nickel".to_string()));
self.set_header_fallback(|| ContentType(MediaType::Html.into()));
}
/// Return an error with the appropriate status code for error handlers to
/// provide output for.
pub fn error<T>(self, status: StatusCode, message: T) -> MiddlewareResult<'a>
where T: Into<Cow<'static, str>> {
Err(NickelError::new(self, message, status))
}
/// Sets the header if not already set.
///
/// If the header is not set then `f` will be called.
/// Renders the given template bound with the given data.
///
/// # Examples
/// ```{rust}
/// #[macro_use] extern crate nickel;
/// extern crate hyper;
///
/// use nickel::{Nickel, HttpRouter, MediaType};
/// use hyper::header::ContentType;
///
/// # #[allow(unreachable_code)]
/// fn main() {
/// let mut server = Nickel::new();
/// server.get("/", middleware! { |_, mut res|
/// res.set(MediaType::Html);
/// res.set_header_fallback(|| {
/// panic!("Should not get called");
/// ContentType(MediaType::Txt.into())
/// });
///
/// "<h1>Hello World</h1>"
/// });
///
/// // ...
/// }
/// ```
pub fn set_header_fallback<F, H>(&mut self, f: F)
where H: Header + HeaderFormat, F: FnOnce() -> H {
let headers = self.origin.headers_mut();
if !headers.has::<H>() { headers.set(f()) }
}
/// Renders the given template bound with the given data.
///
/// # Examples
/// ```{rust}
/// use std::collections::HashMap;
/// use nickel::{Request, Response, MiddlewareResult};
///
/// # #[allow(dead_code)]
/// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> {
/// let mut data = HashMap::new();
/// data.insert("name", "user");
/// res.render("examples/assets/template.tpl", &data)
/// }
/// ```
pub fn render<T, P>(self, path: P, data: &T) -> MiddlewareResult<'a>
where T: Encodable, P: AsRef<str> + Into<String> {
fn render<'a, T>(res: Response<'a>, template: &Template, data: &T)
-> MiddlewareResult<'a> where T: Encodable {
let mut stream = try!(res.start());
match template.render(&mut stream, data) {
Ok(()) => Ok(Halt(stream)),
Err(e) => stream.bail(format!("Problem rendering template: {:?}", e))
}
}
// Fast path doesn't need writer lock
if let Some(t) = self.templates.read().unwrap().get(path.as_ref()) {
return render(self, t, data);
}
// We didn't find the template, get writers lock
let mut templates = self.templates.write().unwrap();
// Additional clone required for now as the entry api doesn't give us a key ref
let path = path.into();
// Search again incase there was a race to compile the template
let template = match templates.entry(path.clone()) {
Vacant(entry) => {
let template = try_with!(self, {
mustache::compile_path(&path)
.map_err(|e| format!("Failed to compile template '{}': {:?}",
path, e))
});
entry.insert(template)
},
Occupied(entry) => entry.into_mut()
};
render(self, template, data)
}
pub fn start(mut self) -> Result<Response<'a, Streaming>, NickelError<'a>> {
self.set_fallback_headers();
let Response { origin, templates } = self;
match origin.start() {
Ok(origin) => Ok(Response { origin: origin, templates: templates }),
Err(e) =>
unsafe {
Err(NickelError::without_response(format!("Failed to start response: {}", e)))
}
}
}
}
impl<'a, 'b> Write for Response<'a, Streaming> {
#[inline(always)]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.origin.write(buf)
}
#[inline(always)]
fn flush(&mut self) -> io::Result<()> {
self.origin.flush()
}
}
impl<'a, 'b> Response<'a, Streaming> {
/// In the case of an unrecoverable error while a stream is already in
/// progress, there is no standard way to signal to the client that an
/// error has occurred. `bail` will drop the connection and log an error
/// message.
pub fn bail<T>(self, message: T) -> MiddlewareResult<'a>
where T: Into<Cow<'static, str>> {
let _ = self.end();
unsafe { Err(NickelError::without_response(message)) }
}
/// Flushes all writing of a response to the client.
pub fn end(self) -> io::Result<()> |
}
impl <'a, T: 'static + Any> Response<'a, T> {
/// The status of this response.
pub fn status(&self) -> StatusCode {
self.origin.status()
}
/// The headers of this response.
pub fn headers(&self) -> &Headers {
self.origin.headers()
}
}
fn mime_from_filename<P: AsRef<Path>>(path: P) -> Option<MediaType> {
path.as_ref()
.extension()
.and_then(|os| os.to_str())
// Lookup mime from file extension
.and_then(|s| s.parse().ok())
}
#[test]
fn matches_content_type () {
assert_eq!(Some(MediaType::Txt), mime_from_filename("test.txt"));
assert_eq!(Some(MediaType::Json), mime_from_filename("test.json"));
assert_eq!(Some(MediaType::Bin), mime_from_filename("test.bin"));
}
mod modifier_impls {
use hyper::header::*;
use hyper::status::StatusCode;
use modifier::Modifier;
use {Response, MediaType};
impl<'a> Modifier<Response<'a>> for StatusCode {
fn modify(self, res: &mut Response<'a>) {
*res.status_mut() = self
}
}
impl<'a> Modifier<Response<'a>> for MediaType {
fn modify(self, res: &mut Response<'a>) {
ContentType(self.into()).modify(res)
}
}
macro_rules! header_modifiers {
($($t:ty),+) => (
$(
impl<'a> Modifier<Response<'a>> for $t {
fn modify(self, res: &mut Response<'a>) {
res.headers_mut().set(self)
}
}
)+
)
}
header_modifiers! {
Accept,
AccessControlAllowHeaders,
AccessControlAllowMethods,
AccessControlAllowOrigin,
AccessControlMaxAge,
AccessControlRequestHeaders,
AccessControlRequestMethod,
AcceptCharset,
AcceptEncoding,
AcceptLanguage,
AcceptRanges,
Allow,
Authorization<Basic>,
Authorization<String>,
CacheControl,
Cookie,
Connection,
ContentEncoding,
ContentLanguage,
ContentLength,
ContentType,
Date,
ETag,
Expect,
Expires,
From,
Host,
IfMatch,
IfModifiedSince,
IfNoneMatch,
IfRange,
IfUnmodifiedSince,
LastModified,
Location,
Pragma,
Referer,
Server,
SetCookie,
TransferEncoding,
Upgrade,
UserAgent,
Vary
}
}
| {
self.origin.end()
} | identifier_body |
response.rs | use std::borrow::Cow;
use std::sync::RwLock;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::path::Path;
use serialize::Encodable;
use hyper::status::StatusCode;
use hyper::server::Response as HyperResponse;
use hyper::header::{
Headers, Date, HttpDate, Server, ContentType, ContentLength, Header, HeaderFormat
};
use hyper::net::{Fresh, Streaming};
use time;
use mimes::MediaType;
use mustache;
use mustache::Template;
use std::io::{self, Read, Write, copy};
use std::fs::File;
use std::any::Any;
use {NickelError, Halt, MiddlewareResult, Responder};
use modifier::Modifier;
pub type TemplateCache = RwLock<HashMap<String, Template>>;
///A container for the response
pub struct Response<'a, T: 'static + Any = Fresh> {
///the original `hyper::server::Response`
origin: HyperResponse<'a, T>,
templates: &'a TemplateCache
}
impl<'a> Response<'a, Fresh> {
pub fn from_internal<'c, 'd>(response: HyperResponse<'c, Fresh>,
templates: &'c TemplateCache)
-> Response<'c, Fresh> {
Response {
origin: response,
templates: templates
}
}
/// Get a mutable reference to the status.
pub fn status_mut(&mut self) -> &mut StatusCode {
self.origin.status_mut()
}
/// Get a mutable reference to the Headers.
pub fn headers_mut(&mut self) -> &mut Headers {
self.origin.headers_mut()
}
/// Modify the response with the provided data.
///
/// # Examples
/// ```{rust}
/// extern crate hyper;
/// #[macro_use] extern crate nickel;
///
/// use nickel::{Nickel, HttpRouter, MediaType};
/// use nickel::status::StatusCode;
/// use hyper::header::Location;
///
/// fn main() {
/// let mut server = Nickel::new();
/// server.get("/a", middleware! { |_, mut res|
/// // set the Status
/// res.set(StatusCode::PermanentRedirect)
/// // update a Header value
/// .set(Location("http://nickel.rs".into()));
///
/// ""
/// });
///
/// server.get("/b", middleware! { |_, mut res|
/// // setting the content type
/// res.set(MediaType::Json);
///
/// "{'foo': 'bar'}"
/// });
///
/// // ...
/// }
/// ```
pub fn set<T: Modifier<Response<'a>>>(&mut self, attribute: T) -> &mut Response<'a> {
attribute.modify(self);
self
}
/// Writes a response
///
/// # Examples
/// ```{rust}
/// use nickel::{Request, Response, MiddlewareResult};
///
/// # #[allow(dead_code)]
/// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> {
/// res.send("hello world")
/// }
/// ```
#[inline]
pub fn send<T: Responder>(self, data: T) -> MiddlewareResult<'a> {
data.respond(self)
}
/// Writes a file to the output.
///
/// # Examples
/// ```{rust}
/// use nickel::{Request, Response, MiddlewareResult};
/// use std::path::Path;
///
/// # #[allow(dead_code)]
/// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> {
/// let favicon = Path::new("/assets/favicon.ico");
/// res.send_file(favicon)
/// }
/// ```
pub fn send_file(mut self, path: &Path) -> MiddlewareResult<'a> {
// Chunk the response
self.origin.headers_mut().remove::<ContentLength>();
// Determine content type by file extension or default to binary
let mime = mime_from_filename(path).unwrap_or(MediaType::Bin);
self.set(mime);
let mut file = try_with!(self, {
File::open(path).map_err(|e| format!("Failed to send file '{:?}': {}",
path, e))
});
let mut stream = try!(self.start());
match copy(&mut file, &mut stream) {
Ok(_) => Ok(Halt(stream)),
Err(e) => stream.bail(format!("Failed to send file: {}", e))
}
}
// TODO: This needs to be more sophisticated to return the correct headers
// not just "some headers" :)
//
// Also, it should only set them if not already set.
fn set_fallback_headers(&mut self) {
self.set_header_fallback(|| Date(HttpDate(time::now_utc())));
self.set_header_fallback(|| Server("Nickel".to_string()));
self.set_header_fallback(|| ContentType(MediaType::Html.into()));
}
/// Return an error with the appropriate status code for error handlers to
/// provide output for.
pub fn error<T>(self, status: StatusCode, message: T) -> MiddlewareResult<'a>
where T: Into<Cow<'static, str>> {
Err(NickelError::new(self, message, status))
}
/// Sets the header if not already set.
///
/// If the header is not set then `f` will be called.
/// Renders the given template bound with the given data.
///
/// # Examples
/// ```{rust}
/// #[macro_use] extern crate nickel;
/// extern crate hyper;
///
/// use nickel::{Nickel, HttpRouter, MediaType};
/// use hyper::header::ContentType;
///
/// # #[allow(unreachable_code)]
/// fn main() {
/// let mut server = Nickel::new();
/// server.get("/", middleware! { |_, mut res|
/// res.set(MediaType::Html);
/// res.set_header_fallback(|| {
/// panic!("Should not get called");
/// ContentType(MediaType::Txt.into())
/// });
///
/// "<h1>Hello World</h1>"
/// });
///
/// // ...
/// }
/// ```
pub fn set_header_fallback<F, H>(&mut self, f: F)
where H: Header + HeaderFormat, F: FnOnce() -> H {
let headers = self.origin.headers_mut();
if !headers.has::<H>() |
}
/// Renders the given template bound with the given data.
///
/// # Examples
/// ```{rust}
/// use std::collections::HashMap;
/// use nickel::{Request, Response, MiddlewareResult};
///
/// # #[allow(dead_code)]
/// fn handler<'a>(_: &mut Request, res: Response<'a>) -> MiddlewareResult<'a> {
/// let mut data = HashMap::new();
/// data.insert("name", "user");
/// res.render("examples/assets/template.tpl", &data)
/// }
/// ```
pub fn render<T, P>(self, path: P, data: &T) -> MiddlewareResult<'a>
where T: Encodable, P: AsRef<str> + Into<String> {
fn render<'a, T>(res: Response<'a>, template: &Template, data: &T)
-> MiddlewareResult<'a> where T: Encodable {
let mut stream = try!(res.start());
match template.render(&mut stream, data) {
Ok(()) => Ok(Halt(stream)),
Err(e) => stream.bail(format!("Problem rendering template: {:?}", e))
}
}
// Fast path doesn't need writer lock
if let Some(t) = self.templates.read().unwrap().get(path.as_ref()) {
return render(self, t, data);
}
// We didn't find the template, get writers lock
let mut templates = self.templates.write().unwrap();
// Additional clone required for now as the entry api doesn't give us a key ref
let path = path.into();
// Search again incase there was a race to compile the template
let template = match templates.entry(path.clone()) {
Vacant(entry) => {
let template = try_with!(self, {
mustache::compile_path(&path)
.map_err(|e| format!("Failed to compile template '{}': {:?}",
path, e))
});
entry.insert(template)
},
Occupied(entry) => entry.into_mut()
};
render(self, template, data)
}
pub fn start(mut self) -> Result<Response<'a, Streaming>, NickelError<'a>> {
self.set_fallback_headers();
let Response { origin, templates } = self;
match origin.start() {
Ok(origin) => Ok(Response { origin: origin, templates: templates }),
Err(e) =>
unsafe {
Err(NickelError::without_response(format!("Failed to start response: {}", e)))
}
}
}
}
impl<'a, 'b> Write for Response<'a, Streaming> {
#[inline(always)]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.origin.write(buf)
}
#[inline(always)]
fn flush(&mut self) -> io::Result<()> {
self.origin.flush()
}
}
impl<'a, 'b> Response<'a, Streaming> {
/// In the case of an unrecoverable error while a stream is already in
/// progress, there is no standard way to signal to the client that an
/// error has occurred. `bail` will drop the connection and log an error
/// message.
pub fn bail<T>(self, message: T) -> MiddlewareResult<'a>
where T: Into<Cow<'static, str>> {
let _ = self.end();
unsafe { Err(NickelError::without_response(message)) }
}
/// Flushes all writing of a response to the client.
pub fn end(self) -> io::Result<()> {
self.origin.end()
}
}
impl <'a, T: 'static + Any> Response<'a, T> {
/// The status of this response.
pub fn status(&self) -> StatusCode {
self.origin.status()
}
/// The headers of this response.
pub fn headers(&self) -> &Headers {
self.origin.headers()
}
}
fn mime_from_filename<P: AsRef<Path>>(path: P) -> Option<MediaType> {
path.as_ref()
.extension()
.and_then(|os| os.to_str())
// Lookup mime from file extension
.and_then(|s| s.parse().ok())
}
#[test]
fn matches_content_type () {
assert_eq!(Some(MediaType::Txt), mime_from_filename("test.txt"));
assert_eq!(Some(MediaType::Json), mime_from_filename("test.json"));
assert_eq!(Some(MediaType::Bin), mime_from_filename("test.bin"));
}
mod modifier_impls {
use hyper::header::*;
use hyper::status::StatusCode;
use modifier::Modifier;
use {Response, MediaType};
impl<'a> Modifier<Response<'a>> for StatusCode {
fn modify(self, res: &mut Response<'a>) {
*res.status_mut() = self
}
}
impl<'a> Modifier<Response<'a>> for MediaType {
fn modify(self, res: &mut Response<'a>) {
ContentType(self.into()).modify(res)
}
}
macro_rules! header_modifiers {
($($t:ty),+) => (
$(
impl<'a> Modifier<Response<'a>> for $t {
fn modify(self, res: &mut Response<'a>) {
res.headers_mut().set(self)
}
}
)+
)
}
header_modifiers! {
Accept,
AccessControlAllowHeaders,
AccessControlAllowMethods,
AccessControlAllowOrigin,
AccessControlMaxAge,
AccessControlRequestHeaders,
AccessControlRequestMethod,
AcceptCharset,
AcceptEncoding,
AcceptLanguage,
AcceptRanges,
Allow,
Authorization<Basic>,
Authorization<String>,
CacheControl,
Cookie,
Connection,
ContentEncoding,
ContentLanguage,
ContentLength,
ContentType,
Date,
ETag,
Expect,
Expires,
From,
Host,
IfMatch,
IfModifiedSince,
IfNoneMatch,
IfRange,
IfUnmodifiedSince,
LastModified,
Location,
Pragma,
Referer,
Server,
SetCookie,
TransferEncoding,
Upgrade,
UserAgent,
Vary
}
}
| { headers.set(f()) } | conditional_block |
indicadoranaliticahl7.js | (function(module){
'use strict';
var Pojo = require('../pojo');
function indicadoranaliticahl7() |
indicadoranaliticahl7.prototype = Object.create(Pojo.prototype);
indicadoranaliticahl7.prototype.constructor = indicadoranaliticahl7;
module.exports = indicadoranaliticahl7;
})(module); | {
this.indicadoranaliticahl7id = '';
this.nombrehl7 = '';
this.nombre = '';
this.idindicador = '';
this.coste = '';
this.categoriahl7 = '';
this.orden = '';
this._metadata = {
attrs: {
'indicadoranaliticahl7id' : {type: 'int', PK: 1},
'nombrehl7' : {type: 'varchar'},
'nombre' : {type: 'varchar'},
'idindicador' : {type: 'varchar'},
'coste' : {type: 'float'},
'categoriahl7' : {type: 'varchar'},
'orden' : {type: 'int', nullable: true}
},
attrsid: [],
sqls: {
insert: '',
select: '',
delete: '',
get: ''
},
tablename: 'indicadoranaliticahl7'
};
Pojo.call(this);
} | identifier_body |
indicadoranaliticahl7.js | (function(module){
'use strict';
var Pojo = require('../pojo');
function | (){
this.indicadoranaliticahl7id = '';
this.nombrehl7 = '';
this.nombre = '';
this.idindicador = '';
this.coste = '';
this.categoriahl7 = '';
this.orden = '';
this._metadata = {
attrs: {
'indicadoranaliticahl7id' : {type: 'int', PK: 1},
'nombrehl7' : {type: 'varchar'},
'nombre' : {type: 'varchar'},
'idindicador' : {type: 'varchar'},
'coste' : {type: 'float'},
'categoriahl7' : {type: 'varchar'},
'orden' : {type: 'int', nullable: true}
},
attrsid: [],
sqls: {
insert: '',
select: '',
delete: '',
get: ''
},
tablename: 'indicadoranaliticahl7'
};
Pojo.call(this);
}
indicadoranaliticahl7.prototype = Object.create(Pojo.prototype);
indicadoranaliticahl7.prototype.constructor = indicadoranaliticahl7;
module.exports = indicadoranaliticahl7;
})(module); | indicadoranaliticahl7 | identifier_name |
indicadoranaliticahl7.js | (function(module){
'use strict';
var Pojo = require('../pojo');
function indicadoranaliticahl7(){
this.indicadoranaliticahl7id = '';
this.nombrehl7 = '';
this.nombre = '';
this.idindicador = ''; | attrs: {
'indicadoranaliticahl7id' : {type: 'int', PK: 1},
'nombrehl7' : {type: 'varchar'},
'nombre' : {type: 'varchar'},
'idindicador' : {type: 'varchar'},
'coste' : {type: 'float'},
'categoriahl7' : {type: 'varchar'},
'orden' : {type: 'int', nullable: true}
},
attrsid: [],
sqls: {
insert: '',
select: '',
delete: '',
get: ''
},
tablename: 'indicadoranaliticahl7'
};
Pojo.call(this);
}
indicadoranaliticahl7.prototype = Object.create(Pojo.prototype);
indicadoranaliticahl7.prototype.constructor = indicadoranaliticahl7;
module.exports = indicadoranaliticahl7;
})(module); | this.coste = '';
this.categoriahl7 = '';
this.orden = '';
this._metadata = { | random_line_split |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
import os
import codecs
from setuptools import setup
def read(fname):
|
setup(
name='pytest-typehints',
version='0.1.0',
author='Edward Dunn Ekelund',
author_email='edward.ekelund@gmail.com',
maintainer='Edward Dunn Ekelund',
maintainer_email='edward.ekelund@gmail.com',
license='BSD-3',
url='https://github.com/eddie-dunn/pytest-typehints',
description='Pytest plugin that checks for type hinting',
long_description=read('README.rst'),
py_modules=['pytest_typehints'],
install_requires=['pytest>=2.9.2'],
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Pytest',
'Intended Audience :: Developers',
'Topic :: Software Development :: Testing',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Operating System :: OS Independent',
'License :: OSI Approved :: BSD License',
],
entry_points={
'pytest11': [
'typehints = pytest_typehints',
],
},
)
| file_path = os.path.join(os.path.dirname(__file__), fname)
return codecs.open(file_path, encoding='utf-8').read() | identifier_body |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
import os
import codecs
from setuptools import setup
def | (fname):
file_path = os.path.join(os.path.dirname(__file__), fname)
return codecs.open(file_path, encoding='utf-8').read()
setup(
name='pytest-typehints',
version='0.1.0',
author='Edward Dunn Ekelund',
author_email='edward.ekelund@gmail.com',
maintainer='Edward Dunn Ekelund',
maintainer_email='edward.ekelund@gmail.com',
license='BSD-3',
url='https://github.com/eddie-dunn/pytest-typehints',
description='Pytest plugin that checks for type hinting',
long_description=read('README.rst'),
py_modules=['pytest_typehints'],
install_requires=['pytest>=2.9.2'],
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Pytest',
'Intended Audience :: Developers',
'Topic :: Software Development :: Testing',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Operating System :: OS Independent',
'License :: OSI Approved :: BSD License',
],
entry_points={
'pytest11': [
'typehints = pytest_typehints',
],
},
)
| read | identifier_name |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
import os
import codecs
from setuptools import setup
def read(fname):
file_path = os.path.join(os.path.dirname(__file__), fname)
return codecs.open(file_path, encoding='utf-8').read()
setup(
name='pytest-typehints',
version='0.1.0',
author='Edward Dunn Ekelund',
author_email='edward.ekelund@gmail.com',
maintainer='Edward Dunn Ekelund',
maintainer_email='edward.ekelund@gmail.com',
license='BSD-3',
url='https://github.com/eddie-dunn/pytest-typehints',
description='Pytest plugin that checks for type hinting',
long_description=read('README.rst'),
py_modules=['pytest_typehints'],
install_requires=['pytest>=2.9.2'],
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Pytest',
'Intended Audience :: Developers',
'Topic :: Software Development :: Testing',
'Programming Language :: Python', | 'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Operating System :: OS Independent',
'License :: OSI Approved :: BSD License',
],
entry_points={
'pytest11': [
'typehints = pytest_typehints',
],
},
) | random_line_split | |
strings.js | define({
"_widgetLabel": "Tra cứu Địa lý",
"description": "Duyệt đến hoặc Kéo <a href='./widgets/GeoLookup/data/sample.csv' tooltip='Download an example sheet' target='_blank'> trang tính </a> tại đây để mô phỏng và thêm các dữ liệu bản đồ vào trang tính đó.",
"selectCSV": "Chọn một CSV",
"loadingCSV": "Đang tải CSV",
"savingCSV": "Xuất CSV",
"clearResults": "Xóa",
"downloadResults": "Tải xuống",
"plotOnly": "Chỉ các Điểm Vẽ bản đồ",
"plottingRows": "Hàng vẽ bản đồ",
"projectionChoice": "CSV trong",
"projectionLat": "Vĩ độ/Kinh độ",
"projectionMap": "Phép chiếu Bản đồ",
"messages": "Thông báo",
"error": {
"fetchingCSV": "Đã xảy ra lỗi khi truy xuất các mục từ kho lưu trữ CSV: ${0}",
"fileIssue": "Không xử lý được tệp.",
"notCSVFile": "Hiện chỉ hỗ trợ các tệp được ngăn cách bằng dấu phẩy (.csv).",
"invalidCoord": "Trường vị trí không hợp lệ. Vui lòng kiểm tra tệp .csv.", | "CSVNoRecords": "Tệp không chứa bất kỳ hồ sơ nào.",
"CSVEmptyFile": "Không có nội dung trong tệp."
},
"results": {
"csvLoaded": "Đã tải ${0} bản ghi từ tệp CSV",
"recordsPlotted": "Đã định vị ${0}/${1} bản ghi trên bản đồ",
"recordsEnriched": "Đã xử lý ${0}/${1}, đã bổ sung ${2} so với ${3}",
"recordsError": "${0} bản ghi có lỗi",
"recordsErrorList": "Hàng ${0} có sự cố",
"label": "Kết quả CSV"
}
}); | "tooManyRecords": "Rất tiếc, hiện không được có quá ${0} bản ghi.", | random_line_split |
xset.js | 'use strict';
const fs = require('fs');
const Q = require('q');
const exec = require('child_process').exec;
const searchpaths = ["/bin/xset"];
class XSetDriver {
constructor(props) {
this.name = "Backlight Control";
this.devicePath = "xset";
this.description = "Screensaver control via Xwindows xset command";
this.devices = [];
this.driver = {};
//this.depends = [];
}
probe(props) {
searchpaths.forEach(function(p) {
if(fs.existsSync(p)) {
let stat = fs.lstatSync(p);
if (stat.isFile()) {
console.log("found xset control at "+p);
this.devices.push(new XSetDriver.Channel(this, p, props));
}
}
}.bind(this));
return this.devices.length>0;
}
}
class XSetChannel {
constructor(driver, path, props)
{
this.value = 1;
this.setCommand = path;
this.enabled = true;
this.display = ":0.0";
this.error = 0;
// internal variables
this.lastReset = new Date();
}
enable() {
this.set("on");
}
disable() {
this.set("off");
}
activate() {
this.set("activate");
}
blank() {
this.set("blank");
}
reset() {
this.set("reset");
this.lastReset=new Date();
}
setTimeout(secs) {
this.set(""+secs);
}
set(action) {
if(!this.enabled) return false;
var ss = this;
exec("DISPLAY="+this.display+" "+this.setCommand+" s "+action, function(error,stdout, stderr) {
if(error) {
if(ss.error++ >10) {
ss.enabled=false;
}
console.log("xset error "+error);
console.log(stdout);
console.log("errors:");
console.log(stderr);
} | }
XSetDriver.Channel = XSetChannel;
module.exports = XSetDriver;
/*
Treadmill.prototype.init_screensaver = function(action)
{
this.screensaver = {
// config/settings
enabled: !simulate,
display: ":0.0",
error: 0,
// internal variables
lastReset: new Date(),
// screensaver functions
enable: function() { this.set("on"); },
disable: function() { this.set("off"); },
activate: function() { this.set("activate"); },
blank: function() { this.set("blank"); },
reset: function() { this.set("reset"); this.lastReset=new Date(); },
timeout: function(secs) { this.set(""+secs); },
// main set() function calls command "xset s <action>"
set: function(action) {
if(!this.enabled) return false;
var ss = this;
exec("DISPLAY="+this.display+" xset s "+action, function(error,stdout, stderr) {
if(error) {
if(ss.error++ >10) {
ss.enabled=false;
}
console.log("xset error "+error);
console.log(stdout);
console.log("errors:");
console.log(stderr);
}
});
}
};
if(simulate) return false;
// initialize the screensaver
var ss = this.screensaver;
exec("./screensaver.conf "+this.screensaver.display, function(error,stdout, stderr) {
if(error) {
ss.enabled = false;
console.log("screensaver.conf error "+error);
console.log(stdout);
console.log("errors:");
console.log(stderr);
}
});
this.screensaver.enable();
}
*/ | }.bind(this));
} | random_line_split |
xset.js | 'use strict';
const fs = require('fs');
const Q = require('q');
const exec = require('child_process').exec;
const searchpaths = ["/bin/xset"];
class XSetDriver {
constructor(props) {
this.name = "Backlight Control";
this.devicePath = "xset";
this.description = "Screensaver control via Xwindows xset command";
this.devices = [];
this.driver = {};
//this.depends = [];
}
probe(props) {
searchpaths.forEach(function(p) {
if(fs.existsSync(p)) {
let stat = fs.lstatSync(p);
if (stat.isFile()) {
console.log("found xset control at "+p);
this.devices.push(new XSetDriver.Channel(this, p, props));
}
}
}.bind(this));
return this.devices.length>0;
}
}
class | {
constructor(driver, path, props)
{
this.value = 1;
this.setCommand = path;
this.enabled = true;
this.display = ":0.0";
this.error = 0;
// internal variables
this.lastReset = new Date();
}
enable() {
this.set("on");
}
disable() {
this.set("off");
}
activate() {
this.set("activate");
}
blank() {
this.set("blank");
}
reset() {
this.set("reset");
this.lastReset=new Date();
}
setTimeout(secs) {
this.set(""+secs);
}
set(action) {
if(!this.enabled) return false;
var ss = this;
exec("DISPLAY="+this.display+" "+this.setCommand+" s "+action, function(error,stdout, stderr) {
if(error) {
if(ss.error++ >10) {
ss.enabled=false;
}
console.log("xset error "+error);
console.log(stdout);
console.log("errors:");
console.log(stderr);
}
}.bind(this));
}
}
XSetDriver.Channel = XSetChannel;
module.exports = XSetDriver;
/*
Treadmill.prototype.init_screensaver = function(action)
{
this.screensaver = {
// config/settings
enabled: !simulate,
display: ":0.0",
error: 0,
// internal variables
lastReset: new Date(),
// screensaver functions
enable: function() { this.set("on"); },
disable: function() { this.set("off"); },
activate: function() { this.set("activate"); },
blank: function() { this.set("blank"); },
reset: function() { this.set("reset"); this.lastReset=new Date(); },
timeout: function(secs) { this.set(""+secs); },
// main set() function calls command "xset s <action>"
set: function(action) {
if(!this.enabled) return false;
var ss = this;
exec("DISPLAY="+this.display+" xset s "+action, function(error,stdout, stderr) {
if(error) {
if(ss.error++ >10) {
ss.enabled=false;
}
console.log("xset error "+error);
console.log(stdout);
console.log("errors:");
console.log(stderr);
}
});
}
};
if(simulate) return false;
// initialize the screensaver
var ss = this.screensaver;
exec("./screensaver.conf "+this.screensaver.display, function(error,stdout, stderr) {
if(error) {
ss.enabled = false;
console.log("screensaver.conf error "+error);
console.log(stdout);
console.log("errors:");
console.log(stderr);
}
});
this.screensaver.enable();
}
*/ | XSetChannel | identifier_name |
xset.js | 'use strict';
const fs = require('fs');
const Q = require('q');
const exec = require('child_process').exec;
const searchpaths = ["/bin/xset"];
class XSetDriver {
constructor(props) {
this.name = "Backlight Control";
this.devicePath = "xset";
this.description = "Screensaver control via Xwindows xset command";
this.devices = [];
this.driver = {};
//this.depends = [];
}
probe(props) {
searchpaths.forEach(function(p) {
if(fs.existsSync(p)) |
}.bind(this));
return this.devices.length>0;
}
}
class XSetChannel {
constructor(driver, path, props)
{
this.value = 1;
this.setCommand = path;
this.enabled = true;
this.display = ":0.0";
this.error = 0;
// internal variables
this.lastReset = new Date();
}
enable() {
this.set("on");
}
disable() {
this.set("off");
}
activate() {
this.set("activate");
}
blank() {
this.set("blank");
}
reset() {
this.set("reset");
this.lastReset=new Date();
}
setTimeout(secs) {
this.set(""+secs);
}
set(action) {
if(!this.enabled) return false;
var ss = this;
exec("DISPLAY="+this.display+" "+this.setCommand+" s "+action, function(error,stdout, stderr) {
if(error) {
if(ss.error++ >10) {
ss.enabled=false;
}
console.log("xset error "+error);
console.log(stdout);
console.log("errors:");
console.log(stderr);
}
}.bind(this));
}
}
XSetDriver.Channel = XSetChannel;
module.exports = XSetDriver;
/*
Treadmill.prototype.init_screensaver = function(action)
{
this.screensaver = {
// config/settings
enabled: !simulate,
display: ":0.0",
error: 0,
// internal variables
lastReset: new Date(),
// screensaver functions
enable: function() { this.set("on"); },
disable: function() { this.set("off"); },
activate: function() { this.set("activate"); },
blank: function() { this.set("blank"); },
reset: function() { this.set("reset"); this.lastReset=new Date(); },
timeout: function(secs) { this.set(""+secs); },
// main set() function calls command "xset s <action>"
set: function(action) {
if(!this.enabled) return false;
var ss = this;
exec("DISPLAY="+this.display+" xset s "+action, function(error,stdout, stderr) {
if(error) {
if(ss.error++ >10) {
ss.enabled=false;
}
console.log("xset error "+error);
console.log(stdout);
console.log("errors:");
console.log(stderr);
}
});
}
};
if(simulate) return false;
// initialize the screensaver
var ss = this.screensaver;
exec("./screensaver.conf "+this.screensaver.display, function(error,stdout, stderr) {
if(error) {
ss.enabled = false;
console.log("screensaver.conf error "+error);
console.log(stdout);
console.log("errors:");
console.log(stderr);
}
});
this.screensaver.enable();
}
*/ | {
let stat = fs.lstatSync(p);
if (stat.isFile()) {
console.log("found xset control at "+p);
this.devices.push(new XSetDriver.Channel(this, p, props));
}
} | conditional_block |
hid_usb_test.py | #
# DAPLink Interface Firmware
# Copyright (c) 2016-2017, ARM Limited, All Rights Reserved
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import mbed_lstools
import threading
import time
import pyocd
should_exit = False
exit_cond = threading.Condition()
print_mut = threading.RLock()
global_start_time = time.time()
def _get_time():
return time.time() - global_start_time
def sync_print(msg):
|
def hid_main(thread_index, board_id):
global should_exit
count = 0
try:
device = pyocd.probe.pydapaccess.DAPAccess.get_device(board_id)
while not should_exit:
device.open()
info = device.vendor(0)
info = str(bytearray(info[1:1 + info[0]]))
assert info == board_id
device.close()
if count % 100 == 0:
sync_print("Thread %i on loop %10i at %.6f - %s - board %s" %
(thread_index, count, _get_time(),
time.strftime("%H:%M:%S"), board_id))
count += 1
except:
sync_print("Thread %i exception board %s" % (thread_index, board_id))
with exit_cond:
should_exit = 1
exit_cond.notify_all()
raise
def main():
global should_exit
lstools = mbed_lstools.create()
mbed_list = lstools.list_mbeds()
for thread_index, mbed in enumerate(mbed_list):
msd_thread = threading.Thread(target=hid_main,
args=(thread_index, mbed['target_id']))
msd_thread.start()
try:
with exit_cond:
while not should_exit:
exit_cond.wait(1)
except KeyboardInterrupt:
pass
should_exit = True
sync_print("Exiting")
if __name__ == "__main__":
main()
| with print_mut:
print(msg) | identifier_body |
hid_usb_test.py | #
# DAPLink Interface Firmware
# Copyright (c) 2016-2017, ARM Limited, All Rights Reserved
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import mbed_lstools
import threading
import time
import pyocd
should_exit = False
exit_cond = threading.Condition()
print_mut = threading.RLock()
global_start_time = time.time()
def _get_time():
return time.time() - global_start_time
def sync_print(msg):
with print_mut:
print(msg)
def hid_main(thread_index, board_id):
global should_exit
count = 0 | while not should_exit:
device.open()
info = device.vendor(0)
info = str(bytearray(info[1:1 + info[0]]))
assert info == board_id
device.close()
if count % 100 == 0:
sync_print("Thread %i on loop %10i at %.6f - %s - board %s" %
(thread_index, count, _get_time(),
time.strftime("%H:%M:%S"), board_id))
count += 1
except:
sync_print("Thread %i exception board %s" % (thread_index, board_id))
with exit_cond:
should_exit = 1
exit_cond.notify_all()
raise
def main():
global should_exit
lstools = mbed_lstools.create()
mbed_list = lstools.list_mbeds()
for thread_index, mbed in enumerate(mbed_list):
msd_thread = threading.Thread(target=hid_main,
args=(thread_index, mbed['target_id']))
msd_thread.start()
try:
with exit_cond:
while not should_exit:
exit_cond.wait(1)
except KeyboardInterrupt:
pass
should_exit = True
sync_print("Exiting")
if __name__ == "__main__":
main() | try:
device = pyocd.probe.pydapaccess.DAPAccess.get_device(board_id) | random_line_split |
hid_usb_test.py | #
# DAPLink Interface Firmware
# Copyright (c) 2016-2017, ARM Limited, All Rights Reserved
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import mbed_lstools
import threading
import time
import pyocd
should_exit = False
exit_cond = threading.Condition()
print_mut = threading.RLock()
global_start_time = time.time()
def _get_time():
return time.time() - global_start_time
def sync_print(msg):
with print_mut:
print(msg)
def | (thread_index, board_id):
global should_exit
count = 0
try:
device = pyocd.probe.pydapaccess.DAPAccess.get_device(board_id)
while not should_exit:
device.open()
info = device.vendor(0)
info = str(bytearray(info[1:1 + info[0]]))
assert info == board_id
device.close()
if count % 100 == 0:
sync_print("Thread %i on loop %10i at %.6f - %s - board %s" %
(thread_index, count, _get_time(),
time.strftime("%H:%M:%S"), board_id))
count += 1
except:
sync_print("Thread %i exception board %s" % (thread_index, board_id))
with exit_cond:
should_exit = 1
exit_cond.notify_all()
raise
def main():
global should_exit
lstools = mbed_lstools.create()
mbed_list = lstools.list_mbeds()
for thread_index, mbed in enumerate(mbed_list):
msd_thread = threading.Thread(target=hid_main,
args=(thread_index, mbed['target_id']))
msd_thread.start()
try:
with exit_cond:
while not should_exit:
exit_cond.wait(1)
except KeyboardInterrupt:
pass
should_exit = True
sync_print("Exiting")
if __name__ == "__main__":
main()
| hid_main | identifier_name |
hid_usb_test.py | #
# DAPLink Interface Firmware
# Copyright (c) 2016-2017, ARM Limited, All Rights Reserved
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import mbed_lstools
import threading
import time
import pyocd
should_exit = False
exit_cond = threading.Condition()
print_mut = threading.RLock()
global_start_time = time.time()
def _get_time():
return time.time() - global_start_time
def sync_print(msg):
with print_mut:
print(msg)
def hid_main(thread_index, board_id):
global should_exit
count = 0
try:
device = pyocd.probe.pydapaccess.DAPAccess.get_device(board_id)
while not should_exit:
device.open()
info = device.vendor(0)
info = str(bytearray(info[1:1 + info[0]]))
assert info == board_id
device.close()
if count % 100 == 0:
sync_print("Thread %i on loop %10i at %.6f - %s - board %s" %
(thread_index, count, _get_time(),
time.strftime("%H:%M:%S"), board_id))
count += 1
except:
sync_print("Thread %i exception board %s" % (thread_index, board_id))
with exit_cond:
should_exit = 1
exit_cond.notify_all()
raise
def main():
global should_exit
lstools = mbed_lstools.create()
mbed_list = lstools.list_mbeds()
for thread_index, mbed in enumerate(mbed_list):
|
try:
with exit_cond:
while not should_exit:
exit_cond.wait(1)
except KeyboardInterrupt:
pass
should_exit = True
sync_print("Exiting")
if __name__ == "__main__":
main()
| msd_thread = threading.Thread(target=hid_main,
args=(thread_index, mbed['target_id']))
msd_thread.start() | conditional_block |
index.ts | import formatDistance from '../en-US/_lib/formatDistance/index'
import formatRelative from '../en-US/_lib/formatRelative/index'
import localize from '../en-US/_lib/localize/index'
import match from '../en-US/_lib/match/index'
import type { Locale } from '../types'
import formatLong from './_lib/formatLong/index'
/**
* @type {Locale}
* @category Locales
* @summary English locale (New Zealand).
* @language English
* @iso-639-2 eng
* @author Murray Lucas [@muntact]{@link https://github.com/muntact}
*/
const locale: Locale = {
code: 'en-NZ',
formatDistance: formatDistance,
formatLong: formatLong,
formatRelative: formatRelative,
localize: localize,
match: match,
options: { | }
export default locale | weekStartsOn: 1 /* Monday */,
firstWeekContainsDate: 4,
}, | random_line_split |
typeclasses-eq-example-static.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Example from lkuper's intern talk, August 2012 -- now with static
// methods!
trait Equal {
fn isEq(a: Self, b: Self) -> bool;
}
enum Color { cyan, magenta, yellow, black }
impl Equal for Color {
fn isEq(a: Color, b: Color) -> bool {
match (a, b) {
(cyan, cyan) => { true }
(magenta, magenta) => { true }
(yellow, yellow) => { true }
(black, black) => { true }
_ => { false }
}
}
}
enum | {
leaf(Color),
branch(@ColorTree, @ColorTree)
}
impl Equal for ColorTree {
fn isEq(a: ColorTree, b: ColorTree) -> bool {
match (a, b) {
(leaf(x), leaf(y)) => { Equal::isEq(x, y) }
(branch(l1, r1), branch(l2, r2)) => {
Equal::isEq(*l1, *l2) && Equal::isEq(*r1, *r2)
}
_ => { false }
}
}
}
pub fn main() {
assert!(Equal::isEq(cyan, cyan));
assert!(Equal::isEq(magenta, magenta));
assert!(!Equal::isEq(cyan, yellow));
assert!(!Equal::isEq(magenta, cyan));
assert!(Equal::isEq(leaf(cyan), leaf(cyan)));
assert!(!Equal::isEq(leaf(cyan), leaf(yellow)));
assert!(Equal::isEq(branch(@leaf(magenta), @leaf(cyan)),
branch(@leaf(magenta), @leaf(cyan))));
assert!(!Equal::isEq(branch(@leaf(magenta), @leaf(cyan)),
branch(@leaf(magenta), @leaf(magenta))));
error2!("Assertions all succeeded!");
}
| ColorTree | identifier_name |
typeclasses-eq-example-static.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Example from lkuper's intern talk, August 2012 -- now with static
// methods!
trait Equal {
fn isEq(a: Self, b: Self) -> bool;
}
enum Color { cyan, magenta, yellow, black }
impl Equal for Color {
fn isEq(a: Color, b: Color) -> bool {
match (a, b) {
(cyan, cyan) => { true }
(magenta, magenta) => { true }
(yellow, yellow) => { true }
(black, black) => { true }
_ => { false }
}
}
}
| branch(@ColorTree, @ColorTree)
}
impl Equal for ColorTree {
fn isEq(a: ColorTree, b: ColorTree) -> bool {
match (a, b) {
(leaf(x), leaf(y)) => { Equal::isEq(x, y) }
(branch(l1, r1), branch(l2, r2)) => {
Equal::isEq(*l1, *l2) && Equal::isEq(*r1, *r2)
}
_ => { false }
}
}
}
pub fn main() {
assert!(Equal::isEq(cyan, cyan));
assert!(Equal::isEq(magenta, magenta));
assert!(!Equal::isEq(cyan, yellow));
assert!(!Equal::isEq(magenta, cyan));
assert!(Equal::isEq(leaf(cyan), leaf(cyan)));
assert!(!Equal::isEq(leaf(cyan), leaf(yellow)));
assert!(Equal::isEq(branch(@leaf(magenta), @leaf(cyan)),
branch(@leaf(magenta), @leaf(cyan))));
assert!(!Equal::isEq(branch(@leaf(magenta), @leaf(cyan)),
branch(@leaf(magenta), @leaf(magenta))));
error2!("Assertions all succeeded!");
} | enum ColorTree {
leaf(Color), | random_line_split |
typeclasses-eq-example-static.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Example from lkuper's intern talk, August 2012 -- now with static
// methods!
trait Equal {
fn isEq(a: Self, b: Self) -> bool;
}
enum Color { cyan, magenta, yellow, black }
impl Equal for Color {
fn isEq(a: Color, b: Color) -> bool {
match (a, b) {
(cyan, cyan) => { true }
(magenta, magenta) => |
(yellow, yellow) => { true }
(black, black) => { true }
_ => { false }
}
}
}
enum ColorTree {
leaf(Color),
branch(@ColorTree, @ColorTree)
}
impl Equal for ColorTree {
fn isEq(a: ColorTree, b: ColorTree) -> bool {
match (a, b) {
(leaf(x), leaf(y)) => { Equal::isEq(x, y) }
(branch(l1, r1), branch(l2, r2)) => {
Equal::isEq(*l1, *l2) && Equal::isEq(*r1, *r2)
}
_ => { false }
}
}
}
pub fn main() {
assert!(Equal::isEq(cyan, cyan));
assert!(Equal::isEq(magenta, magenta));
assert!(!Equal::isEq(cyan, yellow));
assert!(!Equal::isEq(magenta, cyan));
assert!(Equal::isEq(leaf(cyan), leaf(cyan)));
assert!(!Equal::isEq(leaf(cyan), leaf(yellow)));
assert!(Equal::isEq(branch(@leaf(magenta), @leaf(cyan)),
branch(@leaf(magenta), @leaf(cyan))));
assert!(!Equal::isEq(branch(@leaf(magenta), @leaf(cyan)),
branch(@leaf(magenta), @leaf(magenta))));
error2!("Assertions all succeeded!");
}
| { true } | conditional_block |
home.component.ts | import { Component } from '@angular/core';
import {ROUTER_DIRECTIVES} from "@angular/router"
import { AppState } from '../app.service';
@Component({
// The selector is what angular internally uses
// for `document.querySelectorAll(selector)` in our index.html
// where, in this case, selector is the string 'home'
selector: 'home', // <home></home>
// We need to tell Angular's Dependency Injection which providers are in our app.
providers: [
],
// We need to tell Angular's compiler which directives are in our template.
// Doing so will allow Angular to attach our behavior to an element
directives: [
ROUTER_DIRECTIVES
],
// We need to tell Angular's compiler which custom pipes are in our template.
pipes: [ ],
// Our list of styles in our component. We may add more to compose many styles together
styleUrls: [ './home.style.css' ],
// Every Angular template is first compiled by the browser before Angular runs it's compiler
templateUrl: './home.template.html'
})
export class Home {
// TypeScript public modifiers
constructor(public appState: AppState) {
}
ngOnInit() {
}
|
} | random_line_split | |
home.component.ts | import { Component } from '@angular/core';
import {ROUTER_DIRECTIVES} from "@angular/router"
import { AppState } from '../app.service';
@Component({
// The selector is what angular internally uses
// for `document.querySelectorAll(selector)` in our index.html
// where, in this case, selector is the string 'home'
selector: 'home', // <home></home>
// We need to tell Angular's Dependency Injection which providers are in our app.
providers: [
],
// We need to tell Angular's compiler which directives are in our template.
// Doing so will allow Angular to attach our behavior to an element
directives: [
ROUTER_DIRECTIVES
],
// We need to tell Angular's compiler which custom pipes are in our template.
pipes: [ ],
// Our list of styles in our component. We may add more to compose many styles together
styleUrls: [ './home.style.css' ],
// Every Angular template is first compiled by the browser before Angular runs it's compiler
templateUrl: './home.template.html'
})
export class Home {
// TypeScript public modifiers
constructor(public appState: AppState) {
}
| () {
}
}
| ngOnInit | identifier_name |
backend.rs | use crate::codec::{FramedIo, Message, ZmqFramedRead, ZmqFramedWrite};
use crate::fair_queue::QueueInner;
use crate::util::PeerIdentity;
use crate::{
MultiPeerBackend, SocketBackend, SocketEvent, SocketOptions, SocketType, ZmqError, ZmqResult,
};
use async_trait::async_trait;
use crossbeam::queue::SegQueue;
use dashmap::DashMap;
use futures::channel::mpsc;
use futures::SinkExt;
use parking_lot::Mutex;
use std::sync::Arc;
pub(crate) struct Peer {
pub(crate) send_queue: ZmqFramedWrite,
}
pub(crate) struct GenericSocketBackend {
pub(crate) peers: DashMap<PeerIdentity, Peer>,
fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>,
pub(crate) round_robin: SegQueue<PeerIdentity>,
socket_type: SocketType,
socket_options: SocketOptions,
pub(crate) socket_monitor: Mutex<Option<mpsc::Sender<SocketEvent>>>,
}
impl GenericSocketBackend {
pub(crate) fn with_options(
fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>,
socket_type: SocketType,
options: SocketOptions,
) -> Self {
Self {
peers: DashMap::new(),
fair_queue_inner,
round_robin: SegQueue::new(),
socket_type,
socket_options: options,
socket_monitor: Mutex::new(None),
}
}
pub(crate) async fn send_round_robin(&self, message: Message) -> ZmqResult<PeerIdentity> {
// In normal scenario this will always be only 1 iteration
// There can be special case when peer has disconnected and his id is still in
// RR queue This happens because SegQueue don't have an api to delete
// items from queue. So in such case we'll just pop item and skip it if
// we don't have a matching peer in peers map
loop {
let next_peer_id = match self.round_robin.pop() {
Ok(peer) => peer,
Err(_) => match message {
Message::Greeting(_) => panic!("Sending greeting is not supported"),
Message::Command(_) => panic!("Sending commands is not supported"),
Message::Message(m) => {
return Err(ZmqError::ReturnToSender {
reason: "Not connected to peers. Unable to send messages",
message: m,
})
}
},
};
let send_result = match self.peers.get_mut(&next_peer_id) {
Some(mut peer) => peer.send_queue.send(message).await,
None => continue,
};
return match send_result {
Ok(()) => {
self.round_robin.push(next_peer_id.clone());
Ok(next_peer_id) | self.peer_disconnected(&next_peer_id);
Err(e.into())
}
};
}
}
}
impl SocketBackend for GenericSocketBackend {
fn socket_type(&self) -> SocketType {
self.socket_type
}
fn socket_options(&self) -> &SocketOptions {
&self.socket_options
}
fn shutdown(&self) {
self.peers.clear();
}
fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>> {
&self.socket_monitor
}
}
#[async_trait]
impl MultiPeerBackend for GenericSocketBackend {
async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo) {
let (recv_queue, send_queue) = io.into_parts();
self.peers.insert(peer_id.clone(), Peer { send_queue });
self.round_robin.push(peer_id.clone());
match &self.fair_queue_inner {
None => {}
Some(inner) => {
inner.lock().insert(peer_id.clone(), recv_queue);
}
};
}
fn peer_disconnected(&self, peer_id: &PeerIdentity) {
self.peers.remove(peer_id);
match &self.fair_queue_inner {
None => {}
Some(inner) => {
inner.lock().remove(peer_id);
}
};
}
} | }
Err(e) => { | random_line_split |
backend.rs | use crate::codec::{FramedIo, Message, ZmqFramedRead, ZmqFramedWrite};
use crate::fair_queue::QueueInner;
use crate::util::PeerIdentity;
use crate::{
MultiPeerBackend, SocketBackend, SocketEvent, SocketOptions, SocketType, ZmqError, ZmqResult,
};
use async_trait::async_trait;
use crossbeam::queue::SegQueue;
use dashmap::DashMap;
use futures::channel::mpsc;
use futures::SinkExt;
use parking_lot::Mutex;
use std::sync::Arc;
pub(crate) struct Peer {
pub(crate) send_queue: ZmqFramedWrite,
}
pub(crate) struct GenericSocketBackend {
pub(crate) peers: DashMap<PeerIdentity, Peer>,
fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>,
pub(crate) round_robin: SegQueue<PeerIdentity>,
socket_type: SocketType,
socket_options: SocketOptions,
pub(crate) socket_monitor: Mutex<Option<mpsc::Sender<SocketEvent>>>,
}
impl GenericSocketBackend {
pub(crate) fn with_options(
fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>,
socket_type: SocketType,
options: SocketOptions,
) -> Self {
Self {
peers: DashMap::new(),
fair_queue_inner,
round_robin: SegQueue::new(),
socket_type,
socket_options: options,
socket_monitor: Mutex::new(None),
}
}
pub(crate) async fn send_round_robin(&self, message: Message) -> ZmqResult<PeerIdentity> {
// In normal scenario this will always be only 1 iteration
// There can be special case when peer has disconnected and his id is still in
// RR queue This happens because SegQueue don't have an api to delete
// items from queue. So in such case we'll just pop item and skip it if
// we don't have a matching peer in peers map
loop {
let next_peer_id = match self.round_robin.pop() {
Ok(peer) => peer,
Err(_) => match message {
Message::Greeting(_) => panic!("Sending greeting is not supported"),
Message::Command(_) => panic!("Sending commands is not supported"),
Message::Message(m) => {
return Err(ZmqError::ReturnToSender {
reason: "Not connected to peers. Unable to send messages",
message: m,
})
}
},
};
let send_result = match self.peers.get_mut(&next_peer_id) {
Some(mut peer) => peer.send_queue.send(message).await,
None => continue,
};
return match send_result {
Ok(()) => {
self.round_robin.push(next_peer_id.clone());
Ok(next_peer_id)
}
Err(e) => {
self.peer_disconnected(&next_peer_id);
Err(e.into())
}
};
}
}
}
impl SocketBackend for GenericSocketBackend {
fn socket_type(&self) -> SocketType {
self.socket_type
}
fn socket_options(&self) -> &SocketOptions {
&self.socket_options
}
fn shutdown(&self) {
self.peers.clear();
}
fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>> {
&self.socket_monitor
}
}
#[async_trait]
impl MultiPeerBackend for GenericSocketBackend {
async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo) {
let (recv_queue, send_queue) = io.into_parts();
self.peers.insert(peer_id.clone(), Peer { send_queue });
self.round_robin.push(peer_id.clone());
match &self.fair_queue_inner {
None => {}
Some(inner) => {
inner.lock().insert(peer_id.clone(), recv_queue);
}
};
}
fn | (&self, peer_id: &PeerIdentity) {
self.peers.remove(peer_id);
match &self.fair_queue_inner {
None => {}
Some(inner) => {
inner.lock().remove(peer_id);
}
};
}
}
| peer_disconnected | identifier_name |
backend.rs | use crate::codec::{FramedIo, Message, ZmqFramedRead, ZmqFramedWrite};
use crate::fair_queue::QueueInner;
use crate::util::PeerIdentity;
use crate::{
MultiPeerBackend, SocketBackend, SocketEvent, SocketOptions, SocketType, ZmqError, ZmqResult,
};
use async_trait::async_trait;
use crossbeam::queue::SegQueue;
use dashmap::DashMap;
use futures::channel::mpsc;
use futures::SinkExt;
use parking_lot::Mutex;
use std::sync::Arc;
pub(crate) struct Peer {
pub(crate) send_queue: ZmqFramedWrite,
}
pub(crate) struct GenericSocketBackend {
pub(crate) peers: DashMap<PeerIdentity, Peer>,
fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>,
pub(crate) round_robin: SegQueue<PeerIdentity>,
socket_type: SocketType,
socket_options: SocketOptions,
pub(crate) socket_monitor: Mutex<Option<mpsc::Sender<SocketEvent>>>,
}
impl GenericSocketBackend {
pub(crate) fn with_options(
fair_queue_inner: Option<Arc<Mutex<QueueInner<ZmqFramedRead, PeerIdentity>>>>,
socket_type: SocketType,
options: SocketOptions,
) -> Self {
Self {
peers: DashMap::new(),
fair_queue_inner,
round_robin: SegQueue::new(),
socket_type,
socket_options: options,
socket_monitor: Mutex::new(None),
}
}
pub(crate) async fn send_round_robin(&self, message: Message) -> ZmqResult<PeerIdentity> {
// In normal scenario this will always be only 1 iteration
// There can be special case when peer has disconnected and his id is still in
// RR queue This happens because SegQueue don't have an api to delete
// items from queue. So in such case we'll just pop item and skip it if
// we don't have a matching peer in peers map
loop {
let next_peer_id = match self.round_robin.pop() {
Ok(peer) => peer,
Err(_) => match message {
Message::Greeting(_) => panic!("Sending greeting is not supported"),
Message::Command(_) => panic!("Sending commands is not supported"),
Message::Message(m) => {
return Err(ZmqError::ReturnToSender {
reason: "Not connected to peers. Unable to send messages",
message: m,
})
}
},
};
let send_result = match self.peers.get_mut(&next_peer_id) {
Some(mut peer) => peer.send_queue.send(message).await,
None => continue,
};
return match send_result {
Ok(()) => {
self.round_robin.push(next_peer_id.clone());
Ok(next_peer_id)
}
Err(e) => {
self.peer_disconnected(&next_peer_id);
Err(e.into())
}
};
}
}
}
impl SocketBackend for GenericSocketBackend {
fn socket_type(&self) -> SocketType {
self.socket_type
}
fn socket_options(&self) -> &SocketOptions {
&self.socket_options
}
fn shutdown(&self) {
self.peers.clear();
}
fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>> |
}
#[async_trait]
impl MultiPeerBackend for GenericSocketBackend {
async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo) {
let (recv_queue, send_queue) = io.into_parts();
self.peers.insert(peer_id.clone(), Peer { send_queue });
self.round_robin.push(peer_id.clone());
match &self.fair_queue_inner {
None => {}
Some(inner) => {
inner.lock().insert(peer_id.clone(), recv_queue);
}
};
}
fn peer_disconnected(&self, peer_id: &PeerIdentity) {
self.peers.remove(peer_id);
match &self.fair_queue_inner {
None => {}
Some(inner) => {
inner.lock().remove(peer_id);
}
};
}
}
| {
&self.socket_monitor
} | identifier_body |
semester.component.ts | import { Component, OnInit } from '@angular/core'
import { URLSearchParams } from '@angular/http'
import { MdDialog } from '@angular/material'
import { DataService } from '../_core/data'
import { AuthenticationService } from '../_core/security'
import { SemesterDialog } from './dialogs/semester.dialog'
import { CourseDialog } from './dialogs/course.dialog'
@Component({
selector: 'semester',
templateUrl: 'semester.component.html',
styleUrls: ['semester.component.scss']
})
export class SemesterComponent implements OnInit {
constructor(
private dataService: DataService,
private authService: AuthenticationService,
private dialog: MdDialog) {
this.getSemester()
}
semester: any
ngOnInit() {
}
private getSemester() {
var params = new URLSearchParams()
params.set('userId', this.authService.getCurrentUserId())
// @TODO add url param for specific semester
this.dataService.get('/api/semester/default', params)
.subscribe(response => {
console.log(response)
var body = response.json()
this.semester = body
}, err => {
if (err.status === 404) {
this.openSemesterDialog()
}
})
}
| () {
var dialogRef = this.dialog.open(SemesterDialog)
dialogRef.afterClosed()
.subscribe(result => {
if (result) {
this.semester = result
}
})
}
openCourseDialog() {
var dialogRef = this.dialog.open(CourseDialog)
dialogRef.componentInstance.semesterId = this.semester._id
dialogRef.afterClosed()
.subscribe(result => {
if (result) {
this.semester.courses.push(result)
}
})
}
} | openSemesterDialog | identifier_name |
semester.component.ts | import { Component, OnInit } from '@angular/core'
import { URLSearchParams } from '@angular/http'
import { MdDialog } from '@angular/material'
import { DataService } from '../_core/data'
import { AuthenticationService } from '../_core/security'
import { SemesterDialog } from './dialogs/semester.dialog'
import { CourseDialog } from './dialogs/course.dialog'
@Component({
selector: 'semester',
templateUrl: 'semester.component.html',
styleUrls: ['semester.component.scss']
})
export class SemesterComponent implements OnInit {
constructor(
private dataService: DataService,
private authService: AuthenticationService,
private dialog: MdDialog) {
this.getSemester()
}
semester: any
ngOnInit() {
}
private getSemester() {
var params = new URLSearchParams()
params.set('userId', this.authService.getCurrentUserId())
// @TODO add url param for specific semester
this.dataService.get('/api/semester/default', params)
.subscribe(response => {
console.log(response)
var body = response.json()
this.semester = body
}, err => {
if (err.status === 404) {
this.openSemesterDialog()
}
})
}
openSemesterDialog() {
var dialogRef = this.dialog.open(SemesterDialog)
dialogRef.afterClosed()
.subscribe(result => {
if (result) |
})
}
openCourseDialog() {
var dialogRef = this.dialog.open(CourseDialog)
dialogRef.componentInstance.semesterId = this.semester._id
dialogRef.afterClosed()
.subscribe(result => {
if (result) {
this.semester.courses.push(result)
}
})
}
} | {
this.semester = result
} | conditional_block |
semester.component.ts | import { Component, OnInit } from '@angular/core'
import { URLSearchParams } from '@angular/http'
import { MdDialog } from '@angular/material'
import { DataService } from '../_core/data'
import { AuthenticationService } from '../_core/security'
import { SemesterDialog } from './dialogs/semester.dialog'
import { CourseDialog } from './dialogs/course.dialog'
@Component({
selector: 'semester',
templateUrl: 'semester.component.html',
styleUrls: ['semester.component.scss']
})
export class SemesterComponent implements OnInit {
constructor(
private dataService: DataService,
private authService: AuthenticationService,
private dialog: MdDialog) {
this.getSemester()
}
semester: any
ngOnInit() {
}
private getSemester() {
var params = new URLSearchParams()
params.set('userId', this.authService.getCurrentUserId())
// @TODO add url param for specific semester
this.dataService.get('/api/semester/default', params)
.subscribe(response => {
console.log(response)
var body = response.json()
this.semester = body
}, err => {
if (err.status === 404) {
this.openSemesterDialog()
}
})
}
openSemesterDialog() {
var dialogRef = this.dialog.open(SemesterDialog)
dialogRef.afterClosed()
.subscribe(result => {
if (result) {
this.semester = result
}
})
}
openCourseDialog() |
} | {
var dialogRef = this.dialog.open(CourseDialog)
dialogRef.componentInstance.semesterId = this.semester._id
dialogRef.afterClosed()
.subscribe(result => {
if (result) {
this.semester.courses.push(result)
}
})
} | identifier_body |
semester.component.ts | import { Component, OnInit } from '@angular/core'
import { URLSearchParams } from '@angular/http'
import { MdDialog } from '@angular/material'
import { DataService } from '../_core/data'
import { AuthenticationService } from '../_core/security'
import { SemesterDialog } from './dialogs/semester.dialog'
import { CourseDialog } from './dialogs/course.dialog'
@Component({
selector: 'semester',
templateUrl: 'semester.component.html',
styleUrls: ['semester.component.scss']
})
export class SemesterComponent implements OnInit {
constructor(
private dataService: DataService,
private authService: AuthenticationService,
private dialog: MdDialog) {
this.getSemester()
}
semester: any
ngOnInit() {
}
private getSemester() {
var params = new URLSearchParams()
params.set('userId', this.authService.getCurrentUserId())
// @TODO add url param for specific semester
this.dataService.get('/api/semester/default', params)
.subscribe(response => {
console.log(response)
var body = response.json()
this.semester = body
}, err => {
if (err.status === 404) {
this.openSemesterDialog()
}
})
}
openSemesterDialog() {
var dialogRef = this.dialog.open(SemesterDialog)
dialogRef.afterClosed()
.subscribe(result => {
if (result) {
this.semester = result
}
})
}
openCourseDialog() {
var dialogRef = this.dialog.open(CourseDialog)
dialogRef.componentInstance.semesterId = this.semester._id
dialogRef.afterClosed()
.subscribe(result => {
if (result) {
this.semester.courses.push(result) | })
}
} | } | random_line_split |
color.js | /**
* @module zrender/tool/color
*/
var kCSSColorTable = {
'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
'beige': [245,245,220,1], 'bisque': [255,228,196,1],
'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
'gray': [128,128,128,1], 'green': [0,128,0,1],
'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
'orange': [255,165,0,1], 'orangered': [255,69,0,1],
'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
'pink': [255,192,203,1], 'plum': [221,160,221,1],
'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
'sienna': [160,82,45,1], 'silver': [192,192,192,1],
'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
'teal': [0,128,128,1], 'thistle': [216,191,216,1],
'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
'violet': [238,130,238,1], 'wheat': [245,222,179,1],
'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
};
function clampCssByte(i) { // Clamp to integer 0 .. 255.
i = Math.round(i); // Seems to be what Chrome does (vs truncation).
return i < 0 ? 0 : i > 255 ? 255 : i;
}
function clampCssAngle(i) { // Clamp to integer 0 .. 360.
i = Math.round(i); // Seems to be what Chrome does (vs truncation).
return i < 0 ? 0 : i > 360 ? 360 : i;
}
function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
return f < 0 ? 0 : f > 1 ? 1 : f;
}
function parseCssInt(str) { // int or percentage.
if (str.length && str.charAt(str.length - 1) === '%') {
return clampCssByte(parseFloat(str) / 100 * 255);
}
return clampCssByte(parseInt(str, 10));
}
function parseCssFloat(str) { // float or percentage.
if (str.length && str.charAt(str.length - 1) === '%') {
return clampCssFloat(parseFloat(str) / 100);
}
return clampCssFloat(parseFloat(str));
}
function cssHueToRgb(m1, m2, h) {
if (h < 0) {
h += 1;
}
else if (h > 1) {
h -= 1;
}
if (h * 6 < 1) {
return m1 + (m2 - m1) * h * 6;
}
if (h * 2 < 1) {
return m2;
}
if (h * 3 < 2) {
return m1 + (m2 - m1) * (2/3 - h) * 6;
}
return m1;
}
function lerp(a, b, p) {
return a + (b - a) * p;
}
/**
* @param {string} colorStr
* @return {Array.<number>}
* @memberOf module:zrender/util/color
*/
function parse(colorStr) {
if (!colorStr) {
return;
}
// colorStr may be not string
colorStr = colorStr + '';
// Remove all whitespace, not compliant, but should just be more accepting.
var str = colorStr.replace(/ /g, '').toLowerCase();
// Color keywords (and transparent) lookup.
if (str in kCSSColorTable) {
return kCSSColorTable[str].slice(); // dup.
}
// #abc and #abc123 syntax.
if (str.charAt(0) === '#') {
if (str.length === 4) {
var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
if (!(iv >= 0 && iv <= 0xfff)) {
return; // Covers NaN.
}
return [
((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
(iv & 0xf0) | ((iv & 0xf0) >> 4),
(iv & 0xf) | ((iv & 0xf) << 4),
1
];
}
else if (str.length === 7) {
var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
if (!(iv >= 0 && iv <= 0xffffff)) {
return; // Covers NaN.
}
return [
(iv & 0xff0000) >> 16,
(iv & 0xff00) >> 8,
iv & 0xff,
1
];
}
return;
}
var op = str.indexOf('('), ep = str.indexOf(')');
if (op !== -1 && ep + 1 === str.length) {
var fname = str.substr(0, op);
var params = str.substr(op + 1, ep - (op + 1)).split(',');
var alpha = 1; // To allow case fallthrough.
switch (fname) {
case 'rgba':
if (params.length !== 4) {
return;
}
alpha = parseCssFloat(params.pop()); // jshint ignore:line
// Fall through.
case 'rgb':
if (params.length !== 3) {
return;
}
return [
parseCssInt(params[0]),
parseCssInt(params[1]),
parseCssInt(params[2]),
alpha
];
case 'hsla':
if (params.length !== 4) {
return;
}
params[3] = parseCssFloat(params[3]);
return hsla2rgba(params);
case 'hsl':
if (params.length !== 3) {
return;
}
return hsla2rgba(params);
default:
return;
}
}
return;
}
/**
* @param {Array.<number>} hsla
* @return {Array.<number>} rgba
*/
function hsla2rgba(hsla) {
var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
// NOTE(deanm): According to the CSS spec s/l should only be
// percentages, but we don't bother and let float or percentage.
var s = parseCssFloat(hsla[1]);
var l = parseCssFloat(hsla[2]);
var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
var m1 = l * 2 - m2;
var rgba = [
clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
clampCssByte(cssHueToRgb(m1, m2, h) * 255),
clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255)
];
if (hsla.length === 4) {
rgba[3] = hsla[3];
}
return rgba;
}
/**
* @param {Array.<number>} rgba
* @return {Array.<number>} hsla
*/
function | (rgba) {
if (!rgba) {
return;
}
// RGB from 0 to 255
var R = rgba[0] / 255;
var G = rgba[1] / 255;
var B = rgba[2] / 255;
var vMin = Math.min(R, G, B); // Min. value of RGB
var vMax = Math.max(R, G, B); // Max. value of RGB
var delta = vMax - vMin; // Delta RGB value
var L = (vMax + vMin) / 2;
var H;
var S;
// HSL results from 0 to 1
if (delta === 0) {
H = 0;
S = 0;
}
else {
if (L < 0.5) {
S = delta / (vMax + vMin);
}
else {
S = delta / (2 - vMax - vMin);
}
var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
if (R === vMax) {
H = deltaB - deltaG;
}
else if (G === vMax) {
H = (1 / 3) + deltaR - deltaB;
}
else if (B === vMax) {
H = (2 / 3) + deltaG - deltaR;
}
if (H < 0) {
H += 1;
}
if (H > 1) {
H -= 1;
}
}
var hsla = [H * 360, S, L];
if (rgba[3] != null) {
hsla.push(rgba[3]);
}
return hsla;
}
/**
* @param {string} color
* @param {number} level
* @return {string}
* @memberOf module:zrender/util/color
*/
function lift(color, level) {
var colorArr = parse(color);
if (colorArr) {
for (var i = 0; i < 3; i++) {
if (level < 0) {
colorArr[i] = colorArr[i] * (1 - level) | 0;
}
else {
colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
}
}
return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
}
}
/**
* @param {string} color
* @return {string}
* @memberOf module:zrender/util/color
*/
function toHex(color, level) {
var colorArr = parse(color);
if (colorArr) {
return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
}
}
/**
* Map value to color. Faster than mapToColor methods because color is represented by rgba array
* @param {number} normalizedValue A float between 0 and 1.
* @param {Array.<Array.<number>>} colors List of rgba color array
* @param {Array.<number>} [out] Mapped gba color array
* @return {Array.<number>}
*/
function fastMapToColor(normalizedValue, colors, out) {
if (!(colors && colors.length)
|| !(normalizedValue >= 0 && normalizedValue <= 1)
) {
return;
}
out = out || [0, 0, 0, 0];
var value = normalizedValue * (colors.length - 1);
var leftIndex = Math.floor(value);
var rightIndex = Math.ceil(value);
var leftColor = colors[leftIndex];
var rightColor = colors[rightIndex];
var dv = value - leftIndex;
out[0] = clampCssByte(lerp(leftColor[0], rightColor[0], dv));
out[1] = clampCssByte(lerp(leftColor[1], rightColor[1], dv));
out[2] = clampCssByte(lerp(leftColor[2], rightColor[2], dv));
out[3] = clampCssByte(lerp(leftColor[3], rightColor[3], dv));
return out;
}
/**
* @param {number} normalizedValue A float between 0 and 1.
* @param {Array.<string>} colors Color list.
* @param {boolean=} fullOutput Default false.
* @return {(string|Object)} Result color. If fullOutput,
* return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
* @memberOf module:zrender/util/color
*/
function mapToColor(normalizedValue, colors, fullOutput) {
if (!(colors && colors.length)
|| !(normalizedValue >= 0 && normalizedValue <= 1)
) {
return;
}
var value = normalizedValue * (colors.length - 1);
var leftIndex = Math.floor(value);
var rightIndex = Math.ceil(value);
var leftColor = parse(colors[leftIndex]);
var rightColor = parse(colors[rightIndex]);
var dv = value - leftIndex;
var color = stringify(
[
clampCssByte(lerp(leftColor[0], rightColor[0], dv)),
clampCssByte(lerp(leftColor[1], rightColor[1], dv)),
clampCssByte(lerp(leftColor[2], rightColor[2], dv)),
clampCssFloat(lerp(leftColor[3], rightColor[3], dv))
],
'rgba'
);
return fullOutput
? {
color: color,
leftIndex: leftIndex,
rightIndex: rightIndex,
value: value
}
: color;
}
/**
* @param {string} color
* @param {number=} h 0 ~ 360, ignore when null.
* @param {number=} s 0 ~ 1, ignore when null.
* @param {number=} l 0 ~ 1, ignore when null.
* @return {string} Color string in rgba format.
* @memberOf module:zrender/util/color
*/
function modifyHSL(color, h, s, l) {
color = parse(color);
if (color) {
color = rgba2hsla(color);
h != null && (color[0] = clampCssAngle(h));
s != null && (color[1] = parseCssFloat(s));
l != null && (color[2] = parseCssFloat(l));
return stringify(hsla2rgba(color), 'rgba');
}
}
/**
* @param {string} color
* @param {number=} alpha 0 ~ 1
* @return {string} Color string in rgba format.
* @memberOf module:zrender/util/color
*/
function modifyAlpha(color, alpha) {
color = parse(color);
if (color && alpha != null) {
color[3] = clampCssFloat(alpha);
return stringify(color, 'rgba');
}
}
/**
* @param {Array.<string>} colors Color list.
* @param {string} type 'rgba', 'hsva', ...
* @return {string} Result color.
*/
function stringify(arrColor, type) {
var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
colorStr += ',' + arrColor[3];
}
return type + '(' + colorStr + ')';
}
module.exports = {
parse: parse,
lift: lift,
toHex: toHex,
fastMapToColor: fastMapToColor,
mapToColor: mapToColor,
modifyHSL: modifyHSL,
modifyAlpha: modifyAlpha,
stringify: stringify
};
| rgba2hsla | identifier_name |
color.js | /**
* @module zrender/tool/color
*/
var kCSSColorTable = {
'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
'beige': [245,245,220,1], 'bisque': [255,228,196,1],
'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
'gray': [128,128,128,1], 'green': [0,128,0,1],
'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
'orange': [255,165,0,1], 'orangered': [255,69,0,1],
'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
'pink': [255,192,203,1], 'plum': [221,160,221,1],
'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
'sienna': [160,82,45,1], 'silver': [192,192,192,1],
'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
'teal': [0,128,128,1], 'thistle': [216,191,216,1],
'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
'violet': [238,130,238,1], 'wheat': [245,222,179,1],
'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
};
function clampCssByte(i) { // Clamp to integer 0 .. 255.
i = Math.round(i); // Seems to be what Chrome does (vs truncation).
return i < 0 ? 0 : i > 255 ? 255 : i;
}
function clampCssAngle(i) { // Clamp to integer 0 .. 360.
i = Math.round(i); // Seems to be what Chrome does (vs truncation).
return i < 0 ? 0 : i > 360 ? 360 : i;
}
function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
return f < 0 ? 0 : f > 1 ? 1 : f;
}
function parseCssInt(str) { // int or percentage.
if (str.length && str.charAt(str.length - 1) === '%') {
return clampCssByte(parseFloat(str) / 100 * 255);
}
return clampCssByte(parseInt(str, 10));
}
function parseCssFloat(str) { // float or percentage.
if (str.length && str.charAt(str.length - 1) === '%') {
return clampCssFloat(parseFloat(str) / 100);
}
return clampCssFloat(parseFloat(str));
}
function cssHueToRgb(m1, m2, h) {
if (h < 0) {
h += 1;
}
else if (h > 1) {
h -= 1;
}
if (h * 6 < 1) {
return m1 + (m2 - m1) * h * 6;
}
if (h * 2 < 1) {
return m2;
}
if (h * 3 < 2) {
return m1 + (m2 - m1) * (2/3 - h) * 6;
}
return m1;
}
function lerp(a, b, p) {
return a + (b - a) * p;
}
/**
* @param {string} colorStr
* @return {Array.<number>}
* @memberOf module:zrender/util/color
*/
function parse(colorStr) {
if (!colorStr) {
return;
}
// colorStr may be not string
colorStr = colorStr + '';
// Remove all whitespace, not compliant, but should just be more accepting.
var str = colorStr.replace(/ /g, '').toLowerCase();
// Color keywords (and transparent) lookup.
if (str in kCSSColorTable) {
return kCSSColorTable[str].slice(); // dup.
}
// #abc and #abc123 syntax.
if (str.charAt(0) === '#') {
if (str.length === 4) {
var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
if (!(iv >= 0 && iv <= 0xfff)) {
return; // Covers NaN.
}
return [
((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
(iv & 0xf0) | ((iv & 0xf0) >> 4),
(iv & 0xf) | ((iv & 0xf) << 4),
1
];
}
else if (str.length === 7) {
var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
if (!(iv >= 0 && iv <= 0xffffff)) {
return; // Covers NaN.
}
return [
(iv & 0xff0000) >> 16,
(iv & 0xff00) >> 8,
iv & 0xff,
1
];
}
return;
}
var op = str.indexOf('('), ep = str.indexOf(')');
if (op !== -1 && ep + 1 === str.length) {
var fname = str.substr(0, op);
var params = str.substr(op + 1, ep - (op + 1)).split(',');
var alpha = 1; // To allow case fallthrough.
switch (fname) {
case 'rgba':
if (params.length !== 4) {
return;
}
alpha = parseCssFloat(params.pop()); // jshint ignore:line
// Fall through.
case 'rgb':
if (params.length !== 3) {
return;
}
return [
parseCssInt(params[0]),
parseCssInt(params[1]),
parseCssInt(params[2]),
alpha
];
case 'hsla':
if (params.length !== 4) {
return;
}
params[3] = parseCssFloat(params[3]);
return hsla2rgba(params);
case 'hsl':
if (params.length !== 3) {
return;
}
return hsla2rgba(params);
default:
return;
}
}
return;
}
/**
* @param {Array.<number>} hsla
* @return {Array.<number>} rgba
*/
function hsla2rgba(hsla) {
var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
// NOTE(deanm): According to the CSS spec s/l should only be
// percentages, but we don't bother and let float or percentage.
var s = parseCssFloat(hsla[1]);
var l = parseCssFloat(hsla[2]);
var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
var m1 = l * 2 - m2;
var rgba = [
clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
clampCssByte(cssHueToRgb(m1, m2, h) * 255),
clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255)
];
if (hsla.length === 4) {
rgba[3] = hsla[3];
}
return rgba;
}
/**
* @param {Array.<number>} rgba
* @return {Array.<number>} hsla
*/
function rgba2hsla(rgba) {
if (!rgba) {
return;
}
// RGB from 0 to 255
var R = rgba[0] / 255;
var G = rgba[1] / 255;
var B = rgba[2] / 255;
var vMin = Math.min(R, G, B); // Min. value of RGB
var vMax = Math.max(R, G, B); // Max. value of RGB
var delta = vMax - vMin; // Delta RGB value
var L = (vMax + vMin) / 2;
var H;
var S;
// HSL results from 0 to 1
if (delta === 0) {
H = 0;
S = 0;
}
else {
if (L < 0.5) {
S = delta / (vMax + vMin);
}
else {
S = delta / (2 - vMax - vMin);
}
var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
if (R === vMax) {
H = deltaB - deltaG;
}
else if (G === vMax) {
H = (1 / 3) + deltaR - deltaB;
}
else if (B === vMax) {
H = (2 / 3) + deltaG - deltaR;
}
| }
if (H > 1) {
H -= 1;
}
}
var hsla = [H * 360, S, L];
if (rgba[3] != null) {
hsla.push(rgba[3]);
}
return hsla;
}
/**
* @param {string} color
* @param {number} level
* @return {string}
* @memberOf module:zrender/util/color
*/
function lift(color, level) {
var colorArr = parse(color);
if (colorArr) {
for (var i = 0; i < 3; i++) {
if (level < 0) {
colorArr[i] = colorArr[i] * (1 - level) | 0;
}
else {
colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
}
}
return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
}
}
/**
* @param {string} color
* @return {string}
* @memberOf module:zrender/util/color
*/
function toHex(color, level) {
var colorArr = parse(color);
if (colorArr) {
return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
}
}
/**
* Map value to color. Faster than mapToColor methods because color is represented by rgba array
* @param {number} normalizedValue A float between 0 and 1.
* @param {Array.<Array.<number>>} colors List of rgba color array
* @param {Array.<number>} [out] Mapped gba color array
* @return {Array.<number>}
*/
function fastMapToColor(normalizedValue, colors, out) {
if (!(colors && colors.length)
|| !(normalizedValue >= 0 && normalizedValue <= 1)
) {
return;
}
out = out || [0, 0, 0, 0];
var value = normalizedValue * (colors.length - 1);
var leftIndex = Math.floor(value);
var rightIndex = Math.ceil(value);
var leftColor = colors[leftIndex];
var rightColor = colors[rightIndex];
var dv = value - leftIndex;
out[0] = clampCssByte(lerp(leftColor[0], rightColor[0], dv));
out[1] = clampCssByte(lerp(leftColor[1], rightColor[1], dv));
out[2] = clampCssByte(lerp(leftColor[2], rightColor[2], dv));
out[3] = clampCssByte(lerp(leftColor[3], rightColor[3], dv));
return out;
}
/**
* @param {number} normalizedValue A float between 0 and 1.
* @param {Array.<string>} colors Color list.
* @param {boolean=} fullOutput Default false.
* @return {(string|Object)} Result color. If fullOutput,
* return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
* @memberOf module:zrender/util/color
*/
function mapToColor(normalizedValue, colors, fullOutput) {
if (!(colors && colors.length)
|| !(normalizedValue >= 0 && normalizedValue <= 1)
) {
return;
}
var value = normalizedValue * (colors.length - 1);
var leftIndex = Math.floor(value);
var rightIndex = Math.ceil(value);
var leftColor = parse(colors[leftIndex]);
var rightColor = parse(colors[rightIndex]);
var dv = value - leftIndex;
var color = stringify(
[
clampCssByte(lerp(leftColor[0], rightColor[0], dv)),
clampCssByte(lerp(leftColor[1], rightColor[1], dv)),
clampCssByte(lerp(leftColor[2], rightColor[2], dv)),
clampCssFloat(lerp(leftColor[3], rightColor[3], dv))
],
'rgba'
);
return fullOutput
? {
color: color,
leftIndex: leftIndex,
rightIndex: rightIndex,
value: value
}
: color;
}
/**
* @param {string} color
* @param {number=} h 0 ~ 360, ignore when null.
* @param {number=} s 0 ~ 1, ignore when null.
* @param {number=} l 0 ~ 1, ignore when null.
* @return {string} Color string in rgba format.
* @memberOf module:zrender/util/color
*/
function modifyHSL(color, h, s, l) {
color = parse(color);
if (color) {
color = rgba2hsla(color);
h != null && (color[0] = clampCssAngle(h));
s != null && (color[1] = parseCssFloat(s));
l != null && (color[2] = parseCssFloat(l));
return stringify(hsla2rgba(color), 'rgba');
}
}
/**
* @param {string} color
* @param {number=} alpha 0 ~ 1
* @return {string} Color string in rgba format.
* @memberOf module:zrender/util/color
*/
function modifyAlpha(color, alpha) {
color = parse(color);
if (color && alpha != null) {
color[3] = clampCssFloat(alpha);
return stringify(color, 'rgba');
}
}
/**
* @param {Array.<string>} colors Color list.
* @param {string} type 'rgba', 'hsva', ...
* @return {string} Result color.
*/
function stringify(arrColor, type) {
var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
colorStr += ',' + arrColor[3];
}
return type + '(' + colorStr + ')';
}
module.exports = {
parse: parse,
lift: lift,
toHex: toHex,
fastMapToColor: fastMapToColor,
mapToColor: mapToColor,
modifyHSL: modifyHSL,
modifyAlpha: modifyAlpha,
stringify: stringify
}; | if (H < 0) {
H += 1; | random_line_split |
color.js | /**
* @module zrender/tool/color
*/
var kCSSColorTable = {
'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
'beige': [245,245,220,1], 'bisque': [255,228,196,1],
'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
'gray': [128,128,128,1], 'green': [0,128,0,1],
'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
'orange': [255,165,0,1], 'orangered': [255,69,0,1],
'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
'pink': [255,192,203,1], 'plum': [221,160,221,1],
'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
'sienna': [160,82,45,1], 'silver': [192,192,192,1],
'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
'teal': [0,128,128,1], 'thistle': [216,191,216,1],
'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
'violet': [238,130,238,1], 'wheat': [245,222,179,1],
'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
};
function clampCssByte(i) { // Clamp to integer 0 .. 255.
i = Math.round(i); // Seems to be what Chrome does (vs truncation).
return i < 0 ? 0 : i > 255 ? 255 : i;
}
function clampCssAngle(i) { // Clamp to integer 0 .. 360.
i = Math.round(i); // Seems to be what Chrome does (vs truncation).
return i < 0 ? 0 : i > 360 ? 360 : i;
}
function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
return f < 0 ? 0 : f > 1 ? 1 : f;
}
function parseCssInt(str) { // int or percentage.
if (str.length && str.charAt(str.length - 1) === '%') {
return clampCssByte(parseFloat(str) / 100 * 255);
}
return clampCssByte(parseInt(str, 10));
}
function parseCssFloat(str) { // float or percentage.
if (str.length && str.charAt(str.length - 1) === '%') {
return clampCssFloat(parseFloat(str) / 100);
}
return clampCssFloat(parseFloat(str));
}
function cssHueToRgb(m1, m2, h) {
if (h < 0) {
h += 1;
}
else if (h > 1) {
h -= 1;
}
if (h * 6 < 1) {
return m1 + (m2 - m1) * h * 6;
}
if (h * 2 < 1) {
return m2;
}
if (h * 3 < 2) {
return m1 + (m2 - m1) * (2/3 - h) * 6;
}
return m1;
}
function lerp(a, b, p) {
return a + (b - a) * p;
}
/**
* @param {string} colorStr
* @return {Array.<number>}
* @memberOf module:zrender/util/color
*/
function parse(colorStr) {
if (!colorStr) {
return;
}
// colorStr may be not string
colorStr = colorStr + '';
// Remove all whitespace, not compliant, but should just be more accepting.
var str = colorStr.replace(/ /g, '').toLowerCase();
// Color keywords (and transparent) lookup.
if (str in kCSSColorTable) {
return kCSSColorTable[str].slice(); // dup.
}
// #abc and #abc123 syntax.
if (str.charAt(0) === '#') {
if (str.length === 4) {
var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
if (!(iv >= 0 && iv <= 0xfff)) {
return; // Covers NaN.
}
return [
((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
(iv & 0xf0) | ((iv & 0xf0) >> 4),
(iv & 0xf) | ((iv & 0xf) << 4),
1
];
}
else if (str.length === 7) {
var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
if (!(iv >= 0 && iv <= 0xffffff)) {
return; // Covers NaN.
}
return [
(iv & 0xff0000) >> 16,
(iv & 0xff00) >> 8,
iv & 0xff,
1
];
}
return;
}
var op = str.indexOf('('), ep = str.indexOf(')');
if (op !== -1 && ep + 1 === str.length) {
var fname = str.substr(0, op);
var params = str.substr(op + 1, ep - (op + 1)).split(',');
var alpha = 1; // To allow case fallthrough.
switch (fname) {
case 'rgba':
if (params.length !== 4) {
return;
}
alpha = parseCssFloat(params.pop()); // jshint ignore:line
// Fall through.
case 'rgb':
if (params.length !== 3) {
return;
}
return [
parseCssInt(params[0]),
parseCssInt(params[1]),
parseCssInt(params[2]),
alpha
];
case 'hsla':
if (params.length !== 4) {
return;
}
params[3] = parseCssFloat(params[3]);
return hsla2rgba(params);
case 'hsl':
if (params.length !== 3) {
return;
}
return hsla2rgba(params);
default:
return;
}
}
return;
}
/**
* @param {Array.<number>} hsla
* @return {Array.<number>} rgba
*/
function hsla2rgba(hsla) {
var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
// NOTE(deanm): According to the CSS spec s/l should only be
// percentages, but we don't bother and let float or percentage.
var s = parseCssFloat(hsla[1]);
var l = parseCssFloat(hsla[2]);
var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
var m1 = l * 2 - m2;
var rgba = [
clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
clampCssByte(cssHueToRgb(m1, m2, h) * 255),
clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255)
];
if (hsla.length === 4) |
return rgba;
}
/**
* @param {Array.<number>} rgba
* @return {Array.<number>} hsla
*/
function rgba2hsla(rgba) {
if (!rgba) {
return;
}
// RGB from 0 to 255
var R = rgba[0] / 255;
var G = rgba[1] / 255;
var B = rgba[2] / 255;
var vMin = Math.min(R, G, B); // Min. value of RGB
var vMax = Math.max(R, G, B); // Max. value of RGB
var delta = vMax - vMin; // Delta RGB value
var L = (vMax + vMin) / 2;
var H;
var S;
// HSL results from 0 to 1
if (delta === 0) {
H = 0;
S = 0;
}
else {
if (L < 0.5) {
S = delta / (vMax + vMin);
}
else {
S = delta / (2 - vMax - vMin);
}
var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
if (R === vMax) {
H = deltaB - deltaG;
}
else if (G === vMax) {
H = (1 / 3) + deltaR - deltaB;
}
else if (B === vMax) {
H = (2 / 3) + deltaG - deltaR;
}
if (H < 0) {
H += 1;
}
if (H > 1) {
H -= 1;
}
}
var hsla = [H * 360, S, L];
if (rgba[3] != null) {
hsla.push(rgba[3]);
}
return hsla;
}
/**
* @param {string} color
* @param {number} level
* @return {string}
* @memberOf module:zrender/util/color
*/
function lift(color, level) {
var colorArr = parse(color);
if (colorArr) {
for (var i = 0; i < 3; i++) {
if (level < 0) {
colorArr[i] = colorArr[i] * (1 - level) | 0;
}
else {
colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
}
}
return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
}
}
/**
* @param {string} color
* @return {string}
* @memberOf module:zrender/util/color
*/
function toHex(color, level) {
var colorArr = parse(color);
if (colorArr) {
return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
}
}
/**
* Map value to color. Faster than mapToColor methods because color is represented by rgba array
* @param {number} normalizedValue A float between 0 and 1.
* @param {Array.<Array.<number>>} colors List of rgba color array
* @param {Array.<number>} [out] Mapped gba color array
* @return {Array.<number>}
*/
function fastMapToColor(normalizedValue, colors, out) {
if (!(colors && colors.length)
|| !(normalizedValue >= 0 && normalizedValue <= 1)
) {
return;
}
out = out || [0, 0, 0, 0];
var value = normalizedValue * (colors.length - 1);
var leftIndex = Math.floor(value);
var rightIndex = Math.ceil(value);
var leftColor = colors[leftIndex];
var rightColor = colors[rightIndex];
var dv = value - leftIndex;
out[0] = clampCssByte(lerp(leftColor[0], rightColor[0], dv));
out[1] = clampCssByte(lerp(leftColor[1], rightColor[1], dv));
out[2] = clampCssByte(lerp(leftColor[2], rightColor[2], dv));
out[3] = clampCssByte(lerp(leftColor[3], rightColor[3], dv));
return out;
}
/**
* @param {number} normalizedValue A float between 0 and 1.
* @param {Array.<string>} colors Color list.
* @param {boolean=} fullOutput Default false.
* @return {(string|Object)} Result color. If fullOutput,
* return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
* @memberOf module:zrender/util/color
*/
function mapToColor(normalizedValue, colors, fullOutput) {
if (!(colors && colors.length)
|| !(normalizedValue >= 0 && normalizedValue <= 1)
) {
return;
}
var value = normalizedValue * (colors.length - 1);
var leftIndex = Math.floor(value);
var rightIndex = Math.ceil(value);
var leftColor = parse(colors[leftIndex]);
var rightColor = parse(colors[rightIndex]);
var dv = value - leftIndex;
var color = stringify(
[
clampCssByte(lerp(leftColor[0], rightColor[0], dv)),
clampCssByte(lerp(leftColor[1], rightColor[1], dv)),
clampCssByte(lerp(leftColor[2], rightColor[2], dv)),
clampCssFloat(lerp(leftColor[3], rightColor[3], dv))
],
'rgba'
);
return fullOutput
? {
color: color,
leftIndex: leftIndex,
rightIndex: rightIndex,
value: value
}
: color;
}
/**
* @param {string} color
* @param {number=} h 0 ~ 360, ignore when null.
* @param {number=} s 0 ~ 1, ignore when null.
* @param {number=} l 0 ~ 1, ignore when null.
* @return {string} Color string in rgba format.
* @memberOf module:zrender/util/color
*/
function modifyHSL(color, h, s, l) {
color = parse(color);
if (color) {
color = rgba2hsla(color);
h != null && (color[0] = clampCssAngle(h));
s != null && (color[1] = parseCssFloat(s));
l != null && (color[2] = parseCssFloat(l));
return stringify(hsla2rgba(color), 'rgba');
}
}
/**
* @param {string} color
* @param {number=} alpha 0 ~ 1
* @return {string} Color string in rgba format.
* @memberOf module:zrender/util/color
*/
function modifyAlpha(color, alpha) {
color = parse(color);
if (color && alpha != null) {
color[3] = clampCssFloat(alpha);
return stringify(color, 'rgba');
}
}
/**
* @param {Array.<string>} colors Color list.
* @param {string} type 'rgba', 'hsva', ...
* @return {string} Result color.
*/
function stringify(arrColor, type) {
var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
colorStr += ',' + arrColor[3];
}
return type + '(' + colorStr + ')';
}
module.exports = {
parse: parse,
lift: lift,
toHex: toHex,
fastMapToColor: fastMapToColor,
mapToColor: mapToColor,
modifyHSL: modifyHSL,
modifyAlpha: modifyAlpha,
stringify: stringify
};
| {
rgba[3] = hsla[3];
} | conditional_block |
color.js | /**
* @module zrender/tool/color
*/
var kCSSColorTable = {
'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
'beige': [245,245,220,1], 'bisque': [255,228,196,1],
'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
'gray': [128,128,128,1], 'green': [0,128,0,1],
'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
'orange': [255,165,0,1], 'orangered': [255,69,0,1],
'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
'pink': [255,192,203,1], 'plum': [221,160,221,1],
'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
'sienna': [160,82,45,1], 'silver': [192,192,192,1],
'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
'teal': [0,128,128,1], 'thistle': [216,191,216,1],
'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
'violet': [238,130,238,1], 'wheat': [245,222,179,1],
'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
};
function clampCssByte(i) { // Clamp to integer 0 .. 255.
i = Math.round(i); // Seems to be what Chrome does (vs truncation).
return i < 0 ? 0 : i > 255 ? 255 : i;
}
function clampCssAngle(i) { // Clamp to integer 0 .. 360.
i = Math.round(i); // Seems to be what Chrome does (vs truncation).
return i < 0 ? 0 : i > 360 ? 360 : i;
}
function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
return f < 0 ? 0 : f > 1 ? 1 : f;
}
function parseCssInt(str) { // int or percentage.
if (str.length && str.charAt(str.length - 1) === '%') {
return clampCssByte(parseFloat(str) / 100 * 255);
}
return clampCssByte(parseInt(str, 10));
}
function parseCssFloat(str) { // float or percentage.
if (str.length && str.charAt(str.length - 1) === '%') {
return clampCssFloat(parseFloat(str) / 100);
}
return clampCssFloat(parseFloat(str));
}
function cssHueToRgb(m1, m2, h) {
if (h < 0) {
h += 1;
}
else if (h > 1) {
h -= 1;
}
if (h * 6 < 1) {
return m1 + (m2 - m1) * h * 6;
}
if (h * 2 < 1) {
return m2;
}
if (h * 3 < 2) {
return m1 + (m2 - m1) * (2/3 - h) * 6;
}
return m1;
}
function lerp(a, b, p) {
return a + (b - a) * p;
}
/**
* @param {string} colorStr
* @return {Array.<number>}
* @memberOf module:zrender/util/color
*/
function parse(colorStr) |
/**
* @param {Array.<number>} hsla
* @return {Array.<number>} rgba
*/
function hsla2rgba(hsla) {
var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
// NOTE(deanm): According to the CSS spec s/l should only be
// percentages, but we don't bother and let float or percentage.
var s = parseCssFloat(hsla[1]);
var l = parseCssFloat(hsla[2]);
var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
var m1 = l * 2 - m2;
var rgba = [
clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
clampCssByte(cssHueToRgb(m1, m2, h) * 255),
clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255)
];
if (hsla.length === 4) {
rgba[3] = hsla[3];
}
return rgba;
}
/**
* @param {Array.<number>} rgba
* @return {Array.<number>} hsla
*/
function rgba2hsla(rgba) {
if (!rgba) {
return;
}
// RGB from 0 to 255
var R = rgba[0] / 255;
var G = rgba[1] / 255;
var B = rgba[2] / 255;
var vMin = Math.min(R, G, B); // Min. value of RGB
var vMax = Math.max(R, G, B); // Max. value of RGB
var delta = vMax - vMin; // Delta RGB value
var L = (vMax + vMin) / 2;
var H;
var S;
// HSL results from 0 to 1
if (delta === 0) {
H = 0;
S = 0;
}
else {
if (L < 0.5) {
S = delta / (vMax + vMin);
}
else {
S = delta / (2 - vMax - vMin);
}
var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
if (R === vMax) {
H = deltaB - deltaG;
}
else if (G === vMax) {
H = (1 / 3) + deltaR - deltaB;
}
else if (B === vMax) {
H = (2 / 3) + deltaG - deltaR;
}
if (H < 0) {
H += 1;
}
if (H > 1) {
H -= 1;
}
}
var hsla = [H * 360, S, L];
if (rgba[3] != null) {
hsla.push(rgba[3]);
}
return hsla;
}
/**
* @param {string} color
* @param {number} level
* @return {string}
* @memberOf module:zrender/util/color
*/
function lift(color, level) {
var colorArr = parse(color);
if (colorArr) {
for (var i = 0; i < 3; i++) {
if (level < 0) {
colorArr[i] = colorArr[i] * (1 - level) | 0;
}
else {
colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
}
}
return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
}
}
/**
* @param {string} color
* @return {string}
* @memberOf module:zrender/util/color
*/
function toHex(color, level) {
var colorArr = parse(color);
if (colorArr) {
return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
}
}
/**
* Map value to color. Faster than mapToColor methods because color is represented by rgba array
* @param {number} normalizedValue A float between 0 and 1.
* @param {Array.<Array.<number>>} colors List of rgba color array
* @param {Array.<number>} [out] Mapped gba color array
* @return {Array.<number>}
*/
function fastMapToColor(normalizedValue, colors, out) {
if (!(colors && colors.length)
|| !(normalizedValue >= 0 && normalizedValue <= 1)
) {
return;
}
out = out || [0, 0, 0, 0];
var value = normalizedValue * (colors.length - 1);
var leftIndex = Math.floor(value);
var rightIndex = Math.ceil(value);
var leftColor = colors[leftIndex];
var rightColor = colors[rightIndex];
var dv = value - leftIndex;
out[0] = clampCssByte(lerp(leftColor[0], rightColor[0], dv));
out[1] = clampCssByte(lerp(leftColor[1], rightColor[1], dv));
out[2] = clampCssByte(lerp(leftColor[2], rightColor[2], dv));
out[3] = clampCssByte(lerp(leftColor[3], rightColor[3], dv));
return out;
}
/**
* @param {number} normalizedValue A float between 0 and 1.
* @param {Array.<string>} colors Color list.
* @param {boolean=} fullOutput Default false.
* @return {(string|Object)} Result color. If fullOutput,
* return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
* @memberOf module:zrender/util/color
*/
function mapToColor(normalizedValue, colors, fullOutput) {
if (!(colors && colors.length)
|| !(normalizedValue >= 0 && normalizedValue <= 1)
) {
return;
}
var value = normalizedValue * (colors.length - 1);
var leftIndex = Math.floor(value);
var rightIndex = Math.ceil(value);
var leftColor = parse(colors[leftIndex]);
var rightColor = parse(colors[rightIndex]);
var dv = value - leftIndex;
var color = stringify(
[
clampCssByte(lerp(leftColor[0], rightColor[0], dv)),
clampCssByte(lerp(leftColor[1], rightColor[1], dv)),
clampCssByte(lerp(leftColor[2], rightColor[2], dv)),
clampCssFloat(lerp(leftColor[3], rightColor[3], dv))
],
'rgba'
);
return fullOutput
? {
color: color,
leftIndex: leftIndex,
rightIndex: rightIndex,
value: value
}
: color;
}
/**
* @param {string} color
* @param {number=} h 0 ~ 360, ignore when null.
* @param {number=} s 0 ~ 1, ignore when null.
* @param {number=} l 0 ~ 1, ignore when null.
* @return {string} Color string in rgba format.
* @memberOf module:zrender/util/color
*/
function modifyHSL(color, h, s, l) {
color = parse(color);
if (color) {
color = rgba2hsla(color);
h != null && (color[0] = clampCssAngle(h));
s != null && (color[1] = parseCssFloat(s));
l != null && (color[2] = parseCssFloat(l));
return stringify(hsla2rgba(color), 'rgba');
}
}
/**
* @param {string} color
* @param {number=} alpha 0 ~ 1
* @return {string} Color string in rgba format.
* @memberOf module:zrender/util/color
*/
function modifyAlpha(color, alpha) {
color = parse(color);
if (color && alpha != null) {
color[3] = clampCssFloat(alpha);
return stringify(color, 'rgba');
}
}
/**
* @param {Array.<string>} colors Color list.
* @param {string} type 'rgba', 'hsva', ...
* @return {string} Result color.
*/
function stringify(arrColor, type) {
var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
colorStr += ',' + arrColor[3];
}
return type + '(' + colorStr + ')';
}
module.exports = {
parse: parse,
lift: lift,
toHex: toHex,
fastMapToColor: fastMapToColor,
mapToColor: mapToColor,
modifyHSL: modifyHSL,
modifyAlpha: modifyAlpha,
stringify: stringify
};
| {
if (!colorStr) {
return;
}
// colorStr may be not string
colorStr = colorStr + '';
// Remove all whitespace, not compliant, but should just be more accepting.
var str = colorStr.replace(/ /g, '').toLowerCase();
// Color keywords (and transparent) lookup.
if (str in kCSSColorTable) {
return kCSSColorTable[str].slice(); // dup.
}
// #abc and #abc123 syntax.
if (str.charAt(0) === '#') {
if (str.length === 4) {
var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
if (!(iv >= 0 && iv <= 0xfff)) {
return; // Covers NaN.
}
return [
((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
(iv & 0xf0) | ((iv & 0xf0) >> 4),
(iv & 0xf) | ((iv & 0xf) << 4),
1
];
}
else if (str.length === 7) {
var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
if (!(iv >= 0 && iv <= 0xffffff)) {
return; // Covers NaN.
}
return [
(iv & 0xff0000) >> 16,
(iv & 0xff00) >> 8,
iv & 0xff,
1
];
}
return;
}
var op = str.indexOf('('), ep = str.indexOf(')');
if (op !== -1 && ep + 1 === str.length) {
var fname = str.substr(0, op);
var params = str.substr(op + 1, ep - (op + 1)).split(',');
var alpha = 1; // To allow case fallthrough.
switch (fname) {
case 'rgba':
if (params.length !== 4) {
return;
}
alpha = parseCssFloat(params.pop()); // jshint ignore:line
// Fall through.
case 'rgb':
if (params.length !== 3) {
return;
}
return [
parseCssInt(params[0]),
parseCssInt(params[1]),
parseCssInt(params[2]),
alpha
];
case 'hsla':
if (params.length !== 4) {
return;
}
params[3] = parseCssFloat(params[3]);
return hsla2rgba(params);
case 'hsl':
if (params.length !== 3) {
return;
}
return hsla2rgba(params);
default:
return;
}
}
return;
} | identifier_body |
builder.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
#![cfg_attr(not(feature = "v3_10"), allow(unused_imports))]
use libc::{c_char, ssize_t};
use glib::Object;
use glib::object::{Downcast, IsA};
use glib::translate::*;
use ffi;
use std::path::Path;
use Error;
glib_wrapper! {
pub struct Builder(Object<ffi::GtkBuilder>);
match fn {
get_type => || ffi::gtk_builder_get_type(),
}
}
impl Builder {
pub fn new() -> Builder {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gtk_builder_new()) }
}
#[cfg(feature = "v3_10")]
pub fn new_from_file<T: AsRef<Path>>(file_path: T) -> Builder {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gtk_builder_new_from_file(file_path.as_ref().to_glib_none().0)) }
}
#[cfg(feature = "v3_10")]
pub fn new_from_resource(resource_path: &str) -> Builder {
assert_initialized_main_thread!();
unsafe {
from_glib_full(ffi::gtk_builder_new_from_resource(resource_path.to_glib_none().0))
}
}
#[cfg(feature = "v3_10")]
pub fn new_from_string(string: &str) -> Builder {
assert_initialized_main_thread!();
unsafe {
// Don't need a null-terminated string here
from_glib_full(
ffi::gtk_builder_new_from_string(string.as_ptr() as *const c_char,
string.len() as ssize_t))
}
}
pub fn get_object<T: IsA<Object>>(&self, name: &str) -> Option<T> {
unsafe {
Option::<Object>::from_glib_none(
ffi::gtk_builder_get_object(self.to_glib_none().0, name.to_glib_none().0))
.and_then(|obj| obj.downcast().ok())
}
}
pub fn add_from_file<T: AsRef<Path>>(&self, file_path: T) -> Result<(), Error> {
unsafe {
let mut error = ::std::ptr::null_mut();
ffi::gtk_builder_add_from_file(self.to_glib_none().0,
file_path.as_ref().to_glib_none().0,
&mut error);
if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }
}
}
pub fn add_from_resource(&self, resource_path: &str) -> Result<(), Error> {
unsafe {
let mut error = ::std::ptr::null_mut();
ffi::gtk_builder_add_from_resource(self.to_glib_none().0,
resource_path.to_glib_none().0,
&mut error);
if error.is_null() { Ok(()) } else |
}
}
pub fn add_from_string(&self, string: &str) -> Result<(), Error> {
unsafe {
let mut error = ::std::ptr::null_mut();
ffi::gtk_builder_add_from_string(self.to_glib_none().0,
string.as_ptr() as *const c_char,
string.len(), &mut error);
if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }
}
}
pub fn set_translation_domain(&self, domain: Option<&str>) {
unsafe {
ffi::gtk_builder_set_translation_domain(self.to_glib_none().0, domain.to_glib_none().0);
}
}
pub fn get_translation_domain(&self) -> Option<String> {
unsafe {
from_glib_none(ffi::gtk_builder_get_translation_domain(self.to_glib_none().0))
}
}
}
| { Err(from_glib_full(error)) } | conditional_block |
builder.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
#![cfg_attr(not(feature = "v3_10"), allow(unused_imports))]
use libc::{c_char, ssize_t};
use glib::Object;
use glib::object::{Downcast, IsA};
use glib::translate::*;
use ffi;
use std::path::Path;
use Error;
glib_wrapper! {
pub struct Builder(Object<ffi::GtkBuilder>);
match fn {
get_type => || ffi::gtk_builder_get_type(),
}
}
impl Builder {
pub fn new() -> Builder |
#[cfg(feature = "v3_10")]
pub fn new_from_file<T: AsRef<Path>>(file_path: T) -> Builder {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gtk_builder_new_from_file(file_path.as_ref().to_glib_none().0)) }
}
#[cfg(feature = "v3_10")]
pub fn new_from_resource(resource_path: &str) -> Builder {
assert_initialized_main_thread!();
unsafe {
from_glib_full(ffi::gtk_builder_new_from_resource(resource_path.to_glib_none().0))
}
}
#[cfg(feature = "v3_10")]
pub fn new_from_string(string: &str) -> Builder {
assert_initialized_main_thread!();
unsafe {
// Don't need a null-terminated string here
from_glib_full(
ffi::gtk_builder_new_from_string(string.as_ptr() as *const c_char,
string.len() as ssize_t))
}
}
pub fn get_object<T: IsA<Object>>(&self, name: &str) -> Option<T> {
unsafe {
Option::<Object>::from_glib_none(
ffi::gtk_builder_get_object(self.to_glib_none().0, name.to_glib_none().0))
.and_then(|obj| obj.downcast().ok())
}
}
pub fn add_from_file<T: AsRef<Path>>(&self, file_path: T) -> Result<(), Error> {
unsafe {
let mut error = ::std::ptr::null_mut();
ffi::gtk_builder_add_from_file(self.to_glib_none().0,
file_path.as_ref().to_glib_none().0,
&mut error);
if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }
}
}
pub fn add_from_resource(&self, resource_path: &str) -> Result<(), Error> {
unsafe {
let mut error = ::std::ptr::null_mut();
ffi::gtk_builder_add_from_resource(self.to_glib_none().0,
resource_path.to_glib_none().0,
&mut error);
if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }
}
}
pub fn add_from_string(&self, string: &str) -> Result<(), Error> {
unsafe {
let mut error = ::std::ptr::null_mut();
ffi::gtk_builder_add_from_string(self.to_glib_none().0,
string.as_ptr() as *const c_char,
string.len(), &mut error);
if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }
}
}
pub fn set_translation_domain(&self, domain: Option<&str>) {
unsafe {
ffi::gtk_builder_set_translation_domain(self.to_glib_none().0, domain.to_glib_none().0);
}
}
pub fn get_translation_domain(&self) -> Option<String> {
unsafe {
from_glib_none(ffi::gtk_builder_get_translation_domain(self.to_glib_none().0))
}
}
}
| {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gtk_builder_new()) }
} | identifier_body |
builder.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
#![cfg_attr(not(feature = "v3_10"), allow(unused_imports))]
use libc::{c_char, ssize_t};
use glib::Object;
use glib::object::{Downcast, IsA};
use glib::translate::*;
use ffi;
use std::path::Path;
use Error;
glib_wrapper! {
pub struct Builder(Object<ffi::GtkBuilder>);
match fn {
get_type => || ffi::gtk_builder_get_type(),
}
}
impl Builder {
pub fn new() -> Builder {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gtk_builder_new()) }
}
#[cfg(feature = "v3_10")]
pub fn new_from_file<T: AsRef<Path>>(file_path: T) -> Builder {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gtk_builder_new_from_file(file_path.as_ref().to_glib_none().0)) }
}
#[cfg(feature = "v3_10")]
pub fn new_from_resource(resource_path: &str) -> Builder {
assert_initialized_main_thread!();
unsafe {
from_glib_full(ffi::gtk_builder_new_from_resource(resource_path.to_glib_none().0))
}
}
#[cfg(feature = "v3_10")]
pub fn new_from_string(string: &str) -> Builder {
assert_initialized_main_thread!();
unsafe {
// Don't need a null-terminated string here
from_glib_full(
ffi::gtk_builder_new_from_string(string.as_ptr() as *const c_char,
string.len() as ssize_t))
}
}
pub fn | <T: IsA<Object>>(&self, name: &str) -> Option<T> {
unsafe {
Option::<Object>::from_glib_none(
ffi::gtk_builder_get_object(self.to_glib_none().0, name.to_glib_none().0))
.and_then(|obj| obj.downcast().ok())
}
}
pub fn add_from_file<T: AsRef<Path>>(&self, file_path: T) -> Result<(), Error> {
unsafe {
let mut error = ::std::ptr::null_mut();
ffi::gtk_builder_add_from_file(self.to_glib_none().0,
file_path.as_ref().to_glib_none().0,
&mut error);
if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }
}
}
pub fn add_from_resource(&self, resource_path: &str) -> Result<(), Error> {
unsafe {
let mut error = ::std::ptr::null_mut();
ffi::gtk_builder_add_from_resource(self.to_glib_none().0,
resource_path.to_glib_none().0,
&mut error);
if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }
}
}
pub fn add_from_string(&self, string: &str) -> Result<(), Error> {
unsafe {
let mut error = ::std::ptr::null_mut();
ffi::gtk_builder_add_from_string(self.to_glib_none().0,
string.as_ptr() as *const c_char,
string.len(), &mut error);
if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }
}
}
pub fn set_translation_domain(&self, domain: Option<&str>) {
unsafe {
ffi::gtk_builder_set_translation_domain(self.to_glib_none().0, domain.to_glib_none().0);
}
}
pub fn get_translation_domain(&self) -> Option<String> {
unsafe {
from_glib_none(ffi::gtk_builder_get_translation_domain(self.to_glib_none().0))
}
}
}
| get_object | identifier_name |
builder.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
#![cfg_attr(not(feature = "v3_10"), allow(unused_imports))]
use libc::{c_char, ssize_t};
use glib::Object;
use glib::object::{Downcast, IsA};
use glib::translate::*;
use ffi;
use std::path::Path;
use Error;
glib_wrapper! {
pub struct Builder(Object<ffi::GtkBuilder>);
match fn {
get_type => || ffi::gtk_builder_get_type(),
}
}
impl Builder {
pub fn new() -> Builder {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gtk_builder_new()) }
}
#[cfg(feature = "v3_10")]
pub fn new_from_file<T: AsRef<Path>>(file_path: T) -> Builder {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gtk_builder_new_from_file(file_path.as_ref().to_glib_none().0)) }
}
#[cfg(feature = "v3_10")]
pub fn new_from_resource(resource_path: &str) -> Builder {
assert_initialized_main_thread!();
unsafe {
from_glib_full(ffi::gtk_builder_new_from_resource(resource_path.to_glib_none().0))
}
}
| from_glib_full(
ffi::gtk_builder_new_from_string(string.as_ptr() as *const c_char,
string.len() as ssize_t))
}
}
pub fn get_object<T: IsA<Object>>(&self, name: &str) -> Option<T> {
unsafe {
Option::<Object>::from_glib_none(
ffi::gtk_builder_get_object(self.to_glib_none().0, name.to_glib_none().0))
.and_then(|obj| obj.downcast().ok())
}
}
pub fn add_from_file<T: AsRef<Path>>(&self, file_path: T) -> Result<(), Error> {
unsafe {
let mut error = ::std::ptr::null_mut();
ffi::gtk_builder_add_from_file(self.to_glib_none().0,
file_path.as_ref().to_glib_none().0,
&mut error);
if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }
}
}
pub fn add_from_resource(&self, resource_path: &str) -> Result<(), Error> {
unsafe {
let mut error = ::std::ptr::null_mut();
ffi::gtk_builder_add_from_resource(self.to_glib_none().0,
resource_path.to_glib_none().0,
&mut error);
if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }
}
}
pub fn add_from_string(&self, string: &str) -> Result<(), Error> {
unsafe {
let mut error = ::std::ptr::null_mut();
ffi::gtk_builder_add_from_string(self.to_glib_none().0,
string.as_ptr() as *const c_char,
string.len(), &mut error);
if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }
}
}
pub fn set_translation_domain(&self, domain: Option<&str>) {
unsafe {
ffi::gtk_builder_set_translation_domain(self.to_glib_none().0, domain.to_glib_none().0);
}
}
pub fn get_translation_domain(&self) -> Option<String> {
unsafe {
from_glib_none(ffi::gtk_builder_get_translation_domain(self.to_glib_none().0))
}
}
} | #[cfg(feature = "v3_10")]
pub fn new_from_string(string: &str) -> Builder {
assert_initialized_main_thread!();
unsafe {
// Don't need a null-terminated string here | random_line_split |
test_image.py | def test_image_export_reference(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'REFERENCE'
gltf_image_default['uri'] = '../filepath.png'
output = exporters.ImageExporter.export(state, bpy_image_default)
assert output == gltf_image_default
def test_image_export_embed(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'EMBED'
gltf_image_default['uri'] = (
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACElEQVR42gMAAAAAAW'
'/dyZEAAAAASUVORK5CYII='
)
gltf_image_default['mimeType'] = 'image/png'
output = exporters.ImageExporter.export(state, bpy_image_default)
assert output == gltf_image_default
def test_image_export_embed_glb(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'EMBED'
state['settings']['gltf_export_binary'] = True
gltf_image_default['mimeType'] = 'image/png'
gltf_image_default['bufferView'] = 'bufferView_buffer_Image_0'
output = exporters.ImageExporter.export(state, bpy_image_default)
for ref in state['references']:
ref.source[ref.prop] = ref.blender_name
assert output == gltf_image_default
def test_image_to_data_uri(exporters, bpy_image_default):
image_data = (
b'\x89PNG\r\n\x1a\n\x00\x00\x00\r'
b'IHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\x08'
b'IDATx\xda\x03\x00\x00\x00\x00\x01o\xdd\xc9\x91\x00\x00\x00\x00'
b'IEND\xaeB`\x82'
)
assert exporters.ImageExporter.image_to_data_uri(bpy_image_default) == image_data
def test_image_check(exporters, state, bpy_image_default):
assert exporters.ImageExporter.check(state, bpy_image_default)
def test_image_default(exporters, state, bpy_image_default):
assert exporters.ImageExporter.default(state, bpy_image_default) == {
'name': 'Image',
'uri': '',
}
def test_image_check_0_x(exporters, state, bpy_image_default):
bpy_image_default.size = [0, 1]
assert exporters.ImageExporter.check(state, bpy_image_default) is not True
def test_image_check_0_y(exporters, state, bpy_image_default):
bpy_image_default.size = [1, 0]
assert exporters.ImageExporter.check(state, bpy_image_default) is not True
def test_image_check_type(exporters, state, bpy_image_default):
| bpy_image_default.type = 'NOT_IMAGE'
assert exporters.ImageExporter.check(state, bpy_image_default) is not True | identifier_body | |
test_image.py | def test_image_export_reference(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'REFERENCE'
gltf_image_default['uri'] = '../filepath.png'
output = exporters.ImageExporter.export(state, bpy_image_default)
assert output == gltf_image_default
def test_image_export_embed(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'EMBED'
gltf_image_default['uri'] = (
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACElEQVR42gMAAAAAAW'
'/dyZEAAAAASUVORK5CYII='
)
gltf_image_default['mimeType'] = 'image/png'
output = exporters.ImageExporter.export(state, bpy_image_default)
assert output == gltf_image_default
def test_image_export_embed_glb(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'EMBED'
state['settings']['gltf_export_binary'] = True
gltf_image_default['mimeType'] = 'image/png'
gltf_image_default['bufferView'] = 'bufferView_buffer_Image_0'
output = exporters.ImageExporter.export(state, bpy_image_default)
for ref in state['references']:
|
assert output == gltf_image_default
def test_image_to_data_uri(exporters, bpy_image_default):
image_data = (
b'\x89PNG\r\n\x1a\n\x00\x00\x00\r'
b'IHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\x08'
b'IDATx\xda\x03\x00\x00\x00\x00\x01o\xdd\xc9\x91\x00\x00\x00\x00'
b'IEND\xaeB`\x82'
)
assert exporters.ImageExporter.image_to_data_uri(bpy_image_default) == image_data
def test_image_check(exporters, state, bpy_image_default):
assert exporters.ImageExporter.check(state, bpy_image_default)
def test_image_default(exporters, state, bpy_image_default):
assert exporters.ImageExporter.default(state, bpy_image_default) == {
'name': 'Image',
'uri': '',
}
def test_image_check_0_x(exporters, state, bpy_image_default):
bpy_image_default.size = [0, 1]
assert exporters.ImageExporter.check(state, bpy_image_default) is not True
def test_image_check_0_y(exporters, state, bpy_image_default):
bpy_image_default.size = [1, 0]
assert exporters.ImageExporter.check(state, bpy_image_default) is not True
def test_image_check_type(exporters, state, bpy_image_default):
bpy_image_default.type = 'NOT_IMAGE'
assert exporters.ImageExporter.check(state, bpy_image_default) is not True
| ref.source[ref.prop] = ref.blender_name | conditional_block |
test_image.py | def test_image_export_reference(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'REFERENCE'
gltf_image_default['uri'] = '../filepath.png'
output = exporters.ImageExporter.export(state, bpy_image_default)
assert output == gltf_image_default
def test_image_export_embed(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'EMBED'
gltf_image_default['uri'] = (
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACElEQVR42gMAAAAAAW'
'/dyZEAAAAASUVORK5CYII='
)
gltf_image_default['mimeType'] = 'image/png'
output = exporters.ImageExporter.export(state, bpy_image_default)
assert output == gltf_image_default
def test_image_export_embed_glb(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'EMBED'
state['settings']['gltf_export_binary'] = True
gltf_image_default['mimeType'] = 'image/png'
gltf_image_default['bufferView'] = 'bufferView_buffer_Image_0'
output = exporters.ImageExporter.export(state, bpy_image_default)
for ref in state['references']:
ref.source[ref.prop] = ref.blender_name
assert output == gltf_image_default
def test_image_to_data_uri(exporters, bpy_image_default):
image_data = (
b'\x89PNG\r\n\x1a\n\x00\x00\x00\r'
b'IHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\x08'
b'IDATx\xda\x03\x00\x00\x00\x00\x01o\xdd\xc9\x91\x00\x00\x00\x00'
b'IEND\xaeB`\x82'
)
assert exporters.ImageExporter.image_to_data_uri(bpy_image_default) == image_data
def test_image_check(exporters, state, bpy_image_default):
assert exporters.ImageExporter.check(state, bpy_image_default)
def test_image_default(exporters, state, bpy_image_default):
assert exporters.ImageExporter.default(state, bpy_image_default) == {
'name': 'Image',
'uri': '',
}
| assert exporters.ImageExporter.check(state, bpy_image_default) is not True
def test_image_check_0_y(exporters, state, bpy_image_default):
bpy_image_default.size = [1, 0]
assert exporters.ImageExporter.check(state, bpy_image_default) is not True
def test_image_check_type(exporters, state, bpy_image_default):
bpy_image_default.type = 'NOT_IMAGE'
assert exporters.ImageExporter.check(state, bpy_image_default) is not True | def test_image_check_0_x(exporters, state, bpy_image_default):
bpy_image_default.size = [0, 1] | random_line_split |
test_image.py | def test_image_export_reference(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'REFERENCE'
gltf_image_default['uri'] = '../filepath.png'
output = exporters.ImageExporter.export(state, bpy_image_default)
assert output == gltf_image_default
def | (exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'EMBED'
gltf_image_default['uri'] = (
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACElEQVR42gMAAAAAAW'
'/dyZEAAAAASUVORK5CYII='
)
gltf_image_default['mimeType'] = 'image/png'
output = exporters.ImageExporter.export(state, bpy_image_default)
assert output == gltf_image_default
def test_image_export_embed_glb(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'EMBED'
state['settings']['gltf_export_binary'] = True
gltf_image_default['mimeType'] = 'image/png'
gltf_image_default['bufferView'] = 'bufferView_buffer_Image_0'
output = exporters.ImageExporter.export(state, bpy_image_default)
for ref in state['references']:
ref.source[ref.prop] = ref.blender_name
assert output == gltf_image_default
def test_image_to_data_uri(exporters, bpy_image_default):
image_data = (
b'\x89PNG\r\n\x1a\n\x00\x00\x00\r'
b'IHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\x08'
b'IDATx\xda\x03\x00\x00\x00\x00\x01o\xdd\xc9\x91\x00\x00\x00\x00'
b'IEND\xaeB`\x82'
)
assert exporters.ImageExporter.image_to_data_uri(bpy_image_default) == image_data
def test_image_check(exporters, state, bpy_image_default):
assert exporters.ImageExporter.check(state, bpy_image_default)
def test_image_default(exporters, state, bpy_image_default):
assert exporters.ImageExporter.default(state, bpy_image_default) == {
'name': 'Image',
'uri': '',
}
def test_image_check_0_x(exporters, state, bpy_image_default):
bpy_image_default.size = [0, 1]
assert exporters.ImageExporter.check(state, bpy_image_default) is not True
def test_image_check_0_y(exporters, state, bpy_image_default):
bpy_image_default.size = [1, 0]
assert exporters.ImageExporter.check(state, bpy_image_default) is not True
def test_image_check_type(exporters, state, bpy_image_default):
bpy_image_default.type = 'NOT_IMAGE'
assert exporters.ImageExporter.check(state, bpy_image_default) is not True
| test_image_export_embed | identifier_name |
hello.rs | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* <http://www.gnu.org/licenses/>.
*
* Sahid Orentino Ferdjaoui <sahid.ferdjaoui@redhat.com>
*/
//! This file contains trivial example code to connect to the running
//! hypervisor and gather a few bits of information about domains.
//! Similar API's exist for storage pools, networks, and interfaces.
//!
//! Largely inspired by hellolibvirt.c
extern crate virt;
use std::env;
use virt::connect::Connect;
use virt::error::Error;
fn show_hypervisor_info(conn: &Connect) -> Result<(), Error> {
if let Ok(hv_type) = conn.get_type() {
if let Ok(mut hv_ver) = conn.get_hyp_version() {
let major = hv_ver / 1000000;
hv_ver %= 1000000;
let minor = hv_ver / 1000;
let release = hv_ver % 1000;
println!("Hypervisor: '{}' version: {}.{}.{}",
hv_type,
major,
minor,
release);
return Ok(());
}
}
Err(Error::new())
}
fn show_domains(conn: &Connect) -> Result<(), Error> |
fn main() {
let uri = match env::args().nth(1) {
Some(u) => u,
None => String::from(""),
};
println!("Attempting to connect to hypervisor: '{}'", uri);
let conn = match Connect::open(&uri) {
Ok(c) => c,
Err(e) => {
panic!("No connection to hypervisor: code {}, message: {}",
e.code,
e.message)
}
};
match conn.get_uri() {
Ok(u) => println!("Connected to hypervisor at '{}'", u),
Err(e) => {
disconnect(conn);
panic!("Failed to get URI for hypervisor connection: code {}, message: {}",
e.code,
e.message);
}
};
if let Err(e) = show_hypervisor_info(&conn) {
disconnect(conn);
panic!("Failed to show hypervisor info: code {}, message: {}",
e.code,
e.message);
}
if let Err(e) = show_domains(&conn) {
disconnect(conn);
panic!("Failed to show domains info: code {}, message: {}",
e.code,
e.message);
}
fn disconnect(mut conn: Connect) {
if let Err(e) = conn.close() {
panic!("Failed to disconnect from hypervisor: code {}, message: {}",
e.code,
e.message);
}
println!("Disconnected from hypervisor");
}
}
| {
let flags = virt::connect::VIR_CONNECT_LIST_DOMAINS_ACTIVE |
virt::connect::VIR_CONNECT_LIST_DOMAINS_INACTIVE;
if let Ok(num_active_domains) = conn.num_of_domains() {
if let Ok(num_inactive_domains) = conn.num_of_defined_domains() {
println!("There are {} active and {} inactive domains",
num_active_domains,
num_inactive_domains);
/* Return a list of all active and inactive domains. Using this API
* instead of virConnectListDomains() and virConnectListDefinedDomains()
* is preferred since it "solves" an inherit race between separated API
* calls if domains are started or stopped between calls */
if let Ok(doms) = conn.list_all_domains(flags) {
for dom in doms {
let id = dom.get_id().unwrap_or(0);
let name = dom.get_name().unwrap_or(String::from("no-name"));
let active = dom.is_active().unwrap_or(false);
println!("ID: {}, Name: {}, Active: {}", id, name, active);
if let Ok(dinfo) = dom.get_info() {
println!("Domain info:");
println!(" State: {}", dinfo.state);
println!(" Max Memory: {}", dinfo.max_mem);
println!(" Memory: {}", dinfo.memory);
println!(" CPUs: {}", dinfo.nr_virt_cpu);
println!(" CPU Time: {}", dinfo.cpu_time);
}
if let Ok(memtune) = dom.get_memory_parameters(0) {
println!("Memory tune:");
println!(" Hard Limit: {}", memtune.hard_limit.unwrap_or(0));
println!(" Soft Limit: {}", memtune.soft_limit.unwrap_or(0));
println!(" Min Guarantee: {}", memtune.min_guarantee.unwrap_or(0));
println!(" Swap Hard Limit: {}",
memtune.swap_hard_limit.unwrap_or(0));
}
if let Ok(numa) = dom.get_numa_parameters(0) {
println!("NUMA:");
println!(" Node Set: {}",
numa.node_set.unwrap_or(String::from("")));
println!(" Mode: {}", numa.mode.unwrap_or(0));
}
}
}
return Ok(());
}
}
Err(Error::new())
} | identifier_body |
hello.rs | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* <http://www.gnu.org/licenses/>.
*
* Sahid Orentino Ferdjaoui <sahid.ferdjaoui@redhat.com>
*/
//! This file contains trivial example code to connect to the running
//! hypervisor and gather a few bits of information about domains.
//! Similar API's exist for storage pools, networks, and interfaces.
//!
//! Largely inspired by hellolibvirt.c
extern crate virt;
use std::env;
use virt::connect::Connect;
use virt::error::Error;
fn show_hypervisor_info(conn: &Connect) -> Result<(), Error> {
if let Ok(hv_type) = conn.get_type() {
if let Ok(mut hv_ver) = conn.get_hyp_version() {
let major = hv_ver / 1000000;
hv_ver %= 1000000;
let minor = hv_ver / 1000;
let release = hv_ver % 1000;
println!("Hypervisor: '{}' version: {}.{}.{}",
hv_type,
major,
minor,
release);
return Ok(());
}
}
Err(Error::new())
}
fn | (conn: &Connect) -> Result<(), Error> {
let flags = virt::connect::VIR_CONNECT_LIST_DOMAINS_ACTIVE |
virt::connect::VIR_CONNECT_LIST_DOMAINS_INACTIVE;
if let Ok(num_active_domains) = conn.num_of_domains() {
if let Ok(num_inactive_domains) = conn.num_of_defined_domains() {
println!("There are {} active and {} inactive domains",
num_active_domains,
num_inactive_domains);
/* Return a list of all active and inactive domains. Using this API
* instead of virConnectListDomains() and virConnectListDefinedDomains()
* is preferred since it "solves" an inherit race between separated API
* calls if domains are started or stopped between calls */
if let Ok(doms) = conn.list_all_domains(flags) {
for dom in doms {
let id = dom.get_id().unwrap_or(0);
let name = dom.get_name().unwrap_or(String::from("no-name"));
let active = dom.is_active().unwrap_or(false);
println!("ID: {}, Name: {}, Active: {}", id, name, active);
if let Ok(dinfo) = dom.get_info() {
println!("Domain info:");
println!(" State: {}", dinfo.state);
println!(" Max Memory: {}", dinfo.max_mem);
println!(" Memory: {}", dinfo.memory);
println!(" CPUs: {}", dinfo.nr_virt_cpu);
println!(" CPU Time: {}", dinfo.cpu_time);
}
if let Ok(memtune) = dom.get_memory_parameters(0) {
println!("Memory tune:");
println!(" Hard Limit: {}", memtune.hard_limit.unwrap_or(0));
println!(" Soft Limit: {}", memtune.soft_limit.unwrap_or(0));
println!(" Min Guarantee: {}", memtune.min_guarantee.unwrap_or(0));
println!(" Swap Hard Limit: {}",
memtune.swap_hard_limit.unwrap_or(0));
}
if let Ok(numa) = dom.get_numa_parameters(0) {
println!("NUMA:");
println!(" Node Set: {}",
numa.node_set.unwrap_or(String::from("")));
println!(" Mode: {}", numa.mode.unwrap_or(0));
}
}
}
return Ok(());
}
}
Err(Error::new())
}
fn main() {
let uri = match env::args().nth(1) {
Some(u) => u,
None => String::from(""),
};
println!("Attempting to connect to hypervisor: '{}'", uri);
let conn = match Connect::open(&uri) {
Ok(c) => c,
Err(e) => {
panic!("No connection to hypervisor: code {}, message: {}",
e.code,
e.message)
}
};
match conn.get_uri() {
Ok(u) => println!("Connected to hypervisor at '{}'", u),
Err(e) => {
disconnect(conn);
panic!("Failed to get URI for hypervisor connection: code {}, message: {}",
e.code,
e.message);
}
};
if let Err(e) = show_hypervisor_info(&conn) {
disconnect(conn);
panic!("Failed to show hypervisor info: code {}, message: {}",
e.code,
e.message);
}
if let Err(e) = show_domains(&conn) {
disconnect(conn);
panic!("Failed to show domains info: code {}, message: {}",
e.code,
e.message);
}
fn disconnect(mut conn: Connect) {
if let Err(e) = conn.close() {
panic!("Failed to disconnect from hypervisor: code {}, message: {}",
e.code,
e.message);
}
println!("Disconnected from hypervisor");
}
}
| show_domains | identifier_name |
hello.rs | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* <http://www.gnu.org/licenses/>.
*
* Sahid Orentino Ferdjaoui <sahid.ferdjaoui@redhat.com>
*/
//! This file contains trivial example code to connect to the running
//! hypervisor and gather a few bits of information about domains.
//! Similar API's exist for storage pools, networks, and interfaces.
//!
//! Largely inspired by hellolibvirt.c
extern crate virt;
use std::env;
use virt::connect::Connect;
use virt::error::Error;
fn show_hypervisor_info(conn: &Connect) -> Result<(), Error> {
if let Ok(hv_type) = conn.get_type() {
if let Ok(mut hv_ver) = conn.get_hyp_version() {
let major = hv_ver / 1000000;
hv_ver %= 1000000;
let minor = hv_ver / 1000;
let release = hv_ver % 1000;
println!("Hypervisor: '{}' version: {}.{}.{}",
hv_type,
major,
minor,
release);
return Ok(());
}
}
Err(Error::new())
}
fn show_domains(conn: &Connect) -> Result<(), Error> {
let flags = virt::connect::VIR_CONNECT_LIST_DOMAINS_ACTIVE |
virt::connect::VIR_CONNECT_LIST_DOMAINS_INACTIVE;
if let Ok(num_active_domains) = conn.num_of_domains() {
if let Ok(num_inactive_domains) = conn.num_of_defined_domains() {
println!("There are {} active and {} inactive domains",
num_active_domains,
num_inactive_domains);
/* Return a list of all active and inactive domains. Using this API
* instead of virConnectListDomains() and virConnectListDefinedDomains()
* is preferred since it "solves" an inherit race between separated API
* calls if domains are started or stopped between calls */
if let Ok(doms) = conn.list_all_domains(flags) {
for dom in doms {
let id = dom.get_id().unwrap_or(0);
let name = dom.get_name().unwrap_or(String::from("no-name"));
let active = dom.is_active().unwrap_or(false);
println!("ID: {}, Name: {}, Active: {}", id, name, active);
if let Ok(dinfo) = dom.get_info() {
println!("Domain info:");
println!(" State: {}", dinfo.state);
println!(" Max Memory: {}", dinfo.max_mem);
println!(" Memory: {}", dinfo.memory);
println!(" CPUs: {}", dinfo.nr_virt_cpu);
println!(" CPU Time: {}", dinfo.cpu_time);
}
if let Ok(memtune) = dom.get_memory_parameters(0) {
println!("Memory tune:");
println!(" Hard Limit: {}", memtune.hard_limit.unwrap_or(0));
println!(" Soft Limit: {}", memtune.soft_limit.unwrap_or(0));
println!(" Min Guarantee: {}", memtune.min_guarantee.unwrap_or(0));
println!(" Swap Hard Limit: {}",
memtune.swap_hard_limit.unwrap_or(0));
}
if let Ok(numa) = dom.get_numa_parameters(0) {
println!("NUMA:");
println!(" Node Set: {}",
numa.node_set.unwrap_or(String::from("")));
println!(" Mode: {}", numa.mode.unwrap_or(0)); | return Ok(());
}
}
Err(Error::new())
}
fn main() {
let uri = match env::args().nth(1) {
Some(u) => u,
None => String::from(""),
};
println!("Attempting to connect to hypervisor: '{}'", uri);
let conn = match Connect::open(&uri) {
Ok(c) => c,
Err(e) => {
panic!("No connection to hypervisor: code {}, message: {}",
e.code,
e.message)
}
};
match conn.get_uri() {
Ok(u) => println!("Connected to hypervisor at '{}'", u),
Err(e) => {
disconnect(conn);
panic!("Failed to get URI for hypervisor connection: code {}, message: {}",
e.code,
e.message);
}
};
if let Err(e) = show_hypervisor_info(&conn) {
disconnect(conn);
panic!("Failed to show hypervisor info: code {}, message: {}",
e.code,
e.message);
}
if let Err(e) = show_domains(&conn) {
disconnect(conn);
panic!("Failed to show domains info: code {}, message: {}",
e.code,
e.message);
}
fn disconnect(mut conn: Connect) {
if let Err(e) = conn.close() {
panic!("Failed to disconnect from hypervisor: code {}, message: {}",
e.code,
e.message);
}
println!("Disconnected from hypervisor");
}
} | }
}
} | random_line_split |
hello.rs | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* <http://www.gnu.org/licenses/>.
*
* Sahid Orentino Ferdjaoui <sahid.ferdjaoui@redhat.com>
*/
//! This file contains trivial example code to connect to the running
//! hypervisor and gather a few bits of information about domains.
//! Similar API's exist for storage pools, networks, and interfaces.
//!
//! Largely inspired by hellolibvirt.c
extern crate virt;
use std::env;
use virt::connect::Connect;
use virt::error::Error;
fn show_hypervisor_info(conn: &Connect) -> Result<(), Error> {
if let Ok(hv_type) = conn.get_type() {
if let Ok(mut hv_ver) = conn.get_hyp_version() {
let major = hv_ver / 1000000;
hv_ver %= 1000000;
let minor = hv_ver / 1000;
let release = hv_ver % 1000;
println!("Hypervisor: '{}' version: {}.{}.{}",
hv_type,
major,
minor,
release);
return Ok(());
}
}
Err(Error::new())
}
fn show_domains(conn: &Connect) -> Result<(), Error> {
let flags = virt::connect::VIR_CONNECT_LIST_DOMAINS_ACTIVE |
virt::connect::VIR_CONNECT_LIST_DOMAINS_INACTIVE;
if let Ok(num_active_domains) = conn.num_of_domains() {
if let Ok(num_inactive_domains) = conn.num_of_defined_domains() {
println!("There are {} active and {} inactive domains",
num_active_domains,
num_inactive_domains);
/* Return a list of all active and inactive domains. Using this API
* instead of virConnectListDomains() and virConnectListDefinedDomains()
* is preferred since it "solves" an inherit race between separated API
* calls if domains are started or stopped between calls */
if let Ok(doms) = conn.list_all_domains(flags) {
for dom in doms {
let id = dom.get_id().unwrap_or(0);
let name = dom.get_name().unwrap_or(String::from("no-name"));
let active = dom.is_active().unwrap_or(false);
println!("ID: {}, Name: {}, Active: {}", id, name, active);
if let Ok(dinfo) = dom.get_info() {
println!("Domain info:");
println!(" State: {}", dinfo.state);
println!(" Max Memory: {}", dinfo.max_mem);
println!(" Memory: {}", dinfo.memory);
println!(" CPUs: {}", dinfo.nr_virt_cpu);
println!(" CPU Time: {}", dinfo.cpu_time);
}
if let Ok(memtune) = dom.get_memory_parameters(0) {
println!("Memory tune:");
println!(" Hard Limit: {}", memtune.hard_limit.unwrap_or(0));
println!(" Soft Limit: {}", memtune.soft_limit.unwrap_or(0));
println!(" Min Guarantee: {}", memtune.min_guarantee.unwrap_or(0));
println!(" Swap Hard Limit: {}",
memtune.swap_hard_limit.unwrap_or(0));
}
if let Ok(numa) = dom.get_numa_parameters(0) {
println!("NUMA:");
println!(" Node Set: {}",
numa.node_set.unwrap_or(String::from("")));
println!(" Mode: {}", numa.mode.unwrap_or(0));
}
}
}
return Ok(());
}
}
Err(Error::new())
}
fn main() {
let uri = match env::args().nth(1) {
Some(u) => u,
None => String::from(""),
};
println!("Attempting to connect to hypervisor: '{}'", uri);
let conn = match Connect::open(&uri) {
Ok(c) => c,
Err(e) => {
panic!("No connection to hypervisor: code {}, message: {}",
e.code,
e.message)
}
};
match conn.get_uri() {
Ok(u) => println!("Connected to hypervisor at '{}'", u),
Err(e) => {
disconnect(conn);
panic!("Failed to get URI for hypervisor connection: code {}, message: {}",
e.code,
e.message);
}
};
if let Err(e) = show_hypervisor_info(&conn) |
if let Err(e) = show_domains(&conn) {
disconnect(conn);
panic!("Failed to show domains info: code {}, message: {}",
e.code,
e.message);
}
fn disconnect(mut conn: Connect) {
if let Err(e) = conn.close() {
panic!("Failed to disconnect from hypervisor: code {}, message: {}",
e.code,
e.message);
}
println!("Disconnected from hypervisor");
}
}
| {
disconnect(conn);
panic!("Failed to show hypervisor info: code {}, message: {}",
e.code,
e.message);
} | conditional_block |
invalid__missing-present.js | /* | * the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* For use with date input fields. Set the title to this value and
* data-tooltip=""
*/
import I18n from 'i18n!dateformat'
var accessibleDateFormat = () => {
return I18n.t("YYYY-MM-DD hh:mm");
};
export default accessibleDateFormat | * Copyright (C) 2015 Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under | random_line_split |
client.py | #!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains a client to communicate with the Blogger servers.
For documentation on the Blogger API, see:
http://code.google.com/apis/blogger/
"""
__author__ = 'j.s@google.com (Jeff Scudder)'
import gdata.client
import gdata.gauth
import gdata.blogger.data
import atom.data
import atom.http_core
# List user's blogs, takes a user ID, or 'default'.
BLOGS_URL = 'http://www.blogger.com/feeds/%s/blogs'
# Takes a blog ID.
BLOG_POST_URL = 'http://www.blogger.com/feeds/%s/posts/default'
# Takes a blog ID.
BLOG_PAGE_URL = 'http://www.blogger.com/feeds/%s/pages/default'
# Takes a blog ID and post ID.
BLOG_POST_COMMENTS_URL = 'http://www.blogger.com/feeds/%s/%s/comments/default'
# Takes a blog ID.
BLOG_COMMENTS_URL = 'http://www.blogger.com/feeds/%s/comments/default'
# Takes a blog ID.
BLOG_ARCHIVE_URL = 'http://www.blogger.com/feeds/%s/archive/full'
class BloggerClient(gdata.client.GDClient):
|
class Query(gdata.client.Query):
def __init__(self, order_by=None, **kwargs):
gdata.client.Query.__init__(self, **kwargs)
self.order_by = order_by
def modify_request(self, http_request):
gdata.client._add_query_param('orderby', self.order_by, http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request
| api_version = '2'
auth_service = 'blogger'
auth_scopes = gdata.gauth.AUTH_SCOPES['blogger']
def get_blogs(self, user_id='default', auth_token=None,
desired_class=gdata.blogger.data.BlogFeed, **kwargs):
return self.get_feed(BLOGS_URL % user_id, auth_token=auth_token,
desired_class=desired_class, **kwargs)
GetBlogs = get_blogs
def get_posts(self, blog_id, auth_token=None,
desired_class=gdata.blogger.data.BlogPostFeed, query=None,
**kwargs):
return self.get_feed(BLOG_POST_URL % blog_id, auth_token=auth_token,
desired_class=desired_class, query=query, **kwargs)
GetPosts = get_posts
def get_pages(self, blog_id, auth_token=None,
desired_class=gdata.blogger.data.BlogPageFeed, query=None,
**kwargs):
return self.get_feed(BLOG_PAGE_URL % blog_id, auth_token=auth_token,
desired_class=desired_class, query=query, **kwargs)
GetPages = get_pages
def get_post_comments(self, blog_id, post_id, auth_token=None,
desired_class=gdata.blogger.data.CommentFeed,
query=None, **kwargs):
return self.get_feed(BLOG_POST_COMMENTS_URL % (blog_id, post_id),
auth_token=auth_token, desired_class=desired_class,
query=query, **kwargs)
GetPostComments = get_post_comments
def get_blog_comments(self, blog_id, auth_token=None,
desired_class=gdata.blogger.data.CommentFeed,
query=None, **kwargs):
return self.get_feed(BLOG_COMMENTS_URL % blog_id, auth_token=auth_token,
desired_class=desired_class, query=query, **kwargs)
GetBlogComments = get_blog_comments
def get_blog_archive(self, blog_id, auth_token=None, **kwargs):
return self.get_feed(BLOG_ARCHIVE_URL % blog_id, auth_token=auth_token,
**kwargs)
GetBlogArchive = get_blog_archive
def add_post(self, blog_id, title, body, labels=None, draft=False,
auth_token=None, title_type='text', body_type='html', **kwargs):
# Construct an atom Entry for the blog post to be sent to the server.
new_entry = gdata.blogger.data.BlogPost(
title=atom.data.Title(text=title, type=title_type),
content=atom.data.Content(text=body, type=body_type))
if labels:
for label in labels:
new_entry.add_label(label)
if draft:
new_entry.control = atom.data.Control(draft=atom.data.Draft(text='yes'))
return self.post(new_entry, BLOG_POST_URL % blog_id, auth_token=auth_token, **kwargs)
AddPost = add_post
def add_page(self, blog_id, title, body, draft=False, auth_token=None,
title_type='text', body_type='html', **kwargs):
new_entry = gdata.blogger.data.BlogPage(
title=atom.data.Title(text=title, type=title_type),
content=atom.data.Content(text=body, type=body_type))
if draft:
new_entry.control = atom.data.Control(draft=atom.data.Draft(text='yes'))
return self.post(new_entry, BLOG_PAGE_URL % blog_id, auth_token=auth_token, **kwargs)
AddPage = add_page
def add_comment(self, blog_id, post_id, body, auth_token=None,
title_type='text', body_type='html', **kwargs):
new_entry = gdata.blogger.data.Comment(
content=atom.data.Content(text=body, type=body_type))
return self.post(new_entry, BLOG_POST_COMMENTS_URL % (blog_id, post_id),
auth_token=auth_token, **kwargs)
AddComment = add_comment
def update(self, entry, auth_token=None, **kwargs):
# The Blogger API does not currently support ETags, so for now remove
# the ETag before performing an update.
old_etag = entry.etag
entry.etag = None
response = gdata.client.GDClient.update(self, entry,
auth_token=auth_token, **kwargs)
entry.etag = old_etag
return response
Update = update
def delete(self, entry_or_uri, auth_token=None, **kwargs):
if isinstance(entry_or_uri, (str, atom.http_core.Uri)):
return gdata.client.GDClient.delete(self, entry_or_uri,
auth_token=auth_token, **kwargs)
# The Blogger API does not currently support ETags, so for now remove
# the ETag before performing a delete.
old_etag = entry_or_uri.etag
entry_or_uri.etag = None
response = gdata.client.GDClient.delete(self, entry_or_uri,
auth_token=auth_token, **kwargs)
# TODO: if GDClient.delete raises and exception, the entry's etag may be
# left as None. Should revisit this logic.
entry_or_uri.etag = old_etag
return response
Delete = delete | identifier_body |
client.py | #!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains a client to communicate with the Blogger servers.
For documentation on the Blogger API, see:
http://code.google.com/apis/blogger/
"""
__author__ = 'j.s@google.com (Jeff Scudder)'
import gdata.client
import gdata.gauth | import gdata.blogger.data
import atom.data
import atom.http_core
# List user's blogs, takes a user ID, or 'default'.
BLOGS_URL = 'http://www.blogger.com/feeds/%s/blogs'
# Takes a blog ID.
BLOG_POST_URL = 'http://www.blogger.com/feeds/%s/posts/default'
# Takes a blog ID.
BLOG_PAGE_URL = 'http://www.blogger.com/feeds/%s/pages/default'
# Takes a blog ID and post ID.
BLOG_POST_COMMENTS_URL = 'http://www.blogger.com/feeds/%s/%s/comments/default'
# Takes a blog ID.
BLOG_COMMENTS_URL = 'http://www.blogger.com/feeds/%s/comments/default'
# Takes a blog ID.
BLOG_ARCHIVE_URL = 'http://www.blogger.com/feeds/%s/archive/full'
class BloggerClient(gdata.client.GDClient):
api_version = '2'
auth_service = 'blogger'
auth_scopes = gdata.gauth.AUTH_SCOPES['blogger']
def get_blogs(self, user_id='default', auth_token=None,
desired_class=gdata.blogger.data.BlogFeed, **kwargs):
return self.get_feed(BLOGS_URL % user_id, auth_token=auth_token,
desired_class=desired_class, **kwargs)
GetBlogs = get_blogs
def get_posts(self, blog_id, auth_token=None,
desired_class=gdata.blogger.data.BlogPostFeed, query=None,
**kwargs):
return self.get_feed(BLOG_POST_URL % blog_id, auth_token=auth_token,
desired_class=desired_class, query=query, **kwargs)
GetPosts = get_posts
def get_pages(self, blog_id, auth_token=None,
desired_class=gdata.blogger.data.BlogPageFeed, query=None,
**kwargs):
return self.get_feed(BLOG_PAGE_URL % blog_id, auth_token=auth_token,
desired_class=desired_class, query=query, **kwargs)
GetPages = get_pages
def get_post_comments(self, blog_id, post_id, auth_token=None,
desired_class=gdata.blogger.data.CommentFeed,
query=None, **kwargs):
return self.get_feed(BLOG_POST_COMMENTS_URL % (blog_id, post_id),
auth_token=auth_token, desired_class=desired_class,
query=query, **kwargs)
GetPostComments = get_post_comments
def get_blog_comments(self, blog_id, auth_token=None,
desired_class=gdata.blogger.data.CommentFeed,
query=None, **kwargs):
return self.get_feed(BLOG_COMMENTS_URL % blog_id, auth_token=auth_token,
desired_class=desired_class, query=query, **kwargs)
GetBlogComments = get_blog_comments
def get_blog_archive(self, blog_id, auth_token=None, **kwargs):
return self.get_feed(BLOG_ARCHIVE_URL % blog_id, auth_token=auth_token,
**kwargs)
GetBlogArchive = get_blog_archive
def add_post(self, blog_id, title, body, labels=None, draft=False,
auth_token=None, title_type='text', body_type='html', **kwargs):
# Construct an atom Entry for the blog post to be sent to the server.
new_entry = gdata.blogger.data.BlogPost(
title=atom.data.Title(text=title, type=title_type),
content=atom.data.Content(text=body, type=body_type))
if labels:
for label in labels:
new_entry.add_label(label)
if draft:
new_entry.control = atom.data.Control(draft=atom.data.Draft(text='yes'))
return self.post(new_entry, BLOG_POST_URL % blog_id, auth_token=auth_token, **kwargs)
AddPost = add_post
def add_page(self, blog_id, title, body, draft=False, auth_token=None,
title_type='text', body_type='html', **kwargs):
new_entry = gdata.blogger.data.BlogPage(
title=atom.data.Title(text=title, type=title_type),
content=atom.data.Content(text=body, type=body_type))
if draft:
new_entry.control = atom.data.Control(draft=atom.data.Draft(text='yes'))
return self.post(new_entry, BLOG_PAGE_URL % blog_id, auth_token=auth_token, **kwargs)
AddPage = add_page
def add_comment(self, blog_id, post_id, body, auth_token=None,
title_type='text', body_type='html', **kwargs):
new_entry = gdata.blogger.data.Comment(
content=atom.data.Content(text=body, type=body_type))
return self.post(new_entry, BLOG_POST_COMMENTS_URL % (blog_id, post_id),
auth_token=auth_token, **kwargs)
AddComment = add_comment
def update(self, entry, auth_token=None, **kwargs):
# The Blogger API does not currently support ETags, so for now remove
# the ETag before performing an update.
old_etag = entry.etag
entry.etag = None
response = gdata.client.GDClient.update(self, entry,
auth_token=auth_token, **kwargs)
entry.etag = old_etag
return response
Update = update
def delete(self, entry_or_uri, auth_token=None, **kwargs):
if isinstance(entry_or_uri, (str, atom.http_core.Uri)):
return gdata.client.GDClient.delete(self, entry_or_uri,
auth_token=auth_token, **kwargs)
# The Blogger API does not currently support ETags, so for now remove
# the ETag before performing a delete.
old_etag = entry_or_uri.etag
entry_or_uri.etag = None
response = gdata.client.GDClient.delete(self, entry_or_uri,
auth_token=auth_token, **kwargs)
# TODO: if GDClient.delete raises and exception, the entry's etag may be
# left as None. Should revisit this logic.
entry_or_uri.etag = old_etag
return response
Delete = delete
class Query(gdata.client.Query):
def __init__(self, order_by=None, **kwargs):
gdata.client.Query.__init__(self, **kwargs)
self.order_by = order_by
def modify_request(self, http_request):
gdata.client._add_query_param('orderby', self.order_by, http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request | random_line_split | |
client.py | #!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains a client to communicate with the Blogger servers.
For documentation on the Blogger API, see:
http://code.google.com/apis/blogger/
"""
__author__ = 'j.s@google.com (Jeff Scudder)'
import gdata.client
import gdata.gauth
import gdata.blogger.data
import atom.data
import atom.http_core
# List user's blogs, takes a user ID, or 'default'.
BLOGS_URL = 'http://www.blogger.com/feeds/%s/blogs'
# Takes a blog ID.
BLOG_POST_URL = 'http://www.blogger.com/feeds/%s/posts/default'
# Takes a blog ID.
BLOG_PAGE_URL = 'http://www.blogger.com/feeds/%s/pages/default'
# Takes a blog ID and post ID.
BLOG_POST_COMMENTS_URL = 'http://www.blogger.com/feeds/%s/%s/comments/default'
# Takes a blog ID.
BLOG_COMMENTS_URL = 'http://www.blogger.com/feeds/%s/comments/default'
# Takes a blog ID.
BLOG_ARCHIVE_URL = 'http://www.blogger.com/feeds/%s/archive/full'
class BloggerClient(gdata.client.GDClient):
api_version = '2'
auth_service = 'blogger'
auth_scopes = gdata.gauth.AUTH_SCOPES['blogger']
def get_blogs(self, user_id='default', auth_token=None,
desired_class=gdata.blogger.data.BlogFeed, **kwargs):
return self.get_feed(BLOGS_URL % user_id, auth_token=auth_token,
desired_class=desired_class, **kwargs)
GetBlogs = get_blogs
def get_posts(self, blog_id, auth_token=None,
desired_class=gdata.blogger.data.BlogPostFeed, query=None,
**kwargs):
return self.get_feed(BLOG_POST_URL % blog_id, auth_token=auth_token,
desired_class=desired_class, query=query, **kwargs)
GetPosts = get_posts
def get_pages(self, blog_id, auth_token=None,
desired_class=gdata.blogger.data.BlogPageFeed, query=None,
**kwargs):
return self.get_feed(BLOG_PAGE_URL % blog_id, auth_token=auth_token,
desired_class=desired_class, query=query, **kwargs)
GetPages = get_pages
def get_post_comments(self, blog_id, post_id, auth_token=None,
desired_class=gdata.blogger.data.CommentFeed,
query=None, **kwargs):
return self.get_feed(BLOG_POST_COMMENTS_URL % (blog_id, post_id),
auth_token=auth_token, desired_class=desired_class,
query=query, **kwargs)
GetPostComments = get_post_comments
def get_blog_comments(self, blog_id, auth_token=None,
desired_class=gdata.blogger.data.CommentFeed,
query=None, **kwargs):
return self.get_feed(BLOG_COMMENTS_URL % blog_id, auth_token=auth_token,
desired_class=desired_class, query=query, **kwargs)
GetBlogComments = get_blog_comments
def get_blog_archive(self, blog_id, auth_token=None, **kwargs):
return self.get_feed(BLOG_ARCHIVE_URL % blog_id, auth_token=auth_token,
**kwargs)
GetBlogArchive = get_blog_archive
def add_post(self, blog_id, title, body, labels=None, draft=False,
auth_token=None, title_type='text', body_type='html', **kwargs):
# Construct an atom Entry for the blog post to be sent to the server.
new_entry = gdata.blogger.data.BlogPost(
title=atom.data.Title(text=title, type=title_type),
content=atom.data.Content(text=body, type=body_type))
if labels:
for label in labels:
|
if draft:
new_entry.control = atom.data.Control(draft=atom.data.Draft(text='yes'))
return self.post(new_entry, BLOG_POST_URL % blog_id, auth_token=auth_token, **kwargs)
AddPost = add_post
def add_page(self, blog_id, title, body, draft=False, auth_token=None,
title_type='text', body_type='html', **kwargs):
new_entry = gdata.blogger.data.BlogPage(
title=atom.data.Title(text=title, type=title_type),
content=atom.data.Content(text=body, type=body_type))
if draft:
new_entry.control = atom.data.Control(draft=atom.data.Draft(text='yes'))
return self.post(new_entry, BLOG_PAGE_URL % blog_id, auth_token=auth_token, **kwargs)
AddPage = add_page
def add_comment(self, blog_id, post_id, body, auth_token=None,
title_type='text', body_type='html', **kwargs):
new_entry = gdata.blogger.data.Comment(
content=atom.data.Content(text=body, type=body_type))
return self.post(new_entry, BLOG_POST_COMMENTS_URL % (blog_id, post_id),
auth_token=auth_token, **kwargs)
AddComment = add_comment
def update(self, entry, auth_token=None, **kwargs):
# The Blogger API does not currently support ETags, so for now remove
# the ETag before performing an update.
old_etag = entry.etag
entry.etag = None
response = gdata.client.GDClient.update(self, entry,
auth_token=auth_token, **kwargs)
entry.etag = old_etag
return response
Update = update
def delete(self, entry_or_uri, auth_token=None, **kwargs):
if isinstance(entry_or_uri, (str, atom.http_core.Uri)):
return gdata.client.GDClient.delete(self, entry_or_uri,
auth_token=auth_token, **kwargs)
# The Blogger API does not currently support ETags, so for now remove
# the ETag before performing a delete.
old_etag = entry_or_uri.etag
entry_or_uri.etag = None
response = gdata.client.GDClient.delete(self, entry_or_uri,
auth_token=auth_token, **kwargs)
# TODO: if GDClient.delete raises and exception, the entry's etag may be
# left as None. Should revisit this logic.
entry_or_uri.etag = old_etag
return response
Delete = delete
class Query(gdata.client.Query):
def __init__(self, order_by=None, **kwargs):
gdata.client.Query.__init__(self, **kwargs)
self.order_by = order_by
def modify_request(self, http_request):
gdata.client._add_query_param('orderby', self.order_by, http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request
| new_entry.add_label(label) | conditional_block |
client.py | #!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains a client to communicate with the Blogger servers.
For documentation on the Blogger API, see:
http://code.google.com/apis/blogger/
"""
__author__ = 'j.s@google.com (Jeff Scudder)'
import gdata.client
import gdata.gauth
import gdata.blogger.data
import atom.data
import atom.http_core
# List user's blogs, takes a user ID, or 'default'.
BLOGS_URL = 'http://www.blogger.com/feeds/%s/blogs'
# Takes a blog ID.
BLOG_POST_URL = 'http://www.blogger.com/feeds/%s/posts/default'
# Takes a blog ID.
BLOG_PAGE_URL = 'http://www.blogger.com/feeds/%s/pages/default'
# Takes a blog ID and post ID.
BLOG_POST_COMMENTS_URL = 'http://www.blogger.com/feeds/%s/%s/comments/default'
# Takes a blog ID.
BLOG_COMMENTS_URL = 'http://www.blogger.com/feeds/%s/comments/default'
# Takes a blog ID.
BLOG_ARCHIVE_URL = 'http://www.blogger.com/feeds/%s/archive/full'
class BloggerClient(gdata.client.GDClient):
api_version = '2'
auth_service = 'blogger'
auth_scopes = gdata.gauth.AUTH_SCOPES['blogger']
def get_blogs(self, user_id='default', auth_token=None,
desired_class=gdata.blogger.data.BlogFeed, **kwargs):
return self.get_feed(BLOGS_URL % user_id, auth_token=auth_token,
desired_class=desired_class, **kwargs)
GetBlogs = get_blogs
def get_posts(self, blog_id, auth_token=None,
desired_class=gdata.blogger.data.BlogPostFeed, query=None,
**kwargs):
return self.get_feed(BLOG_POST_URL % blog_id, auth_token=auth_token,
desired_class=desired_class, query=query, **kwargs)
GetPosts = get_posts
def get_pages(self, blog_id, auth_token=None,
desired_class=gdata.blogger.data.BlogPageFeed, query=None,
**kwargs):
return self.get_feed(BLOG_PAGE_URL % blog_id, auth_token=auth_token,
desired_class=desired_class, query=query, **kwargs)
GetPages = get_pages
def get_post_comments(self, blog_id, post_id, auth_token=None,
desired_class=gdata.blogger.data.CommentFeed,
query=None, **kwargs):
return self.get_feed(BLOG_POST_COMMENTS_URL % (blog_id, post_id),
auth_token=auth_token, desired_class=desired_class,
query=query, **kwargs)
GetPostComments = get_post_comments
def get_blog_comments(self, blog_id, auth_token=None,
desired_class=gdata.blogger.data.CommentFeed,
query=None, **kwargs):
return self.get_feed(BLOG_COMMENTS_URL % blog_id, auth_token=auth_token,
desired_class=desired_class, query=query, **kwargs)
GetBlogComments = get_blog_comments
def | (self, blog_id, auth_token=None, **kwargs):
return self.get_feed(BLOG_ARCHIVE_URL % blog_id, auth_token=auth_token,
**kwargs)
GetBlogArchive = get_blog_archive
def add_post(self, blog_id, title, body, labels=None, draft=False,
auth_token=None, title_type='text', body_type='html', **kwargs):
# Construct an atom Entry for the blog post to be sent to the server.
new_entry = gdata.blogger.data.BlogPost(
title=atom.data.Title(text=title, type=title_type),
content=atom.data.Content(text=body, type=body_type))
if labels:
for label in labels:
new_entry.add_label(label)
if draft:
new_entry.control = atom.data.Control(draft=atom.data.Draft(text='yes'))
return self.post(new_entry, BLOG_POST_URL % blog_id, auth_token=auth_token, **kwargs)
AddPost = add_post
def add_page(self, blog_id, title, body, draft=False, auth_token=None,
title_type='text', body_type='html', **kwargs):
new_entry = gdata.blogger.data.BlogPage(
title=atom.data.Title(text=title, type=title_type),
content=atom.data.Content(text=body, type=body_type))
if draft:
new_entry.control = atom.data.Control(draft=atom.data.Draft(text='yes'))
return self.post(new_entry, BLOG_PAGE_URL % blog_id, auth_token=auth_token, **kwargs)
AddPage = add_page
def add_comment(self, blog_id, post_id, body, auth_token=None,
title_type='text', body_type='html', **kwargs):
new_entry = gdata.blogger.data.Comment(
content=atom.data.Content(text=body, type=body_type))
return self.post(new_entry, BLOG_POST_COMMENTS_URL % (blog_id, post_id),
auth_token=auth_token, **kwargs)
AddComment = add_comment
def update(self, entry, auth_token=None, **kwargs):
# The Blogger API does not currently support ETags, so for now remove
# the ETag before performing an update.
old_etag = entry.etag
entry.etag = None
response = gdata.client.GDClient.update(self, entry,
auth_token=auth_token, **kwargs)
entry.etag = old_etag
return response
Update = update
def delete(self, entry_or_uri, auth_token=None, **kwargs):
if isinstance(entry_or_uri, (str, atom.http_core.Uri)):
return gdata.client.GDClient.delete(self, entry_or_uri,
auth_token=auth_token, **kwargs)
# The Blogger API does not currently support ETags, so for now remove
# the ETag before performing a delete.
old_etag = entry_or_uri.etag
entry_or_uri.etag = None
response = gdata.client.GDClient.delete(self, entry_or_uri,
auth_token=auth_token, **kwargs)
# TODO: if GDClient.delete raises and exception, the entry's etag may be
# left as None. Should revisit this logic.
entry_or_uri.etag = old_etag
return response
Delete = delete
class Query(gdata.client.Query):
def __init__(self, order_by=None, **kwargs):
gdata.client.Query.__init__(self, **kwargs)
self.order_by = order_by
def modify_request(self, http_request):
gdata.client._add_query_param('orderby', self.order_by, http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request
| get_blog_archive | identifier_name |
Tiled.js | /*
Copyright (C) 2012 by Samuel Ronce
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
if (typeof exports != "undefined") {
var CE = require("canvasengine").listen(),
CanvasEngine = false,
Class = CE.Class;
}
Class.create("Tiled", {
el: null,
url: "",
tile_w: 0,
tile_h: 0,
tile_image_h:0,
tile_image_w:0,
tilesets: [],
width: 0,
height: 0,
layers: [],
objects: {},
scene: null,
_ready: null,
initialize: function() {
},
/**
@doc tiled/
@method ready Calls the function when the layers are drawn
@param {Function} callback
*/
ready: function(callback) {
this._ready = callback;
},
/**
@doc tiled/
@method load Load JSON file and draw layers in the element of the scene. View Tiled class description for more informations (http://canvasengine.net/doc/?p=editor.tiled)
@param {CanvasEngine.Scene} scene
@param {CanvasEngine.Element} el The element containing layers of Tiled
@param {String} url Path to JSON file of Tiled Map Editor
@example
Example with Node.js :
Server :
var CE = require("canvasengine").listen(8333),
Tiled = CE.Core.requireExtend("Tiled").Class,
Class = CE.Class;
CE.Model.init("Main", {
initialize: function(socket) {
var tiled = Class.New("Tiled");
tiled.ready(function(map) {
socket.emit("Scene_Map.load", map);
});
tiled.load("Map/map.json");
}
});
Client :
canvas.Scene.New({
name: "Scene_Map",
events: ["load"],
materials: {
images: {
tileset: "my_tileset.png"
}
},
load: function(data) {
var tiled = canvas.Tiled.New();
tiled.ready(function() {
var tile_w = this.getTileWidth(),
tile_h = this.getTileHeight(),
layer_object = this.getLayerObject();
});
tiled.load(this, this.getStage(), data);
}
});
*/
load: function(scene, el, url) {
var self = this;
if (typeof scene == "string") {
this.url = url = scene;
}
else {
this.el = el;
this.url = url;
this.scene = scene;
}
function ready(data) {
var clone_data = CE.Core.extend({}, data);
self.tile_h = data.tileheight;
self.tile_w = data.tilewidth;
self.width = data.width;
self.height = data.height;
self.tilesets = data.tilesets;
self.layers = data.layers;
self.tilesetsIndexed = [];
for (var i=0 ; i < self.tilesets.length ; i++) {
var props = self.tilesets[i].tileproperties,
new_props = {};
if (props) {
for (var key in props) {
new_props[+key+1] = props[key];
}
self.tilesets[i].tileproperties = new_props;
}
self.tilesetsIndexed[self.tilesets[i].firstgid] = self.tilesets[i];
}
//
// Check to see if the tileset uses a different height/width to the layer
// For example, pseudo-3d tiles such as PlanetCute are 101x171 sprites
// on a Tiled layer grid of 101x80
//
if (self.tilesets[0].tileheight && self.tilesets[0].tilewidth) {
self.tile_image_h = self.tilesets[0].tileheight;
self.tile_image_w = self.tilesets[0].tilewidth;
} else {
self.tile_image_h = self.tile_h;
self.tile_image_w = self.tile_w;
}
var _id, length = self.tilesetsIndexed.length + (Math.round(self.tilesets[self.tilesets.length-1].imageheight / self.tile_h) * (Math.round(self.tilesets[self.tilesets.length-1].imagewidth / self.tile_w)));
for (var m=0; m < length; m++) {
_id = self.tilesetsIndexed[m] ? m : _id;
self.tilesetsIndexed[m] = self.tilesetsIndexed[_id];
}
if (typeof exports == "undefined") {
self._draw();
}
else {
if (self._ready) self._ready.call(self, clone_data);
}
}
if (typeof url === 'string') {
(CanvasEngine || CE.Core).getJSON(this.url, ready);
}
else {
ready(url);
}
},
_drawTile: function(_id, layer_name, data) {
var _tile = this.scene.createElement(),
tileset, tileoffset, nb_tile = {};
if (data.position != "absolute") {
data.x *= this.tile_w;
data.y *= this.tile_h;
}
var flippedHorizontally = false, flippedVertically = false, flippedAntiDiagonally = false;
if (_id & Tiled.FlippedHorizontallyFlag) {
flippedHorizontally = true;
}
if (_id & Tiled.FlippedVerticallyFlag) {
flippedVertically = true;
}
if (_id & Tiled.FlippedAntiDiagonallyFlag) {
flippedAntiDiagonally = true;
}
_id &= ~(Tiled.FlippedHorizontallyFlag | Tiled.FlippedVerticallyFlag | Tiled.FlippedAntiDiagonallyFlag);
tileset = this.tilesetsIndexed[_id];
_id -= tileset.firstgid;
nb_tile = {
width: tileset.imagewidth / this.tile_image_w,
height: tileset.imageheight / this.tile_image_h
};
tileoffset = tileset.tileoffset || {x: 0, y: 0};
y = this.tile_image_h * Math.floor(_id / (nb_tile.width - (nb_tile.width / 2 * tileset.margin)));
x = this.tile_w * (_id % Math.round((tileset.imagewidth - nb_tile.height / 2 * tileset.margin) / this.tile_w));
_tile.drawImage(tileset.name, x + tileset.spacing * x / this.tile_w + tileset.margin, y + tileset.spacing * y / this.tile_h + tileset.margin, this.tile_w, this.tile_h, data.x + tileoffset.x, data.y + tileoffset.y, this.tile_w, this.tile_h);
this.el_layers[layer_name].append(_tile);
var scaleX = (flippedHorizontally) ? -1 : 1,
scaleY = (flippedVertically) ? -1 : 1,
rotation = 0;
if (flippedAntiDiagonally) {
rotation = 90;
scaleX *= -1;
halfDiff = nb_tile.height/2 - nb_tile.width/2
y += halfDiff
}
_tile.drawImage(tileset.name, x + tileset.spacing * x / this.tile_image_w + tileset.margin, y + tileset.spacing * y / this.tile_image_h + tileset.margin, this.tile_image_w, this.tile_image_h, 0, 0, this.tile_image_w, this.tile_image_h);
_tile.x = data.x + tileoffset.x
_tile.y = data.y + tileoffset.y
_tile.width = this.tile_w
_tile.height = this.tile_h
_tile.setOriginPoint("middle");
_tile.scaleX = scaleX
_tile.scaleY = scaleY
_tile.rotation = rotation
if (data.visible === false) {
_tile.hide();
}
this.el_layers[layer_name].append(_tile);
return _tile;
},
_draw: function() {
this.map = this.scene.createElement();
this.el_layers = {};
var x, y, tileset, layer, self = this;
var id, _id, obj, layer_type, el_objs = {};
for (var i=0 ; i < this.layers.length ; i++) {
id = 0;
layer = this.layers[i];
this.el_layers[layer.name] = this.scene.createElement();
if (layer.type == "tilelayer") {
for (var k=0 ; k < layer.height ; k++) {
for (var j=0 ; j < layer.width ; j++) {
_id = layer.data[id];
if (_id != 0) {
this._drawTile(_id, layer.name, {
x: j,
y: k
});
}
id++;
}
}
}
else if (layer.type == "objectgroup") {
for (var j=0 ; j < layer.objects.length ; j++) {
obj = layer.objects[j];
if (!el_objs[obj.name]) el_objs[obj.name] = [];
if (obj.gid) {
el_objs[obj.name].push(this._drawTile(obj.gid, layer.name, CE.extend(obj, {
y: obj.y - this.tile_h,
position: "absolute"
})));
}
}
this.objects[layer.name] = {
layer: this.el_layers[layer.name],
objects: el_objs
};
}
this.map.append(this.el_layers[layer.name]);
}
this.el.append(this.map);
if (this._ready) this._ready.call(this);
},
/**
@doc tiled/
@method getLayerObject Retrieves the object layer.
@param {Integer} name Returns the layer by name
@return {CanvasEngine.Element}
*/
getLayerObject: function(name) {
if (!name) {
for (var id in this.objects) {
name = id;
break;
}
}
if (!this.objects[name]) {
return false;
}
return this.objects[name].layer;
},
// TODO
getObject: function(layer_name, obj_name, pos) {
if (!pos) pos = 0;
return this.objects[layer_name].objects[obj_name][pos];
},
/**
@doc tiled/
@method getLayer Retrieves the layer by its identifier.
@param {String} id Layer name in Tiled Map Editor
@return {CanvasEngine.Element}
*/
getLayer: function(id) {
return this.el_layers[id];
},
/**
@doc tiled/
@method getMap Returns the element containing all the layers
@return {CanvasEngine.Element}
*/
getMap: function() {
return this.map;
},
/**
@doc tiled/
@method getTileWidth Returns the width of the map in tiles
@return {Integer}
*/
getTileWidth: function() {
return this.tile_w;
},
/**
@doc tiled/
@method getTileHeight Returns the height of the map in tiles
@return {Integer}
*/
getTileHeight: function() {
return this.tile_h;
},
/**
@doc tiled/
@method getWidthPixel Returns the width of the map in pixels
@return {Integer}
*/
getWidthPixel: function() {
return this.width * this.getTileWidth();
},
/**
@doc tiled/
@method getHeightPixel Returns the height of the map in pixels
@return {Integer}
*/
getHeightPixel: function() {
return this.height * this.getTileHeight();
},
/**
@doc tiled/
@method getDataLayers Returns the data for each map
@return {Array}
*/
getDataLayers: function() {
var layer = [];
for (var i=0 ; i < this.layers.length ; i++) {
if (this.layers[i].data) layer.push(this.layers[i].data);
}
return layer;
},
/**
@doc tiled/
@method getTileInMap Retrieves the position of a tile to the Tileset according positions X and Y
@params {Integer} x Position X
@params {Integer} y Position Y
@return {Array}
*/
getTileInMap: function(x, y) {
return this.width * y + x;
},
/**
@doc tiled/
@method getTileProperties Gets the properties of a tile depending on its identifier
@params {Integer} tile Id of tile
@params {String} (optional) layer Layer name
@return {Object}
*/
/**
@doc tiled/
@method getTileProperties Gets the properties of a tile depending on its positions
@params {Integer} tile Id of tile. Put "null"
@params {Integer} x Positon X
@params {Integer} y Positon Y
@return {Object}
*/
getTileProperties: function(tile, layerOrX, y) {
var self = this;
var tileset = this.tilesets[0];
function _getTileLayers(tile) |
if (layerOrX === undefined) {
return _getTileLayers(tile);
}
else if (y !== undefined) {
var new_tile = this.getTileInMap(layerOrX, y);
return _getTileLayers(new_tile);
}
return tileset.tileproperties[this.layers[layerOrX].data[tile]];
},
tileToProperty: function(prop_name) {
var layers = this.getDataLayers(), val;
var new_layers = [];
for (var i=0 ; i < layers.length ; i++) {
new_layers[i] = [];
for (var j=0 ; j < layers[i].length ; j++) {
val = this.tilesets[0].tileproperties[layers[i][j]]; // Hack Tiled Bug
new_layers[i][j] = val ? +val[prop_name] : 0;
}
}
return new_layers;
}
});
/**
@doc tiled
@class Tiled Tiled is a general purpose tile map editor. It's built to be easy to use, yet flexible enough to work with varying game engines, whether your game is an RPG, platformer or Breakout clone. Tiled is free software and written in C++, using the Qt application framework.
http://www.mapeditor.org
Consider adding inserting Tiled.js
<script src="extends/Tiled.js"></script>
<script>
var canvas = CE.defines("canvas_id").
extend(Tiled).
ready(function() {
});
</script>
@param {CanvasEngine.Scene} scene
@param {CanvasEngine.Element} el The layers are displayed on this element
@param {String} url Path to the JSON file of Tiled Map Editor
@example
var canvas = CE.defines("canvas_id").
extend(Tiled).
ready(function() {
canvas.Scene.call("MyScene");
});
canvas.Scene.new({
name: "MyScene",
materials: {
images: {
mytileset: "path/to/tileset.png"
}
},
ready: function(stage) {
var el = this.createElement();
var tiled = canvas.Tiled.new();
tiled.ready(function() {
var tile_w = this.getTileWidth(),
tile_h = this.getTileHeight(),
layer_object = this.getLayerObject();
stage.append(el);
});
tiled.load(this, el, "map/map.json");
}
});
1. `mytileset` in material object is the name of tileset in Tiled Map Editor
2. `getLayer()` retrieves a layer. The name is the same as in Tiled Map Editor

*/
var Tiled = {
Tiled: {
FlippedHorizontallyFlag: 0x80000000,
FlippedVerticallyFlag: 0x40000000,
FlippedAntiDiagonallyFlag: 0x20000000,
New: function() { return this["new"].apply(this, arguments); },
"new": function(scene, el, url) {
return Class["new"]("Tiled", [scene, el, url]);
}
}
};
if (typeof exports != "undefined") {
exports.Class = Tiled.Tiled;
}
| {
var _layers = [];
for (var i=0 ; i < self.layers.length ; i++) {
if (self.layers[i].data) _layers.push(tileset.tileproperties[self.layers[i].data[tile]]);
}
return _layers;
} | identifier_body |
Tiled.js | /*
Copyright (C) 2012 by Samuel Ronce
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
if (typeof exports != "undefined") {
var CE = require("canvasengine").listen(),
CanvasEngine = false,
Class = CE.Class;
}
Class.create("Tiled", {
el: null,
url: "",
tile_w: 0,
tile_h: 0,
tile_image_h:0,
tile_image_w:0,
tilesets: [],
width: 0,
height: 0,
layers: [],
objects: {},
scene: null,
_ready: null,
initialize: function() {
},
/**
@doc tiled/
@method ready Calls the function when the layers are drawn
@param {Function} callback
*/
ready: function(callback) {
this._ready = callback;
},
/**
@doc tiled/
@method load Load JSON file and draw layers in the element of the scene. View Tiled class description for more informations (http://canvasengine.net/doc/?p=editor.tiled)
@param {CanvasEngine.Scene} scene
@param {CanvasEngine.Element} el The element containing layers of Tiled
@param {String} url Path to JSON file of Tiled Map Editor
@example
Example with Node.js :
Server :
var CE = require("canvasengine").listen(8333),
Tiled = CE.Core.requireExtend("Tiled").Class,
Class = CE.Class;
CE.Model.init("Main", {
initialize: function(socket) {
var tiled = Class.New("Tiled");
tiled.ready(function(map) {
socket.emit("Scene_Map.load", map);
});
tiled.load("Map/map.json");
}
});
Client :
canvas.Scene.New({
name: "Scene_Map",
events: ["load"],
materials: {
images: {
tileset: "my_tileset.png"
}
},
load: function(data) {
var tiled = canvas.Tiled.New();
tiled.ready(function() {
var tile_w = this.getTileWidth(),
tile_h = this.getTileHeight(),
layer_object = this.getLayerObject();
});
tiled.load(this, this.getStage(), data);
}
});
*/
load: function(scene, el, url) {
var self = this;
if (typeof scene == "string") {
this.url = url = scene;
}
else {
this.el = el;
this.url = url;
this.scene = scene;
}
function | (data) {
var clone_data = CE.Core.extend({}, data);
self.tile_h = data.tileheight;
self.tile_w = data.tilewidth;
self.width = data.width;
self.height = data.height;
self.tilesets = data.tilesets;
self.layers = data.layers;
self.tilesetsIndexed = [];
for (var i=0 ; i < self.tilesets.length ; i++) {
var props = self.tilesets[i].tileproperties,
new_props = {};
if (props) {
for (var key in props) {
new_props[+key+1] = props[key];
}
self.tilesets[i].tileproperties = new_props;
}
self.tilesetsIndexed[self.tilesets[i].firstgid] = self.tilesets[i];
}
//
// Check to see if the tileset uses a different height/width to the layer
// For example, pseudo-3d tiles such as PlanetCute are 101x171 sprites
// on a Tiled layer grid of 101x80
//
if (self.tilesets[0].tileheight && self.tilesets[0].tilewidth) {
self.tile_image_h = self.tilesets[0].tileheight;
self.tile_image_w = self.tilesets[0].tilewidth;
} else {
self.tile_image_h = self.tile_h;
self.tile_image_w = self.tile_w;
}
var _id, length = self.tilesetsIndexed.length + (Math.round(self.tilesets[self.tilesets.length-1].imageheight / self.tile_h) * (Math.round(self.tilesets[self.tilesets.length-1].imagewidth / self.tile_w)));
for (var m=0; m < length; m++) {
_id = self.tilesetsIndexed[m] ? m : _id;
self.tilesetsIndexed[m] = self.tilesetsIndexed[_id];
}
if (typeof exports == "undefined") {
self._draw();
}
else {
if (self._ready) self._ready.call(self, clone_data);
}
}
if (typeof url === 'string') {
(CanvasEngine || CE.Core).getJSON(this.url, ready);
}
else {
ready(url);
}
},
_drawTile: function(_id, layer_name, data) {
var _tile = this.scene.createElement(),
tileset, tileoffset, nb_tile = {};
if (data.position != "absolute") {
data.x *= this.tile_w;
data.y *= this.tile_h;
}
var flippedHorizontally = false, flippedVertically = false, flippedAntiDiagonally = false;
if (_id & Tiled.FlippedHorizontallyFlag) {
flippedHorizontally = true;
}
if (_id & Tiled.FlippedVerticallyFlag) {
flippedVertically = true;
}
if (_id & Tiled.FlippedAntiDiagonallyFlag) {
flippedAntiDiagonally = true;
}
_id &= ~(Tiled.FlippedHorizontallyFlag | Tiled.FlippedVerticallyFlag | Tiled.FlippedAntiDiagonallyFlag);
tileset = this.tilesetsIndexed[_id];
_id -= tileset.firstgid;
nb_tile = {
width: tileset.imagewidth / this.tile_image_w,
height: tileset.imageheight / this.tile_image_h
};
tileoffset = tileset.tileoffset || {x: 0, y: 0};
y = this.tile_image_h * Math.floor(_id / (nb_tile.width - (nb_tile.width / 2 * tileset.margin)));
x = this.tile_w * (_id % Math.round((tileset.imagewidth - nb_tile.height / 2 * tileset.margin) / this.tile_w));
_tile.drawImage(tileset.name, x + tileset.spacing * x / this.tile_w + tileset.margin, y + tileset.spacing * y / this.tile_h + tileset.margin, this.tile_w, this.tile_h, data.x + tileoffset.x, data.y + tileoffset.y, this.tile_w, this.tile_h);
this.el_layers[layer_name].append(_tile);
var scaleX = (flippedHorizontally) ? -1 : 1,
scaleY = (flippedVertically) ? -1 : 1,
rotation = 0;
if (flippedAntiDiagonally) {
rotation = 90;
scaleX *= -1;
halfDiff = nb_tile.height/2 - nb_tile.width/2
y += halfDiff
}
_tile.drawImage(tileset.name, x + tileset.spacing * x / this.tile_image_w + tileset.margin, y + tileset.spacing * y / this.tile_image_h + tileset.margin, this.tile_image_w, this.tile_image_h, 0, 0, this.tile_image_w, this.tile_image_h);
_tile.x = data.x + tileoffset.x
_tile.y = data.y + tileoffset.y
_tile.width = this.tile_w
_tile.height = this.tile_h
_tile.setOriginPoint("middle");
_tile.scaleX = scaleX
_tile.scaleY = scaleY
_tile.rotation = rotation
if (data.visible === false) {
_tile.hide();
}
this.el_layers[layer_name].append(_tile);
return _tile;
},
_draw: function() {
this.map = this.scene.createElement();
this.el_layers = {};
var x, y, tileset, layer, self = this;
var id, _id, obj, layer_type, el_objs = {};
for (var i=0 ; i < this.layers.length ; i++) {
id = 0;
layer = this.layers[i];
this.el_layers[layer.name] = this.scene.createElement();
if (layer.type == "tilelayer") {
for (var k=0 ; k < layer.height ; k++) {
for (var j=0 ; j < layer.width ; j++) {
_id = layer.data[id];
if (_id != 0) {
this._drawTile(_id, layer.name, {
x: j,
y: k
});
}
id++;
}
}
}
else if (layer.type == "objectgroup") {
for (var j=0 ; j < layer.objects.length ; j++) {
obj = layer.objects[j];
if (!el_objs[obj.name]) el_objs[obj.name] = [];
if (obj.gid) {
el_objs[obj.name].push(this._drawTile(obj.gid, layer.name, CE.extend(obj, {
y: obj.y - this.tile_h,
position: "absolute"
})));
}
}
this.objects[layer.name] = {
layer: this.el_layers[layer.name],
objects: el_objs
};
}
this.map.append(this.el_layers[layer.name]);
}
this.el.append(this.map);
if (this._ready) this._ready.call(this);
},
/**
@doc tiled/
@method getLayerObject Retrieves the object layer.
@param {Integer} name Returns the layer by name
@return {CanvasEngine.Element}
*/
getLayerObject: function(name) {
if (!name) {
for (var id in this.objects) {
name = id;
break;
}
}
if (!this.objects[name]) {
return false;
}
return this.objects[name].layer;
},
// TODO
getObject: function(layer_name, obj_name, pos) {
if (!pos) pos = 0;
return this.objects[layer_name].objects[obj_name][pos];
},
/**
@doc tiled/
@method getLayer Retrieves the layer by its identifier.
@param {String} id Layer name in Tiled Map Editor
@return {CanvasEngine.Element}
*/
getLayer: function(id) {
return this.el_layers[id];
},
/**
@doc tiled/
@method getMap Returns the element containing all the layers
@return {CanvasEngine.Element}
*/
getMap: function() {
return this.map;
},
/**
@doc tiled/
@method getTileWidth Returns the width of the map in tiles
@return {Integer}
*/
getTileWidth: function() {
return this.tile_w;
},
/**
@doc tiled/
@method getTileHeight Returns the height of the map in tiles
@return {Integer}
*/
getTileHeight: function() {
return this.tile_h;
},
/**
@doc tiled/
@method getWidthPixel Returns the width of the map in pixels
@return {Integer}
*/
getWidthPixel: function() {
return this.width * this.getTileWidth();
},
/**
@doc tiled/
@method getHeightPixel Returns the height of the map in pixels
@return {Integer}
*/
getHeightPixel: function() {
return this.height * this.getTileHeight();
},
/**
@doc tiled/
@method getDataLayers Returns the data for each map
@return {Array}
*/
getDataLayers: function() {
var layer = [];
for (var i=0 ; i < this.layers.length ; i++) {
if (this.layers[i].data) layer.push(this.layers[i].data);
}
return layer;
},
/**
@doc tiled/
@method getTileInMap Retrieves the position of a tile to the Tileset according positions X and Y
@params {Integer} x Position X
@params {Integer} y Position Y
@return {Array}
*/
getTileInMap: function(x, y) {
return this.width * y + x;
},
/**
@doc tiled/
@method getTileProperties Gets the properties of a tile depending on its identifier
@params {Integer} tile Id of tile
@params {String} (optional) layer Layer name
@return {Object}
*/
/**
@doc tiled/
@method getTileProperties Gets the properties of a tile depending on its positions
@params {Integer} tile Id of tile. Put "null"
@params {Integer} x Positon X
@params {Integer} y Positon Y
@return {Object}
*/
getTileProperties: function(tile, layerOrX, y) {
var self = this;
var tileset = this.tilesets[0];
function _getTileLayers(tile) {
var _layers = [];
for (var i=0 ; i < self.layers.length ; i++) {
if (self.layers[i].data) _layers.push(tileset.tileproperties[self.layers[i].data[tile]]);
}
return _layers;
}
if (layerOrX === undefined) {
return _getTileLayers(tile);
}
else if (y !== undefined) {
var new_tile = this.getTileInMap(layerOrX, y);
return _getTileLayers(new_tile);
}
return tileset.tileproperties[this.layers[layerOrX].data[tile]];
},
tileToProperty: function(prop_name) {
var layers = this.getDataLayers(), val;
var new_layers = [];
for (var i=0 ; i < layers.length ; i++) {
new_layers[i] = [];
for (var j=0 ; j < layers[i].length ; j++) {
val = this.tilesets[0].tileproperties[layers[i][j]]; // Hack Tiled Bug
new_layers[i][j] = val ? +val[prop_name] : 0;
}
}
return new_layers;
}
});
/**
@doc tiled
@class Tiled Tiled is a general purpose tile map editor. It's built to be easy to use, yet flexible enough to work with varying game engines, whether your game is an RPG, platformer or Breakout clone. Tiled is free software and written in C++, using the Qt application framework.
http://www.mapeditor.org
Consider adding inserting Tiled.js
<script src="extends/Tiled.js"></script>
<script>
var canvas = CE.defines("canvas_id").
extend(Tiled).
ready(function() {
});
</script>
@param {CanvasEngine.Scene} scene
@param {CanvasEngine.Element} el The layers are displayed on this element
@param {String} url Path to the JSON file of Tiled Map Editor
@example
var canvas = CE.defines("canvas_id").
extend(Tiled).
ready(function() {
canvas.Scene.call("MyScene");
});
canvas.Scene.new({
name: "MyScene",
materials: {
images: {
mytileset: "path/to/tileset.png"
}
},
ready: function(stage) {
var el = this.createElement();
var tiled = canvas.Tiled.new();
tiled.ready(function() {
var tile_w = this.getTileWidth(),
tile_h = this.getTileHeight(),
layer_object = this.getLayerObject();
stage.append(el);
});
tiled.load(this, el, "map/map.json");
}
});
1. `mytileset` in material object is the name of tileset in Tiled Map Editor
2. `getLayer()` retrieves a layer. The name is the same as in Tiled Map Editor

*/
var Tiled = {
Tiled: {
FlippedHorizontallyFlag: 0x80000000,
FlippedVerticallyFlag: 0x40000000,
FlippedAntiDiagonallyFlag: 0x20000000,
New: function() { return this["new"].apply(this, arguments); },
"new": function(scene, el, url) {
return Class["new"]("Tiled", [scene, el, url]);
}
}
};
if (typeof exports != "undefined") {
exports.Class = Tiled.Tiled;
}
| ready | identifier_name |
Tiled.js | /*
Copyright (C) 2012 by Samuel Ronce
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
if (typeof exports != "undefined") {
var CE = require("canvasengine").listen(),
CanvasEngine = false,
Class = CE.Class;
}
Class.create("Tiled", {
el: null,
url: "",
tile_w: 0,
tile_h: 0,
tile_image_h:0,
tile_image_w:0,
tilesets: [],
width: 0,
height: 0,
layers: [],
objects: {},
scene: null,
_ready: null,
initialize: function() {
},
/**
@doc tiled/
@method ready Calls the function when the layers are drawn
@param {Function} callback
*/
ready: function(callback) {
this._ready = callback;
},
/**
@doc tiled/
@method load Load JSON file and draw layers in the element of the scene. View Tiled class description for more informations (http://canvasengine.net/doc/?p=editor.tiled)
@param {CanvasEngine.Scene} scene
@param {CanvasEngine.Element} el The element containing layers of Tiled
@param {String} url Path to JSON file of Tiled Map Editor
@example
Example with Node.js :
Server :
var CE = require("canvasengine").listen(8333),
Tiled = CE.Core.requireExtend("Tiled").Class,
Class = CE.Class;
CE.Model.init("Main", {
initialize: function(socket) {
var tiled = Class.New("Tiled");
tiled.ready(function(map) {
socket.emit("Scene_Map.load", map);
});
tiled.load("Map/map.json");
}
});
Client :
canvas.Scene.New({
name: "Scene_Map",
events: ["load"],
materials: {
images: {
tileset: "my_tileset.png"
}
},
load: function(data) {
var tiled = canvas.Tiled.New();
tiled.ready(function() {
var tile_w = this.getTileWidth(),
tile_h = this.getTileHeight(),
layer_object = this.getLayerObject();
});
tiled.load(this, this.getStage(), data);
}
});
*/
load: function(scene, el, url) {
var self = this;
if (typeof scene == "string") {
this.url = url = scene;
}
else {
this.el = el;
this.url = url;
this.scene = scene;
}
function ready(data) {
var clone_data = CE.Core.extend({}, data);
self.tile_h = data.tileheight;
self.tile_w = data.tilewidth;
self.width = data.width;
self.height = data.height;
self.tilesets = data.tilesets;
self.layers = data.layers;
self.tilesetsIndexed = [];
for (var i=0 ; i < self.tilesets.length ; i++) {
var props = self.tilesets[i].tileproperties,
new_props = {};
if (props) {
for (var key in props) {
new_props[+key+1] = props[key];
}
self.tilesets[i].tileproperties = new_props;
}
self.tilesetsIndexed[self.tilesets[i].firstgid] = self.tilesets[i];
}
//
// Check to see if the tileset uses a different height/width to the layer
// For example, pseudo-3d tiles such as PlanetCute are 101x171 sprites
// on a Tiled layer grid of 101x80
//
if (self.tilesets[0].tileheight && self.tilesets[0].tilewidth) {
self.tile_image_h = self.tilesets[0].tileheight;
self.tile_image_w = self.tilesets[0].tilewidth;
} else {
self.tile_image_h = self.tile_h;
self.tile_image_w = self.tile_w;
}
var _id, length = self.tilesetsIndexed.length + (Math.round(self.tilesets[self.tilesets.length-1].imageheight / self.tile_h) * (Math.round(self.tilesets[self.tilesets.length-1].imagewidth / self.tile_w)));
for (var m=0; m < length; m++) {
_id = self.tilesetsIndexed[m] ? m : _id;
self.tilesetsIndexed[m] = self.tilesetsIndexed[_id];
}
if (typeof exports == "undefined") {
self._draw();
}
else {
if (self._ready) self._ready.call(self, clone_data);
}
}
if (typeof url === 'string') {
(CanvasEngine || CE.Core).getJSON(this.url, ready);
}
else {
ready(url);
}
},
_drawTile: function(_id, layer_name, data) {
var _tile = this.scene.createElement(),
tileset, tileoffset, nb_tile = {};
if (data.position != "absolute") {
data.x *= this.tile_w;
data.y *= this.tile_h;
}
var flippedHorizontally = false, flippedVertically = false, flippedAntiDiagonally = false;
if (_id & Tiled.FlippedHorizontallyFlag) {
flippedHorizontally = true;
}
if (_id & Tiled.FlippedVerticallyFlag) {
flippedVertically = true;
}
if (_id & Tiled.FlippedAntiDiagonallyFlag) {
flippedAntiDiagonally = true;
}
_id &= ~(Tiled.FlippedHorizontallyFlag | Tiled.FlippedVerticallyFlag | Tiled.FlippedAntiDiagonallyFlag);
tileset = this.tilesetsIndexed[_id];
_id -= tileset.firstgid;
nb_tile = {
width: tileset.imagewidth / this.tile_image_w,
height: tileset.imageheight / this.tile_image_h
};
tileoffset = tileset.tileoffset || {x: 0, y: 0};
y = this.tile_image_h * Math.floor(_id / (nb_tile.width - (nb_tile.width / 2 * tileset.margin)));
x = this.tile_w * (_id % Math.round((tileset.imagewidth - nb_tile.height / 2 * tileset.margin) / this.tile_w));
_tile.drawImage(tileset.name, x + tileset.spacing * x / this.tile_w + tileset.margin, y + tileset.spacing * y / this.tile_h + tileset.margin, this.tile_w, this.tile_h, data.x + tileoffset.x, data.y + tileoffset.y, this.tile_w, this.tile_h);
this.el_layers[layer_name].append(_tile);
var scaleX = (flippedHorizontally) ? -1 : 1,
scaleY = (flippedVertically) ? -1 : 1,
rotation = 0;
if (flippedAntiDiagonally) {
rotation = 90;
scaleX *= -1;
halfDiff = nb_tile.height/2 - nb_tile.width/2
y += halfDiff
}
_tile.drawImage(tileset.name, x + tileset.spacing * x / this.tile_image_w + tileset.margin, y + tileset.spacing * y / this.tile_image_h + tileset.margin, this.tile_image_w, this.tile_image_h, 0, 0, this.tile_image_w, this.tile_image_h);
_tile.x = data.x + tileoffset.x
_tile.y = data.y + tileoffset.y
_tile.width = this.tile_w
_tile.height = this.tile_h
_tile.setOriginPoint("middle");
_tile.scaleX = scaleX
_tile.scaleY = scaleY
_tile.rotation = rotation
if (data.visible === false) {
_tile.hide();
}
this.el_layers[layer_name].append(_tile);
return _tile;
},
_draw: function() {
this.map = this.scene.createElement();
this.el_layers = {};
var x, y, tileset, layer, self = this;
var id, _id, obj, layer_type, el_objs = {};
for (var i=0 ; i < this.layers.length ; i++) {
id = 0;
layer = this.layers[i];
this.el_layers[layer.name] = this.scene.createElement();
if (layer.type == "tilelayer") {
for (var k=0 ; k < layer.height ; k++) {
for (var j=0 ; j < layer.width ; j++) |
}
}
else if (layer.type == "objectgroup") {
for (var j=0 ; j < layer.objects.length ; j++) {
obj = layer.objects[j];
if (!el_objs[obj.name]) el_objs[obj.name] = [];
if (obj.gid) {
el_objs[obj.name].push(this._drawTile(obj.gid, layer.name, CE.extend(obj, {
y: obj.y - this.tile_h,
position: "absolute"
})));
}
}
this.objects[layer.name] = {
layer: this.el_layers[layer.name],
objects: el_objs
};
}
this.map.append(this.el_layers[layer.name]);
}
this.el.append(this.map);
if (this._ready) this._ready.call(this);
},
/**
@doc tiled/
@method getLayerObject Retrieves the object layer.
@param {Integer} name Returns the layer by name
@return {CanvasEngine.Element}
*/
getLayerObject: function(name) {
if (!name) {
for (var id in this.objects) {
name = id;
break;
}
}
if (!this.objects[name]) {
return false;
}
return this.objects[name].layer;
},
// TODO
getObject: function(layer_name, obj_name, pos) {
if (!pos) pos = 0;
return this.objects[layer_name].objects[obj_name][pos];
},
/**
@doc tiled/
@method getLayer Retrieves the layer by its identifier.
@param {String} id Layer name in Tiled Map Editor
@return {CanvasEngine.Element}
*/
getLayer: function(id) {
return this.el_layers[id];
},
/**
@doc tiled/
@method getMap Returns the element containing all the layers
@return {CanvasEngine.Element}
*/
getMap: function() {
return this.map;
},
/**
@doc tiled/
@method getTileWidth Returns the width of the map in tiles
@return {Integer}
*/
getTileWidth: function() {
return this.tile_w;
},
/**
@doc tiled/
@method getTileHeight Returns the height of the map in tiles
@return {Integer}
*/
getTileHeight: function() {
return this.tile_h;
},
/**
@doc tiled/
@method getWidthPixel Returns the width of the map in pixels
@return {Integer}
*/
getWidthPixel: function() {
return this.width * this.getTileWidth();
},
/**
@doc tiled/
@method getHeightPixel Returns the height of the map in pixels
@return {Integer}
*/
getHeightPixel: function() {
return this.height * this.getTileHeight();
},
/**
@doc tiled/
@method getDataLayers Returns the data for each map
@return {Array}
*/
getDataLayers: function() {
var layer = [];
for (var i=0 ; i < this.layers.length ; i++) {
if (this.layers[i].data) layer.push(this.layers[i].data);
}
return layer;
},
/**
@doc tiled/
@method getTileInMap Retrieves the position of a tile to the Tileset according positions X and Y
@params {Integer} x Position X
@params {Integer} y Position Y
@return {Array}
*/
getTileInMap: function(x, y) {
return this.width * y + x;
},
/**
@doc tiled/
@method getTileProperties Gets the properties of a tile depending on its identifier
@params {Integer} tile Id of tile
@params {String} (optional) layer Layer name
@return {Object}
*/
/**
@doc tiled/
@method getTileProperties Gets the properties of a tile depending on its positions
@params {Integer} tile Id of tile. Put "null"
@params {Integer} x Positon X
@params {Integer} y Positon Y
@return {Object}
*/
getTileProperties: function(tile, layerOrX, y) {
var self = this;
var tileset = this.tilesets[0];
function _getTileLayers(tile) {
var _layers = [];
for (var i=0 ; i < self.layers.length ; i++) {
if (self.layers[i].data) _layers.push(tileset.tileproperties[self.layers[i].data[tile]]);
}
return _layers;
}
if (layerOrX === undefined) {
return _getTileLayers(tile);
}
else if (y !== undefined) {
var new_tile = this.getTileInMap(layerOrX, y);
return _getTileLayers(new_tile);
}
return tileset.tileproperties[this.layers[layerOrX].data[tile]];
},
tileToProperty: function(prop_name) {
var layers = this.getDataLayers(), val;
var new_layers = [];
for (var i=0 ; i < layers.length ; i++) {
new_layers[i] = [];
for (var j=0 ; j < layers[i].length ; j++) {
val = this.tilesets[0].tileproperties[layers[i][j]]; // Hack Tiled Bug
new_layers[i][j] = val ? +val[prop_name] : 0;
}
}
return new_layers;
}
});
/**
@doc tiled
@class Tiled Tiled is a general purpose tile map editor. It's built to be easy to use, yet flexible enough to work with varying game engines, whether your game is an RPG, platformer or Breakout clone. Tiled is free software and written in C++, using the Qt application framework.
http://www.mapeditor.org
Consider adding inserting Tiled.js
<script src="extends/Tiled.js"></script>
<script>
var canvas = CE.defines("canvas_id").
extend(Tiled).
ready(function() {
});
</script>
@param {CanvasEngine.Scene} scene
@param {CanvasEngine.Element} el The layers are displayed on this element
@param {String} url Path to the JSON file of Tiled Map Editor
@example
var canvas = CE.defines("canvas_id").
extend(Tiled).
ready(function() {
canvas.Scene.call("MyScene");
});
canvas.Scene.new({
name: "MyScene",
materials: {
images: {
mytileset: "path/to/tileset.png"
}
},
ready: function(stage) {
var el = this.createElement();
var tiled = canvas.Tiled.new();
tiled.ready(function() {
var tile_w = this.getTileWidth(),
tile_h = this.getTileHeight(),
layer_object = this.getLayerObject();
stage.append(el);
});
tiled.load(this, el, "map/map.json");
}
});
1. `mytileset` in material object is the name of tileset in Tiled Map Editor
2. `getLayer()` retrieves a layer. The name is the same as in Tiled Map Editor

*/
var Tiled = {
Tiled: {
FlippedHorizontallyFlag: 0x80000000,
FlippedVerticallyFlag: 0x40000000,
FlippedAntiDiagonallyFlag: 0x20000000,
New: function() { return this["new"].apply(this, arguments); },
"new": function(scene, el, url) {
return Class["new"]("Tiled", [scene, el, url]);
}
}
};
if (typeof exports != "undefined") {
exports.Class = Tiled.Tiled;
}
| {
_id = layer.data[id];
if (_id != 0) {
this._drawTile(_id, layer.name, {
x: j,
y: k
});
}
id++;
} | conditional_block |
Tiled.js | /*
Copyright (C) 2012 by Samuel Ronce | of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
if (typeof exports != "undefined") {
var CE = require("canvasengine").listen(),
CanvasEngine = false,
Class = CE.Class;
}
Class.create("Tiled", {
el: null,
url: "",
tile_w: 0,
tile_h: 0,
tile_image_h:0,
tile_image_w:0,
tilesets: [],
width: 0,
height: 0,
layers: [],
objects: {},
scene: null,
_ready: null,
initialize: function() {
},
/**
@doc tiled/
@method ready Calls the function when the layers are drawn
@param {Function} callback
*/
ready: function(callback) {
this._ready = callback;
},
/**
@doc tiled/
@method load Load JSON file and draw layers in the element of the scene. View Tiled class description for more informations (http://canvasengine.net/doc/?p=editor.tiled)
@param {CanvasEngine.Scene} scene
@param {CanvasEngine.Element} el The element containing layers of Tiled
@param {String} url Path to JSON file of Tiled Map Editor
@example
Example with Node.js :
Server :
var CE = require("canvasengine").listen(8333),
Tiled = CE.Core.requireExtend("Tiled").Class,
Class = CE.Class;
CE.Model.init("Main", {
initialize: function(socket) {
var tiled = Class.New("Tiled");
tiled.ready(function(map) {
socket.emit("Scene_Map.load", map);
});
tiled.load("Map/map.json");
}
});
Client :
canvas.Scene.New({
name: "Scene_Map",
events: ["load"],
materials: {
images: {
tileset: "my_tileset.png"
}
},
load: function(data) {
var tiled = canvas.Tiled.New();
tiled.ready(function() {
var tile_w = this.getTileWidth(),
tile_h = this.getTileHeight(),
layer_object = this.getLayerObject();
});
tiled.load(this, this.getStage(), data);
}
});
*/
load: function(scene, el, url) {
var self = this;
if (typeof scene == "string") {
this.url = url = scene;
}
else {
this.el = el;
this.url = url;
this.scene = scene;
}
function ready(data) {
var clone_data = CE.Core.extend({}, data);
self.tile_h = data.tileheight;
self.tile_w = data.tilewidth;
self.width = data.width;
self.height = data.height;
self.tilesets = data.tilesets;
self.layers = data.layers;
self.tilesetsIndexed = [];
for (var i=0 ; i < self.tilesets.length ; i++) {
var props = self.tilesets[i].tileproperties,
new_props = {};
if (props) {
for (var key in props) {
new_props[+key+1] = props[key];
}
self.tilesets[i].tileproperties = new_props;
}
self.tilesetsIndexed[self.tilesets[i].firstgid] = self.tilesets[i];
}
//
// Check to see if the tileset uses a different height/width to the layer
// For example, pseudo-3d tiles such as PlanetCute are 101x171 sprites
// on a Tiled layer grid of 101x80
//
if (self.tilesets[0].tileheight && self.tilesets[0].tilewidth) {
self.tile_image_h = self.tilesets[0].tileheight;
self.tile_image_w = self.tilesets[0].tilewidth;
} else {
self.tile_image_h = self.tile_h;
self.tile_image_w = self.tile_w;
}
var _id, length = self.tilesetsIndexed.length + (Math.round(self.tilesets[self.tilesets.length-1].imageheight / self.tile_h) * (Math.round(self.tilesets[self.tilesets.length-1].imagewidth / self.tile_w)));
for (var m=0; m < length; m++) {
_id = self.tilesetsIndexed[m] ? m : _id;
self.tilesetsIndexed[m] = self.tilesetsIndexed[_id];
}
if (typeof exports == "undefined") {
self._draw();
}
else {
if (self._ready) self._ready.call(self, clone_data);
}
}
if (typeof url === 'string') {
(CanvasEngine || CE.Core).getJSON(this.url, ready);
}
else {
ready(url);
}
},
_drawTile: function(_id, layer_name, data) {
var _tile = this.scene.createElement(),
tileset, tileoffset, nb_tile = {};
if (data.position != "absolute") {
data.x *= this.tile_w;
data.y *= this.tile_h;
}
var flippedHorizontally = false, flippedVertically = false, flippedAntiDiagonally = false;
if (_id & Tiled.FlippedHorizontallyFlag) {
flippedHorizontally = true;
}
if (_id & Tiled.FlippedVerticallyFlag) {
flippedVertically = true;
}
if (_id & Tiled.FlippedAntiDiagonallyFlag) {
flippedAntiDiagonally = true;
}
_id &= ~(Tiled.FlippedHorizontallyFlag | Tiled.FlippedVerticallyFlag | Tiled.FlippedAntiDiagonallyFlag);
tileset = this.tilesetsIndexed[_id];
_id -= tileset.firstgid;
nb_tile = {
width: tileset.imagewidth / this.tile_image_w,
height: tileset.imageheight / this.tile_image_h
};
tileoffset = tileset.tileoffset || {x: 0, y: 0};
y = this.tile_image_h * Math.floor(_id / (nb_tile.width - (nb_tile.width / 2 * tileset.margin)));
x = this.tile_w * (_id % Math.round((tileset.imagewidth - nb_tile.height / 2 * tileset.margin) / this.tile_w));
_tile.drawImage(tileset.name, x + tileset.spacing * x / this.tile_w + tileset.margin, y + tileset.spacing * y / this.tile_h + tileset.margin, this.tile_w, this.tile_h, data.x + tileoffset.x, data.y + tileoffset.y, this.tile_w, this.tile_h);
this.el_layers[layer_name].append(_tile);
var scaleX = (flippedHorizontally) ? -1 : 1,
scaleY = (flippedVertically) ? -1 : 1,
rotation = 0;
if (flippedAntiDiagonally) {
rotation = 90;
scaleX *= -1;
halfDiff = nb_tile.height/2 - nb_tile.width/2
y += halfDiff
}
_tile.drawImage(tileset.name, x + tileset.spacing * x / this.tile_image_w + tileset.margin, y + tileset.spacing * y / this.tile_image_h + tileset.margin, this.tile_image_w, this.tile_image_h, 0, 0, this.tile_image_w, this.tile_image_h);
_tile.x = data.x + tileoffset.x
_tile.y = data.y + tileoffset.y
_tile.width = this.tile_w
_tile.height = this.tile_h
_tile.setOriginPoint("middle");
_tile.scaleX = scaleX
_tile.scaleY = scaleY
_tile.rotation = rotation
if (data.visible === false) {
_tile.hide();
}
this.el_layers[layer_name].append(_tile);
return _tile;
},
_draw: function() {
this.map = this.scene.createElement();
this.el_layers = {};
var x, y, tileset, layer, self = this;
var id, _id, obj, layer_type, el_objs = {};
for (var i=0 ; i < this.layers.length ; i++) {
id = 0;
layer = this.layers[i];
this.el_layers[layer.name] = this.scene.createElement();
if (layer.type == "tilelayer") {
for (var k=0 ; k < layer.height ; k++) {
for (var j=0 ; j < layer.width ; j++) {
_id = layer.data[id];
if (_id != 0) {
this._drawTile(_id, layer.name, {
x: j,
y: k
});
}
id++;
}
}
}
else if (layer.type == "objectgroup") {
for (var j=0 ; j < layer.objects.length ; j++) {
obj = layer.objects[j];
if (!el_objs[obj.name]) el_objs[obj.name] = [];
if (obj.gid) {
el_objs[obj.name].push(this._drawTile(obj.gid, layer.name, CE.extend(obj, {
y: obj.y - this.tile_h,
position: "absolute"
})));
}
}
this.objects[layer.name] = {
layer: this.el_layers[layer.name],
objects: el_objs
};
}
this.map.append(this.el_layers[layer.name]);
}
this.el.append(this.map);
if (this._ready) this._ready.call(this);
},
/**
@doc tiled/
@method getLayerObject Retrieves the object layer.
@param {Integer} name Returns the layer by name
@return {CanvasEngine.Element}
*/
getLayerObject: function(name) {
if (!name) {
for (var id in this.objects) {
name = id;
break;
}
}
if (!this.objects[name]) {
return false;
}
return this.objects[name].layer;
},
// TODO
getObject: function(layer_name, obj_name, pos) {
if (!pos) pos = 0;
return this.objects[layer_name].objects[obj_name][pos];
},
/**
@doc tiled/
@method getLayer Retrieves the layer by its identifier.
@param {String} id Layer name in Tiled Map Editor
@return {CanvasEngine.Element}
*/
getLayer: function(id) {
return this.el_layers[id];
},
/**
@doc tiled/
@method getMap Returns the element containing all the layers
@return {CanvasEngine.Element}
*/
getMap: function() {
return this.map;
},
/**
@doc tiled/
@method getTileWidth Returns the width of the map in tiles
@return {Integer}
*/
getTileWidth: function() {
return this.tile_w;
},
/**
@doc tiled/
@method getTileHeight Returns the height of the map in tiles
@return {Integer}
*/
getTileHeight: function() {
return this.tile_h;
},
/**
@doc tiled/
@method getWidthPixel Returns the width of the map in pixels
@return {Integer}
*/
getWidthPixel: function() {
return this.width * this.getTileWidth();
},
/**
@doc tiled/
@method getHeightPixel Returns the height of the map in pixels
@return {Integer}
*/
getHeightPixel: function() {
return this.height * this.getTileHeight();
},
/**
@doc tiled/
@method getDataLayers Returns the data for each map
@return {Array}
*/
getDataLayers: function() {
var layer = [];
for (var i=0 ; i < this.layers.length ; i++) {
if (this.layers[i].data) layer.push(this.layers[i].data);
}
return layer;
},
/**
@doc tiled/
@method getTileInMap Retrieves the position of a tile to the Tileset according positions X and Y
@params {Integer} x Position X
@params {Integer} y Position Y
@return {Array}
*/
getTileInMap: function(x, y) {
return this.width * y + x;
},
/**
@doc tiled/
@method getTileProperties Gets the properties of a tile depending on its identifier
@params {Integer} tile Id of tile
@params {String} (optional) layer Layer name
@return {Object}
*/
/**
@doc tiled/
@method getTileProperties Gets the properties of a tile depending on its positions
@params {Integer} tile Id of tile. Put "null"
@params {Integer} x Positon X
@params {Integer} y Positon Y
@return {Object}
*/
getTileProperties: function(tile, layerOrX, y) {
var self = this;
var tileset = this.tilesets[0];
function _getTileLayers(tile) {
var _layers = [];
for (var i=0 ; i < self.layers.length ; i++) {
if (self.layers[i].data) _layers.push(tileset.tileproperties[self.layers[i].data[tile]]);
}
return _layers;
}
if (layerOrX === undefined) {
return _getTileLayers(tile);
}
else if (y !== undefined) {
var new_tile = this.getTileInMap(layerOrX, y);
return _getTileLayers(new_tile);
}
return tileset.tileproperties[this.layers[layerOrX].data[tile]];
},
tileToProperty: function(prop_name) {
var layers = this.getDataLayers(), val;
var new_layers = [];
for (var i=0 ; i < layers.length ; i++) {
new_layers[i] = [];
for (var j=0 ; j < layers[i].length ; j++) {
val = this.tilesets[0].tileproperties[layers[i][j]]; // Hack Tiled Bug
new_layers[i][j] = val ? +val[prop_name] : 0;
}
}
return new_layers;
}
});
/**
@doc tiled
@class Tiled Tiled is a general purpose tile map editor. It's built to be easy to use, yet flexible enough to work with varying game engines, whether your game is an RPG, platformer or Breakout clone. Tiled is free software and written in C++, using the Qt application framework.
http://www.mapeditor.org
Consider adding inserting Tiled.js
<script src="extends/Tiled.js"></script>
<script>
var canvas = CE.defines("canvas_id").
extend(Tiled).
ready(function() {
});
</script>
@param {CanvasEngine.Scene} scene
@param {CanvasEngine.Element} el The layers are displayed on this element
@param {String} url Path to the JSON file of Tiled Map Editor
@example
var canvas = CE.defines("canvas_id").
extend(Tiled).
ready(function() {
canvas.Scene.call("MyScene");
});
canvas.Scene.new({
name: "MyScene",
materials: {
images: {
mytileset: "path/to/tileset.png"
}
},
ready: function(stage) {
var el = this.createElement();
var tiled = canvas.Tiled.new();
tiled.ready(function() {
var tile_w = this.getTileWidth(),
tile_h = this.getTileHeight(),
layer_object = this.getLayerObject();
stage.append(el);
});
tiled.load(this, el, "map/map.json");
}
});
1. `mytileset` in material object is the name of tileset in Tiled Map Editor
2. `getLayer()` retrieves a layer. The name is the same as in Tiled Map Editor

*/
var Tiled = {
Tiled: {
FlippedHorizontallyFlag: 0x80000000,
FlippedVerticallyFlag: 0x40000000,
FlippedAntiDiagonallyFlag: 0x20000000,
New: function() { return this["new"].apply(this, arguments); },
"new": function(scene, el, url) {
return Class["new"]("Tiled", [scene, el, url]);
}
}
};
if (typeof exports != "undefined") {
exports.Class = Tiled.Tiled;
} |
Permission is hereby granted, free of charge, to any person obtaining a copy | random_line_split |
tab-header.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Direction, Directionality} from '@angular/cdk/bidi';
import {ENTER, LEFT_ARROW, RIGHT_ARROW, SPACE} from '@angular/cdk/keycodes';
import {auditTime, startWith} from '@angular/cdk/rxjs';
import {
AfterContentChecked,
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Optional,
Output,
QueryList,
Renderer2,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import {CanDisableRipple, mixinDisableRipple} from '@angular/material/core';
import {fromEvent} from 'rxjs/observable/fromEvent';
import {merge} from 'rxjs/observable/merge';
import {of as observableOf} from 'rxjs/observable/of';
import {Subscription} from 'rxjs/Subscription';
import {MdInkBar} from './ink-bar';
import {MdTabLabelWrapper} from './tab-label-wrapper';
/**
* The directions that scrolling can go in when the header's tabs exceed the header width. 'After'
* will scroll the header towards the end of the tabs list and 'before' will scroll towards the
* beginning of the list.
*/
export type ScrollDirection = 'after' | 'before';
/**
* The distance in pixels that will be overshot when scrolling a tab label into view. This helps
* provide a small affordance to the label next to it.
*/
const EXAGGERATED_OVERSCROLL = 60;
// Boilerplate for applying mixins to MdTabHeader.
/** @docs-private */
export class MdTabHeaderBase {}
export const _MdTabHeaderMixinBase = mixinDisableRipple(MdTabHeaderBase);
/**
* The header of the tab group which displays a list of all the tabs in the tab group. Includes
* an ink bar that follows the currently selected tab. When the tabs list's width exceeds the
* width of the header container, then arrows will be displayed to allow the user to scroll
* left and right across the header.
* @docs-private
*/
@Component({
moduleId: module.id,
selector: 'md-tab-header, mat-tab-header',
templateUrl: 'tab-header.html',
styleUrls: ['tab-header.css'],
inputs: ['disableRipple'],
encapsulation: ViewEncapsulation.None,
preserveWhitespaces: false,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'class': 'mat-tab-header',
'[class.mat-tab-header-pagination-controls-enabled]': '_showPaginationControls',
'[class.mat-tab-header-rtl]': "_getLayoutDirection() == 'rtl'",
}
})
export class MdTabHeader extends _MdTabHeaderMixinBase
implements AfterContentChecked, AfterContentInit, OnDestroy, CanDisableRipple {
@ContentChildren(MdTabLabelWrapper) _labelWrappers: QueryList<MdTabLabelWrapper>;
@ViewChild(MdInkBar) _inkBar: MdInkBar;
@ViewChild('tabListContainer') _tabListContainer: ElementRef;
@ViewChild('tabList') _tabList: ElementRef;
/** The tab index that is focused. */
private _focusIndex: number = 0;
/** The distance in pixels that the tab labels should be translated to the left. */
private _scrollDistance = 0;
/** Whether the header should scroll to the selected index after the view has been checked. */
private _selectedIndexChanged = false;
/** Combines listeners that will re-align the ink bar whenever they're invoked. */
private _realignInkBar = Subscription.EMPTY;
/** Whether the controls for pagination should be displayed */
_showPaginationControls = false;
/** Whether the tab list can be scrolled more towards the end of the tab label list. */
_disableScrollAfter = true;
/** Whether the tab list can be scrolled more towards the beginning of the tab label list. */
_disableScrollBefore = true;
/**
* The number of tab labels that are displayed on the header. When this changes, the header
* should re-evaluate the scroll position.
*/
private _tabLabelCount: number;
/** Whether the scroll distance has changed and should be applied after the view is checked. */
private _scrollDistanceChanged: boolean;
private _selectedIndex: number = 0;
/** The index of the active tab. */
@Input()
get selectedIndex(): number { return this._selectedIndex; }
set selectedIndex(value: number) {
this._selectedIndexChanged = this._selectedIndex != value;
this._selectedIndex = value;
this._focusIndex = value;
}
/** Event emitted when the option is selected. */
@Output() selectFocusedIndex = new EventEmitter();
/** Event emitted when a label is focused. */
@Output() indexFocused = new EventEmitter();
constructor(private _elementRef: ElementRef,
private _renderer: Renderer2,
private _changeDetectorRef: ChangeDetectorRef,
@Optional() private _dir: Directionality) {
super();
}
ngAfterContentChecked(): void {
// If the number of tab labels have changed, check if scrolling should be enabled
if (this._tabLabelCount != this._labelWrappers.length) {
this._updatePagination();
this._tabLabelCount = this._labelWrappers.length;
this._changeDetectorRef.markForCheck();
}
// If the selected index has changed, scroll to the label and check if the scrolling controls
// should be disabled.
if (this._selectedIndexChanged) {
this._scrollToLabel(this._selectedIndex);
this._checkScrollingControls();
this._alignInkBarToSelectedTab();
this._selectedIndexChanged = false;
this._changeDetectorRef.markForCheck();
}
// If the scroll distance has been changed (tab selected, focused, scroll controls activated),
// then translate the header to reflect this.
if (this._scrollDistanceChanged) {
this._updateTabScrollPosition();
this._scrollDistanceChanged = false;
this._changeDetectorRef.markForCheck();
}
}
_handleKeydown(event: KeyboardEvent) {
switch (event.keyCode) {
case RIGHT_ARROW:
this._focusNextTab();
break;
case LEFT_ARROW:
this._focusPreviousTab();
break;
case ENTER:
case SPACE:
this.selectFocusedIndex.emit(this.focusIndex);
event.preventDefault();
break;
}
}
/**
* Aligns the ink bar to the selected tab on load.
*/
ngAfterContentInit() {
const dirChange = this._dir ? this._dir.change : observableOf(null);
const resize = typeof window !== 'undefined' ?
auditTime.call(fromEvent(window, 'resize'), 150) :
observableOf(null);
this._realignInkBar = startWith.call(merge(dirChange, resize), null).subscribe(() => {
this._updatePagination();
this._alignInkBarToSelectedTab();
});
}
ngOnDestroy() {
this._realignInkBar.unsubscribe();
}
/**
* Callback for when the MutationObserver detects that the content has changed.
*/
_onContentChanges() {
this._updatePagination();
this._alignInkBarToSelectedTab();
this._changeDetectorRef.markForCheck();
}
/**
* Updating the view whether pagination should be enabled or not
*/
_updatePagination() {
this._checkPaginationEnabled();
this._checkScrollingControls();
this._updateTabScrollPosition();
}
/** When the focus index is set, we must manually send focus to the correct label */
set focusIndex(value: number) {
if (!this._isValidIndex(value) || this._focusIndex == value) { return; }
this._focusIndex = value;
this.indexFocused.emit(value);
this._setTabFocus(value);
}
/** Tracks which element has focus; used for keyboard navigation */
get focusIndex(): number { return this._focusIndex; }
/**
* Determines if an index is valid. If the tabs are not ready yet, we assume that the user is
* providing a valid index and return true.
*/
_isValidIndex(index: number): boolean {
if (!this._labelWrappers) { return true; }
const tab = this._labelWrappers ? this._labelWrappers.toArray()[index] : null;
return !!tab && !tab.disabled;
}
/**
* Sets focus on the HTML element for the label wrapper and scrolls it into the view if
* scrolling is enabled.
*/
_setTabFocus(tabIndex: number) {
if (this._showPaginationControls) {
this._scrollToLabel(tabIndex);
}
if (this._labelWrappers && this._labelWrappers.length) {
this._labelWrappers.toArray()[tabIndex].focus();
// Do not let the browser manage scrolling to focus the element, this will be handled
// by using translation. In LTR, the scroll left should be 0. In RTL, the scroll width
// should be the full width minus the offset width.
const containerEl = this._tabListContainer.nativeElement;
const dir = this._getLayoutDirection();
if (dir == 'ltr') {
containerEl.scrollLeft = 0;
} else {
containerEl.scrollLeft = containerEl.scrollWidth - containerEl.offsetWidth;
}
}
}
/**
* Moves the focus towards the beginning or the end of the list depending on the offset provided.
* Valid offsets are 1 and -1.
*/
_moveFocus(offset: number) {
if (this._labelWrappers) {
const tabs: MdTabLabelWrapper[] = this._labelWrappers.toArray();
for (let i = this.focusIndex + offset; i < tabs.length && i >= 0; i += offset) {
if (this._isValidIndex(i)) {
this.focusIndex = i;
return;
}
}
}
}
/** Increment the focus index by 1 until a valid tab is found. */
_focusNextTab(): void {
this._moveFocus(this._getLayoutDirection() == 'ltr' ? 1 : -1);
}
/** Decrement the focus index by 1 until a valid tab is found. */
_focusPreviousTab(): void {
this._moveFocus(this._getLayoutDirection() == 'ltr' ? -1 : 1);
}
/** The layout direction of the containing app. */
_getLayoutDirection(): Direction {
return this._dir && this._dir.value === 'rtl' ? 'rtl' : 'ltr';
}
/** Performs the CSS transformation on the tab list that will cause the list to scroll. */
_updateTabScrollPosition() {
const scrollDistance = this.scrollDistance;
const translateX = this._getLayoutDirection() === 'ltr' ? -scrollDistance : scrollDistance;
this._renderer.setStyle(this._tabList.nativeElement, 'transform',
`translate3d(${translateX}px, 0, 0)`);
}
/** Sets the distance in pixels that the tab header should be transformed in the X-axis. */
set scrollDistance(v: number) |
get scrollDistance(): number { return this._scrollDistance; }
/**
* Moves the tab list in the 'before' or 'after' direction (towards the beginning of the list or
* the end of the list, respectively). The distance to scroll is computed to be a third of the
* length of the tab list view window.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_scrollHeader(scrollDir: ScrollDirection) {
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
// Move the scroll distance one-third the length of the tab list's viewport.
this.scrollDistance += (scrollDir == 'before' ? -1 : 1) * viewLength / 3;
}
/**
* Moves the tab list such that the desired tab label (marked by index) is moved into view.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_scrollToLabel(labelIndex: number) {
const selectedLabel = this._labelWrappers ? this._labelWrappers.toArray()[labelIndex] : null;
if (!selectedLabel) { return; }
// The view length is the visible width of the tab labels.
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
let labelBeforePos: number, labelAfterPos: number;
if (this._getLayoutDirection() == 'ltr') {
labelBeforePos = selectedLabel.getOffsetLeft();
labelAfterPos = labelBeforePos + selectedLabel.getOffsetWidth();
} else {
labelAfterPos = this._tabList.nativeElement.offsetWidth - selectedLabel.getOffsetLeft();
labelBeforePos = labelAfterPos - selectedLabel.getOffsetWidth();
}
const beforeVisiblePos = this.scrollDistance;
const afterVisiblePos = this.scrollDistance + viewLength;
if (labelBeforePos < beforeVisiblePos) {
// Scroll header to move label to the before direction
this.scrollDistance -= beforeVisiblePos - labelBeforePos + EXAGGERATED_OVERSCROLL;
} else if (labelAfterPos > afterVisiblePos) {
// Scroll header to move label to the after direction
this.scrollDistance += labelAfterPos - afterVisiblePos + EXAGGERATED_OVERSCROLL;
}
}
/**
* Evaluate whether the pagination controls should be displayed. If the scroll width of the
* tab list is wider than the size of the header container, then the pagination controls should
* be shown.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_checkPaginationEnabled() {
const isEnabled =
this._tabList.nativeElement.scrollWidth > this._elementRef.nativeElement.offsetWidth;
if (!isEnabled) {
this.scrollDistance = 0;
}
if (isEnabled !== this._showPaginationControls) {
this._changeDetectorRef.markForCheck();
}
this._showPaginationControls = isEnabled;
}
/**
* Evaluate whether the before and after controls should be enabled or disabled.
* If the header is at the beginning of the list (scroll distance is equal to 0) then disable the
* before button. If the header is at the end of the list (scroll distance is equal to the
* maximum distance we can scroll), then disable the after button.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_checkScrollingControls() {
// Check if the pagination arrows should be activated.
this._disableScrollBefore = this.scrollDistance == 0;
this._disableScrollAfter = this.scrollDistance == this._getMaxScrollDistance();
this._changeDetectorRef.markForCheck();
}
/**
* Determines what is the maximum length in pixels that can be set for the scroll distance. This
* is equal to the difference in width between the tab list container and tab header container.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_getMaxScrollDistance(): number {
const lengthOfTabList = this._tabList.nativeElement.scrollWidth;
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
return (lengthOfTabList - viewLength) || 0;
}
/** Tells the ink-bar to align itself to the current label wrapper */
private _alignInkBarToSelectedTab(): void {
const selectedLabelWrapper = this._labelWrappers && this._labelWrappers.length ?
this._labelWrappers.toArray()[this.selectedIndex].elementRef.nativeElement :
null;
this._inkBar.alignToElement(selectedLabelWrapper);
}
}
| {
this._scrollDistance = Math.max(0, Math.min(this._getMaxScrollDistance(), v));
// Mark that the scroll distance has changed so that after the view is checked, the CSS
// transformation can move the header.
this._scrollDistanceChanged = true;
this._checkScrollingControls();
} | identifier_body |
tab-header.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Direction, Directionality} from '@angular/cdk/bidi';
import {ENTER, LEFT_ARROW, RIGHT_ARROW, SPACE} from '@angular/cdk/keycodes';
import {auditTime, startWith} from '@angular/cdk/rxjs';
import {
AfterContentChecked,
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Optional,
Output,
QueryList,
Renderer2,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import {CanDisableRipple, mixinDisableRipple} from '@angular/material/core';
import {fromEvent} from 'rxjs/observable/fromEvent';
import {merge} from 'rxjs/observable/merge';
import {of as observableOf} from 'rxjs/observable/of';
import {Subscription} from 'rxjs/Subscription';
import {MdInkBar} from './ink-bar';
import {MdTabLabelWrapper} from './tab-label-wrapper';
/**
* The directions that scrolling can go in when the header's tabs exceed the header width. 'After'
* will scroll the header towards the end of the tabs list and 'before' will scroll towards the
* beginning of the list.
*/
export type ScrollDirection = 'after' | 'before';
/**
* The distance in pixels that will be overshot when scrolling a tab label into view. This helps
* provide a small affordance to the label next to it.
*/
const EXAGGERATED_OVERSCROLL = 60;
// Boilerplate for applying mixins to MdTabHeader.
/** @docs-private */
export class MdTabHeaderBase {}
export const _MdTabHeaderMixinBase = mixinDisableRipple(MdTabHeaderBase);
/**
* The header of the tab group which displays a list of all the tabs in the tab group. Includes
* an ink bar that follows the currently selected tab. When the tabs list's width exceeds the
* width of the header container, then arrows will be displayed to allow the user to scroll
* left and right across the header.
* @docs-private
*/
@Component({
moduleId: module.id,
selector: 'md-tab-header, mat-tab-header',
templateUrl: 'tab-header.html',
styleUrls: ['tab-header.css'],
inputs: ['disableRipple'],
encapsulation: ViewEncapsulation.None,
preserveWhitespaces: false,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'class': 'mat-tab-header',
'[class.mat-tab-header-pagination-controls-enabled]': '_showPaginationControls',
'[class.mat-tab-header-rtl]': "_getLayoutDirection() == 'rtl'",
}
})
export class MdTabHeader extends _MdTabHeaderMixinBase
implements AfterContentChecked, AfterContentInit, OnDestroy, CanDisableRipple {
@ContentChildren(MdTabLabelWrapper) _labelWrappers: QueryList<MdTabLabelWrapper>;
@ViewChild(MdInkBar) _inkBar: MdInkBar;
@ViewChild('tabListContainer') _tabListContainer: ElementRef;
@ViewChild('tabList') _tabList: ElementRef;
/** The tab index that is focused. */
private _focusIndex: number = 0;
/** The distance in pixels that the tab labels should be translated to the left. */
private _scrollDistance = 0;
/** Whether the header should scroll to the selected index after the view has been checked. */
private _selectedIndexChanged = false;
/** Combines listeners that will re-align the ink bar whenever they're invoked. */
private _realignInkBar = Subscription.EMPTY;
/** Whether the controls for pagination should be displayed */
_showPaginationControls = false;
/** Whether the tab list can be scrolled more towards the end of the tab label list. */
_disableScrollAfter = true;
/** Whether the tab list can be scrolled more towards the beginning of the tab label list. */
_disableScrollBefore = true;
/**
* The number of tab labels that are displayed on the header. When this changes, the header
* should re-evaluate the scroll position.
*/
private _tabLabelCount: number;
/** Whether the scroll distance has changed and should be applied after the view is checked. */
private _scrollDistanceChanged: boolean;
private _selectedIndex: number = 0;
/** The index of the active tab. */
@Input()
get selectedIndex(): number { return this._selectedIndex; }
set selectedIndex(value: number) {
this._selectedIndexChanged = this._selectedIndex != value;
this._selectedIndex = value;
this._focusIndex = value;
}
/** Event emitted when the option is selected. */
@Output() selectFocusedIndex = new EventEmitter();
/** Event emitted when a label is focused. */
@Output() indexFocused = new EventEmitter();
constructor(private _elementRef: ElementRef,
private _renderer: Renderer2,
private _changeDetectorRef: ChangeDetectorRef,
@Optional() private _dir: Directionality) {
super();
}
ngAfterContentChecked(): void {
// If the number of tab labels have changed, check if scrolling should be enabled
if (this._tabLabelCount != this._labelWrappers.length) {
this._updatePagination();
this._tabLabelCount = this._labelWrappers.length;
this._changeDetectorRef.markForCheck();
}
// If the selected index has changed, scroll to the label and check if the scrolling controls
// should be disabled.
if (this._selectedIndexChanged) {
this._scrollToLabel(this._selectedIndex);
this._checkScrollingControls();
this._alignInkBarToSelectedTab();
this._selectedIndexChanged = false;
this._changeDetectorRef.markForCheck();
}
// If the scroll distance has been changed (tab selected, focused, scroll controls activated),
// then translate the header to reflect this.
if (this._scrollDistanceChanged) {
this._updateTabScrollPosition();
this._scrollDistanceChanged = false;
this._changeDetectorRef.markForCheck();
}
}
_handleKeydown(event: KeyboardEvent) {
switch (event.keyCode) {
case RIGHT_ARROW:
this._focusNextTab();
break;
case LEFT_ARROW:
this._focusPreviousTab();
break;
case ENTER:
case SPACE:
this.selectFocusedIndex.emit(this.focusIndex);
event.preventDefault();
break;
}
}
/**
* Aligns the ink bar to the selected tab on load.
*/
ngAfterContentInit() {
const dirChange = this._dir ? this._dir.change : observableOf(null);
const resize = typeof window !== 'undefined' ?
auditTime.call(fromEvent(window, 'resize'), 150) :
observableOf(null);
this._realignInkBar = startWith.call(merge(dirChange, resize), null).subscribe(() => {
this._updatePagination();
this._alignInkBarToSelectedTab();
});
}
ngOnDestroy() {
this._realignInkBar.unsubscribe();
}
/**
* Callback for when the MutationObserver detects that the content has changed.
*/
_onContentChanges() {
this._updatePagination();
this._alignInkBarToSelectedTab();
this._changeDetectorRef.markForCheck();
}
/**
* Updating the view whether pagination should be enabled or not
*/
_updatePagination() {
this._checkPaginationEnabled();
this._checkScrollingControls();
this._updateTabScrollPosition();
}
/** When the focus index is set, we must manually send focus to the correct label */
set focusIndex(value: number) {
if (!this._isValidIndex(value) || this._focusIndex == value) { return; }
this._focusIndex = value;
this.indexFocused.emit(value);
this._setTabFocus(value);
}
/** Tracks which element has focus; used for keyboard navigation */
get focusIndex(): number { return this._focusIndex; }
/**
* Determines if an index is valid. If the tabs are not ready yet, we assume that the user is
* providing a valid index and return true.
*/
_isValidIndex(index: number): boolean {
if (!this._labelWrappers) { return true; }
const tab = this._labelWrappers ? this._labelWrappers.toArray()[index] : null;
return !!tab && !tab.disabled;
}
/**
* Sets focus on the HTML element for the label wrapper and scrolls it into the view if
* scrolling is enabled.
*/
_setTabFocus(tabIndex: number) { |
if (this._labelWrappers && this._labelWrappers.length) {
this._labelWrappers.toArray()[tabIndex].focus();
// Do not let the browser manage scrolling to focus the element, this will be handled
// by using translation. In LTR, the scroll left should be 0. In RTL, the scroll width
// should be the full width minus the offset width.
const containerEl = this._tabListContainer.nativeElement;
const dir = this._getLayoutDirection();
if (dir == 'ltr') {
containerEl.scrollLeft = 0;
} else {
containerEl.scrollLeft = containerEl.scrollWidth - containerEl.offsetWidth;
}
}
}
/**
* Moves the focus towards the beginning or the end of the list depending on the offset provided.
* Valid offsets are 1 and -1.
*/
_moveFocus(offset: number) {
if (this._labelWrappers) {
const tabs: MdTabLabelWrapper[] = this._labelWrappers.toArray();
for (let i = this.focusIndex + offset; i < tabs.length && i >= 0; i += offset) {
if (this._isValidIndex(i)) {
this.focusIndex = i;
return;
}
}
}
}
/** Increment the focus index by 1 until a valid tab is found. */
_focusNextTab(): void {
this._moveFocus(this._getLayoutDirection() == 'ltr' ? 1 : -1);
}
/** Decrement the focus index by 1 until a valid tab is found. */
_focusPreviousTab(): void {
this._moveFocus(this._getLayoutDirection() == 'ltr' ? -1 : 1);
}
/** The layout direction of the containing app. */
_getLayoutDirection(): Direction {
return this._dir && this._dir.value === 'rtl' ? 'rtl' : 'ltr';
}
/** Performs the CSS transformation on the tab list that will cause the list to scroll. */
_updateTabScrollPosition() {
const scrollDistance = this.scrollDistance;
const translateX = this._getLayoutDirection() === 'ltr' ? -scrollDistance : scrollDistance;
this._renderer.setStyle(this._tabList.nativeElement, 'transform',
`translate3d(${translateX}px, 0, 0)`);
}
/** Sets the distance in pixels that the tab header should be transformed in the X-axis. */
set scrollDistance(v: number) {
this._scrollDistance = Math.max(0, Math.min(this._getMaxScrollDistance(), v));
// Mark that the scroll distance has changed so that after the view is checked, the CSS
// transformation can move the header.
this._scrollDistanceChanged = true;
this._checkScrollingControls();
}
get scrollDistance(): number { return this._scrollDistance; }
/**
* Moves the tab list in the 'before' or 'after' direction (towards the beginning of the list or
* the end of the list, respectively). The distance to scroll is computed to be a third of the
* length of the tab list view window.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_scrollHeader(scrollDir: ScrollDirection) {
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
// Move the scroll distance one-third the length of the tab list's viewport.
this.scrollDistance += (scrollDir == 'before' ? -1 : 1) * viewLength / 3;
}
/**
* Moves the tab list such that the desired tab label (marked by index) is moved into view.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_scrollToLabel(labelIndex: number) {
const selectedLabel = this._labelWrappers ? this._labelWrappers.toArray()[labelIndex] : null;
if (!selectedLabel) { return; }
// The view length is the visible width of the tab labels.
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
let labelBeforePos: number, labelAfterPos: number;
if (this._getLayoutDirection() == 'ltr') {
labelBeforePos = selectedLabel.getOffsetLeft();
labelAfterPos = labelBeforePos + selectedLabel.getOffsetWidth();
} else {
labelAfterPos = this._tabList.nativeElement.offsetWidth - selectedLabel.getOffsetLeft();
labelBeforePos = labelAfterPos - selectedLabel.getOffsetWidth();
}
const beforeVisiblePos = this.scrollDistance;
const afterVisiblePos = this.scrollDistance + viewLength;
if (labelBeforePos < beforeVisiblePos) {
// Scroll header to move label to the before direction
this.scrollDistance -= beforeVisiblePos - labelBeforePos + EXAGGERATED_OVERSCROLL;
} else if (labelAfterPos > afterVisiblePos) {
// Scroll header to move label to the after direction
this.scrollDistance += labelAfterPos - afterVisiblePos + EXAGGERATED_OVERSCROLL;
}
}
/**
* Evaluate whether the pagination controls should be displayed. If the scroll width of the
* tab list is wider than the size of the header container, then the pagination controls should
* be shown.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_checkPaginationEnabled() {
const isEnabled =
this._tabList.nativeElement.scrollWidth > this._elementRef.nativeElement.offsetWidth;
if (!isEnabled) {
this.scrollDistance = 0;
}
if (isEnabled !== this._showPaginationControls) {
this._changeDetectorRef.markForCheck();
}
this._showPaginationControls = isEnabled;
}
/**
* Evaluate whether the before and after controls should be enabled or disabled.
* If the header is at the beginning of the list (scroll distance is equal to 0) then disable the
* before button. If the header is at the end of the list (scroll distance is equal to the
* maximum distance we can scroll), then disable the after button.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_checkScrollingControls() {
// Check if the pagination arrows should be activated.
this._disableScrollBefore = this.scrollDistance == 0;
this._disableScrollAfter = this.scrollDistance == this._getMaxScrollDistance();
this._changeDetectorRef.markForCheck();
}
/**
* Determines what is the maximum length in pixels that can be set for the scroll distance. This
* is equal to the difference in width between the tab list container and tab header container.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_getMaxScrollDistance(): number {
const lengthOfTabList = this._tabList.nativeElement.scrollWidth;
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
return (lengthOfTabList - viewLength) || 0;
}
/** Tells the ink-bar to align itself to the current label wrapper */
private _alignInkBarToSelectedTab(): void {
const selectedLabelWrapper = this._labelWrappers && this._labelWrappers.length ?
this._labelWrappers.toArray()[this.selectedIndex].elementRef.nativeElement :
null;
this._inkBar.alignToElement(selectedLabelWrapper);
}
} | if (this._showPaginationControls) {
this._scrollToLabel(tabIndex);
} | random_line_split |
tab-header.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Direction, Directionality} from '@angular/cdk/bidi';
import {ENTER, LEFT_ARROW, RIGHT_ARROW, SPACE} from '@angular/cdk/keycodes';
import {auditTime, startWith} from '@angular/cdk/rxjs';
import {
AfterContentChecked,
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Optional,
Output,
QueryList,
Renderer2,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import {CanDisableRipple, mixinDisableRipple} from '@angular/material/core';
import {fromEvent} from 'rxjs/observable/fromEvent';
import {merge} from 'rxjs/observable/merge';
import {of as observableOf} from 'rxjs/observable/of';
import {Subscription} from 'rxjs/Subscription';
import {MdInkBar} from './ink-bar';
import {MdTabLabelWrapper} from './tab-label-wrapper';
/**
* The directions that scrolling can go in when the header's tabs exceed the header width. 'After'
* will scroll the header towards the end of the tabs list and 'before' will scroll towards the
* beginning of the list.
*/
export type ScrollDirection = 'after' | 'before';
/**
* The distance in pixels that will be overshot when scrolling a tab label into view. This helps
* provide a small affordance to the label next to it.
*/
const EXAGGERATED_OVERSCROLL = 60;
// Boilerplate for applying mixins to MdTabHeader.
/** @docs-private */
export class MdTabHeaderBase {}
export const _MdTabHeaderMixinBase = mixinDisableRipple(MdTabHeaderBase);
/**
* The header of the tab group which displays a list of all the tabs in the tab group. Includes
* an ink bar that follows the currently selected tab. When the tabs list's width exceeds the
* width of the header container, then arrows will be displayed to allow the user to scroll
* left and right across the header.
* @docs-private
*/
@Component({
moduleId: module.id,
selector: 'md-tab-header, mat-tab-header',
templateUrl: 'tab-header.html',
styleUrls: ['tab-header.css'],
inputs: ['disableRipple'],
encapsulation: ViewEncapsulation.None,
preserveWhitespaces: false,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'class': 'mat-tab-header',
'[class.mat-tab-header-pagination-controls-enabled]': '_showPaginationControls',
'[class.mat-tab-header-rtl]': "_getLayoutDirection() == 'rtl'",
}
})
export class MdTabHeader extends _MdTabHeaderMixinBase
implements AfterContentChecked, AfterContentInit, OnDestroy, CanDisableRipple {
@ContentChildren(MdTabLabelWrapper) _labelWrappers: QueryList<MdTabLabelWrapper>;
@ViewChild(MdInkBar) _inkBar: MdInkBar;
@ViewChild('tabListContainer') _tabListContainer: ElementRef;
@ViewChild('tabList') _tabList: ElementRef;
/** The tab index that is focused. */
private _focusIndex: number = 0;
/** The distance in pixels that the tab labels should be translated to the left. */
private _scrollDistance = 0;
/** Whether the header should scroll to the selected index after the view has been checked. */
private _selectedIndexChanged = false;
/** Combines listeners that will re-align the ink bar whenever they're invoked. */
private _realignInkBar = Subscription.EMPTY;
/** Whether the controls for pagination should be displayed */
_showPaginationControls = false;
/** Whether the tab list can be scrolled more towards the end of the tab label list. */
_disableScrollAfter = true;
/** Whether the tab list can be scrolled more towards the beginning of the tab label list. */
_disableScrollBefore = true;
/**
* The number of tab labels that are displayed on the header. When this changes, the header
* should re-evaluate the scroll position.
*/
private _tabLabelCount: number;
/** Whether the scroll distance has changed and should be applied after the view is checked. */
private _scrollDistanceChanged: boolean;
private _selectedIndex: number = 0;
/** The index of the active tab. */
@Input()
get selectedIndex(): number { return this._selectedIndex; }
set selectedIndex(value: number) {
this._selectedIndexChanged = this._selectedIndex != value;
this._selectedIndex = value;
this._focusIndex = value;
}
/** Event emitted when the option is selected. */
@Output() selectFocusedIndex = new EventEmitter();
/** Event emitted when a label is focused. */
@Output() indexFocused = new EventEmitter();
constructor(private _elementRef: ElementRef,
private _renderer: Renderer2,
private _changeDetectorRef: ChangeDetectorRef,
@Optional() private _dir: Directionality) {
super();
}
ngAfterContentChecked(): void {
// If the number of tab labels have changed, check if scrolling should be enabled
if (this._tabLabelCount != this._labelWrappers.length) {
this._updatePagination();
this._tabLabelCount = this._labelWrappers.length;
this._changeDetectorRef.markForCheck();
}
// If the selected index has changed, scroll to the label and check if the scrolling controls
// should be disabled.
if (this._selectedIndexChanged) {
this._scrollToLabel(this._selectedIndex);
this._checkScrollingControls();
this._alignInkBarToSelectedTab();
this._selectedIndexChanged = false;
this._changeDetectorRef.markForCheck();
}
// If the scroll distance has been changed (tab selected, focused, scroll controls activated),
// then translate the header to reflect this.
if (this._scrollDistanceChanged) {
this._updateTabScrollPosition();
this._scrollDistanceChanged = false;
this._changeDetectorRef.markForCheck();
}
}
_handleKeydown(event: KeyboardEvent) {
switch (event.keyCode) {
case RIGHT_ARROW:
this._focusNextTab();
break;
case LEFT_ARROW:
this._focusPreviousTab();
break;
case ENTER:
case SPACE:
this.selectFocusedIndex.emit(this.focusIndex);
event.preventDefault();
break;
}
}
/**
* Aligns the ink bar to the selected tab on load.
*/
ngAfterContentInit() {
const dirChange = this._dir ? this._dir.change : observableOf(null);
const resize = typeof window !== 'undefined' ?
auditTime.call(fromEvent(window, 'resize'), 150) :
observableOf(null);
this._realignInkBar = startWith.call(merge(dirChange, resize), null).subscribe(() => {
this._updatePagination();
this._alignInkBarToSelectedTab();
});
}
ngOnDestroy() {
this._realignInkBar.unsubscribe();
}
/**
* Callback for when the MutationObserver detects that the content has changed.
*/
_onContentChanges() {
this._updatePagination();
this._alignInkBarToSelectedTab();
this._changeDetectorRef.markForCheck();
}
/**
* Updating the view whether pagination should be enabled or not
*/
_updatePagination() {
this._checkPaginationEnabled();
this._checkScrollingControls();
this._updateTabScrollPosition();
}
/** When the focus index is set, we must manually send focus to the correct label */
set focusIndex(value: number) {
if (!this._isValidIndex(value) || this._focusIndex == value) { return; }
this._focusIndex = value;
this.indexFocused.emit(value);
this._setTabFocus(value);
}
/** Tracks which element has focus; used for keyboard navigation */
get focusIndex(): number { return this._focusIndex; }
/**
* Determines if an index is valid. If the tabs are not ready yet, we assume that the user is
* providing a valid index and return true.
*/
_isValidIndex(index: number): boolean {
if (!this._labelWrappers) { return true; }
const tab = this._labelWrappers ? this._labelWrappers.toArray()[index] : null;
return !!tab && !tab.disabled;
}
/**
* Sets focus on the HTML element for the label wrapper and scrolls it into the view if
* scrolling is enabled.
*/
_setTabFocus(tabIndex: number) {
if (this._showPaginationControls) {
this._scrollToLabel(tabIndex);
}
if (this._labelWrappers && this._labelWrappers.length) {
this._labelWrappers.toArray()[tabIndex].focus();
// Do not let the browser manage scrolling to focus the element, this will be handled
// by using translation. In LTR, the scroll left should be 0. In RTL, the scroll width
// should be the full width minus the offset width.
const containerEl = this._tabListContainer.nativeElement;
const dir = this._getLayoutDirection();
if (dir == 'ltr') {
containerEl.scrollLeft = 0;
} else {
containerEl.scrollLeft = containerEl.scrollWidth - containerEl.offsetWidth;
}
}
}
/**
* Moves the focus towards the beginning or the end of the list depending on the offset provided.
* Valid offsets are 1 and -1.
*/
_moveFocus(offset: number) {
if (this._labelWrappers) {
const tabs: MdTabLabelWrapper[] = this._labelWrappers.toArray();
for (let i = this.focusIndex + offset; i < tabs.length && i >= 0; i += offset) {
if (this._isValidIndex(i)) {
this.focusIndex = i;
return;
}
}
}
}
/** Increment the focus index by 1 until a valid tab is found. */
_focusNextTab(): void {
this._moveFocus(this._getLayoutDirection() == 'ltr' ? 1 : -1);
}
/** Decrement the focus index by 1 until a valid tab is found. */
| (): void {
this._moveFocus(this._getLayoutDirection() == 'ltr' ? -1 : 1);
}
/** The layout direction of the containing app. */
_getLayoutDirection(): Direction {
return this._dir && this._dir.value === 'rtl' ? 'rtl' : 'ltr';
}
/** Performs the CSS transformation on the tab list that will cause the list to scroll. */
_updateTabScrollPosition() {
const scrollDistance = this.scrollDistance;
const translateX = this._getLayoutDirection() === 'ltr' ? -scrollDistance : scrollDistance;
this._renderer.setStyle(this._tabList.nativeElement, 'transform',
`translate3d(${translateX}px, 0, 0)`);
}
/** Sets the distance in pixels that the tab header should be transformed in the X-axis. */
set scrollDistance(v: number) {
this._scrollDistance = Math.max(0, Math.min(this._getMaxScrollDistance(), v));
// Mark that the scroll distance has changed so that after the view is checked, the CSS
// transformation can move the header.
this._scrollDistanceChanged = true;
this._checkScrollingControls();
}
get scrollDistance(): number { return this._scrollDistance; }
/**
* Moves the tab list in the 'before' or 'after' direction (towards the beginning of the list or
* the end of the list, respectively). The distance to scroll is computed to be a third of the
* length of the tab list view window.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_scrollHeader(scrollDir: ScrollDirection) {
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
// Move the scroll distance one-third the length of the tab list's viewport.
this.scrollDistance += (scrollDir == 'before' ? -1 : 1) * viewLength / 3;
}
/**
* Moves the tab list such that the desired tab label (marked by index) is moved into view.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_scrollToLabel(labelIndex: number) {
const selectedLabel = this._labelWrappers ? this._labelWrappers.toArray()[labelIndex] : null;
if (!selectedLabel) { return; }
// The view length is the visible width of the tab labels.
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
let labelBeforePos: number, labelAfterPos: number;
if (this._getLayoutDirection() == 'ltr') {
labelBeforePos = selectedLabel.getOffsetLeft();
labelAfterPos = labelBeforePos + selectedLabel.getOffsetWidth();
} else {
labelAfterPos = this._tabList.nativeElement.offsetWidth - selectedLabel.getOffsetLeft();
labelBeforePos = labelAfterPos - selectedLabel.getOffsetWidth();
}
const beforeVisiblePos = this.scrollDistance;
const afterVisiblePos = this.scrollDistance + viewLength;
if (labelBeforePos < beforeVisiblePos) {
// Scroll header to move label to the before direction
this.scrollDistance -= beforeVisiblePos - labelBeforePos + EXAGGERATED_OVERSCROLL;
} else if (labelAfterPos > afterVisiblePos) {
// Scroll header to move label to the after direction
this.scrollDistance += labelAfterPos - afterVisiblePos + EXAGGERATED_OVERSCROLL;
}
}
/**
* Evaluate whether the pagination controls should be displayed. If the scroll width of the
* tab list is wider than the size of the header container, then the pagination controls should
* be shown.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_checkPaginationEnabled() {
const isEnabled =
this._tabList.nativeElement.scrollWidth > this._elementRef.nativeElement.offsetWidth;
if (!isEnabled) {
this.scrollDistance = 0;
}
if (isEnabled !== this._showPaginationControls) {
this._changeDetectorRef.markForCheck();
}
this._showPaginationControls = isEnabled;
}
/**
* Evaluate whether the before and after controls should be enabled or disabled.
* If the header is at the beginning of the list (scroll distance is equal to 0) then disable the
* before button. If the header is at the end of the list (scroll distance is equal to the
* maximum distance we can scroll), then disable the after button.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_checkScrollingControls() {
// Check if the pagination arrows should be activated.
this._disableScrollBefore = this.scrollDistance == 0;
this._disableScrollAfter = this.scrollDistance == this._getMaxScrollDistance();
this._changeDetectorRef.markForCheck();
}
/**
* Determines what is the maximum length in pixels that can be set for the scroll distance. This
* is equal to the difference in width between the tab list container and tab header container.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_getMaxScrollDistance(): number {
const lengthOfTabList = this._tabList.nativeElement.scrollWidth;
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
return (lengthOfTabList - viewLength) || 0;
}
/** Tells the ink-bar to align itself to the current label wrapper */
private _alignInkBarToSelectedTab(): void {
const selectedLabelWrapper = this._labelWrappers && this._labelWrappers.length ?
this._labelWrappers.toArray()[this.selectedIndex].elementRef.nativeElement :
null;
this._inkBar.alignToElement(selectedLabelWrapper);
}
}
| _focusPreviousTab | identifier_name |
tab-header.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Direction, Directionality} from '@angular/cdk/bidi';
import {ENTER, LEFT_ARROW, RIGHT_ARROW, SPACE} from '@angular/cdk/keycodes';
import {auditTime, startWith} from '@angular/cdk/rxjs';
import {
AfterContentChecked,
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Optional,
Output,
QueryList,
Renderer2,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import {CanDisableRipple, mixinDisableRipple} from '@angular/material/core';
import {fromEvent} from 'rxjs/observable/fromEvent';
import {merge} from 'rxjs/observable/merge';
import {of as observableOf} from 'rxjs/observable/of';
import {Subscription} from 'rxjs/Subscription';
import {MdInkBar} from './ink-bar';
import {MdTabLabelWrapper} from './tab-label-wrapper';
/**
* The directions that scrolling can go in when the header's tabs exceed the header width. 'After'
* will scroll the header towards the end of the tabs list and 'before' will scroll towards the
* beginning of the list.
*/
export type ScrollDirection = 'after' | 'before';
/**
* The distance in pixels that will be overshot when scrolling a tab label into view. This helps
* provide a small affordance to the label next to it.
*/
const EXAGGERATED_OVERSCROLL = 60;
// Boilerplate for applying mixins to MdTabHeader.
/** @docs-private */
export class MdTabHeaderBase {}
export const _MdTabHeaderMixinBase = mixinDisableRipple(MdTabHeaderBase);
/**
* The header of the tab group which displays a list of all the tabs in the tab group. Includes
* an ink bar that follows the currently selected tab. When the tabs list's width exceeds the
* width of the header container, then arrows will be displayed to allow the user to scroll
* left and right across the header.
* @docs-private
*/
@Component({
moduleId: module.id,
selector: 'md-tab-header, mat-tab-header',
templateUrl: 'tab-header.html',
styleUrls: ['tab-header.css'],
inputs: ['disableRipple'],
encapsulation: ViewEncapsulation.None,
preserveWhitespaces: false,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'class': 'mat-tab-header',
'[class.mat-tab-header-pagination-controls-enabled]': '_showPaginationControls',
'[class.mat-tab-header-rtl]': "_getLayoutDirection() == 'rtl'",
}
})
export class MdTabHeader extends _MdTabHeaderMixinBase
implements AfterContentChecked, AfterContentInit, OnDestroy, CanDisableRipple {
@ContentChildren(MdTabLabelWrapper) _labelWrappers: QueryList<MdTabLabelWrapper>;
@ViewChild(MdInkBar) _inkBar: MdInkBar;
@ViewChild('tabListContainer') _tabListContainer: ElementRef;
@ViewChild('tabList') _tabList: ElementRef;
/** The tab index that is focused. */
private _focusIndex: number = 0;
/** The distance in pixels that the tab labels should be translated to the left. */
private _scrollDistance = 0;
/** Whether the header should scroll to the selected index after the view has been checked. */
private _selectedIndexChanged = false;
/** Combines listeners that will re-align the ink bar whenever they're invoked. */
private _realignInkBar = Subscription.EMPTY;
/** Whether the controls for pagination should be displayed */
_showPaginationControls = false;
/** Whether the tab list can be scrolled more towards the end of the tab label list. */
_disableScrollAfter = true;
/** Whether the tab list can be scrolled more towards the beginning of the tab label list. */
_disableScrollBefore = true;
/**
* The number of tab labels that are displayed on the header. When this changes, the header
* should re-evaluate the scroll position.
*/
private _tabLabelCount: number;
/** Whether the scroll distance has changed and should be applied after the view is checked. */
private _scrollDistanceChanged: boolean;
private _selectedIndex: number = 0;
/** The index of the active tab. */
@Input()
get selectedIndex(): number { return this._selectedIndex; }
set selectedIndex(value: number) {
this._selectedIndexChanged = this._selectedIndex != value;
this._selectedIndex = value;
this._focusIndex = value;
}
/** Event emitted when the option is selected. */
@Output() selectFocusedIndex = new EventEmitter();
/** Event emitted when a label is focused. */
@Output() indexFocused = new EventEmitter();
constructor(private _elementRef: ElementRef,
private _renderer: Renderer2,
private _changeDetectorRef: ChangeDetectorRef,
@Optional() private _dir: Directionality) {
super();
}
ngAfterContentChecked(): void {
// If the number of tab labels have changed, check if scrolling should be enabled
if (this._tabLabelCount != this._labelWrappers.length) {
this._updatePagination();
this._tabLabelCount = this._labelWrappers.length;
this._changeDetectorRef.markForCheck();
}
// If the selected index has changed, scroll to the label and check if the scrolling controls
// should be disabled.
if (this._selectedIndexChanged) {
this._scrollToLabel(this._selectedIndex);
this._checkScrollingControls();
this._alignInkBarToSelectedTab();
this._selectedIndexChanged = false;
this._changeDetectorRef.markForCheck();
}
// If the scroll distance has been changed (tab selected, focused, scroll controls activated),
// then translate the header to reflect this.
if (this._scrollDistanceChanged) {
this._updateTabScrollPosition();
this._scrollDistanceChanged = false;
this._changeDetectorRef.markForCheck();
}
}
_handleKeydown(event: KeyboardEvent) {
switch (event.keyCode) {
case RIGHT_ARROW:
this._focusNextTab();
break;
case LEFT_ARROW:
this._focusPreviousTab();
break;
case ENTER:
case SPACE:
this.selectFocusedIndex.emit(this.focusIndex);
event.preventDefault();
break;
}
}
/**
* Aligns the ink bar to the selected tab on load.
*/
ngAfterContentInit() {
const dirChange = this._dir ? this._dir.change : observableOf(null);
const resize = typeof window !== 'undefined' ?
auditTime.call(fromEvent(window, 'resize'), 150) :
observableOf(null);
this._realignInkBar = startWith.call(merge(dirChange, resize), null).subscribe(() => {
this._updatePagination();
this._alignInkBarToSelectedTab();
});
}
ngOnDestroy() {
this._realignInkBar.unsubscribe();
}
/**
* Callback for when the MutationObserver detects that the content has changed.
*/
_onContentChanges() {
this._updatePagination();
this._alignInkBarToSelectedTab();
this._changeDetectorRef.markForCheck();
}
/**
* Updating the view whether pagination should be enabled or not
*/
_updatePagination() {
this._checkPaginationEnabled();
this._checkScrollingControls();
this._updateTabScrollPosition();
}
/** When the focus index is set, we must manually send focus to the correct label */
set focusIndex(value: number) {
if (!this._isValidIndex(value) || this._focusIndex == value) { return; }
this._focusIndex = value;
this.indexFocused.emit(value);
this._setTabFocus(value);
}
/** Tracks which element has focus; used for keyboard navigation */
get focusIndex(): number { return this._focusIndex; }
/**
* Determines if an index is valid. If the tabs are not ready yet, we assume that the user is
* providing a valid index and return true.
*/
_isValidIndex(index: number): boolean {
if (!this._labelWrappers) { return true; }
const tab = this._labelWrappers ? this._labelWrappers.toArray()[index] : null;
return !!tab && !tab.disabled;
}
/**
* Sets focus on the HTML element for the label wrapper and scrolls it into the view if
* scrolling is enabled.
*/
_setTabFocus(tabIndex: number) {
if (this._showPaginationControls) {
this._scrollToLabel(tabIndex);
}
if (this._labelWrappers && this._labelWrappers.length) {
this._labelWrappers.toArray()[tabIndex].focus();
// Do not let the browser manage scrolling to focus the element, this will be handled
// by using translation. In LTR, the scroll left should be 0. In RTL, the scroll width
// should be the full width minus the offset width.
const containerEl = this._tabListContainer.nativeElement;
const dir = this._getLayoutDirection();
if (dir == 'ltr') {
containerEl.scrollLeft = 0;
} else |
}
}
/**
* Moves the focus towards the beginning or the end of the list depending on the offset provided.
* Valid offsets are 1 and -1.
*/
_moveFocus(offset: number) {
if (this._labelWrappers) {
const tabs: MdTabLabelWrapper[] = this._labelWrappers.toArray();
for (let i = this.focusIndex + offset; i < tabs.length && i >= 0; i += offset) {
if (this._isValidIndex(i)) {
this.focusIndex = i;
return;
}
}
}
}
/** Increment the focus index by 1 until a valid tab is found. */
_focusNextTab(): void {
this._moveFocus(this._getLayoutDirection() == 'ltr' ? 1 : -1);
}
/** Decrement the focus index by 1 until a valid tab is found. */
_focusPreviousTab(): void {
this._moveFocus(this._getLayoutDirection() == 'ltr' ? -1 : 1);
}
/** The layout direction of the containing app. */
_getLayoutDirection(): Direction {
return this._dir && this._dir.value === 'rtl' ? 'rtl' : 'ltr';
}
/** Performs the CSS transformation on the tab list that will cause the list to scroll. */
_updateTabScrollPosition() {
const scrollDistance = this.scrollDistance;
const translateX = this._getLayoutDirection() === 'ltr' ? -scrollDistance : scrollDistance;
this._renderer.setStyle(this._tabList.nativeElement, 'transform',
`translate3d(${translateX}px, 0, 0)`);
}
/** Sets the distance in pixels that the tab header should be transformed in the X-axis. */
set scrollDistance(v: number) {
this._scrollDistance = Math.max(0, Math.min(this._getMaxScrollDistance(), v));
// Mark that the scroll distance has changed so that after the view is checked, the CSS
// transformation can move the header.
this._scrollDistanceChanged = true;
this._checkScrollingControls();
}
get scrollDistance(): number { return this._scrollDistance; }
/**
* Moves the tab list in the 'before' or 'after' direction (towards the beginning of the list or
* the end of the list, respectively). The distance to scroll is computed to be a third of the
* length of the tab list view window.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_scrollHeader(scrollDir: ScrollDirection) {
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
// Move the scroll distance one-third the length of the tab list's viewport.
this.scrollDistance += (scrollDir == 'before' ? -1 : 1) * viewLength / 3;
}
/**
* Moves the tab list such that the desired tab label (marked by index) is moved into view.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_scrollToLabel(labelIndex: number) {
const selectedLabel = this._labelWrappers ? this._labelWrappers.toArray()[labelIndex] : null;
if (!selectedLabel) { return; }
// The view length is the visible width of the tab labels.
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
let labelBeforePos: number, labelAfterPos: number;
if (this._getLayoutDirection() == 'ltr') {
labelBeforePos = selectedLabel.getOffsetLeft();
labelAfterPos = labelBeforePos + selectedLabel.getOffsetWidth();
} else {
labelAfterPos = this._tabList.nativeElement.offsetWidth - selectedLabel.getOffsetLeft();
labelBeforePos = labelAfterPos - selectedLabel.getOffsetWidth();
}
const beforeVisiblePos = this.scrollDistance;
const afterVisiblePos = this.scrollDistance + viewLength;
if (labelBeforePos < beforeVisiblePos) {
// Scroll header to move label to the before direction
this.scrollDistance -= beforeVisiblePos - labelBeforePos + EXAGGERATED_OVERSCROLL;
} else if (labelAfterPos > afterVisiblePos) {
// Scroll header to move label to the after direction
this.scrollDistance += labelAfterPos - afterVisiblePos + EXAGGERATED_OVERSCROLL;
}
}
/**
* Evaluate whether the pagination controls should be displayed. If the scroll width of the
* tab list is wider than the size of the header container, then the pagination controls should
* be shown.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_checkPaginationEnabled() {
const isEnabled =
this._tabList.nativeElement.scrollWidth > this._elementRef.nativeElement.offsetWidth;
if (!isEnabled) {
this.scrollDistance = 0;
}
if (isEnabled !== this._showPaginationControls) {
this._changeDetectorRef.markForCheck();
}
this._showPaginationControls = isEnabled;
}
/**
* Evaluate whether the before and after controls should be enabled or disabled.
* If the header is at the beginning of the list (scroll distance is equal to 0) then disable the
* before button. If the header is at the end of the list (scroll distance is equal to the
* maximum distance we can scroll), then disable the after button.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_checkScrollingControls() {
// Check if the pagination arrows should be activated.
this._disableScrollBefore = this.scrollDistance == 0;
this._disableScrollAfter = this.scrollDistance == this._getMaxScrollDistance();
this._changeDetectorRef.markForCheck();
}
/**
* Determines what is the maximum length in pixels that can be set for the scroll distance. This
* is equal to the difference in width between the tab list container and tab header container.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_getMaxScrollDistance(): number {
const lengthOfTabList = this._tabList.nativeElement.scrollWidth;
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
return (lengthOfTabList - viewLength) || 0;
}
/** Tells the ink-bar to align itself to the current label wrapper */
private _alignInkBarToSelectedTab(): void {
const selectedLabelWrapper = this._labelWrappers && this._labelWrappers.length ?
this._labelWrappers.toArray()[this.selectedIndex].elementRef.nativeElement :
null;
this._inkBar.alignToElement(selectedLabelWrapper);
}
}
| {
containerEl.scrollLeft = containerEl.scrollWidth - containerEl.offsetWidth;
} | conditional_block |
kay_auto.rs | //! This is all auto-generated. Do not touch.
#![rustfmt::skip]
#[allow(unused_imports)]
use kay::{ActorSystem, TypedID, RawID, Fate, Actor, TraitIDFrom, ActorOrActorTrait};
#[allow(unused_imports)]
use super::*;
#[derive(Serialize, Deserialize)] #[serde(transparent)]
pub struct TimeUIID {
_raw_id: RawID
}
impl Copy for TimeUIID {}
impl Clone for TimeUIID { fn clone(&self) -> Self { *self } }
impl ::std::fmt::Debug for TimeUIID {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "TimeUIID({:?})", self._raw_id)
}
}
impl ::std::hash::Hash for TimeUIID {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
self._raw_id.hash(state);
}
}
impl PartialEq for TimeUIID {
fn eq(&self, other: &TimeUIID) -> bool {
self._raw_id == other._raw_id
}
}
impl Eq for TimeUIID {}
pub struct TimeUIRepresentative;
impl ActorOrActorTrait for TimeUIRepresentative {
type ID = TimeUIID;
}
impl TypedID for TimeUIID {
type Target = TimeUIRepresentative;
fn from_raw(id: RawID) -> Self {
TimeUIID { _raw_id: id }
}
fn as_raw(&self) -> RawID {
self._raw_id
}
}
impl<Act: Actor + TimeUI> TraitIDFrom<Act> for TimeUIID {}
impl TimeUIID {
pub fn on_time_info(self, current_instant: :: units :: Instant, speed: u16, world: &mut World) |
pub fn register_trait(system: &mut ActorSystem) {
system.register_trait::<TimeUIRepresentative>();
system.register_trait_message::<MSG_TimeUI_on_time_info>();
}
pub fn register_implementor<Act: Actor + TimeUI>(system: &mut ActorSystem) {
system.register_implementor::<Act, TimeUIRepresentative>();
system.add_handler::<Act, _, _>(
|&MSG_TimeUI_on_time_info(current_instant, speed), instance, world| {
instance.on_time_info(current_instant, speed, world); Fate::Live
}, false
);
}
}
#[derive(Compact, Clone)] #[allow(non_camel_case_types)]
struct MSG_TimeUI_on_time_info(pub :: units :: Instant, pub u16);
impl TimeID {
pub fn get_info(self, requester: TimeUIID, world: &mut World) {
world.send(self.as_raw(), MSG_Time_get_info(requester));
}
pub fn set_speed(self, speed: u16, world: &mut World) {
world.send(self.as_raw(), MSG_Time_set_speed(speed));
}
}
#[derive(Compact, Clone)] #[allow(non_camel_case_types)]
struct MSG_Time_get_info(pub TimeUIID);
#[derive(Compact, Clone)] #[allow(non_camel_case_types)]
struct MSG_Time_set_speed(pub u16);
#[allow(unused_variables)]
#[allow(unused_mut)]
pub fn auto_setup(system: &mut ActorSystem) {
TimeUIID::register_trait(system);
system.add_handler::<Time, _, _>(
|&MSG_Time_get_info(requester), instance, world| {
instance.get_info(requester, world); Fate::Live
}, false
);
system.add_handler::<Time, _, _>(
|&MSG_Time_set_speed(speed), instance, world| {
instance.set_speed(speed, world); Fate::Live
}, false
);
} | {
world.send(self.as_raw(), MSG_TimeUI_on_time_info(current_instant, speed));
} | identifier_body |
kay_auto.rs | //! This is all auto-generated. Do not touch.
#![rustfmt::skip]
#[allow(unused_imports)]
use kay::{ActorSystem, TypedID, RawID, Fate, Actor, TraitIDFrom, ActorOrActorTrait};
#[allow(unused_imports)]
use super::*;
#[derive(Serialize, Deserialize)] #[serde(transparent)]
pub struct TimeUIID {
_raw_id: RawID
}
impl Copy for TimeUIID {}
impl Clone for TimeUIID { fn clone(&self) -> Self { *self } }
impl ::std::fmt::Debug for TimeUIID {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "TimeUIID({:?})", self._raw_id)
}
}
impl ::std::hash::Hash for TimeUIID {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
self._raw_id.hash(state);
}
}
impl PartialEq for TimeUIID {
fn eq(&self, other: &TimeUIID) -> bool {
self._raw_id == other._raw_id
}
}
impl Eq for TimeUIID {}
pub struct TimeUIRepresentative;
impl ActorOrActorTrait for TimeUIRepresentative {
type ID = TimeUIID;
}
impl TypedID for TimeUIID {
type Target = TimeUIRepresentative;
fn from_raw(id: RawID) -> Self {
TimeUIID { _raw_id: id }
}
fn as_raw(&self) -> RawID {
self._raw_id
}
}
impl<Act: Actor + TimeUI> TraitIDFrom<Act> for TimeUIID {}
impl TimeUIID {
pub fn | (self, current_instant: :: units :: Instant, speed: u16, world: &mut World) {
world.send(self.as_raw(), MSG_TimeUI_on_time_info(current_instant, speed));
}
pub fn register_trait(system: &mut ActorSystem) {
system.register_trait::<TimeUIRepresentative>();
system.register_trait_message::<MSG_TimeUI_on_time_info>();
}
pub fn register_implementor<Act: Actor + TimeUI>(system: &mut ActorSystem) {
system.register_implementor::<Act, TimeUIRepresentative>();
system.add_handler::<Act, _, _>(
|&MSG_TimeUI_on_time_info(current_instant, speed), instance, world| {
instance.on_time_info(current_instant, speed, world); Fate::Live
}, false
);
}
}
#[derive(Compact, Clone)] #[allow(non_camel_case_types)]
struct MSG_TimeUI_on_time_info(pub :: units :: Instant, pub u16);
impl TimeID {
pub fn get_info(self, requester: TimeUIID, world: &mut World) {
world.send(self.as_raw(), MSG_Time_get_info(requester));
}
pub fn set_speed(self, speed: u16, world: &mut World) {
world.send(self.as_raw(), MSG_Time_set_speed(speed));
}
}
#[derive(Compact, Clone)] #[allow(non_camel_case_types)]
struct MSG_Time_get_info(pub TimeUIID);
#[derive(Compact, Clone)] #[allow(non_camel_case_types)]
struct MSG_Time_set_speed(pub u16);
#[allow(unused_variables)]
#[allow(unused_mut)]
pub fn auto_setup(system: &mut ActorSystem) {
TimeUIID::register_trait(system);
system.add_handler::<Time, _, _>(
|&MSG_Time_get_info(requester), instance, world| {
instance.get_info(requester, world); Fate::Live
}, false
);
system.add_handler::<Time, _, _>(
|&MSG_Time_set_speed(speed), instance, world| {
instance.set_speed(speed, world); Fate::Live
}, false
);
} | on_time_info | identifier_name |
kay_auto.rs | //! This is all auto-generated. Do not touch.
#![rustfmt::skip]
#[allow(unused_imports)]
use kay::{ActorSystem, TypedID, RawID, Fate, Actor, TraitIDFrom, ActorOrActorTrait};
#[allow(unused_imports)]
use super::*;
#[derive(Serialize, Deserialize)] #[serde(transparent)]
pub struct TimeUIID {
_raw_id: RawID
}
| }
}
impl ::std::hash::Hash for TimeUIID {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
self._raw_id.hash(state);
}
}
impl PartialEq for TimeUIID {
fn eq(&self, other: &TimeUIID) -> bool {
self._raw_id == other._raw_id
}
}
impl Eq for TimeUIID {}
pub struct TimeUIRepresentative;
impl ActorOrActorTrait for TimeUIRepresentative {
type ID = TimeUIID;
}
impl TypedID for TimeUIID {
type Target = TimeUIRepresentative;
fn from_raw(id: RawID) -> Self {
TimeUIID { _raw_id: id }
}
fn as_raw(&self) -> RawID {
self._raw_id
}
}
impl<Act: Actor + TimeUI> TraitIDFrom<Act> for TimeUIID {}
impl TimeUIID {
pub fn on_time_info(self, current_instant: :: units :: Instant, speed: u16, world: &mut World) {
world.send(self.as_raw(), MSG_TimeUI_on_time_info(current_instant, speed));
}
pub fn register_trait(system: &mut ActorSystem) {
system.register_trait::<TimeUIRepresentative>();
system.register_trait_message::<MSG_TimeUI_on_time_info>();
}
pub fn register_implementor<Act: Actor + TimeUI>(system: &mut ActorSystem) {
system.register_implementor::<Act, TimeUIRepresentative>();
system.add_handler::<Act, _, _>(
|&MSG_TimeUI_on_time_info(current_instant, speed), instance, world| {
instance.on_time_info(current_instant, speed, world); Fate::Live
}, false
);
}
}
#[derive(Compact, Clone)] #[allow(non_camel_case_types)]
struct MSG_TimeUI_on_time_info(pub :: units :: Instant, pub u16);
impl TimeID {
pub fn get_info(self, requester: TimeUIID, world: &mut World) {
world.send(self.as_raw(), MSG_Time_get_info(requester));
}
pub fn set_speed(self, speed: u16, world: &mut World) {
world.send(self.as_raw(), MSG_Time_set_speed(speed));
}
}
#[derive(Compact, Clone)] #[allow(non_camel_case_types)]
struct MSG_Time_get_info(pub TimeUIID);
#[derive(Compact, Clone)] #[allow(non_camel_case_types)]
struct MSG_Time_set_speed(pub u16);
#[allow(unused_variables)]
#[allow(unused_mut)]
pub fn auto_setup(system: &mut ActorSystem) {
TimeUIID::register_trait(system);
system.add_handler::<Time, _, _>(
|&MSG_Time_get_info(requester), instance, world| {
instance.get_info(requester, world); Fate::Live
}, false
);
system.add_handler::<Time, _, _>(
|&MSG_Time_set_speed(speed), instance, world| {
instance.set_speed(speed, world); Fate::Live
}, false
);
} | impl Copy for TimeUIID {}
impl Clone for TimeUIID { fn clone(&self) -> Self { *self } }
impl ::std::fmt::Debug for TimeUIID {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "TimeUIID({:?})", self._raw_id) | random_line_split |
ComponentsGridItem.tsx | import React, { memo, useCallback, MouseEvent } from 'react'
import { Link } from 'gatsby'
import styled, { useTheme } from 'styled-components'
import media from '../../../theming/mediaQueries'
import { ChartNavData } from '../../../types'
export const ComponentsGridItem = memo(({ name, id, flavors }: ChartNavData) => {
const theme = useTheme()
const handleVariantClick = useCallback((event: MouseEvent) => {
event.stopPropagation()
}, [])
return (
<Container>
<Icon className={`sprite-icons-${id}-${theme.id}-colored`} />
<Header>
<Name>{name}</Name>
<Flavors>
<Flavor to={`/${id}/`}>SVG</Flavor>
{flavors.html && (
<Flavor onClick={handleVariantClick} to={`/${id}/html/`}>
HTML
</Flavor>
)}
{flavors.canvas && ( | <Flavor onClick={handleVariantClick} to={`/${id}/canvas/`}>
Canvas
</Flavor>
)}
{flavors.api && (
<Flavor onClick={handleVariantClick} to={`/${id}/api/`}>
API
</Flavor>
)}
</Flavors>
</Header>
</Container>
)
})
const Container = styled.div`
background-color: ${({ theme }) => theme.colors.cardBackground};
border-radius: 2px;
padding: 12px;
color: ${({ theme }) => theme.colors.text};
border: 1px solid ${({ theme }) => theme.colors.cardBackground};
box-shadow: ${({ theme }) => theme.cardShadow};
display: flex;
align-items: flex-start;
justify-content: space-between;
&:focus,
&:hover {
box-shadow: none;
border-color: ${({ theme }) => theme.colors.accent};
outline: 0;
}
${media.mobile`
& {
border-width: 0;
border-top-width: 1px;
border-color: ${({ theme }) => theme.colors.borderLight};
box-shadow: none;
}
&:focus,
&:hover {
background-color: ${({ theme }) => theme.colors.background};
border-color: ${({ theme }) => theme.colors.borderLight};
}
&:first-child {
border-top-width: 0;
}
`}
`
const Header = styled.div`
flex: 1;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
`
const Name = styled.span`
font-size: 15px;
font-weight: 600;
`
const Icon = styled.span`
margin-right: 15px;
display: block;
width: 52px;
height: 52px;
`
const Flavors = styled.div`
font-size: 0.8rem;
line-height: 0.8rem;
margin-top: 4px;
display: flex;
align-items: center;
flex-wrap: wrap;
`
const Flavor = styled(Link)`
cursor: pointer;
text-decoration: none;
font-size: 0.75rem;
line-height: 1em;
font-weight: 700;
padding: 3px 4px;
margin-right: 3px;
margin-bottom: 3px;
border-radius: 2px;
background-color: ${({ theme }) => theme.colors.accent};
border: 1px solid ${({ theme }) => theme.colors.accent};
color: #ffffff;
&:hover {
background-color: ${({ theme }) => theme.colors.cardBackground};
color: ${({ theme }) => theme.colors.accent};
}
` | random_line_split | |
bookmark.js | /*
* This file is part of the Exposure package.
* |
$("a[data-op='bookmark-remove']").click(function(e) {
e.preventDefault() ;
var listItem = $(this).closest('li') ;
var postData = "token=" + $(this).closest('ul').data('token')
+ "&project_id=" + $(this).data("project-id")
+ "&action=project_bookmark_remove" ;
$.post("/", postData, function(result) {
if (result === true) {
listItem.fadeOut() ;
}
});
}) ;
$("a[data-op='bookmark-add']").click(function(e) {
e.preventDefault() ;
var link = $(this) ;
var postData = "token=" + link.data('token')
+ "&project_id=" + link.data('project-id')
+ "&action=project_bookmark_add" ;
$.post("/", postData, function(result) {
if (result === true) {
$('#sponsor-bookmark').text(link.data('success')) ;
}
});
}) ; | * Copyright 2013 by Sébastien Pujadas
*
* For the full copyright and licence information, please view the LICENCE
* file that was distributed with this source code.
*/ | random_line_split |
bookmark.js | /*
* This file is part of the Exposure package.
*
* Copyright 2013 by Sébastien Pujadas
*
* For the full copyright and licence information, please view the LICENCE
* file that was distributed with this source code.
*/
$("a[data-op='bookmark-remove']").click(function(e) {
e.preventDefault() ;
var listItem = $(this).closest('li') ;
var postData = "token=" + $(this).closest('ul').data('token')
+ "&project_id=" + $(this).data("project-id")
+ "&action=project_bookmark_remove" ;
$.post("/", postData, function(result) {
if (result === true) {
listItem.fadeOut() ;
}
});
}) ;
$("a[data-op='bookmark-add']").click(function(e) {
e.preventDefault() ;
var link = $(this) ;
var postData = "token=" + link.data('token')
+ "&project_id=" + link.data('project-id')
+ "&action=project_bookmark_add" ;
$.post("/", postData, function(result) {
if (result === true) { | });
}) ;
|
$('#sponsor-bookmark').text(link.data('success')) ;
}
| conditional_block |
lexer.ts | enum TokenType {
NONE,
IDENTIFIER,
NUMBER,
BOOLEAN,
STRING,
SYMBOL,
DELIMITER
}
class Token {
index:number;
text:string;
type:TokenType;
constructor(index:number, text:string, type:TokenType) {
this.index = index;
this.text = text;
this.type = type;
}
}
abstract class Lexer {
public abstract lex ():Array<[RegExp|Function,TokenType]>;
public fetch(code:string, index:number):Token {
let rules = this.lex();
for (var i = 0; i < rules.length; i++) {
let element = rules[i];
let rule = element[0];
let type = element[1];
if (rule instanceof Function) {
throw new Error("Does not support Function as rule yet.");
}
let re = new RegExp("^("+ rule.source + ")");
let found = re.exec (code.slice(index));
if (found != null) {
return new Token(index, found[0], type);
}
}
throw new Error("unexpected code from index " + index + ".");
}
public parse (code:string): Array<Token> {
let tokens:Array<Token> = [];
let index:number = 0;
while(true) |
return tokens;
}
}
/**
* Lexer for Racket.
*/
class RacketLexer extends Lexer {
public lex ():Array<[RegExp|Function,TokenType]> {
return [
[ /[0-9]+/, TokenType.NUMBER ],
[ /\#true|\#false|\#t|\#f/, TokenType.BOOLEAN ],
// Boolean is also symbol, but so far I don't want to support other symbols yet
[ /\#[^\(\)\[\]\{\}\"\,\'\`\;\#\|\\\s]+/, TokenType.SYMBOL ],
[ /[^\(\)\[\]\{\}\"\,\'\`\;\#\|\\\s]+/, TokenType.IDENTIFIER ],
[ /\"(:?\\.|[^\"])*\"/, TokenType.STRING ],
[ /[\(\)\[\]\{\}\"\,\'\`\;\#\|\\]/, TokenType.DELIMITER ],
[ /[\s]+/, TokenType.NONE ]
];
}
public static parse (code:string): Array<Token> {
return new RacketLexer().parse(code);
}
} | {
let token:Token = this.fetch(code, index);
if (token.type != TokenType.NONE) {
tokens.push(token);
}
index += token.text.length;
if (code.length <= index) {
break;
}
} | conditional_block |
lexer.ts | enum TokenType {
NONE,
IDENTIFIER,
NUMBER,
BOOLEAN,
STRING,
SYMBOL,
DELIMITER
}
class Token {
index:number;
text:string;
type:TokenType;
constructor(index:number, text:string, type:TokenType) {
this.index = index;
this.text = text;
this.type = type;
}
}
abstract class Lexer {
public abstract lex ():Array<[RegExp|Function,TokenType]>;
public fetch(code:string, index:number):Token {
let rules = this.lex();
for (var i = 0; i < rules.length; i++) {
let element = rules[i];
let rule = element[0];
let type = element[1];
if (rule instanceof Function) {
throw new Error("Does not support Function as rule yet.");
}
let re = new RegExp("^("+ rule.source + ")");
let found = re.exec (code.slice(index));
if (found != null) {
return new Token(index, found[0], type);
}
}
throw new Error("unexpected code from index " + index + ".");
}
public parse (code:string): Array<Token> {
let tokens:Array<Token> = [];
let index:number = 0;
while(true) {
let token:Token = this.fetch(code, index);
if (token.type != TokenType.NONE) {
tokens.push(token);
}
index += token.text.length;
if (code.length <= index) {
break;
}
}
return tokens;
}
}
/**
* Lexer for Racket.
*/
class RacketLexer extends Lexer {
public lex ():Array<[RegExp|Function,TokenType]> {
return [
[ /[0-9]+/, TokenType.NUMBER ],
[ /\#true|\#false|\#t|\#f/, TokenType.BOOLEAN ],
// Boolean is also symbol, but so far I don't want to support other symbols yet
[ /\#[^\(\)\[\]\{\}\"\,\'\`\;\#\|\\\s]+/, TokenType.SYMBOL ],
[ /[^\(\)\[\]\{\}\"\,\'\`\;\#\|\\\s]+/, TokenType.IDENTIFIER ],
[ /\"(:?\\.|[^\"])*\"/, TokenType.STRING ],
[ /[\(\)\[\]\{\}\"\,\'\`\;\#\|\\]/, TokenType.DELIMITER ],
[ /[\s]+/, TokenType.NONE ]
];
}
public static | (code:string): Array<Token> {
return new RacketLexer().parse(code);
}
} | parse | identifier_name |
lexer.ts | enum TokenType {
NONE,
IDENTIFIER,
NUMBER,
BOOLEAN,
STRING,
SYMBOL,
DELIMITER
}
class Token {
index:number;
text:string;
type:TokenType;
constructor(index:number, text:string, type:TokenType) {
this.index = index;
this.text = text;
this.type = type;
}
}
abstract class Lexer {
public abstract lex ():Array<[RegExp|Function,TokenType]>;
public fetch(code:string, index:number):Token {
let rules = this.lex();
for (var i = 0; i < rules.length; i++) {
let element = rules[i];
let rule = element[0];
let type = element[1];
if (rule instanceof Function) {
throw new Error("Does not support Function as rule yet.");
}
let re = new RegExp("^("+ rule.source + ")");
let found = re.exec (code.slice(index));
if (found != null) {
return new Token(index, found[0], type);
}
}
throw new Error("unexpected code from index " + index + ".");
}
public parse (code:string): Array<Token> {
let tokens:Array<Token> = [];
let index:number = 0;
while(true) {
let token:Token = this.fetch(code, index);
if (token.type != TokenType.NONE) {
tokens.push(token);
}
index += token.text.length;
if (code.length <= index) {
break;
}
}
return tokens;
}
}
/**
* Lexer for Racket.
*/
class RacketLexer extends Lexer {
public lex ():Array<[RegExp|Function,TokenType]> {
return [
[ /[0-9]+/, TokenType.NUMBER ],
[ /\#true|\#false|\#t|\#f/, TokenType.BOOLEAN ],
// Boolean is also symbol, but so far I don't want to support other symbols yet
[ /\#[^\(\)\[\]\{\}\"\,\'\`\;\#\|\\\s]+/, TokenType.SYMBOL ],
[ /[^\(\)\[\]\{\}\"\,\'\`\;\#\|\\\s]+/, TokenType.IDENTIFIER ],
[ /\"(:?\\.|[^\"])*\"/, TokenType.STRING ],
[ /[\(\)\[\]\{\}\"\,\'\`\;\#\|\\]/, TokenType.DELIMITER ],
[ /[\s]+/, TokenType.NONE ]
];
}
public static parse (code:string): Array<Token> { | return new RacketLexer().parse(code);
}
} | random_line_split | |
reciprocals.py | """
An integer that is not co-prime to 10 but has a prime factor other than 2 or 5
has a reciprocal that is eventually periodic, but with a non-repeating sequence
of digits that precede the repeating part. The reciprocal can be expressed as:
\frac{1}{2^a 5^b p^k q^\ell \cdots}\, ,
where a and b are not both zero.
This fraction can also be expressed as:
\frac{5^{a-b}}{10^a p^k q^\ell \cdots}\, ,
if a > b, or as
\frac{2^{b-a}}{10^b p^k q^\ell \cdots}\, ,
if b > a, or as
\frac{1}{10^a p^k q^\ell \cdots}\, ,
if a = b.
The decimal has:
An initial transient of max(a, b) digits after the decimal point. Some or
all of the digits in the transient can be zeros.
A subsequent repetend which is the same as that for the fraction
\frac{1}{p^k q^\ell \cdots}.
For example 1/28 = 0.03571428571428…:
the initial non-repeating digits are 03; and
the subsequent repeating digits are 571428.
"""
def transient ( d , bfactor ) :
"""
Computes the length of the non repeating part in 1 / d decimals in
base b. Returns tuple ( n , hasrepetend ) where n is the length of the
non repeating part and hasrepetend determines if 1 / d repeats or not.
"""
n = 0
for f in bfactor :
|
while d % f == 0 :
m += 1
d //= f
if m > n : n = m
return n , d > 1
def repetend ( n , d , b ) :
"""
Computes the length of the repetend of 1 divided by d in base b
with non repeating part of size n.
"""
a = 1
for i in range( n ) :
a *= b
a %= d
x = a
a *= b
a %= d
l = 1
while a != x :
a *= b
a %= d
l += 1
return l | m = 0 | random_line_split |
reciprocals.py | """
An integer that is not co-prime to 10 but has a prime factor other than 2 or 5
has a reciprocal that is eventually periodic, but with a non-repeating sequence
of digits that precede the repeating part. The reciprocal can be expressed as:
\frac{1}{2^a 5^b p^k q^\ell \cdots}\, ,
where a and b are not both zero.
This fraction can also be expressed as:
\frac{5^{a-b}}{10^a p^k q^\ell \cdots}\, ,
if a > b, or as
\frac{2^{b-a}}{10^b p^k q^\ell \cdots}\, ,
if b > a, or as
\frac{1}{10^a p^k q^\ell \cdots}\, ,
if a = b.
The decimal has:
An initial transient of max(a, b) digits after the decimal point. Some or
all of the digits in the transient can be zeros.
A subsequent repetend which is the same as that for the fraction
\frac{1}{p^k q^\ell \cdots}.
For example 1/28 = 0.03571428571428…:
the initial non-repeating digits are 03; and
the subsequent repeating digits are 571428.
"""
def transient ( d , bfactor ) :
"" |
def repetend ( n , d , b ) :
"""
Computes the length of the repetend of 1 divided by d in base b
with non repeating part of size n.
"""
a = 1
for i in range( n ) :
a *= b
a %= d
x = a
a *= b
a %= d
l = 1
while a != x :
a *= b
a %= d
l += 1
return l
| "
Computes the length of the non repeating part in 1 / d decimals in
base b. Returns tuple ( n , hasrepetend ) where n is the length of the
non repeating part and hasrepetend determines if 1 / d repeats or not.
"""
n = 0
for f in bfactor :
m = 0
while d % f == 0 :
m += 1
d //= f
if m > n : n = m
return n , d > 1
| identifier_body |
reciprocals.py | """
An integer that is not co-prime to 10 but has a prime factor other than 2 or 5
has a reciprocal that is eventually periodic, but with a non-repeating sequence
of digits that precede the repeating part. The reciprocal can be expressed as:
\frac{1}{2^a 5^b p^k q^\ell \cdots}\, ,
where a and b are not both zero.
This fraction can also be expressed as:
\frac{5^{a-b}}{10^a p^k q^\ell \cdots}\, ,
if a > b, or as
\frac{2^{b-a}}{10^b p^k q^\ell \cdots}\, ,
if b > a, or as
\frac{1}{10^a p^k q^\ell \cdots}\, ,
if a = b.
The decimal has:
An initial transient of max(a, b) digits after the decimal point. Some or
all of the digits in the transient can be zeros.
A subsequent repetend which is the same as that for the fraction
\frac{1}{p^k q^\ell \cdots}.
For example 1/28 = 0.03571428571428…:
the initial non-repeating digits are 03; and
the subsequent repeating digits are 571428.
"""
def transient ( d , bfactor ) :
"""
Computes the length of the non repeating part in 1 / d decimals in
base b. Returns tuple ( n , hasrepetend ) where n is the length of the
non repeating part and hasrepetend determines if 1 / d repeats or not.
"""
n = 0
for f in bfactor :
m = 0
while d % f == 0 :
m += 1
d //= f
if m > n : n = m
return n , d > 1
def repetend ( n , d , b ) :
"""
Computes the length of the repetend of 1 divided by d in base b
with non repeating part of size n.
"""
a = 1
for i in range( n ) :
a | x = a
a *= b
a %= d
l = 1
while a != x :
a *= b
a %= d
l += 1
return l
| *= b
a %= d
| conditional_block |
reciprocals.py | """
An integer that is not co-prime to 10 but has a prime factor other than 2 or 5
has a reciprocal that is eventually periodic, but with a non-repeating sequence
of digits that precede the repeating part. The reciprocal can be expressed as:
\frac{1}{2^a 5^b p^k q^\ell \cdots}\, ,
where a and b are not both zero.
This fraction can also be expressed as:
\frac{5^{a-b}}{10^a p^k q^\ell \cdots}\, ,
if a > b, or as
\frac{2^{b-a}}{10^b p^k q^\ell \cdots}\, ,
if b > a, or as
\frac{1}{10^a p^k q^\ell \cdots}\, ,
if a = b.
The decimal has:
An initial transient of max(a, b) digits after the decimal point. Some or
all of the digits in the transient can be zeros.
A subsequent repetend which is the same as that for the fraction
\frac{1}{p^k q^\ell \cdots}.
For example 1/28 = 0.03571428571428…:
the initial non-repeating digits are 03; and
the subsequent repeating digits are 571428.
"""
def tr | d , bfactor ) :
"""
Computes the length of the non repeating part in 1 / d decimals in
base b. Returns tuple ( n , hasrepetend ) where n is the length of the
non repeating part and hasrepetend determines if 1 / d repeats or not.
"""
n = 0
for f in bfactor :
m = 0
while d % f == 0 :
m += 1
d //= f
if m > n : n = m
return n , d > 1
def repetend ( n , d , b ) :
"""
Computes the length of the repetend of 1 divided by d in base b
with non repeating part of size n.
"""
a = 1
for i in range( n ) :
a *= b
a %= d
x = a
a *= b
a %= d
l = 1
while a != x :
a *= b
a %= d
l += 1
return l
| ansient ( | identifier_name |
create-image2.py | import cv2
import numpy as np
import sys
def reshapeImg(img, l, w, p):
# reshape image to (l, w) and add/remove pixels as needed
while len(img) % p != 0:
img = np.append(img, 255)
olds = img.size / p
news = l*w
if news < olds:
img = img[:p*news]
elif news > olds:
|
return img.reshape(l, w, p)
if __name__ == "__main__":
# Usage: python create-image2.py <height> <width> <array>
# for random image do <array> = random
# array format string = xyz...
l = int(sys.argv[1])
w = int(sys.argv[2])
s = sys.argv[3]
# create random image if no array given
if s == "random":
arr = np.random.randint(256, size=l*w*3)
else:
arr = np.asarray([int(s[i:i+3]) for i in range(0, len(s)-3, 3)])
# write image to new file
cv2.imwrite("img.png", reshapeImg(arr, l, w, 3))
| img = np.concatenate( (img, np.zeros(p*(news-olds))) ) | conditional_block |
create-image2.py | import cv2
import numpy as np
import sys
def reshapeImg(img, l, w, p):
# reshape image to (l, w) and add/remove pixels as needed
|
if __name__ == "__main__":
# Usage: python create-image2.py <height> <width> <array>
# for random image do <array> = random
# array format string = xyz...
l = int(sys.argv[1])
w = int(sys.argv[2])
s = sys.argv[3]
# create random image if no array given
if s == "random":
arr = np.random.randint(256, size=l*w*3)
else:
arr = np.asarray([int(s[i:i+3]) for i in range(0, len(s)-3, 3)])
# write image to new file
cv2.imwrite("img.png", reshapeImg(arr, l, w, 3))
| while len(img) % p != 0:
img = np.append(img, 255)
olds = img.size / p
news = l*w
if news < olds:
img = img[:p*news]
elif news > olds:
img = np.concatenate( (img, np.zeros(p*(news-olds))) )
return img.reshape(l, w, p) | identifier_body |
create-image2.py | import cv2
import numpy as np
import sys
def reshapeImg(img, l, w, p):
# reshape image to (l, w) and add/remove pixels as needed
while len(img) % p != 0:
img = np.append(img, 255)
olds = img.size / p
news = l*w
if news < olds:
img = img[:p*news]
elif news > olds:
img = np.concatenate( (img, np.zeros(p*(news-olds))) )
return img.reshape(l, w, p)
if __name__ == "__main__":
# Usage: python create-image2.py <height> <width> <array>
# for random image do <array> = random
# array format string = xyz...
l = int(sys.argv[1])
w = int(sys.argv[2])
s = sys.argv[3]
# create random image if no array given
if s == "random":
arr = np.random.randint(256, size=l*w*3)
else:
arr = np.asarray([int(s[i:i+3]) for i in range(0, len(s)-3, 3)])
# write image to new file | cv2.imwrite("img.png", reshapeImg(arr, l, w, 3)) | random_line_split | |
create-image2.py | import cv2
import numpy as np
import sys
def | (img, l, w, p):
# reshape image to (l, w) and add/remove pixels as needed
while len(img) % p != 0:
img = np.append(img, 255)
olds = img.size / p
news = l*w
if news < olds:
img = img[:p*news]
elif news > olds:
img = np.concatenate( (img, np.zeros(p*(news-olds))) )
return img.reshape(l, w, p)
if __name__ == "__main__":
# Usage: python create-image2.py <height> <width> <array>
# for random image do <array> = random
# array format string = xyz...
l = int(sys.argv[1])
w = int(sys.argv[2])
s = sys.argv[3]
# create random image if no array given
if s == "random":
arr = np.random.randint(256, size=l*w*3)
else:
arr = np.asarray([int(s[i:i+3]) for i in range(0, len(s)-3, 3)])
# write image to new file
cv2.imwrite("img.png", reshapeImg(arr, l, w, 3))
| reshapeImg | identifier_name |
ng_for.ts | import {DoCheck} from 'angular2/lifecycle_hooks';
import {Directive} from 'angular2/src/core/metadata';
import {
ChangeDetectorRef,
IterableDiffer,
IterableDiffers
} from 'angular2/src/core/change_detection';
import {ViewContainerRef, TemplateRef, ViewRef} from 'angular2/src/core/linker';
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
/**
* The `NgFor` directive instantiates a template once per item from an iterable. The context for
* each instantiated template inherits from the outer context with the given loop variable set
* to the current item from the iterable.
*
* # Local Variables
*
* `NgFor` provides several exported values that can be aliased to local variables:
*
* * `index` will be set to the current loop iteration for each template context.
* * `last` will be set to a boolean value indicating whether the item is the last one in the
* iteration.
* * `even` will be set to a boolean value indicating whether this item has an even index.
* * `odd` will be set to a boolean value indicating whether this item has an odd index.
*
* # Change Propagation
*
* When the contents of the iterator changes, `NgFor` makes the corresponding changes to the DOM:
*
* * When an item is added, a new instance of the template is added to the DOM.
* * When an item is removed, its template instance is removed from the DOM.
* * When items are reordered, their respective templates are reordered in the DOM.
* * Otherwise, the DOM element for that item will remain the same.
*
* Angular uses object identity to track insertions and deletions within the iterator and reproduce
* those changes in the DOM. This has important implications for animations and any stateful
* controls
* (such as `<input>` elements which accept user input) that are present. Inserted rows can be
* animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state such
* as user input.
*
* It is possible for the identities of elements in the iterator to change while the data does not.
* This can happen, for example, if the iterator produced from an RPC to the server, and that
* RPC is re-run. Even if the data hasn't changed, the second response will produce objects with
* different identities, and Angular will tear down the entire DOM and rebuild it (as if all old
* elements were deleted and all new elements inserted). This is an expensive operation and should
* be avoided if possible.
*
* # Syntax
*
* - `<li *ng-for="#item of items; #i = index">...</li>`
* - `<li template="ng-for #item of items; #i = index">...</li>`
* - `<template ng-for #item [ng-for-of]="items" #i="index"><li>...</li></template>`
*
* ### Example
*
* See a [live demo](http://plnkr.co/edit/KVuXxDp0qinGDyo307QW?p=preview) for a more detailed
* example.
*/
@Directive({selector: '[ng-for][ng-for-of]', inputs: ['ngForOf', 'ngForTemplate']})
export class NgFor implements DoCheck {
/** @internal */
_ngForOf: any;
private _differ: IterableDiffer;
constructor(private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef,
private _iterableDiffers: IterableDiffers, private _cdr: ChangeDetectorRef) {}
set ngForOf(value: any) {
this._ngForOf = value;
if (isBlank(this._differ) && isPresent(value)) {
this._differ = this._iterableDiffers.find(value).create(this._cdr);
}
}
set ngForTemplate(value: TemplateRef) { this._templateRef = value; }
doCheck() |
private _applyChanges(changes) {
// TODO(rado): check if change detection can produce a change record that is
// easier to consume than current.
var recordViewTuples = [];
changes.forEachRemovedItem((removedRecord) =>
recordViewTuples.push(new RecordViewTuple(removedRecord, null)));
changes.forEachMovedItem((movedRecord) =>
recordViewTuples.push(new RecordViewTuple(movedRecord, null)));
var insertTuples = this._bulkRemove(recordViewTuples);
changes.forEachAddedItem((addedRecord) =>
insertTuples.push(new RecordViewTuple(addedRecord, null)));
this._bulkInsert(insertTuples);
for (var i = 0; i < insertTuples.length; i++) {
this._perViewChange(insertTuples[i].view, insertTuples[i].record);
}
for (var i = 0, ilen = this._viewContainer.length; i < ilen; i++) {
this._viewContainer.get(i).setLocal('last', i === ilen - 1);
}
}
private _perViewChange(view, record) {
view.setLocal('\$implicit', record.item);
view.setLocal('index', record.currentIndex);
view.setLocal('even', (record.currentIndex % 2 == 0));
view.setLocal('odd', (record.currentIndex % 2 == 1));
}
private _bulkRemove(tuples: RecordViewTuple[]): RecordViewTuple[] {
tuples.sort((a, b) => a.record.previousIndex - b.record.previousIndex);
var movedTuples = [];
for (var i = tuples.length - 1; i >= 0; i--) {
var tuple = tuples[i];
// separate moved views from removed views.
if (isPresent(tuple.record.currentIndex)) {
tuple.view = this._viewContainer.detach(tuple.record.previousIndex);
movedTuples.push(tuple);
} else {
this._viewContainer.remove(tuple.record.previousIndex);
}
}
return movedTuples;
}
private _bulkInsert(tuples: RecordViewTuple[]): RecordViewTuple[] {
tuples.sort((a, b) => a.record.currentIndex - b.record.currentIndex);
for (var i = 0; i < tuples.length; i++) {
var tuple = tuples[i];
if (isPresent(tuple.view)) {
this._viewContainer.insert(tuple.view, tuple.record.currentIndex);
} else {
tuple.view =
this._viewContainer.createEmbeddedView(this._templateRef, tuple.record.currentIndex);
}
}
return tuples;
}
}
class RecordViewTuple {
view: ViewRef;
record: any;
constructor(record, view) {
this.record = record;
this.view = view;
}
}
| {
if (isPresent(this._differ)) {
var changes = this._differ.diff(this._ngForOf);
if (isPresent(changes)) this._applyChanges(changes);
}
} | identifier_body |
ng_for.ts | import {DoCheck} from 'angular2/lifecycle_hooks';
import {Directive} from 'angular2/src/core/metadata';
import {
ChangeDetectorRef,
IterableDiffer,
IterableDiffers
} from 'angular2/src/core/change_detection';
import {ViewContainerRef, TemplateRef, ViewRef} from 'angular2/src/core/linker';
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
/**
* The `NgFor` directive instantiates a template once per item from an iterable. The context for
* each instantiated template inherits from the outer context with the given loop variable set
* to the current item from the iterable.
*
* # Local Variables
*
* `NgFor` provides several exported values that can be aliased to local variables:
*
* * `index` will be set to the current loop iteration for each template context.
* * `last` will be set to a boolean value indicating whether the item is the last one in the
* iteration.
* * `even` will be set to a boolean value indicating whether this item has an even index.
* * `odd` will be set to a boolean value indicating whether this item has an odd index.
*
* # Change Propagation
*
* When the contents of the iterator changes, `NgFor` makes the corresponding changes to the DOM:
*
* * When an item is added, a new instance of the template is added to the DOM.
* * When an item is removed, its template instance is removed from the DOM.
* * When items are reordered, their respective templates are reordered in the DOM.
* * Otherwise, the DOM element for that item will remain the same.
*
* Angular uses object identity to track insertions and deletions within the iterator and reproduce
* those changes in the DOM. This has important implications for animations and any stateful
* controls
* (such as `<input>` elements which accept user input) that are present. Inserted rows can be
* animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state such
* as user input.
*
* It is possible for the identities of elements in the iterator to change while the data does not.
* This can happen, for example, if the iterator produced from an RPC to the server, and that
* RPC is re-run. Even if the data hasn't changed, the second response will produce objects with
* different identities, and Angular will tear down the entire DOM and rebuild it (as if all old
* elements were deleted and all new elements inserted). This is an expensive operation and should
* be avoided if possible.
*
* # Syntax
*
* - `<li *ng-for="#item of items; #i = index">...</li>`
* - `<li template="ng-for #item of items; #i = index">...</li>`
* - `<template ng-for #item [ng-for-of]="items" #i="index"><li>...</li></template>`
*
* ### Example
*
* See a [live demo](http://plnkr.co/edit/KVuXxDp0qinGDyo307QW?p=preview) for a more detailed
* example.
*/
@Directive({selector: '[ng-for][ng-for-of]', inputs: ['ngForOf', 'ngForTemplate']})
export class NgFor implements DoCheck {
/** @internal */
_ngForOf: any;
private _differ: IterableDiffer;
constructor(private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef,
private _iterableDiffers: IterableDiffers, private _cdr: ChangeDetectorRef) {}
set ngForOf(value: any) {
this._ngForOf = value;
if (isBlank(this._differ) && isPresent(value)) {
this._differ = this._iterableDiffers.find(value).create(this._cdr);
}
}
set ngForTemplate(value: TemplateRef) { this._templateRef = value; }
doCheck() {
if (isPresent(this._differ)) {
var changes = this._differ.diff(this._ngForOf);
if (isPresent(changes)) this._applyChanges(changes);
}
}
private _applyChanges(changes) {
// TODO(rado): check if change detection can produce a change record that is
// easier to consume than current.
var recordViewTuples = [];
changes.forEachRemovedItem((removedRecord) =>
recordViewTuples.push(new RecordViewTuple(removedRecord, null)));
changes.forEachMovedItem((movedRecord) =>
recordViewTuples.push(new RecordViewTuple(movedRecord, null)));
var insertTuples = this._bulkRemove(recordViewTuples);
changes.forEachAddedItem((addedRecord) =>
insertTuples.push(new RecordViewTuple(addedRecord, null)));
this._bulkInsert(insertTuples);
for (var i = 0; i < insertTuples.length; i++) {
this._perViewChange(insertTuples[i].view, insertTuples[i].record);
}
for (var i = 0, ilen = this._viewContainer.length; i < ilen; i++) {
this._viewContainer.get(i).setLocal('last', i === ilen - 1);
}
}
private _perViewChange(view, record) {
view.setLocal('\$implicit', record.item);
view.setLocal('index', record.currentIndex);
view.setLocal('even', (record.currentIndex % 2 == 0));
view.setLocal('odd', (record.currentIndex % 2 == 1));
}
private _bulkRemove(tuples: RecordViewTuple[]): RecordViewTuple[] {
tuples.sort((a, b) => a.record.previousIndex - b.record.previousIndex);
var movedTuples = [];
for (var i = tuples.length - 1; i >= 0; i--) |
return movedTuples;
}
private _bulkInsert(tuples: RecordViewTuple[]): RecordViewTuple[] {
tuples.sort((a, b) => a.record.currentIndex - b.record.currentIndex);
for (var i = 0; i < tuples.length; i++) {
var tuple = tuples[i];
if (isPresent(tuple.view)) {
this._viewContainer.insert(tuple.view, tuple.record.currentIndex);
} else {
tuple.view =
this._viewContainer.createEmbeddedView(this._templateRef, tuple.record.currentIndex);
}
}
return tuples;
}
}
class RecordViewTuple {
view: ViewRef;
record: any;
constructor(record, view) {
this.record = record;
this.view = view;
}
}
| {
var tuple = tuples[i];
// separate moved views from removed views.
if (isPresent(tuple.record.currentIndex)) {
tuple.view = this._viewContainer.detach(tuple.record.previousIndex);
movedTuples.push(tuple);
} else {
this._viewContainer.remove(tuple.record.previousIndex);
}
} | conditional_block |
ng_for.ts | import {DoCheck} from 'angular2/lifecycle_hooks';
import {Directive} from 'angular2/src/core/metadata';
import {
ChangeDetectorRef,
IterableDiffer,
IterableDiffers
} from 'angular2/src/core/change_detection';
import {ViewContainerRef, TemplateRef, ViewRef} from 'angular2/src/core/linker';
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
/**
* The `NgFor` directive instantiates a template once per item from an iterable. The context for
* each instantiated template inherits from the outer context with the given loop variable set
* to the current item from the iterable.
*
* # Local Variables
*
* `NgFor` provides several exported values that can be aliased to local variables:
*
* * `index` will be set to the current loop iteration for each template context.
* * `last` will be set to a boolean value indicating whether the item is the last one in the
* iteration.
* * `even` will be set to a boolean value indicating whether this item has an even index.
* * `odd` will be set to a boolean value indicating whether this item has an odd index.
*
* # Change Propagation
*
* When the contents of the iterator changes, `NgFor` makes the corresponding changes to the DOM:
*
* * When an item is added, a new instance of the template is added to the DOM.
* * When an item is removed, its template instance is removed from the DOM.
* * When items are reordered, their respective templates are reordered in the DOM.
* * Otherwise, the DOM element for that item will remain the same.
*
* Angular uses object identity to track insertions and deletions within the iterator and reproduce
* those changes in the DOM. This has important implications for animations and any stateful
* controls
* (such as `<input>` elements which accept user input) that are present. Inserted rows can be
* animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state such
* as user input.
*
* It is possible for the identities of elements in the iterator to change while the data does not.
* This can happen, for example, if the iterator produced from an RPC to the server, and that
* RPC is re-run. Even if the data hasn't changed, the second response will produce objects with
* different identities, and Angular will tear down the entire DOM and rebuild it (as if all old
* elements were deleted and all new elements inserted). This is an expensive operation and should
* be avoided if possible.
*
* # Syntax
*
* - `<li *ng-for="#item of items; #i = index">...</li>`
* - `<li template="ng-for #item of items; #i = index">...</li>`
* - `<template ng-for #item [ng-for-of]="items" #i="index"><li>...</li></template>`
*
* ### Example
*
* See a [live demo](http://plnkr.co/edit/KVuXxDp0qinGDyo307QW?p=preview) for a more detailed
* example.
*/
@Directive({selector: '[ng-for][ng-for-of]', inputs: ['ngForOf', 'ngForTemplate']})
export class NgFor implements DoCheck {
/** @internal */
_ngForOf: any;
private _differ: IterableDiffer;
constructor(private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef,
private _iterableDiffers: IterableDiffers, private _cdr: ChangeDetectorRef) {}
set | (value: any) {
this._ngForOf = value;
if (isBlank(this._differ) && isPresent(value)) {
this._differ = this._iterableDiffers.find(value).create(this._cdr);
}
}
set ngForTemplate(value: TemplateRef) { this._templateRef = value; }
doCheck() {
if (isPresent(this._differ)) {
var changes = this._differ.diff(this._ngForOf);
if (isPresent(changes)) this._applyChanges(changes);
}
}
private _applyChanges(changes) {
// TODO(rado): check if change detection can produce a change record that is
// easier to consume than current.
var recordViewTuples = [];
changes.forEachRemovedItem((removedRecord) =>
recordViewTuples.push(new RecordViewTuple(removedRecord, null)));
changes.forEachMovedItem((movedRecord) =>
recordViewTuples.push(new RecordViewTuple(movedRecord, null)));
var insertTuples = this._bulkRemove(recordViewTuples);
changes.forEachAddedItem((addedRecord) =>
insertTuples.push(new RecordViewTuple(addedRecord, null)));
this._bulkInsert(insertTuples);
for (var i = 0; i < insertTuples.length; i++) {
this._perViewChange(insertTuples[i].view, insertTuples[i].record);
}
for (var i = 0, ilen = this._viewContainer.length; i < ilen; i++) {
this._viewContainer.get(i).setLocal('last', i === ilen - 1);
}
}
private _perViewChange(view, record) {
view.setLocal('\$implicit', record.item);
view.setLocal('index', record.currentIndex);
view.setLocal('even', (record.currentIndex % 2 == 0));
view.setLocal('odd', (record.currentIndex % 2 == 1));
}
private _bulkRemove(tuples: RecordViewTuple[]): RecordViewTuple[] {
tuples.sort((a, b) => a.record.previousIndex - b.record.previousIndex);
var movedTuples = [];
for (var i = tuples.length - 1; i >= 0; i--) {
var tuple = tuples[i];
// separate moved views from removed views.
if (isPresent(tuple.record.currentIndex)) {
tuple.view = this._viewContainer.detach(tuple.record.previousIndex);
movedTuples.push(tuple);
} else {
this._viewContainer.remove(tuple.record.previousIndex);
}
}
return movedTuples;
}
private _bulkInsert(tuples: RecordViewTuple[]): RecordViewTuple[] {
tuples.sort((a, b) => a.record.currentIndex - b.record.currentIndex);
for (var i = 0; i < tuples.length; i++) {
var tuple = tuples[i];
if (isPresent(tuple.view)) {
this._viewContainer.insert(tuple.view, tuple.record.currentIndex);
} else {
tuple.view =
this._viewContainer.createEmbeddedView(this._templateRef, tuple.record.currentIndex);
}
}
return tuples;
}
}
class RecordViewTuple {
view: ViewRef;
record: any;
constructor(record, view) {
this.record = record;
this.view = view;
}
}
| ngForOf | identifier_name |
ng_for.ts | import {DoCheck} from 'angular2/lifecycle_hooks';
import {Directive} from 'angular2/src/core/metadata';
import {
ChangeDetectorRef,
IterableDiffer,
IterableDiffers
} from 'angular2/src/core/change_detection';
import {ViewContainerRef, TemplateRef, ViewRef} from 'angular2/src/core/linker';
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
/**
* The `NgFor` directive instantiates a template once per item from an iterable. The context for
* each instantiated template inherits from the outer context with the given loop variable set
* to the current item from the iterable.
*
* # Local Variables
*
* `NgFor` provides several exported values that can be aliased to local variables:
*
* * `index` will be set to the current loop iteration for each template context.
* * `last` will be set to a boolean value indicating whether the item is the last one in the
* iteration.
* * `even` will be set to a boolean value indicating whether this item has an even index.
* * `odd` will be set to a boolean value indicating whether this item has an odd index.
*
* # Change Propagation
*
* When the contents of the iterator changes, `NgFor` makes the corresponding changes to the DOM:
*
* * When an item is added, a new instance of the template is added to the DOM.
* * When an item is removed, its template instance is removed from the DOM.
* * When items are reordered, their respective templates are reordered in the DOM.
* * Otherwise, the DOM element for that item will remain the same.
*
* Angular uses object identity to track insertions and deletions within the iterator and reproduce
* those changes in the DOM. This has important implications for animations and any stateful
* controls
* (such as `<input>` elements which accept user input) that are present. Inserted rows can be
* animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state such
* as user input.
*
* It is possible for the identities of elements in the iterator to change while the data does not.
* This can happen, for example, if the iterator produced from an RPC to the server, and that
* RPC is re-run. Even if the data hasn't changed, the second response will produce objects with
* different identities, and Angular will tear down the entire DOM and rebuild it (as if all old
* elements were deleted and all new elements inserted). This is an expensive operation and should
* be avoided if possible.
*
* # Syntax
*
* - `<li *ng-for="#item of items; #i = index">...</li>`
* - `<li template="ng-for #item of items; #i = index">...</li>`
* - `<template ng-for #item [ng-for-of]="items" #i="index"><li>...</li></template>`
*
* ### Example
*
* See a [live demo](http://plnkr.co/edit/KVuXxDp0qinGDyo307QW?p=preview) for a more detailed
* example.
*/
@Directive({selector: '[ng-for][ng-for-of]', inputs: ['ngForOf', 'ngForTemplate']})
export class NgFor implements DoCheck {
/** @internal */
_ngForOf: any;
private _differ: IterableDiffer;
constructor(private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef,
private _iterableDiffers: IterableDiffers, private _cdr: ChangeDetectorRef) {}
set ngForOf(value: any) {
this._ngForOf = value;
if (isBlank(this._differ) && isPresent(value)) {
this._differ = this._iterableDiffers.find(value).create(this._cdr);
}
}
set ngForTemplate(value: TemplateRef) { this._templateRef = value; }
doCheck() {
if (isPresent(this._differ)) {
var changes = this._differ.diff(this._ngForOf);
if (isPresent(changes)) this._applyChanges(changes);
}
}
private _applyChanges(changes) {
// TODO(rado): check if change detection can produce a change record that is
// easier to consume than current.
var recordViewTuples = [];
changes.forEachRemovedItem((removedRecord) =>
recordViewTuples.push(new RecordViewTuple(removedRecord, null)));
changes.forEachMovedItem((movedRecord) =>
recordViewTuples.push(new RecordViewTuple(movedRecord, null)));
var insertTuples = this._bulkRemove(recordViewTuples);
|
for (var i = 0; i < insertTuples.length; i++) {
this._perViewChange(insertTuples[i].view, insertTuples[i].record);
}
for (var i = 0, ilen = this._viewContainer.length; i < ilen; i++) {
this._viewContainer.get(i).setLocal('last', i === ilen - 1);
}
}
private _perViewChange(view, record) {
view.setLocal('\$implicit', record.item);
view.setLocal('index', record.currentIndex);
view.setLocal('even', (record.currentIndex % 2 == 0));
view.setLocal('odd', (record.currentIndex % 2 == 1));
}
private _bulkRemove(tuples: RecordViewTuple[]): RecordViewTuple[] {
tuples.sort((a, b) => a.record.previousIndex - b.record.previousIndex);
var movedTuples = [];
for (var i = tuples.length - 1; i >= 0; i--) {
var tuple = tuples[i];
// separate moved views from removed views.
if (isPresent(tuple.record.currentIndex)) {
tuple.view = this._viewContainer.detach(tuple.record.previousIndex);
movedTuples.push(tuple);
} else {
this._viewContainer.remove(tuple.record.previousIndex);
}
}
return movedTuples;
}
private _bulkInsert(tuples: RecordViewTuple[]): RecordViewTuple[] {
tuples.sort((a, b) => a.record.currentIndex - b.record.currentIndex);
for (var i = 0; i < tuples.length; i++) {
var tuple = tuples[i];
if (isPresent(tuple.view)) {
this._viewContainer.insert(tuple.view, tuple.record.currentIndex);
} else {
tuple.view =
this._viewContainer.createEmbeddedView(this._templateRef, tuple.record.currentIndex);
}
}
return tuples;
}
}
class RecordViewTuple {
view: ViewRef;
record: any;
constructor(record, view) {
this.record = record;
this.view = view;
}
} | changes.forEachAddedItem((addedRecord) =>
insertTuples.push(new RecordViewTuple(addedRecord, null)));
this._bulkInsert(insertTuples); | random_line_split |
CodeEditor.d.ts | /// <reference path="../../includes.d.ts" />
/**
* Module that contains several helper functions related to hawtio's code editor
*
* @module CodeEditor
* @main CodeEditor
*/
declare module CodeEditor {
/**
* Options for the CodeMirror text editor
*
* @class CodeMirrorOptions
*/
interface CodeMirrorOptions {
/**
* @property theme
* @type String
*/
theme: string;
/**
* @property tabSize
* @type number
*/
tabSize: number;
/**
* @property lineNumbers | * @property indentWithTabs
* @type boolean
*/
indentWithTabs: boolean;
/**
* @property lineWrapping
* @type boolean
*/
lineWrapping: boolean;
/**
* @property autoClosetags
* @type boolean
*/
autoClosetags: boolean;
}
/**
* @property GlobalCodeMirrorOptions
* @for CodeEditor
* @type CodeMirrorOptions
*/
var GlobalCodeMirrorOptions: {
theme: string;
tabSize: number;
lineNumbers: boolean;
indentWithTabs: boolean;
lineWrapping: boolean;
autoCloseTags: boolean;
};
/**
* Tries to figure out what kind of text we're going to render in the editor, either
* text, javascript or XML.
*
* @method detectTextFormat
* @for CodeEditor
* @static
* @param value
* @returns {string}
*/
function detectTextFormat(value: any): string;
/**
* Auto formats the CodeMirror editor content to pretty print
*
* @method autoFormatEditor
* @for CodeEditor
* @static
* @param {CodeMirrorEditor} editor
* @return {void}
*/
function autoFormatEditor(editor: CodeMirrorEditor): void;
/**
* Used to configures the default editor settings (per Editor Instance)
*
* @method createEditorSettings
* @for CodeEditor
* @static
* @param {Object} options
* @return {Object}
*/
function createEditorSettings(options?: any): any;
} | * @type boolean
*/
lineNumbers: boolean;
/** | random_line_split |
ec2_vpc_subnet.py | #!/usr/bin/python
#
# This is a free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This Ansible library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this library. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'curated'}
DOCUMENTATION = '''
---
module: ec2_vpc_subnet
short_description: Manage subnets in AWS virtual private clouds
description:
- Manage subnets in AWS virtual private clouds
version_added: "2.0"
author: Robert Estelle (@erydo)
options:
az:
description:
- "The availability zone for the subnet. Only required when state=present."
required: false
default: null
cidr:
description:
- "The CIDR block for the subnet. E.g. 192.0.2.0/24. Only required when state=present."
required: false
default: null
tags:
description:
- "A dict of tags to apply to the subnet. Any tags currently applied to the subnet and not present here will be removed."
required: false
default: null
aliases: [ 'resource_tags' ]
state:
description:
- "Create or remove the subnet"
required: false
default: present
choices: [ 'present', 'absent' ]
vpc_id:
description:
- "VPC ID of the VPC in which to create the subnet."
required: false
default: null
extends_documentation_fragment:
- aws
- ec2
'''
EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.
- name: Create subnet for database servers
ec2_vpc_subnet:
state: present
vpc_id: vpc-123456
cidr: 10.0.1.16/28
resource_tags:
Name: Database Subnet
register: database_subnet
- name: Remove subnet for database servers
ec2_vpc_subnet:
state: absent
vpc_id: vpc-123456
cidr: 10.0.1.16/28
'''
import time
try:
import boto.ec2
import boto.vpc
from boto.exception import EC2ResponseError
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
if __name__ != '__main__':
raise
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import AnsibleAWSError, connect_to_aws, ec2_argument_spec, get_aws_connection_info
class AnsibleVPCSubnetException(Exception):
pass
class AnsibleVPCSubnetCreationException(AnsibleVPCSubnetException):
pass
class AnsibleVPCSubnetDeletionException(AnsibleVPCSubnetException):
pass
class AnsibleTagCreationException(AnsibleVPCSubnetException):
pass
def get_subnet_info(subnet):
subnet_info = {'id': subnet.id,
'availability_zone': subnet.availability_zone,
'available_ip_address_count': subnet.available_ip_address_count,
'cidr_block': subnet.cidr_block,
'default_for_az': subnet.defaultForAz,
'map_public_ip_on_launch': subnet.mapPublicIpOnLaunch,
'state': subnet.state,
'tags': subnet.tags,
'vpc_id': subnet.vpc_id
}
return subnet_info
def subnet_exists(vpc_conn, subnet_id):
filters = {'subnet-id': subnet_id}
subnet = vpc_conn.get_all_subnets(filters=filters)
if subnet and subnet[0].state == "available":
return subnet[0]
else:
return False
def create_subnet(vpc_conn, vpc_id, cidr, az, check_mode):
try:
new_subnet = vpc_conn.create_subnet(vpc_id, cidr, az, dry_run=check_mode)
# Sometimes AWS takes its time to create a subnet and so using
# new subnets's id to do things like create tags results in
# exception. boto doesn't seem to refresh 'state' of the newly
# created subnet, i.e.: it's always 'pending'.
subnet = False
while subnet is False:
subnet = subnet_exists(vpc_conn, new_subnet.id)
time.sleep(0.1)
except EC2ResponseError as e:
if e.error_code == "DryRunOperation":
subnet = None
elif e.error_code == "InvalidSubnet.Conflict":
raise AnsibleVPCSubnetCreationException("%s: the CIDR %s conflicts with another subnet with the VPC ID %s." % (e.error_code, cidr, vpc_id))
else:
raise AnsibleVPCSubnetCreationException(
'Unable to create subnet {0}, error: {1}'.format(cidr, e))
return subnet
def get_resource_tags(vpc_conn, resource_id):
return dict((t.name, t.value) for t in
vpc_conn.get_all_tags(filters={'resource-id': resource_id}))
def ensure_tags(vpc_conn, resource_id, tags, add_only, check_mode):
try:
cur_tags = get_resource_tags(vpc_conn, resource_id)
if cur_tags == tags:
return {'changed': False, 'tags': cur_tags}
to_delete = dict((k, cur_tags[k]) for k in cur_tags if k not in tags)
if to_delete and not add_only:
vpc_conn.delete_tags(resource_id, to_delete, dry_run=check_mode)
to_add = dict((k, tags[k]) for k in tags if k not in cur_tags or cur_tags[k] != tags[k])
if to_add:
vpc_conn.create_tags(resource_id, to_add, dry_run=check_mode)
latest_tags = get_resource_tags(vpc_conn, resource_id)
return {'changed': True, 'tags': latest_tags}
except EC2ResponseError as e:
raise AnsibleTagCreationException(
'Unable to update tags for {0}, error: {1}'.format(resource_id, e))
def get_matching_subnet(vpc_conn, vpc_id, cidr):
subnets = vpc_conn.get_all_subnets(filters={'vpc_id': vpc_id})
return next((s for s in subnets if s.cidr_block == cidr), None)
def ensure_subnet_present(vpc_conn, vpc_id, cidr, az, tags, check_mode):
|
def ensure_subnet_absent(vpc_conn, vpc_id, cidr, check_mode):
subnet = get_matching_subnet(vpc_conn, vpc_id, cidr)
if subnet is None:
return {'changed': False}
try:
vpc_conn.delete_subnet(subnet.id, dry_run=check_mode)
return {'changed': True}
except EC2ResponseError as e:
raise AnsibleVPCSubnetDeletionException(
'Unable to delete subnet {0}, error: {1}'
.format(subnet.cidr_block, e))
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
az=dict(default=None, required=False),
cidr=dict(default=None, required=True),
state=dict(default='present', choices=['present', 'absent']),
tags=dict(default={}, required=False, type='dict', aliases=['resource_tags']),
vpc_id=dict(default=None, required=True)
)
)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_BOTO:
module.fail_json(msg='boto is required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if region:
try:
connection = connect_to_aws(boto.vpc, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
module.fail_json(msg=str(e))
else:
module.fail_json(msg="region must be specified")
vpc_id = module.params.get('vpc_id')
tags = module.params.get('tags')
cidr = module.params.get('cidr')
az = module.params.get('az')
state = module.params.get('state')
try:
if state == 'present':
result = ensure_subnet_present(connection, vpc_id, cidr, az, tags,
check_mode=module.check_mode)
elif state == 'absent':
result = ensure_subnet_absent(connection, vpc_id, cidr,
check_mode=module.check_mode)
except AnsibleVPCSubnetException as e:
module.fail_json(msg=str(e))
module.exit_json(**result)
if __name__ == '__main__':
main()
| subnet = get_matching_subnet(vpc_conn, vpc_id, cidr)
changed = False
if subnet is None:
subnet = create_subnet(vpc_conn, vpc_id, cidr, az, check_mode)
changed = True
# Subnet will be None when check_mode is true
if subnet is None:
return {
'changed': changed,
'subnet': {}
}
if tags != subnet.tags:
ensure_tags(vpc_conn, subnet.id, tags, False, check_mode)
subnet.tags = tags
changed = True
subnet_info = get_subnet_info(subnet)
return {
'changed': changed,
'subnet': subnet_info
} | identifier_body |
ec2_vpc_subnet.py | #!/usr/bin/python
#
# This is a free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This Ansible library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this library. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'curated'}
DOCUMENTATION = '''
---
module: ec2_vpc_subnet
short_description: Manage subnets in AWS virtual private clouds
description:
- Manage subnets in AWS virtual private clouds
version_added: "2.0"
author: Robert Estelle (@erydo)
options:
az:
description:
- "The availability zone for the subnet. Only required when state=present."
required: false
default: null
cidr:
description:
- "The CIDR block for the subnet. E.g. 192.0.2.0/24. Only required when state=present."
required: false
default: null
tags:
description:
- "A dict of tags to apply to the subnet. Any tags currently applied to the subnet and not present here will be removed."
required: false
default: null
aliases: [ 'resource_tags' ]
state:
description:
- "Create or remove the subnet"
required: false
default: present
choices: [ 'present', 'absent' ]
vpc_id:
description:
- "VPC ID of the VPC in which to create the subnet."
required: false
default: null
extends_documentation_fragment:
- aws
- ec2
'''
EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.
- name: Create subnet for database servers
ec2_vpc_subnet:
state: present
vpc_id: vpc-123456
cidr: 10.0.1.16/28
resource_tags:
Name: Database Subnet
register: database_subnet
- name: Remove subnet for database servers
ec2_vpc_subnet:
state: absent
vpc_id: vpc-123456
cidr: 10.0.1.16/28
'''
import time
try:
import boto.ec2
import boto.vpc
from boto.exception import EC2ResponseError
HAS_BOTO = True
except ImportError: |
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import AnsibleAWSError, connect_to_aws, ec2_argument_spec, get_aws_connection_info
class AnsibleVPCSubnetException(Exception):
pass
class AnsibleVPCSubnetCreationException(AnsibleVPCSubnetException):
pass
class AnsibleVPCSubnetDeletionException(AnsibleVPCSubnetException):
pass
class AnsibleTagCreationException(AnsibleVPCSubnetException):
pass
def get_subnet_info(subnet):
subnet_info = {'id': subnet.id,
'availability_zone': subnet.availability_zone,
'available_ip_address_count': subnet.available_ip_address_count,
'cidr_block': subnet.cidr_block,
'default_for_az': subnet.defaultForAz,
'map_public_ip_on_launch': subnet.mapPublicIpOnLaunch,
'state': subnet.state,
'tags': subnet.tags,
'vpc_id': subnet.vpc_id
}
return subnet_info
def subnet_exists(vpc_conn, subnet_id):
filters = {'subnet-id': subnet_id}
subnet = vpc_conn.get_all_subnets(filters=filters)
if subnet and subnet[0].state == "available":
return subnet[0]
else:
return False
def create_subnet(vpc_conn, vpc_id, cidr, az, check_mode):
try:
new_subnet = vpc_conn.create_subnet(vpc_id, cidr, az, dry_run=check_mode)
# Sometimes AWS takes its time to create a subnet and so using
# new subnets's id to do things like create tags results in
# exception. boto doesn't seem to refresh 'state' of the newly
# created subnet, i.e.: it's always 'pending'.
subnet = False
while subnet is False:
subnet = subnet_exists(vpc_conn, new_subnet.id)
time.sleep(0.1)
except EC2ResponseError as e:
if e.error_code == "DryRunOperation":
subnet = None
elif e.error_code == "InvalidSubnet.Conflict":
raise AnsibleVPCSubnetCreationException("%s: the CIDR %s conflicts with another subnet with the VPC ID %s." % (e.error_code, cidr, vpc_id))
else:
raise AnsibleVPCSubnetCreationException(
'Unable to create subnet {0}, error: {1}'.format(cidr, e))
return subnet
def get_resource_tags(vpc_conn, resource_id):
return dict((t.name, t.value) for t in
vpc_conn.get_all_tags(filters={'resource-id': resource_id}))
def ensure_tags(vpc_conn, resource_id, tags, add_only, check_mode):
try:
cur_tags = get_resource_tags(vpc_conn, resource_id)
if cur_tags == tags:
return {'changed': False, 'tags': cur_tags}
to_delete = dict((k, cur_tags[k]) for k in cur_tags if k not in tags)
if to_delete and not add_only:
vpc_conn.delete_tags(resource_id, to_delete, dry_run=check_mode)
to_add = dict((k, tags[k]) for k in tags if k not in cur_tags or cur_tags[k] != tags[k])
if to_add:
vpc_conn.create_tags(resource_id, to_add, dry_run=check_mode)
latest_tags = get_resource_tags(vpc_conn, resource_id)
return {'changed': True, 'tags': latest_tags}
except EC2ResponseError as e:
raise AnsibleTagCreationException(
'Unable to update tags for {0}, error: {1}'.format(resource_id, e))
def get_matching_subnet(vpc_conn, vpc_id, cidr):
subnets = vpc_conn.get_all_subnets(filters={'vpc_id': vpc_id})
return next((s for s in subnets if s.cidr_block == cidr), None)
def ensure_subnet_present(vpc_conn, vpc_id, cidr, az, tags, check_mode):
subnet = get_matching_subnet(vpc_conn, vpc_id, cidr)
changed = False
if subnet is None:
subnet = create_subnet(vpc_conn, vpc_id, cidr, az, check_mode)
changed = True
# Subnet will be None when check_mode is true
if subnet is None:
return {
'changed': changed,
'subnet': {}
}
if tags != subnet.tags:
ensure_tags(vpc_conn, subnet.id, tags, False, check_mode)
subnet.tags = tags
changed = True
subnet_info = get_subnet_info(subnet)
return {
'changed': changed,
'subnet': subnet_info
}
def ensure_subnet_absent(vpc_conn, vpc_id, cidr, check_mode):
subnet = get_matching_subnet(vpc_conn, vpc_id, cidr)
if subnet is None:
return {'changed': False}
try:
vpc_conn.delete_subnet(subnet.id, dry_run=check_mode)
return {'changed': True}
except EC2ResponseError as e:
raise AnsibleVPCSubnetDeletionException(
'Unable to delete subnet {0}, error: {1}'
.format(subnet.cidr_block, e))
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
az=dict(default=None, required=False),
cidr=dict(default=None, required=True),
state=dict(default='present', choices=['present', 'absent']),
tags=dict(default={}, required=False, type='dict', aliases=['resource_tags']),
vpc_id=dict(default=None, required=True)
)
)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_BOTO:
module.fail_json(msg='boto is required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if region:
try:
connection = connect_to_aws(boto.vpc, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
module.fail_json(msg=str(e))
else:
module.fail_json(msg="region must be specified")
vpc_id = module.params.get('vpc_id')
tags = module.params.get('tags')
cidr = module.params.get('cidr')
az = module.params.get('az')
state = module.params.get('state')
try:
if state == 'present':
result = ensure_subnet_present(connection, vpc_id, cidr, az, tags,
check_mode=module.check_mode)
elif state == 'absent':
result = ensure_subnet_absent(connection, vpc_id, cidr,
check_mode=module.check_mode)
except AnsibleVPCSubnetException as e:
module.fail_json(msg=str(e))
module.exit_json(**result)
if __name__ == '__main__':
main() | HAS_BOTO = False
if __name__ != '__main__':
raise | random_line_split |
ec2_vpc_subnet.py | #!/usr/bin/python
#
# This is a free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This Ansible library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this library. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'curated'}
DOCUMENTATION = '''
---
module: ec2_vpc_subnet
short_description: Manage subnets in AWS virtual private clouds
description:
- Manage subnets in AWS virtual private clouds
version_added: "2.0"
author: Robert Estelle (@erydo)
options:
az:
description:
- "The availability zone for the subnet. Only required when state=present."
required: false
default: null
cidr:
description:
- "The CIDR block for the subnet. E.g. 192.0.2.0/24. Only required when state=present."
required: false
default: null
tags:
description:
- "A dict of tags to apply to the subnet. Any tags currently applied to the subnet and not present here will be removed."
required: false
default: null
aliases: [ 'resource_tags' ]
state:
description:
- "Create or remove the subnet"
required: false
default: present
choices: [ 'present', 'absent' ]
vpc_id:
description:
- "VPC ID of the VPC in which to create the subnet."
required: false
default: null
extends_documentation_fragment:
- aws
- ec2
'''
EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.
- name: Create subnet for database servers
ec2_vpc_subnet:
state: present
vpc_id: vpc-123456
cidr: 10.0.1.16/28
resource_tags:
Name: Database Subnet
register: database_subnet
- name: Remove subnet for database servers
ec2_vpc_subnet:
state: absent
vpc_id: vpc-123456
cidr: 10.0.1.16/28
'''
import time
try:
import boto.ec2
import boto.vpc
from boto.exception import EC2ResponseError
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
if __name__ != '__main__':
raise
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import AnsibleAWSError, connect_to_aws, ec2_argument_spec, get_aws_connection_info
class AnsibleVPCSubnetException(Exception):
pass
class | (AnsibleVPCSubnetException):
pass
class AnsibleVPCSubnetDeletionException(AnsibleVPCSubnetException):
pass
class AnsibleTagCreationException(AnsibleVPCSubnetException):
pass
def get_subnet_info(subnet):
subnet_info = {'id': subnet.id,
'availability_zone': subnet.availability_zone,
'available_ip_address_count': subnet.available_ip_address_count,
'cidr_block': subnet.cidr_block,
'default_for_az': subnet.defaultForAz,
'map_public_ip_on_launch': subnet.mapPublicIpOnLaunch,
'state': subnet.state,
'tags': subnet.tags,
'vpc_id': subnet.vpc_id
}
return subnet_info
def subnet_exists(vpc_conn, subnet_id):
filters = {'subnet-id': subnet_id}
subnet = vpc_conn.get_all_subnets(filters=filters)
if subnet and subnet[0].state == "available":
return subnet[0]
else:
return False
def create_subnet(vpc_conn, vpc_id, cidr, az, check_mode):
try:
new_subnet = vpc_conn.create_subnet(vpc_id, cidr, az, dry_run=check_mode)
# Sometimes AWS takes its time to create a subnet and so using
# new subnets's id to do things like create tags results in
# exception. boto doesn't seem to refresh 'state' of the newly
# created subnet, i.e.: it's always 'pending'.
subnet = False
while subnet is False:
subnet = subnet_exists(vpc_conn, new_subnet.id)
time.sleep(0.1)
except EC2ResponseError as e:
if e.error_code == "DryRunOperation":
subnet = None
elif e.error_code == "InvalidSubnet.Conflict":
raise AnsibleVPCSubnetCreationException("%s: the CIDR %s conflicts with another subnet with the VPC ID %s." % (e.error_code, cidr, vpc_id))
else:
raise AnsibleVPCSubnetCreationException(
'Unable to create subnet {0}, error: {1}'.format(cidr, e))
return subnet
def get_resource_tags(vpc_conn, resource_id):
return dict((t.name, t.value) for t in
vpc_conn.get_all_tags(filters={'resource-id': resource_id}))
def ensure_tags(vpc_conn, resource_id, tags, add_only, check_mode):
try:
cur_tags = get_resource_tags(vpc_conn, resource_id)
if cur_tags == tags:
return {'changed': False, 'tags': cur_tags}
to_delete = dict((k, cur_tags[k]) for k in cur_tags if k not in tags)
if to_delete and not add_only:
vpc_conn.delete_tags(resource_id, to_delete, dry_run=check_mode)
to_add = dict((k, tags[k]) for k in tags if k not in cur_tags or cur_tags[k] != tags[k])
if to_add:
vpc_conn.create_tags(resource_id, to_add, dry_run=check_mode)
latest_tags = get_resource_tags(vpc_conn, resource_id)
return {'changed': True, 'tags': latest_tags}
except EC2ResponseError as e:
raise AnsibleTagCreationException(
'Unable to update tags for {0}, error: {1}'.format(resource_id, e))
def get_matching_subnet(vpc_conn, vpc_id, cidr):
subnets = vpc_conn.get_all_subnets(filters={'vpc_id': vpc_id})
return next((s for s in subnets if s.cidr_block == cidr), None)
def ensure_subnet_present(vpc_conn, vpc_id, cidr, az, tags, check_mode):
subnet = get_matching_subnet(vpc_conn, vpc_id, cidr)
changed = False
if subnet is None:
subnet = create_subnet(vpc_conn, vpc_id, cidr, az, check_mode)
changed = True
# Subnet will be None when check_mode is true
if subnet is None:
return {
'changed': changed,
'subnet': {}
}
if tags != subnet.tags:
ensure_tags(vpc_conn, subnet.id, tags, False, check_mode)
subnet.tags = tags
changed = True
subnet_info = get_subnet_info(subnet)
return {
'changed': changed,
'subnet': subnet_info
}
def ensure_subnet_absent(vpc_conn, vpc_id, cidr, check_mode):
subnet = get_matching_subnet(vpc_conn, vpc_id, cidr)
if subnet is None:
return {'changed': False}
try:
vpc_conn.delete_subnet(subnet.id, dry_run=check_mode)
return {'changed': True}
except EC2ResponseError as e:
raise AnsibleVPCSubnetDeletionException(
'Unable to delete subnet {0}, error: {1}'
.format(subnet.cidr_block, e))
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
az=dict(default=None, required=False),
cidr=dict(default=None, required=True),
state=dict(default='present', choices=['present', 'absent']),
tags=dict(default={}, required=False, type='dict', aliases=['resource_tags']),
vpc_id=dict(default=None, required=True)
)
)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_BOTO:
module.fail_json(msg='boto is required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if region:
try:
connection = connect_to_aws(boto.vpc, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
module.fail_json(msg=str(e))
else:
module.fail_json(msg="region must be specified")
vpc_id = module.params.get('vpc_id')
tags = module.params.get('tags')
cidr = module.params.get('cidr')
az = module.params.get('az')
state = module.params.get('state')
try:
if state == 'present':
result = ensure_subnet_present(connection, vpc_id, cidr, az, tags,
check_mode=module.check_mode)
elif state == 'absent':
result = ensure_subnet_absent(connection, vpc_id, cidr,
check_mode=module.check_mode)
except AnsibleVPCSubnetException as e:
module.fail_json(msg=str(e))
module.exit_json(**result)
if __name__ == '__main__':
main()
| AnsibleVPCSubnetCreationException | identifier_name |
ec2_vpc_subnet.py | #!/usr/bin/python
#
# This is a free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This Ansible library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this library. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'curated'}
DOCUMENTATION = '''
---
module: ec2_vpc_subnet
short_description: Manage subnets in AWS virtual private clouds
description:
- Manage subnets in AWS virtual private clouds
version_added: "2.0"
author: Robert Estelle (@erydo)
options:
az:
description:
- "The availability zone for the subnet. Only required when state=present."
required: false
default: null
cidr:
description:
- "The CIDR block for the subnet. E.g. 192.0.2.0/24. Only required when state=present."
required: false
default: null
tags:
description:
- "A dict of tags to apply to the subnet. Any tags currently applied to the subnet and not present here will be removed."
required: false
default: null
aliases: [ 'resource_tags' ]
state:
description:
- "Create or remove the subnet"
required: false
default: present
choices: [ 'present', 'absent' ]
vpc_id:
description:
- "VPC ID of the VPC in which to create the subnet."
required: false
default: null
extends_documentation_fragment:
- aws
- ec2
'''
EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.
- name: Create subnet for database servers
ec2_vpc_subnet:
state: present
vpc_id: vpc-123456
cidr: 10.0.1.16/28
resource_tags:
Name: Database Subnet
register: database_subnet
- name: Remove subnet for database servers
ec2_vpc_subnet:
state: absent
vpc_id: vpc-123456
cidr: 10.0.1.16/28
'''
import time
try:
import boto.ec2
import boto.vpc
from boto.exception import EC2ResponseError
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
if __name__ != '__main__':
raise
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import AnsibleAWSError, connect_to_aws, ec2_argument_spec, get_aws_connection_info
class AnsibleVPCSubnetException(Exception):
pass
class AnsibleVPCSubnetCreationException(AnsibleVPCSubnetException):
pass
class AnsibleVPCSubnetDeletionException(AnsibleVPCSubnetException):
pass
class AnsibleTagCreationException(AnsibleVPCSubnetException):
pass
def get_subnet_info(subnet):
subnet_info = {'id': subnet.id,
'availability_zone': subnet.availability_zone,
'available_ip_address_count': subnet.available_ip_address_count,
'cidr_block': subnet.cidr_block,
'default_for_az': subnet.defaultForAz,
'map_public_ip_on_launch': subnet.mapPublicIpOnLaunch,
'state': subnet.state,
'tags': subnet.tags,
'vpc_id': subnet.vpc_id
}
return subnet_info
def subnet_exists(vpc_conn, subnet_id):
filters = {'subnet-id': subnet_id}
subnet = vpc_conn.get_all_subnets(filters=filters)
if subnet and subnet[0].state == "available":
return subnet[0]
else:
return False
def create_subnet(vpc_conn, vpc_id, cidr, az, check_mode):
try:
new_subnet = vpc_conn.create_subnet(vpc_id, cidr, az, dry_run=check_mode)
# Sometimes AWS takes its time to create a subnet and so using
# new subnets's id to do things like create tags results in
# exception. boto doesn't seem to refresh 'state' of the newly
# created subnet, i.e.: it's always 'pending'.
subnet = False
while subnet is False:
subnet = subnet_exists(vpc_conn, new_subnet.id)
time.sleep(0.1)
except EC2ResponseError as e:
if e.error_code == "DryRunOperation":
subnet = None
elif e.error_code == "InvalidSubnet.Conflict":
raise AnsibleVPCSubnetCreationException("%s: the CIDR %s conflicts with another subnet with the VPC ID %s." % (e.error_code, cidr, vpc_id))
else:
raise AnsibleVPCSubnetCreationException(
'Unable to create subnet {0}, error: {1}'.format(cidr, e))
return subnet
def get_resource_tags(vpc_conn, resource_id):
return dict((t.name, t.value) for t in
vpc_conn.get_all_tags(filters={'resource-id': resource_id}))
def ensure_tags(vpc_conn, resource_id, tags, add_only, check_mode):
try:
cur_tags = get_resource_tags(vpc_conn, resource_id)
if cur_tags == tags:
return {'changed': False, 'tags': cur_tags}
to_delete = dict((k, cur_tags[k]) for k in cur_tags if k not in tags)
if to_delete and not add_only:
vpc_conn.delete_tags(resource_id, to_delete, dry_run=check_mode)
to_add = dict((k, tags[k]) for k in tags if k not in cur_tags or cur_tags[k] != tags[k])
if to_add:
vpc_conn.create_tags(resource_id, to_add, dry_run=check_mode)
latest_tags = get_resource_tags(vpc_conn, resource_id)
return {'changed': True, 'tags': latest_tags}
except EC2ResponseError as e:
raise AnsibleTagCreationException(
'Unable to update tags for {0}, error: {1}'.format(resource_id, e))
def get_matching_subnet(vpc_conn, vpc_id, cidr):
subnets = vpc_conn.get_all_subnets(filters={'vpc_id': vpc_id})
return next((s for s in subnets if s.cidr_block == cidr), None)
def ensure_subnet_present(vpc_conn, vpc_id, cidr, az, tags, check_mode):
subnet = get_matching_subnet(vpc_conn, vpc_id, cidr)
changed = False
if subnet is None:
subnet = create_subnet(vpc_conn, vpc_id, cidr, az, check_mode)
changed = True
# Subnet will be None when check_mode is true
if subnet is None:
return {
'changed': changed,
'subnet': {}
}
if tags != subnet.tags:
ensure_tags(vpc_conn, subnet.id, tags, False, check_mode)
subnet.tags = tags
changed = True
subnet_info = get_subnet_info(subnet)
return {
'changed': changed,
'subnet': subnet_info
}
def ensure_subnet_absent(vpc_conn, vpc_id, cidr, check_mode):
subnet = get_matching_subnet(vpc_conn, vpc_id, cidr)
if subnet is None:
return {'changed': False}
try:
vpc_conn.delete_subnet(subnet.id, dry_run=check_mode)
return {'changed': True}
except EC2ResponseError as e:
raise AnsibleVPCSubnetDeletionException(
'Unable to delete subnet {0}, error: {1}'
.format(subnet.cidr_block, e))
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
az=dict(default=None, required=False),
cidr=dict(default=None, required=True),
state=dict(default='present', choices=['present', 'absent']),
tags=dict(default={}, required=False, type='dict', aliases=['resource_tags']),
vpc_id=dict(default=None, required=True)
)
)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_BOTO:
|
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if region:
try:
connection = connect_to_aws(boto.vpc, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
module.fail_json(msg=str(e))
else:
module.fail_json(msg="region must be specified")
vpc_id = module.params.get('vpc_id')
tags = module.params.get('tags')
cidr = module.params.get('cidr')
az = module.params.get('az')
state = module.params.get('state')
try:
if state == 'present':
result = ensure_subnet_present(connection, vpc_id, cidr, az, tags,
check_mode=module.check_mode)
elif state == 'absent':
result = ensure_subnet_absent(connection, vpc_id, cidr,
check_mode=module.check_mode)
except AnsibleVPCSubnetException as e:
module.fail_json(msg=str(e))
module.exit_json(**result)
if __name__ == '__main__':
main()
| module.fail_json(msg='boto is required for this module') | conditional_block |
ConfluxOfElementsResto.tsx | import SPELLS from 'common/SPELLS';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import calculateEffectiveHealing from 'parser/core/calculateEffectiveHealing';
import Events, { HealEvent } from 'parser/core/Events';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import ItemPercentHealingDone from 'parser/ui/ItemPercentHealingDone';
import Statistic from 'parser/ui/Statistic';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
import * as React from 'react';
const CONFLUX_OF_ELEMENTS_EFFECT_BY_RANK = [
0.15,
0.165,
0.18,
0.195,
0.21,
0.225,
0.24,
0.255,
0.27,
0.285,
0.3,
0.315,
0.33,
0.345,
0.36,
];
/**
* **Conflux of Elements**
* Conduit - Night Fae
*
* While channeling Convoke the Spirits, your damage and healing are increased by X%.
*/
class ConfluxOfElementsResto extends Analyzer {
_confluxOfElementsBoost: number;
healing: number = 0;
constructor(options: Options) {
super(options);
this.active = this.selectedCombatant.hasConduitBySpellID(SPELLS.CONFLUX_OF_ELEMENTS.id);
this._confluxOfElementsBoost =
CONFLUX_OF_ELEMENTS_EFFECT_BY_RANK[
this.selectedCombatant.conduitRankBySpellID(SPELLS.CONFLUX_OF_ELEMENTS.id)
];
this.addEventListener(Events.heal.by(SELECTED_PLAYER), this.onHeal);
}
onHeal(event: HealEvent) |
statistic(): React.ReactNode {
return (
<Statistic
size="flexible"
position={STATISTIC_ORDER.OPTIONAL(0)}
category={STATISTIC_CATEGORY.COVENANTS}
tooltip={
<>
This is the healing attributable specifically to Conflux of Elements's boost to healing
during Convoke.
</>
}
>
<BoringSpellValueText
spellId={SPELLS.CONFLUX_OF_ELEMENTS.id}
ilvl={this.selectedCombatant.conduitsByConduitID[SPELLS.CONFLUX_OF_ELEMENTS.id].itemLevel}
>
<ItemPercentHealingDone amount={this.healing} />
<br />
</BoringSpellValueText>
</Statistic>
);
}
}
export default ConfluxOfElementsResto;
| {
if (this.selectedCombatant.hasBuff(SPELLS.CONVOKE_SPIRITS.id)) {
this.healing += calculateEffectiveHealing(event, this._confluxOfElementsBoost);
}
} | identifier_body |
ConfluxOfElementsResto.tsx | import SPELLS from 'common/SPELLS';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import calculateEffectiveHealing from 'parser/core/calculateEffectiveHealing';
import Events, { HealEvent } from 'parser/core/Events';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import ItemPercentHealingDone from 'parser/ui/ItemPercentHealingDone';
import Statistic from 'parser/ui/Statistic';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
import * as React from 'react';
const CONFLUX_OF_ELEMENTS_EFFECT_BY_RANK = [
0.15,
0.165,
0.18,
0.195,
0.21,
0.225,
0.24,
0.255,
0.27,
0.285,
0.3,
0.315,
0.33,
0.345,
0.36,
];
/**
* **Conflux of Elements**
* Conduit - Night Fae
*
* While channeling Convoke the Spirits, your damage and healing are increased by X%.
*/
class ConfluxOfElementsResto extends Analyzer {
_confluxOfElementsBoost: number;
healing: number = 0;
constructor(options: Options) {
super(options);
this.active = this.selectedCombatant.hasConduitBySpellID(SPELLS.CONFLUX_OF_ELEMENTS.id);
this._confluxOfElementsBoost =
CONFLUX_OF_ELEMENTS_EFFECT_BY_RANK[
this.selectedCombatant.conduitRankBySpellID(SPELLS.CONFLUX_OF_ELEMENTS.id)
];
this.addEventListener(Events.heal.by(SELECTED_PLAYER), this.onHeal);
}
onHeal(event: HealEvent) {
if (this.selectedCombatant.hasBuff(SPELLS.CONVOKE_SPIRITS.id)) |
}
statistic(): React.ReactNode {
return (
<Statistic
size="flexible"
position={STATISTIC_ORDER.OPTIONAL(0)}
category={STATISTIC_CATEGORY.COVENANTS}
tooltip={
<>
This is the healing attributable specifically to Conflux of Elements's boost to healing
during Convoke.
</>
}
>
<BoringSpellValueText
spellId={SPELLS.CONFLUX_OF_ELEMENTS.id}
ilvl={this.selectedCombatant.conduitsByConduitID[SPELLS.CONFLUX_OF_ELEMENTS.id].itemLevel}
>
<ItemPercentHealingDone amount={this.healing} />
<br />
</BoringSpellValueText>
</Statistic>
);
}
}
export default ConfluxOfElementsResto;
| {
this.healing += calculateEffectiveHealing(event, this._confluxOfElementsBoost);
} | conditional_block |
ConfluxOfElementsResto.tsx | import SPELLS from 'common/SPELLS';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import calculateEffectiveHealing from 'parser/core/calculateEffectiveHealing';
import Events, { HealEvent } from 'parser/core/Events';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import ItemPercentHealingDone from 'parser/ui/ItemPercentHealingDone';
import Statistic from 'parser/ui/Statistic';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
import * as React from 'react';
const CONFLUX_OF_ELEMENTS_EFFECT_BY_RANK = [
0.15,
0.165,
0.18,
0.195,
0.21,
0.225,
0.24,
0.255,
0.27,
0.285,
0.3,
0.315,
0.33,
0.345,
0.36,
];
/**
* **Conflux of Elements**
* Conduit - Night Fae
*
* While channeling Convoke the Spirits, your damage and healing are increased by X%.
*/
class ConfluxOfElementsResto extends Analyzer {
_confluxOfElementsBoost: number;
healing: number = 0;
| (options: Options) {
super(options);
this.active = this.selectedCombatant.hasConduitBySpellID(SPELLS.CONFLUX_OF_ELEMENTS.id);
this._confluxOfElementsBoost =
CONFLUX_OF_ELEMENTS_EFFECT_BY_RANK[
this.selectedCombatant.conduitRankBySpellID(SPELLS.CONFLUX_OF_ELEMENTS.id)
];
this.addEventListener(Events.heal.by(SELECTED_PLAYER), this.onHeal);
}
onHeal(event: HealEvent) {
if (this.selectedCombatant.hasBuff(SPELLS.CONVOKE_SPIRITS.id)) {
this.healing += calculateEffectiveHealing(event, this._confluxOfElementsBoost);
}
}
statistic(): React.ReactNode {
return (
<Statistic
size="flexible"
position={STATISTIC_ORDER.OPTIONAL(0)}
category={STATISTIC_CATEGORY.COVENANTS}
tooltip={
<>
This is the healing attributable specifically to Conflux of Elements's boost to healing
during Convoke.
</>
}
>
<BoringSpellValueText
spellId={SPELLS.CONFLUX_OF_ELEMENTS.id}
ilvl={this.selectedCombatant.conduitsByConduitID[SPELLS.CONFLUX_OF_ELEMENTS.id].itemLevel}
>
<ItemPercentHealingDone amount={this.healing} />
<br />
</BoringSpellValueText>
</Statistic>
);
}
}
export default ConfluxOfElementsResto;
| constructor | identifier_name |
ConfluxOfElementsResto.tsx | import SPELLS from 'common/SPELLS';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import calculateEffectiveHealing from 'parser/core/calculateEffectiveHealing';
import Events, { HealEvent } from 'parser/core/Events';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import ItemPercentHealingDone from 'parser/ui/ItemPercentHealingDone';
import Statistic from 'parser/ui/Statistic';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
import * as React from 'react';
const CONFLUX_OF_ELEMENTS_EFFECT_BY_RANK = [
0.15,
0.165,
0.18,
0.195,
0.21,
0.225,
0.24,
0.255,
0.27,
0.285,
0.3,
0.315,
0.33,
0.345,
0.36,
];
/**
* **Conflux of Elements**
* Conduit - Night Fae
*
* While channeling Convoke the Spirits, your damage and healing are increased by X%.
*/
class ConfluxOfElementsResto extends Analyzer {
_confluxOfElementsBoost: number;
healing: number = 0;
constructor(options: Options) {
super(options);
this.active = this.selectedCombatant.hasConduitBySpellID(SPELLS.CONFLUX_OF_ELEMENTS.id);
this._confluxOfElementsBoost =
CONFLUX_OF_ELEMENTS_EFFECT_BY_RANK[
this.selectedCombatant.conduitRankBySpellID(SPELLS.CONFLUX_OF_ELEMENTS.id)
];
this.addEventListener(Events.heal.by(SELECTED_PLAYER), this.onHeal);
}
onHeal(event: HealEvent) {
if (this.selectedCombatant.hasBuff(SPELLS.CONVOKE_SPIRITS.id)) {
this.healing += calculateEffectiveHealing(event, this._confluxOfElementsBoost);
}
}
statistic(): React.ReactNode {
return (
<Statistic
size="flexible"
position={STATISTIC_ORDER.OPTIONAL(0)}
category={STATISTIC_CATEGORY.COVENANTS}
tooltip={
<>
This is the healing attributable specifically to Conflux of Elements's boost to healing
during Convoke.
</>
}
>
<BoringSpellValueText
spellId={SPELLS.CONFLUX_OF_ELEMENTS.id}
ilvl={this.selectedCombatant.conduitsByConduitID[SPELLS.CONFLUX_OF_ELEMENTS.id].itemLevel}
>
<ItemPercentHealingDone amount={this.healing} />
<br />
</BoringSpellValueText>
</Statistic>
); | }
}
export default ConfluxOfElementsResto; | random_line_split | |
numberFormatter.py | import math
def formatAmount(val, prec=3, lowest=0, highest=0, currency=False, forceSign=False):
"""
Add suffix to value, transform value to match new suffix and round it.
Keyword arguments:
val -- value to process
prec -- precision of final number (number of significant positions to show)
lowest -- lowest order for suffixizing for numbers 0 < |num| < 1
highest -- highest order for suffixizing for numbers |num| > 1
currency -- if currency, billion suffix will be B instead of G
forceSign -- if True, positive numbers are signed too
"""
if val is None:
return ""
# Define suffix maps
posSuffixMap = {3: "k", 6: "M", 9: "B" if currency is True else "G"}
negSuffixMap = {-6: '\u03bc', -3: "m"}
# Define tuple of the map keys
# As we're going to go from the biggest order of abs(key), sort
# them differently due to one set of values being negative
# and other positive
posOrders = tuple(sorted(iter(posSuffixMap.keys()), reverse=True))
negOrders = tuple(sorted(iter(negSuffixMap.keys()), reverse=False))
# Find the least abs(key)
posLowest = min(posOrders)
negHighest = max(negOrders)
# By default, mantissa takes just value and no suffix
mantissa, suffix = val, ""
# Positive suffixes
if abs(val) > 1 and highest >= posLowest:
# Start from highest possible suffix
for key in posOrders:
# Find first suitable suffix and check if it's not above highest order
if abs(val) >= 10 ** key and key <= highest:
mantissa, suffix = val / float(10 ** key), posSuffixMap[key]
# Do additional step to eliminate results like 999999 => 1000k
# If we're already using our greatest order, we can't do anything useful
if posOrders.index(key) == 0:
break
else:
# Get order greater than current
prevKey = posOrders[posOrders.index(key) - 1]
# Check if the key to which we potentially can change is greater
# than our highest boundary
if prevKey > highest:
# If it is, bail - we already have acceptable results
break
# Find multiplier to get from one order to another
orderDiff = 10 ** (prevKey - key)
# If rounded mantissa according to our specifications is greater than
# or equal to multiplier
if roundToPrec(mantissa, prec) >= orderDiff:
# Divide mantissa and use suffix of greater order
mantissa, suffix = mantissa / orderDiff, posSuffixMap[prevKey]
# Otherwise consider current results as acceptable
break
# Take numbers between 0 and 1, and matching/below highest possible negative suffix
elif abs(val) < 1 and val != 0 and lowest <= negHighest:
# Start from lowest possible suffix
for key in negOrders:
# Get next order
try:
nextKey = negOrders[negOrders.index(key) + 1]
except IndexError:
nextKey = 0
# Check if mantissa with next suffix is in range [1, 1000)
if abs(val) < 10 ** nextKey and key >= lowest:
mantissa, suffix = val / float(10 ** key), negSuffixMap[key]
# Do additional step to eliminate results like 0.9999 => 1000m
# Check if the key we're potentially switching to is greater than our
# upper boundary
if nextKey > highest:
# If it is, leave loop with results we already have
break
# Find the multiplier between current and next order
orderDiff = 10 ** (nextKey - key)
# If rounded mantissa according to our specifications is greater than
# or equal to multiplier
if roundToPrec(mantissa, prec) >= orderDiff:
# Divide mantissa and use suffix of greater order
# Use special handling of zero key as it's not on the map
mantissa, suffix = mantissa / orderDiff, posSuffixMap[nextKey] if nextKey != 0 else ""
# Otherwise consider current results as acceptable
break
# Round mantissa according to our prec variable
mantissa = roundToPrec(mantissa, prec)
sign = "+" if forceSign is True and mantissa > 0 else ""
# Round mantissa and add suffix
result = "{0}{1}{2}".format(sign, mantissa, suffix)
return result
def roundToPrec(val, prec):
# We're not rounding integers anyway
# Also make sure that we do not ask to calculate logarithm of zero
if int(val) == val:
return int(val)
# Find round factor, taking into consideration that we want to keep at least prec
# positions for fractions with zero integer part (e.g. 0.0000354 for prec=3)
roundFactor = int(prec - math.ceil(math.log10(abs(val))))
# But we don't want to round integers
if roundFactor < 0:
roundFactor = 0
# Do actual rounding
val = round(val, roundFactor)
# Make sure numbers with .0 part designating float don't get through
if int(val) == val:
val = int(val)
return val
def | (val, prec):
if int(val) == val:
return int(val)
return round(val, prec)
| roundDec | identifier_name |
numberFormatter.py | import math
def formatAmount(val, prec=3, lowest=0, highest=0, currency=False, forceSign=False):
"""
Add suffix to value, transform value to match new suffix and round it.
Keyword arguments:
val -- value to process
prec -- precision of final number (number of significant positions to show)
lowest -- lowest order for suffixizing for numbers 0 < |num| < 1
highest -- highest order for suffixizing for numbers |num| > 1
currency -- if currency, billion suffix will be B instead of G
forceSign -- if True, positive numbers are signed too
"""
if val is None:
return ""
# Define suffix maps
posSuffixMap = {3: "k", 6: "M", 9: "B" if currency is True else "G"}
negSuffixMap = {-6: '\u03bc', -3: "m"}
# Define tuple of the map keys
# As we're going to go from the biggest order of abs(key), sort
# them differently due to one set of values being negative
# and other positive
posOrders = tuple(sorted(iter(posSuffixMap.keys()), reverse=True))
negOrders = tuple(sorted(iter(negSuffixMap.keys()), reverse=False))
# Find the least abs(key)
posLowest = min(posOrders)
negHighest = max(negOrders)
# By default, mantissa takes just value and no suffix
mantissa, suffix = val, ""
# Positive suffixes
if abs(val) > 1 and highest >= posLowest:
# Start from highest possible suffix
for key in posOrders:
# Find first suitable suffix and check if it's not above highest order
if abs(val) >= 10 ** key and key <= highest:
mantissa, suffix = val / float(10 ** key), posSuffixMap[key]
# Do additional step to eliminate results like 999999 => 1000k
# If we're already using our greatest order, we can't do anything useful
if posOrders.index(key) == 0:
break
else:
# Get order greater than current
prevKey = posOrders[posOrders.index(key) - 1]
# Check if the key to which we potentially can change is greater
# than our highest boundary
if prevKey > highest:
# If it is, bail - we already have acceptable results
break
# Find multiplier to get from one order to another
orderDiff = 10 ** (prevKey - key)
# If rounded mantissa according to our specifications is greater than
# or equal to multiplier
if roundToPrec(mantissa, prec) >= orderDiff:
# Divide mantissa and use suffix of greater order
mantissa, suffix = mantissa / orderDiff, posSuffixMap[prevKey]
# Otherwise consider current results as acceptable
break
# Take numbers between 0 and 1, and matching/below highest possible negative suffix
elif abs(val) < 1 and val != 0 and lowest <= negHighest:
# Start from lowest possible suffix
for key in negOrders:
# Get next order
try:
nextKey = negOrders[negOrders.index(key) + 1]
except IndexError:
nextKey = 0
# Check if mantissa with next suffix is in range [1, 1000)
if abs(val) < 10 ** nextKey and key >= lowest:
mantissa, suffix = val / float(10 ** key), negSuffixMap[key]
# Do additional step to eliminate results like 0.9999 => 1000m
# Check if the key we're potentially switching to is greater than our
# upper boundary
if nextKey > highest:
# If it is, leave loop with results we already have
break
# Find the multiplier between current and next order
orderDiff = 10 ** (nextKey - key)
# If rounded mantissa according to our specifications is greater than
# or equal to multiplier
if roundToPrec(mantissa, prec) >= orderDiff:
# Divide mantissa and use suffix of greater order
# Use special handling of zero key as it's not on the map
mantissa, suffix = mantissa / orderDiff, posSuffixMap[nextKey] if nextKey != 0 else ""
# Otherwise consider current results as acceptable
break
# Round mantissa according to our prec variable
mantissa = roundToPrec(mantissa, prec)
sign = "+" if forceSign is True and mantissa > 0 else ""
# Round mantissa and add suffix
result = "{0}{1}{2}".format(sign, mantissa, suffix)
return result
def roundToPrec(val, prec):
# We're not rounding integers anyway
# Also make sure that we do not ask to calculate logarithm of zero
if int(val) == val:
return int(val)
# Find round factor, taking into consideration that we want to keep at least prec
# positions for fractions with zero integer part (e.g. 0.0000354 for prec=3)
roundFactor = int(prec - math.ceil(math.log10(abs(val))))
# But we don't want to round integers
if roundFactor < 0:
roundFactor = 0
# Do actual rounding
val = round(val, roundFactor)
# Make sure numbers with .0 part designating float don't get through
if int(val) == val:
val = int(val)
return val
def roundDec(val, prec):
| if int(val) == val:
return int(val)
return round(val, prec) | identifier_body | |
numberFormatter.py | import math
def formatAmount(val, prec=3, lowest=0, highest=0, currency=False, forceSign=False):
"""
Add suffix to value, transform value to match new suffix and round it.
Keyword arguments:
val -- value to process
prec -- precision of final number (number of significant positions to show)
lowest -- lowest order for suffixizing for numbers 0 < |num| < 1
highest -- highest order for suffixizing for numbers |num| > 1
currency -- if currency, billion suffix will be B instead of G
forceSign -- if True, positive numbers are signed too
"""
if val is None:
return ""
# Define suffix maps
posSuffixMap = {3: "k", 6: "M", 9: "B" if currency is True else "G"}
negSuffixMap = {-6: '\u03bc', -3: "m"}
# Define tuple of the map keys
# As we're going to go from the biggest order of abs(key), sort
# them differently due to one set of values being negative
# and other positive
posOrders = tuple(sorted(iter(posSuffixMap.keys()), reverse=True))
negOrders = tuple(sorted(iter(negSuffixMap.keys()), reverse=False)) | # Positive suffixes
if abs(val) > 1 and highest >= posLowest:
# Start from highest possible suffix
for key in posOrders:
# Find first suitable suffix and check if it's not above highest order
if abs(val) >= 10 ** key and key <= highest:
mantissa, suffix = val / float(10 ** key), posSuffixMap[key]
# Do additional step to eliminate results like 999999 => 1000k
# If we're already using our greatest order, we can't do anything useful
if posOrders.index(key) == 0:
break
else:
# Get order greater than current
prevKey = posOrders[posOrders.index(key) - 1]
# Check if the key to which we potentially can change is greater
# than our highest boundary
if prevKey > highest:
# If it is, bail - we already have acceptable results
break
# Find multiplier to get from one order to another
orderDiff = 10 ** (prevKey - key)
# If rounded mantissa according to our specifications is greater than
# or equal to multiplier
if roundToPrec(mantissa, prec) >= orderDiff:
# Divide mantissa and use suffix of greater order
mantissa, suffix = mantissa / orderDiff, posSuffixMap[prevKey]
# Otherwise consider current results as acceptable
break
# Take numbers between 0 and 1, and matching/below highest possible negative suffix
elif abs(val) < 1 and val != 0 and lowest <= negHighest:
# Start from lowest possible suffix
for key in negOrders:
# Get next order
try:
nextKey = negOrders[negOrders.index(key) + 1]
except IndexError:
nextKey = 0
# Check if mantissa with next suffix is in range [1, 1000)
if abs(val) < 10 ** nextKey and key >= lowest:
mantissa, suffix = val / float(10 ** key), negSuffixMap[key]
# Do additional step to eliminate results like 0.9999 => 1000m
# Check if the key we're potentially switching to is greater than our
# upper boundary
if nextKey > highest:
# If it is, leave loop with results we already have
break
# Find the multiplier between current and next order
orderDiff = 10 ** (nextKey - key)
# If rounded mantissa according to our specifications is greater than
# or equal to multiplier
if roundToPrec(mantissa, prec) >= orderDiff:
# Divide mantissa and use suffix of greater order
# Use special handling of zero key as it's not on the map
mantissa, suffix = mantissa / orderDiff, posSuffixMap[nextKey] if nextKey != 0 else ""
# Otherwise consider current results as acceptable
break
# Round mantissa according to our prec variable
mantissa = roundToPrec(mantissa, prec)
sign = "+" if forceSign is True and mantissa > 0 else ""
# Round mantissa and add suffix
result = "{0}{1}{2}".format(sign, mantissa, suffix)
return result
def roundToPrec(val, prec):
# We're not rounding integers anyway
# Also make sure that we do not ask to calculate logarithm of zero
if int(val) == val:
return int(val)
# Find round factor, taking into consideration that we want to keep at least prec
# positions for fractions with zero integer part (e.g. 0.0000354 for prec=3)
roundFactor = int(prec - math.ceil(math.log10(abs(val))))
# But we don't want to round integers
if roundFactor < 0:
roundFactor = 0
# Do actual rounding
val = round(val, roundFactor)
# Make sure numbers with .0 part designating float don't get through
if int(val) == val:
val = int(val)
return val
def roundDec(val, prec):
if int(val) == val:
return int(val)
return round(val, prec) | # Find the least abs(key)
posLowest = min(posOrders)
negHighest = max(negOrders)
# By default, mantissa takes just value and no suffix
mantissa, suffix = val, "" | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.