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 |
|---|---|---|---|---|
transform.ts | /// <reference path="..\compiler\transformer.ts"/>
/// <reference path="transpile.ts"/>
namespace ts {
/**
* Transform one or more nodes using the supplied transformers.
* @param source A single `Node` or an array of `Node` objects.
* @param transformers An array of `TransformerFactory` callbacks used to process the transformation.
* @param compilerOptions Optional compiler options.
*/
export function transform<T extends Node>(source: T | T[], transformers: TransformerFactory<T>[], compilerOptions?: CompilerOptions) |
} | {
const diagnostics: Diagnostic[] = [];
compilerOptions = fixupCompilerOptions(compilerOptions, diagnostics);
const nodes = isArray(source) ? source : [source];
const result = transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true);
result.diagnostics = concatenate(result.diagnostics, diagnostics);
return result;
} | identifier_body |
build.rs | // Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// 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.
extern crate webgl_generator;
use std::env;
use std::fs::File;
use std::path::*;
use webgl_generator::*;
fn main() {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("bindings.rs")).unwrap();
Registry::new(Api::WebGl2, Exts::ALL)
.write_bindings(StdwebGenerator, &mut file)
.unwrap(); | } | random_line_split | |
build.rs | // Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// 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.
extern crate webgl_generator;
use std::env;
use std::fs::File;
use std::path::*;
use webgl_generator::*;
fn | () {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("bindings.rs")).unwrap();
Registry::new(Api::WebGl2, Exts::ALL)
.write_bindings(StdwebGenerator, &mut file)
.unwrap();
}
| main | identifier_name |
build.rs | // Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// 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.
extern crate webgl_generator;
use std::env;
use std::fs::File;
use std::path::*;
use webgl_generator::*;
fn main() | {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("bindings.rs")).unwrap();
Registry::new(Api::WebGl2, Exts::ALL)
.write_bindings(StdwebGenerator, &mut file)
.unwrap();
} | identifier_body | |
rust.rs | /*
mandelbrot
2015 Gabriel De Luca | */
const NX: usize = 500; // number of points
const NT: i32 = 100000; // number of timesteps
fn main() {
let mut x: [f64; NX] = [0.0_f64;NX]; // position along wave
let mut y: [f64; NX] = [0.0_f64;NX]; // elevation of wave
let mut v: [f64; NX] = [0.0_f64;NX]; // speed of wave (y direction)
let mut dvdt: [f64; NX] = [0.0_f64;NX]; // acceleration of wave (y direction)
let mut dx: f64; // spacing in x
let mut dt: f64; // spacing in t
let xmin: f64;
let xmax: f64;
let tmin: f64;
let tmax: f64;
// define x array
xmin = 0.0;
xmax = 10.0;
dx = (xmax-xmin)/((NX as f64)-1.0); // range divided by # intervals
// x = [f64;NX];
x[0 as usize] = xmin;
for i in 1..(NX-1) {
x[i as usize]=xmin+(i as f64)*dx; // min + i * dx
}
x[(NX-1) as usize] = xmax;
// define t spacing
tmin = 0.0;
tmax = 10.0;
dt = (tmax-tmin)/((NT as f64)-1.0);
// instantiate y, x, dvdt arrays
// initialize arrays
// y is a peak in the middle of the wave
for i in 0..NX {
y[i as usize] = ( -(x[i as usize] - (xmax - xmin) / 2.0) * (x[i as usize] - (xmax - xmin) / 2.0)).exp();
v[i as usize] = 0.0;
}
// iterative loop
for it in 0..(NT-1) {
// calculation dvdt at interior positions
for i in 1..(NX-1) {
dvdt[i as usize] = (y[(i+1) as usize] + y[(i-1) as usize] - 2.0 * y[i as usize]) / (dx * dx);
}
// update v and y
for i in 0..NX {
v[i as usize] = v[i as usize] + dt * dvdt[i as usize];
y[i as usize] = y[i as usize] + dt * v[i as usize];
}
}
// output
for i in 0..NX {
println!("{:1.32}\t{:1.32}",x[i as usize],y[i as usize]);
}
} | MIT Licensed | random_line_split |
rust.rs | /*
mandelbrot
2015 Gabriel De Luca
MIT Licensed
*/
const NX: usize = 500; // number of points
const NT: i32 = 100000; // number of timesteps
fn | () {
let mut x: [f64; NX] = [0.0_f64;NX]; // position along wave
let mut y: [f64; NX] = [0.0_f64;NX]; // elevation of wave
let mut v: [f64; NX] = [0.0_f64;NX]; // speed of wave (y direction)
let mut dvdt: [f64; NX] = [0.0_f64;NX]; // acceleration of wave (y direction)
let mut dx: f64; // spacing in x
let mut dt: f64; // spacing in t
let xmin: f64;
let xmax: f64;
let tmin: f64;
let tmax: f64;
// define x array
xmin = 0.0;
xmax = 10.0;
dx = (xmax-xmin)/((NX as f64)-1.0); // range divided by # intervals
// x = [f64;NX];
x[0 as usize] = xmin;
for i in 1..(NX-1) {
x[i as usize]=xmin+(i as f64)*dx; // min + i * dx
}
x[(NX-1) as usize] = xmax;
// define t spacing
tmin = 0.0;
tmax = 10.0;
dt = (tmax-tmin)/((NT as f64)-1.0);
// instantiate y, x, dvdt arrays
// initialize arrays
// y is a peak in the middle of the wave
for i in 0..NX {
y[i as usize] = ( -(x[i as usize] - (xmax - xmin) / 2.0) * (x[i as usize] - (xmax - xmin) / 2.0)).exp();
v[i as usize] = 0.0;
}
// iterative loop
for it in 0..(NT-1) {
// calculation dvdt at interior positions
for i in 1..(NX-1) {
dvdt[i as usize] = (y[(i+1) as usize] + y[(i-1) as usize] - 2.0 * y[i as usize]) / (dx * dx);
}
// update v and y
for i in 0..NX {
v[i as usize] = v[i as usize] + dt * dvdt[i as usize];
y[i as usize] = y[i as usize] + dt * v[i as usize];
}
}
// output
for i in 0..NX {
println!("{:1.32}\t{:1.32}",x[i as usize],y[i as usize]);
}
}
| main | identifier_name |
rust.rs | /*
mandelbrot
2015 Gabriel De Luca
MIT Licensed
*/
const NX: usize = 500; // number of points
const NT: i32 = 100000; // number of timesteps
fn main() | {
let mut x: [f64; NX] = [0.0_f64;NX]; // position along wave
let mut y: [f64; NX] = [0.0_f64;NX]; // elevation of wave
let mut v: [f64; NX] = [0.0_f64;NX]; // speed of wave (y direction)
let mut dvdt: [f64; NX] = [0.0_f64;NX]; // acceleration of wave (y direction)
let mut dx: f64; // spacing in x
let mut dt: f64; // spacing in t
let xmin: f64;
let xmax: f64;
let tmin: f64;
let tmax: f64;
// define x array
xmin = 0.0;
xmax = 10.0;
dx = (xmax-xmin)/((NX as f64)-1.0); // range divided by # intervals
// x = [f64;NX];
x[0 as usize] = xmin;
for i in 1..(NX-1) {
x[i as usize]=xmin+(i as f64)*dx; // min + i * dx
}
x[(NX-1) as usize] = xmax;
// define t spacing
tmin = 0.0;
tmax = 10.0;
dt = (tmax-tmin)/((NT as f64)-1.0);
// instantiate y, x, dvdt arrays
// initialize arrays
// y is a peak in the middle of the wave
for i in 0..NX {
y[i as usize] = ( -(x[i as usize] - (xmax - xmin) / 2.0) * (x[i as usize] - (xmax - xmin) / 2.0)).exp();
v[i as usize] = 0.0;
}
// iterative loop
for it in 0..(NT-1) {
// calculation dvdt at interior positions
for i in 1..(NX-1) {
dvdt[i as usize] = (y[(i+1) as usize] + y[(i-1) as usize] - 2.0 * y[i as usize]) / (dx * dx);
}
// update v and y
for i in 0..NX {
v[i as usize] = v[i as usize] + dt * dvdt[i as usize];
y[i as usize] = y[i as usize] + dt * v[i as usize];
}
}
// output
for i in 0..NX {
println!("{:1.32}\t{:1.32}",x[i as usize],y[i as usize]);
}
} | identifier_body | |
types.rs | // Copyright 2020 Google Inc. All Rights Reserved.
//
// 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.
use crate::builtins::WasmbinCountable;
use crate::indices::TypeId;
use crate::io::{Decode, DecodeError, DecodeWithDiscriminant, Encode, PathItem, Wasmbin};
use crate::visit::Visit;
use crate::wasmbin_discriminants;
use arbitrary::Arbitrary;
use std::convert::TryFrom;
use std::fmt::{self, Debug, Formatter};
const OP_CODE_EMPTY_BLOCK: u8 = 0x40;
#[wasmbin_discriminants]
#[derive(Wasmbin, WasmbinCountable, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[repr(u8)]
pub enum ValueType {
#[cfg(feature = "simd")]
V128 = 0x7B,
F64 = 0x7C,
F32 = 0x7D,
I64 = 0x7E,
I32 = 0x7F,
Ref(RefType),
}
#[derive(Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[repr(u8)]
pub enum BlockType {
Empty,
Value(ValueType),
MultiValue(TypeId),
}
impl Encode for BlockType {
fn encode(&self, w: &mut impl std::io::Write) -> std::io::Result<()> {
match self {
BlockType::Empty => OP_CODE_EMPTY_BLOCK.encode(w),
BlockType::Value(ty) => ty.encode(w),
BlockType::MultiValue(id) => i64::from(id.index).encode(w),
}
}
}
impl Decode for BlockType {
fn decode(r: &mut impl std::io::Read) -> Result<Self, DecodeError> {
let discriminant = u8::decode(r)?;
if discriminant == OP_CODE_EMPTY_BLOCK {
return Ok(BlockType::Empty);
}
if let Some(ty) = ValueType::maybe_decode_with_discriminant(discriminant, r)
.map_err(|err| err.in_path(PathItem::Variant("BlockType::Value")))?
{
return Ok(BlockType::Value(ty));
}
let index = (move || -> Result<_, DecodeError> {
// We have already read one byte that could've been either a
// discriminant or a part of an s33 LEB128 specially used for
// type indices.
//
// To recover the LEB128 sequence, we need to chain it back.
let buf = [discriminant];
let mut r = std::io::Read::chain(&buf[..], r);
let as_i64 = i64::decode(&mut r)?;
// These indices are encoded as positive signed integers.
// Convert them to unsigned integers and error out if they're out of range.
let index = u32::try_from(as_i64)?;
Ok(index)
})()
.map_err(|err| err.in_path(PathItem::Variant("BlockType::MultiValue")))?;
Ok(BlockType::MultiValue(TypeId { index }))
}
}
#[derive(Wasmbin, WasmbinCountable, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[wasmbin(discriminant = 0x60)]
pub struct FuncType {
pub params: Vec<ValueType>,
pub results: Vec<ValueType>,
}
impl Debug for FuncType {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
fn encode_types(types: &[ValueType], f: &mut Formatter) -> fmt::Result {
f.write_str("(")?;
for (i, ty) in types.iter().enumerate() {
if i != 0 {
f.write_str(", ")?;
}
ty.fmt(f)?;
}
f.write_str(")")
}
encode_types(&self.params, f)?;
f.write_str(" -> ")?;
encode_types(&self.results, f)
}
}
#[derive(Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct Limits {
pub min: u32,
pub max: Option<u32>,
}
impl Debug for Limits {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}..", self.min)?;
if let Some(max) = self.max {
write!(f, "={}", max)?;
}
Ok(())
}
}
#[wasmbin_discriminants]
#[derive(Wasmbin)]
#[repr(u8)]
enum LimitsRepr {
Min { min: u32 } = 0x00,
MinMax { min: u32, max: u32 } = 0x01,
}
encode_decode_as!(Limits, {
(Limits { min, max: None }) <=> (LimitsRepr::Min { min }),
(Limits { min, max: Some(max) }) <=> (LimitsRepr::MinMax { min, max }),
});
#[cfg(feature = "threads")]
#[wasmbin_discriminants]
#[derive(Wasmbin)]
#[repr(u8)]
enum MemTypeRepr {
Unshared(LimitsRepr),
SharedMin { min: u32 } = 0x02,
SharedMinMax { min: u32, max: u32 } = 0x03,
}
#[cfg_attr(not(feature = "threads"), derive(Wasmbin))]
#[derive(WasmbinCountable, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct MemType {
#[cfg(feature = "threads")]
pub is_shared: bool,
pub limits: Limits,
}
#[cfg(feature = "threads")]
encode_decode_as!(MemType, {
(MemType { is_shared: false, limits: Limits { min, max: None } }) <=> (MemTypeRepr::Unshared(LimitsRepr::Min { min })),
(MemType { is_shared: false, limits: Limits { min, max: Some(max) } }) <=> (MemTypeRepr::Unshared(LimitsRepr::MinMax { min, max })),
(MemType { is_shared: true, limits: Limits { min, max: None } }) <=> (MemTypeRepr::SharedMin { min }),
(MemType { is_shared: true, limits: Limits { min, max: Some(max) } }) <=> (MemTypeRepr::SharedMinMax { min, max }),
});
#[derive(Wasmbin, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[repr(u8)]
pub enum | {
Func = 0x70,
Extern = 0x6F,
}
#[derive(Wasmbin, WasmbinCountable, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct TableType {
pub elem_type: RefType,
pub limits: Limits,
}
#[derive(Wasmbin, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct GlobalType {
pub value_type: ValueType,
pub mutable: bool,
}
| RefType | identifier_name |
types.rs | // Copyright 2020 Google Inc. All Rights Reserved.
//
// 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.
use crate::builtins::WasmbinCountable;
use crate::indices::TypeId;
use crate::io::{Decode, DecodeError, DecodeWithDiscriminant, Encode, PathItem, Wasmbin};
use crate::visit::Visit;
use crate::wasmbin_discriminants;
use arbitrary::Arbitrary;
use std::convert::TryFrom;
use std::fmt::{self, Debug, Formatter};
const OP_CODE_EMPTY_BLOCK: u8 = 0x40;
#[wasmbin_discriminants]
#[derive(Wasmbin, WasmbinCountable, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[repr(u8)]
pub enum ValueType {
#[cfg(feature = "simd")]
V128 = 0x7B,
F64 = 0x7C,
F32 = 0x7D,
I64 = 0x7E,
I32 = 0x7F,
Ref(RefType),
}
#[derive(Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[repr(u8)]
pub enum BlockType {
Empty,
Value(ValueType),
MultiValue(TypeId),
}
impl Encode for BlockType {
fn encode(&self, w: &mut impl std::io::Write) -> std::io::Result<()> {
match self {
BlockType::Empty => OP_CODE_EMPTY_BLOCK.encode(w),
BlockType::Value(ty) => ty.encode(w),
BlockType::MultiValue(id) => i64::from(id.index).encode(w),
}
}
}
impl Decode for BlockType {
fn decode(r: &mut impl std::io::Read) -> Result<Self, DecodeError> {
let discriminant = u8::decode(r)?;
if discriminant == OP_CODE_EMPTY_BLOCK {
return Ok(BlockType::Empty);
}
if let Some(ty) = ValueType::maybe_decode_with_discriminant(discriminant, r)
.map_err(|err| err.in_path(PathItem::Variant("BlockType::Value")))?
{
return Ok(BlockType::Value(ty));
}
let index = (move || -> Result<_, DecodeError> {
// We have already read one byte that could've been either a
// discriminant or a part of an s33 LEB128 specially used for
// type indices.
//
// To recover the LEB128 sequence, we need to chain it back.
let buf = [discriminant];
let mut r = std::io::Read::chain(&buf[..], r);
let as_i64 = i64::decode(&mut r)?;
// These indices are encoded as positive signed integers.
// Convert them to unsigned integers and error out if they're out of range.
let index = u32::try_from(as_i64)?;
Ok(index)
})()
.map_err(|err| err.in_path(PathItem::Variant("BlockType::MultiValue")))?;
Ok(BlockType::MultiValue(TypeId { index }))
}
}
#[derive(Wasmbin, WasmbinCountable, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[wasmbin(discriminant = 0x60)]
pub struct FuncType {
pub params: Vec<ValueType>,
pub results: Vec<ValueType>,
}
impl Debug for FuncType {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
fn encode_types(types: &[ValueType], f: &mut Formatter) -> fmt::Result {
f.write_str("(")?;
for (i, ty) in types.iter().enumerate() {
if i != 0 {
f.write_str(", ")?;
}
ty.fmt(f)?;
}
f.write_str(")")
}
encode_types(&self.params, f)?;
f.write_str(" -> ")?;
encode_types(&self.results, f)
}
}
#[derive(Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct Limits {
pub min: u32,
pub max: Option<u32>,
}
impl Debug for Limits {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}..", self.min)?;
if let Some(max) = self.max |
Ok(())
}
}
#[wasmbin_discriminants]
#[derive(Wasmbin)]
#[repr(u8)]
enum LimitsRepr {
Min { min: u32 } = 0x00,
MinMax { min: u32, max: u32 } = 0x01,
}
encode_decode_as!(Limits, {
(Limits { min, max: None }) <=> (LimitsRepr::Min { min }),
(Limits { min, max: Some(max) }) <=> (LimitsRepr::MinMax { min, max }),
});
#[cfg(feature = "threads")]
#[wasmbin_discriminants]
#[derive(Wasmbin)]
#[repr(u8)]
enum MemTypeRepr {
Unshared(LimitsRepr),
SharedMin { min: u32 } = 0x02,
SharedMinMax { min: u32, max: u32 } = 0x03,
}
#[cfg_attr(not(feature = "threads"), derive(Wasmbin))]
#[derive(WasmbinCountable, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct MemType {
#[cfg(feature = "threads")]
pub is_shared: bool,
pub limits: Limits,
}
#[cfg(feature = "threads")]
encode_decode_as!(MemType, {
(MemType { is_shared: false, limits: Limits { min, max: None } }) <=> (MemTypeRepr::Unshared(LimitsRepr::Min { min })),
(MemType { is_shared: false, limits: Limits { min, max: Some(max) } }) <=> (MemTypeRepr::Unshared(LimitsRepr::MinMax { min, max })),
(MemType { is_shared: true, limits: Limits { min, max: None } }) <=> (MemTypeRepr::SharedMin { min }),
(MemType { is_shared: true, limits: Limits { min, max: Some(max) } }) <=> (MemTypeRepr::SharedMinMax { min, max }),
});
#[derive(Wasmbin, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[repr(u8)]
pub enum RefType {
Func = 0x70,
Extern = 0x6F,
}
#[derive(Wasmbin, WasmbinCountable, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct TableType {
pub elem_type: RefType,
pub limits: Limits,
}
#[derive(Wasmbin, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct GlobalType {
pub value_type: ValueType,
pub mutable: bool,
}
| {
write!(f, "={}", max)?;
} | conditional_block |
types.rs | // Copyright 2020 Google Inc. All Rights Reserved.
//
// 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.
use crate::builtins::WasmbinCountable;
use crate::indices::TypeId; | use crate::visit::Visit;
use crate::wasmbin_discriminants;
use arbitrary::Arbitrary;
use std::convert::TryFrom;
use std::fmt::{self, Debug, Formatter};
const OP_CODE_EMPTY_BLOCK: u8 = 0x40;
#[wasmbin_discriminants]
#[derive(Wasmbin, WasmbinCountable, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[repr(u8)]
pub enum ValueType {
#[cfg(feature = "simd")]
V128 = 0x7B,
F64 = 0x7C,
F32 = 0x7D,
I64 = 0x7E,
I32 = 0x7F,
Ref(RefType),
}
#[derive(Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[repr(u8)]
pub enum BlockType {
Empty,
Value(ValueType),
MultiValue(TypeId),
}
impl Encode for BlockType {
fn encode(&self, w: &mut impl std::io::Write) -> std::io::Result<()> {
match self {
BlockType::Empty => OP_CODE_EMPTY_BLOCK.encode(w),
BlockType::Value(ty) => ty.encode(w),
BlockType::MultiValue(id) => i64::from(id.index).encode(w),
}
}
}
impl Decode for BlockType {
fn decode(r: &mut impl std::io::Read) -> Result<Self, DecodeError> {
let discriminant = u8::decode(r)?;
if discriminant == OP_CODE_EMPTY_BLOCK {
return Ok(BlockType::Empty);
}
if let Some(ty) = ValueType::maybe_decode_with_discriminant(discriminant, r)
.map_err(|err| err.in_path(PathItem::Variant("BlockType::Value")))?
{
return Ok(BlockType::Value(ty));
}
let index = (move || -> Result<_, DecodeError> {
// We have already read one byte that could've been either a
// discriminant or a part of an s33 LEB128 specially used for
// type indices.
//
// To recover the LEB128 sequence, we need to chain it back.
let buf = [discriminant];
let mut r = std::io::Read::chain(&buf[..], r);
let as_i64 = i64::decode(&mut r)?;
// These indices are encoded as positive signed integers.
// Convert them to unsigned integers and error out if they're out of range.
let index = u32::try_from(as_i64)?;
Ok(index)
})()
.map_err(|err| err.in_path(PathItem::Variant("BlockType::MultiValue")))?;
Ok(BlockType::MultiValue(TypeId { index }))
}
}
#[derive(Wasmbin, WasmbinCountable, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[wasmbin(discriminant = 0x60)]
pub struct FuncType {
pub params: Vec<ValueType>,
pub results: Vec<ValueType>,
}
impl Debug for FuncType {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
fn encode_types(types: &[ValueType], f: &mut Formatter) -> fmt::Result {
f.write_str("(")?;
for (i, ty) in types.iter().enumerate() {
if i != 0 {
f.write_str(", ")?;
}
ty.fmt(f)?;
}
f.write_str(")")
}
encode_types(&self.params, f)?;
f.write_str(" -> ")?;
encode_types(&self.results, f)
}
}
#[derive(Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct Limits {
pub min: u32,
pub max: Option<u32>,
}
impl Debug for Limits {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}..", self.min)?;
if let Some(max) = self.max {
write!(f, "={}", max)?;
}
Ok(())
}
}
#[wasmbin_discriminants]
#[derive(Wasmbin)]
#[repr(u8)]
enum LimitsRepr {
Min { min: u32 } = 0x00,
MinMax { min: u32, max: u32 } = 0x01,
}
encode_decode_as!(Limits, {
(Limits { min, max: None }) <=> (LimitsRepr::Min { min }),
(Limits { min, max: Some(max) }) <=> (LimitsRepr::MinMax { min, max }),
});
#[cfg(feature = "threads")]
#[wasmbin_discriminants]
#[derive(Wasmbin)]
#[repr(u8)]
enum MemTypeRepr {
Unshared(LimitsRepr),
SharedMin { min: u32 } = 0x02,
SharedMinMax { min: u32, max: u32 } = 0x03,
}
#[cfg_attr(not(feature = "threads"), derive(Wasmbin))]
#[derive(WasmbinCountable, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct MemType {
#[cfg(feature = "threads")]
pub is_shared: bool,
pub limits: Limits,
}
#[cfg(feature = "threads")]
encode_decode_as!(MemType, {
(MemType { is_shared: false, limits: Limits { min, max: None } }) <=> (MemTypeRepr::Unshared(LimitsRepr::Min { min })),
(MemType { is_shared: false, limits: Limits { min, max: Some(max) } }) <=> (MemTypeRepr::Unshared(LimitsRepr::MinMax { min, max })),
(MemType { is_shared: true, limits: Limits { min, max: None } }) <=> (MemTypeRepr::SharedMin { min }),
(MemType { is_shared: true, limits: Limits { min, max: Some(max) } }) <=> (MemTypeRepr::SharedMinMax { min, max }),
});
#[derive(Wasmbin, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
#[repr(u8)]
pub enum RefType {
Func = 0x70,
Extern = 0x6F,
}
#[derive(Wasmbin, WasmbinCountable, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct TableType {
pub elem_type: RefType,
pub limits: Limits,
}
#[derive(Wasmbin, Debug, Arbitrary, PartialEq, Eq, Hash, Clone, Visit)]
pub struct GlobalType {
pub value_type: ValueType,
pub mutable: bool,
} | use crate::io::{Decode, DecodeError, DecodeWithDiscriminant, Encode, PathItem, Wasmbin}; | random_line_split |
entities_to_cascades.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from django.core.management.base import BaseCommand
from optparse import make_option
from py3compat import PY2
from snisi_core.models.Entities import AdministrativeEntity as AEntity
if PY2:
import unicodecsv as csv
else:
import csv
logger = logging.getLogger(__name__)
class | (BaseCommand):
option_list = BaseCommand.option_list + (
make_option('-f',
help='CSV file',
action='store',
dest='filename'),
)
def handle(self, *args, **options):
headers = ['name', 'region', 'cercle_commune', 'commune_quartier']
f = open(options.get('filename'), 'w')
csv_writer = csv.DictWriter(f, fieldnames=headers)
csv_writer.writeheader()
csv_writer.writerow({
'name': "label",
'region': "Région",
'cercle_commune': "Cercle",
'commune_quartier': "Commune",
})
for region in AEntity.objects.filter(type__slug='region'):
logger.info(region)
is_bko = region.name == 'BAMAKO'
for cercle in AEntity.objects.filter(parent=region):
logger.info(cercle)
for commune in AEntity.objects.filter(parent=cercle):
logger.info(commune)
if not is_bko:
csv_writer.writerow({
'name': "choice_label",
'region': region.name,
'cercle_commune': cercle.name,
'commune_quartier': commune.name
})
continue
for vfq in AEntity.objects.filter(parent=commune):
for v in (region, cercle, commune, vfq):
if not len(v.name.strip()):
continue
csv_writer.writerow({
'name': "choice_label",
'region': region.name,
'cercle_commune': commune.name,
'commune_quartier': vfq.name
})
f.close()
| Command | identifier_name |
entities_to_cascades.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from django.core.management.base import BaseCommand
from optparse import make_option
from py3compat import PY2
from snisi_core.models.Entities import AdministrativeEntity as AEntity
if PY2:
import unicodecsv as csv
else:
import csv
logger = logging.getLogger(__name__)
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('-f',
help='CSV file',
action='store',
dest='filename'),
)
def handle(self, *args, **options):
headers = ['name', 'region', 'cercle_commune', 'commune_quartier']
f = open(options.get('filename'), 'w')
csv_writer = csv.DictWriter(f, fieldnames=headers)
csv_writer.writeheader()
csv_writer.writerow({
'name': "label",
'region': "Région",
'cercle_commune': "Cercle", | 'commune_quartier': "Commune",
})
for region in AEntity.objects.filter(type__slug='region'):
logger.info(region)
is_bko = region.name == 'BAMAKO'
for cercle in AEntity.objects.filter(parent=region):
logger.info(cercle)
for commune in AEntity.objects.filter(parent=cercle):
logger.info(commune)
if not is_bko:
csv_writer.writerow({
'name': "choice_label",
'region': region.name,
'cercle_commune': cercle.name,
'commune_quartier': commune.name
})
continue
for vfq in AEntity.objects.filter(parent=commune):
for v in (region, cercle, commune, vfq):
if not len(v.name.strip()):
continue
csv_writer.writerow({
'name': "choice_label",
'region': region.name,
'cercle_commune': commune.name,
'commune_quartier': vfq.name
})
f.close() | random_line_split | |
entities_to_cascades.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from django.core.management.base import BaseCommand
from optparse import make_option
from py3compat import PY2
from snisi_core.models.Entities import AdministrativeEntity as AEntity
if PY2:
import unicodecsv as csv
else:
import csv
logger = logging.getLogger(__name__)
class Command(BaseCommand):
| option_list = BaseCommand.option_list + (
make_option('-f',
help='CSV file',
action='store',
dest='filename'),
)
def handle(self, *args, **options):
headers = ['name', 'region', 'cercle_commune', 'commune_quartier']
f = open(options.get('filename'), 'w')
csv_writer = csv.DictWriter(f, fieldnames=headers)
csv_writer.writeheader()
csv_writer.writerow({
'name': "label",
'region': "Région",
'cercle_commune': "Cercle",
'commune_quartier': "Commune",
})
for region in AEntity.objects.filter(type__slug='region'):
logger.info(region)
is_bko = region.name == 'BAMAKO'
for cercle in AEntity.objects.filter(parent=region):
logger.info(cercle)
for commune in AEntity.objects.filter(parent=cercle):
logger.info(commune)
if not is_bko:
csv_writer.writerow({
'name': "choice_label",
'region': region.name,
'cercle_commune': cercle.name,
'commune_quartier': commune.name
})
continue
for vfq in AEntity.objects.filter(parent=commune):
for v in (region, cercle, commune, vfq):
if not len(v.name.strip()):
continue
csv_writer.writerow({
'name': "choice_label",
'region': region.name,
'cercle_commune': commune.name,
'commune_quartier': vfq.name
})
f.close()
| identifier_body | |
entities_to_cascades.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from django.core.management.base import BaseCommand
from optparse import make_option
from py3compat import PY2
from snisi_core.models.Entities import AdministrativeEntity as AEntity
if PY2:
import unicodecsv as csv
else:
import csv
logger = logging.getLogger(__name__)
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('-f',
help='CSV file',
action='store',
dest='filename'),
)
def handle(self, *args, **options):
headers = ['name', 'region', 'cercle_commune', 'commune_quartier']
f = open(options.get('filename'), 'w')
csv_writer = csv.DictWriter(f, fieldnames=headers)
csv_writer.writeheader()
csv_writer.writerow({
'name': "label",
'region': "Région",
'cercle_commune': "Cercle",
'commune_quartier': "Commune",
})
for region in AEntity.objects.filter(type__slug='region'):
logger.info(region)
is_bko = region.name == 'BAMAKO'
for cercle in AEntity.objects.filter(parent=region):
l | f.close()
| ogger.info(cercle)
for commune in AEntity.objects.filter(parent=cercle):
logger.info(commune)
if not is_bko:
csv_writer.writerow({
'name': "choice_label",
'region': region.name,
'cercle_commune': cercle.name,
'commune_quartier': commune.name
})
continue
for vfq in AEntity.objects.filter(parent=commune):
for v in (region, cercle, commune, vfq):
if not len(v.name.strip()):
continue
csv_writer.writerow({
'name': "choice_label",
'region': region.name,
'cercle_commune': commune.name,
'commune_quartier': vfq.name
})
| conditional_block |
2.common.stories.tsx | import * as React from "react"; | import { storiesOf } from "@storybook/react";
import { action } from "@storybook/addon-actions";
import { ColorPicker } from '../components/color-picker';
import { withKnobs, text, boolean } from '@storybook/addon-knobs';
import { VectorStyleEditor } from '../components/vector-style-editor';
import "../styles/index.css";
storiesOf("Common Components", module)
.addDecorator(withKnobs)
.add("Color Picker", () => {
const act = action("color changed");
const [color, setColor] = React.useState<string | undefined>(undefined);
const onSetColor = (val: string) => {
act(val);
setColor(val);
};
return <ColorPicker locale="en" value={color} onChange={onSetColor} />;
})
.add("Vector Style Editor", () => {
return <VectorStyleEditor onChange={action("style changed")}
locale="en"
enablePoint={boolean("Enable Point", true)}
enableLine={boolean("Enable Line", true)}
enablePolygon={boolean("Enable Polygon", true)} />;
}); | random_line_split | |
roles.js | var Router = require('koa-router');
var Role = require('../../lib/role');
var Middleware = require('../../lib/middleware');
var router = module.exports = new Router();
router.use(Middleware.allow('admin.roles'));
router.get('/admin/api/roles', function *() {
var page = parseInt(this.request.query.page) || 1;
var perPage = parseInt(this.request.query.perpage) || 100;
var perms = this.request.query.permissions || false;
var q = {};
try {
q = JSON.parse(this.request.query.q);
} catch(e) {}
var conditions = {};
if (q.name) {
conditions.name = new RegExp(q.name, 'i');
}
// Setup options
var _opts = {
skip: (page - 1) * perPage,
limit: perPage
};
// Setup fields
var _fields = [
'name',
'desc',
'created'
];
if (perms) |
// Fetching a list with specific condition
var data = yield Role.list(conditions, _fields, _opts);
this.body = {
page: page,
perPage: perPage,
pageCount: Math.ceil(data.count / perPage),
roles: data.roles
};
});
router.post('/admin/api/roles', function *() {
if (!this.request.body.name || !this.request.body.desc || !this.request.body.perms) {
this.status = 401;
return;
}
try {
// Create a new role
var role = yield Role.create({
name: this.request.body.name,
desc: this.request.body.desc,
perms: this.request.body.perms
});
} catch(e) {
console.log(e);
}
this.body = {
role: {
_id: role._id,
name: role.name,
desc: role.desc,
perms: role.perms
}
};
});
| {
_opts.populatedPermission = perms;
_fields.push('permissions');
} | conditional_block |
roles.js | var Router = require('koa-router');
var Role = require('../../lib/role');
var Middleware = require('../../lib/middleware');
var router = module.exports = new Router();
router.use(Middleware.allow('admin.roles'));
router.get('/admin/api/roles', function *() {
var page = parseInt(this.request.query.page) || 1;
var perPage = parseInt(this.request.query.perpage) || 100;
var perms = this.request.query.permissions || false;
var q = {};
try {
q = JSON.parse(this.request.query.q);
} catch(e) {}
| // Setup options
var _opts = {
skip: (page - 1) * perPage,
limit: perPage
};
// Setup fields
var _fields = [
'name',
'desc',
'created'
];
if (perms) {
_opts.populatedPermission = perms;
_fields.push('permissions');
}
// Fetching a list with specific condition
var data = yield Role.list(conditions, _fields, _opts);
this.body = {
page: page,
perPage: perPage,
pageCount: Math.ceil(data.count / perPage),
roles: data.roles
};
});
router.post('/admin/api/roles', function *() {
if (!this.request.body.name || !this.request.body.desc || !this.request.body.perms) {
this.status = 401;
return;
}
try {
// Create a new role
var role = yield Role.create({
name: this.request.body.name,
desc: this.request.body.desc,
perms: this.request.body.perms
});
} catch(e) {
console.log(e);
}
this.body = {
role: {
_id: role._id,
name: role.name,
desc: role.desc,
perms: role.perms
}
};
}); | var conditions = {};
if (q.name) {
conditions.name = new RegExp(q.name, 'i');
}
| random_line_split |
views.py | # -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.files.storage import FileSystemStorage
from django.forms import Form
from django.template.response import SimpleTemplateResponse
from django.urls import NoReverseMatch
from formtools.wizard.views import SessionWizardView
from cms.models import Page
from cms.utils import get_current_site
from cms.utils.i18n import get_site_language_from_request
from .wizard_pool import wizard_pool
from .forms import (
WizardStep1Form,
WizardStep2BaseForm,
step2_form_factory,
)
class WizardCreateView(SessionWizardView):
template_name = 'cms/wizards/start.html'
file_storage = FileSystemStorage(
location=os.path.join(settings.MEDIA_ROOT, 'wizard_tmp_files'))
form_list = [
('0', WizardStep1Form),
# Form is used as a placeholder form.
# the real form will be loaded after step 0
('1', Form),
]
def dispatch(self, *args, **kwargs):
user = self.request.user
if not user.is_active or not user.is_staff:
raise PermissionDenied
self.site = get_current_site()
return super(WizardCreateView, self).dispatch(*args, **kwargs)
def get_current_step(self):
"""Returns the current step, if possible, else None."""
try:
return self.steps.current
except AttributeError:
return None
def is_first_step(self, step=None):
step = step or self.get_current_step()
return step == '0'
def is_second_step(self, step=None):
step = step or self.get_current_step()
return step == '1'
def get_context_data(self, **kwargs):
context = super(WizardCreateView, self).get_context_data(**kwargs)
if self.is_second_step():
context['wizard_entry'] = self.get_selected_entry()
return context
def get_form(self, step=None, data=None, files=None):
if step is None:
step = self.steps.current
# We need to grab the page from pre-validated data so that the wizard
# has it to prepare the list of valid entries.
if data:
page_key = "{0}-page".format(step)
self.page_pk = data.get(page_key, None)
else:
self.page_pk = None
if self.is_second_step(step):
self.form_list[step] = self.get_step_2_form(step, data, files)
return super(WizardCreateView, self).get_form(step, data, files)
def get_form_kwargs(self, step=None):
"""This is called by self.get_form()"""
kwargs = super(WizardCreateView, self).get_form_kwargs()
kwargs['wizard_user'] = self.request.user
if self.is_second_step(step):
kwargs['wizard_page'] = self.get_origin_page()
kwargs['wizard_language'] = self.get_origin_language()
else:
page_pk = self.page_pk or self.request.GET.get('page', None)
if page_pk and page_pk != 'None':
kwargs['wizard_page'] = Page.objects.filter(pk=page_pk).first()
else:
kwargs['wizard_page'] = None
kwargs['wizard_language'] = get_site_language_from_request(
self.request,
site_id=self.site.pk,
)
return kwargs
def get_form_initial(self, step):
"""This is called by self.get_form()"""
initial = super(WizardCreateView, self).get_form_initial(step)
if self.is_first_step(step):
initial['page'] = self.request.GET.get('page')
initial['language'] = self.request.GET.get('language')
return initial
def get_step_2_form(self, step=None, data=None, files=None):
entry_form_class = self.get_selected_entry().form
step_2_base_form = self.get_step_2_base_form()
form = step2_form_factory(
mixin_cls=step_2_base_form,
entry_form_class=entry_form_class,
)
return form
def get_step_2_base_form(self):
"""
Returns the base form to be used for step 2.
This form is sub classed dynamically by the form defined per module.
"""
return WizardStep2BaseForm
def get_template_names(self):
if self.is_first_step():
template_name = self.template_name
else:
template_name = self.get_selected_entry().template_name
return template_name
def done(self, form_list, **kwargs):
"""
This step only runs if all forms are valid. Simply emits a simple
template that uses JS to redirect to the newly created object.
"""
form_one, form_two = list(form_list)
instance = form_two.save()
url = self.get_success_url(instance)
language = form_one.cleaned_data['language']
if not url:
page = self.get_origin_page()
if page:
|
else:
url = '/'
return SimpleTemplateResponse("cms/wizards/done.html", {"url": url})
def get_selected_entry(self):
data = self.get_cleaned_data_for_step('0')
return wizard_pool.get_entry(data['entry'])
def get_origin_page(self):
data = self.get_cleaned_data_for_step('0')
return data.get('page')
def get_origin_language(self):
data = self.get_cleaned_data_for_step('0')
return data.get('language')
def get_success_url(self, instance):
entry = self.get_selected_entry()
language = self.get_origin_language()
success_url = entry.get_success_url(
obj=instance,
language=language,
)
return success_url
| try:
url = page.get_absolute_url(language)
except NoReverseMatch:
url = '/' | conditional_block |
views.py | # -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.files.storage import FileSystemStorage
from django.forms import Form
from django.template.response import SimpleTemplateResponse
from django.urls import NoReverseMatch
from formtools.wizard.views import SessionWizardView
from cms.models import Page
from cms.utils import get_current_site
from cms.utils.i18n import get_site_language_from_request
from .wizard_pool import wizard_pool
from .forms import (
WizardStep1Form,
WizardStep2BaseForm,
step2_form_factory,
)
class WizardCreateView(SessionWizardView):
template_name = 'cms/wizards/start.html'
file_storage = FileSystemStorage(
location=os.path.join(settings.MEDIA_ROOT, 'wizard_tmp_files'))
form_list = [
('0', WizardStep1Form),
# Form is used as a placeholder form.
# the real form will be loaded after step 0
('1', Form),
]
def dispatch(self, *args, **kwargs):
user = self.request.user
if not user.is_active or not user.is_staff:
raise PermissionDenied
self.site = get_current_site()
return super(WizardCreateView, self).dispatch(*args, **kwargs)
def get_current_step(self):
"""Returns the current step, if possible, else None."""
try:
return self.steps.current
except AttributeError:
return None
def is_first_step(self, step=None):
step = step or self.get_current_step()
return step == '0'
def is_second_step(self, step=None):
step = step or self.get_current_step()
return step == '1'
def get_context_data(self, **kwargs):
context = super(WizardCreateView, self).get_context_data(**kwargs)
if self.is_second_step():
context['wizard_entry'] = self.get_selected_entry()
return context
def get_form(self, step=None, data=None, files=None):
|
def get_form_kwargs(self, step=None):
"""This is called by self.get_form()"""
kwargs = super(WizardCreateView, self).get_form_kwargs()
kwargs['wizard_user'] = self.request.user
if self.is_second_step(step):
kwargs['wizard_page'] = self.get_origin_page()
kwargs['wizard_language'] = self.get_origin_language()
else:
page_pk = self.page_pk or self.request.GET.get('page', None)
if page_pk and page_pk != 'None':
kwargs['wizard_page'] = Page.objects.filter(pk=page_pk).first()
else:
kwargs['wizard_page'] = None
kwargs['wizard_language'] = get_site_language_from_request(
self.request,
site_id=self.site.pk,
)
return kwargs
def get_form_initial(self, step):
"""This is called by self.get_form()"""
initial = super(WizardCreateView, self).get_form_initial(step)
if self.is_first_step(step):
initial['page'] = self.request.GET.get('page')
initial['language'] = self.request.GET.get('language')
return initial
def get_step_2_form(self, step=None, data=None, files=None):
entry_form_class = self.get_selected_entry().form
step_2_base_form = self.get_step_2_base_form()
form = step2_form_factory(
mixin_cls=step_2_base_form,
entry_form_class=entry_form_class,
)
return form
def get_step_2_base_form(self):
"""
Returns the base form to be used for step 2.
This form is sub classed dynamically by the form defined per module.
"""
return WizardStep2BaseForm
def get_template_names(self):
if self.is_first_step():
template_name = self.template_name
else:
template_name = self.get_selected_entry().template_name
return template_name
def done(self, form_list, **kwargs):
"""
This step only runs if all forms are valid. Simply emits a simple
template that uses JS to redirect to the newly created object.
"""
form_one, form_two = list(form_list)
instance = form_two.save()
url = self.get_success_url(instance)
language = form_one.cleaned_data['language']
if not url:
page = self.get_origin_page()
if page:
try:
url = page.get_absolute_url(language)
except NoReverseMatch:
url = '/'
else:
url = '/'
return SimpleTemplateResponse("cms/wizards/done.html", {"url": url})
def get_selected_entry(self):
data = self.get_cleaned_data_for_step('0')
return wizard_pool.get_entry(data['entry'])
def get_origin_page(self):
data = self.get_cleaned_data_for_step('0')
return data.get('page')
def get_origin_language(self):
data = self.get_cleaned_data_for_step('0')
return data.get('language')
def get_success_url(self, instance):
entry = self.get_selected_entry()
language = self.get_origin_language()
success_url = entry.get_success_url(
obj=instance,
language=language,
)
return success_url
| if step is None:
step = self.steps.current
# We need to grab the page from pre-validated data so that the wizard
# has it to prepare the list of valid entries.
if data:
page_key = "{0}-page".format(step)
self.page_pk = data.get(page_key, None)
else:
self.page_pk = None
if self.is_second_step(step):
self.form_list[step] = self.get_step_2_form(step, data, files)
return super(WizardCreateView, self).get_form(step, data, files) | identifier_body |
views.py | # -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.files.storage import FileSystemStorage
from django.forms import Form
from django.template.response import SimpleTemplateResponse
from django.urls import NoReverseMatch
from formtools.wizard.views import SessionWizardView
from cms.models import Page
from cms.utils import get_current_site
from cms.utils.i18n import get_site_language_from_request
from .wizard_pool import wizard_pool
from .forms import (
WizardStep1Form,
WizardStep2BaseForm,
step2_form_factory,
)
class WizardCreateView(SessionWizardView):
template_name = 'cms/wizards/start.html'
file_storage = FileSystemStorage(
location=os.path.join(settings.MEDIA_ROOT, 'wizard_tmp_files'))
form_list = [
('0', WizardStep1Form),
# Form is used as a placeholder form.
# the real form will be loaded after step 0
('1', Form), | ]
def dispatch(self, *args, **kwargs):
user = self.request.user
if not user.is_active or not user.is_staff:
raise PermissionDenied
self.site = get_current_site()
return super(WizardCreateView, self).dispatch(*args, **kwargs)
def get_current_step(self):
"""Returns the current step, if possible, else None."""
try:
return self.steps.current
except AttributeError:
return None
def is_first_step(self, step=None):
step = step or self.get_current_step()
return step == '0'
def is_second_step(self, step=None):
step = step or self.get_current_step()
return step == '1'
def get_context_data(self, **kwargs):
context = super(WizardCreateView, self).get_context_data(**kwargs)
if self.is_second_step():
context['wizard_entry'] = self.get_selected_entry()
return context
def get_form(self, step=None, data=None, files=None):
if step is None:
step = self.steps.current
# We need to grab the page from pre-validated data so that the wizard
# has it to prepare the list of valid entries.
if data:
page_key = "{0}-page".format(step)
self.page_pk = data.get(page_key, None)
else:
self.page_pk = None
if self.is_second_step(step):
self.form_list[step] = self.get_step_2_form(step, data, files)
return super(WizardCreateView, self).get_form(step, data, files)
def get_form_kwargs(self, step=None):
"""This is called by self.get_form()"""
kwargs = super(WizardCreateView, self).get_form_kwargs()
kwargs['wizard_user'] = self.request.user
if self.is_second_step(step):
kwargs['wizard_page'] = self.get_origin_page()
kwargs['wizard_language'] = self.get_origin_language()
else:
page_pk = self.page_pk or self.request.GET.get('page', None)
if page_pk and page_pk != 'None':
kwargs['wizard_page'] = Page.objects.filter(pk=page_pk).first()
else:
kwargs['wizard_page'] = None
kwargs['wizard_language'] = get_site_language_from_request(
self.request,
site_id=self.site.pk,
)
return kwargs
def get_form_initial(self, step):
"""This is called by self.get_form()"""
initial = super(WizardCreateView, self).get_form_initial(step)
if self.is_first_step(step):
initial['page'] = self.request.GET.get('page')
initial['language'] = self.request.GET.get('language')
return initial
def get_step_2_form(self, step=None, data=None, files=None):
entry_form_class = self.get_selected_entry().form
step_2_base_form = self.get_step_2_base_form()
form = step2_form_factory(
mixin_cls=step_2_base_form,
entry_form_class=entry_form_class,
)
return form
def get_step_2_base_form(self):
"""
Returns the base form to be used for step 2.
This form is sub classed dynamically by the form defined per module.
"""
return WizardStep2BaseForm
def get_template_names(self):
if self.is_first_step():
template_name = self.template_name
else:
template_name = self.get_selected_entry().template_name
return template_name
def done(self, form_list, **kwargs):
"""
This step only runs if all forms are valid. Simply emits a simple
template that uses JS to redirect to the newly created object.
"""
form_one, form_two = list(form_list)
instance = form_two.save()
url = self.get_success_url(instance)
language = form_one.cleaned_data['language']
if not url:
page = self.get_origin_page()
if page:
try:
url = page.get_absolute_url(language)
except NoReverseMatch:
url = '/'
else:
url = '/'
return SimpleTemplateResponse("cms/wizards/done.html", {"url": url})
def get_selected_entry(self):
data = self.get_cleaned_data_for_step('0')
return wizard_pool.get_entry(data['entry'])
def get_origin_page(self):
data = self.get_cleaned_data_for_step('0')
return data.get('page')
def get_origin_language(self):
data = self.get_cleaned_data_for_step('0')
return data.get('language')
def get_success_url(self, instance):
entry = self.get_selected_entry()
language = self.get_origin_language()
success_url = entry.get_success_url(
obj=instance,
language=language,
)
return success_url | random_line_split | |
views.py | # -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.files.storage import FileSystemStorage
from django.forms import Form
from django.template.response import SimpleTemplateResponse
from django.urls import NoReverseMatch
from formtools.wizard.views import SessionWizardView
from cms.models import Page
from cms.utils import get_current_site
from cms.utils.i18n import get_site_language_from_request
from .wizard_pool import wizard_pool
from .forms import (
WizardStep1Form,
WizardStep2BaseForm,
step2_form_factory,
)
class | (SessionWizardView):
template_name = 'cms/wizards/start.html'
file_storage = FileSystemStorage(
location=os.path.join(settings.MEDIA_ROOT, 'wizard_tmp_files'))
form_list = [
('0', WizardStep1Form),
# Form is used as a placeholder form.
# the real form will be loaded after step 0
('1', Form),
]
def dispatch(self, *args, **kwargs):
user = self.request.user
if not user.is_active or not user.is_staff:
raise PermissionDenied
self.site = get_current_site()
return super(WizardCreateView, self).dispatch(*args, **kwargs)
def get_current_step(self):
"""Returns the current step, if possible, else None."""
try:
return self.steps.current
except AttributeError:
return None
def is_first_step(self, step=None):
step = step or self.get_current_step()
return step == '0'
def is_second_step(self, step=None):
step = step or self.get_current_step()
return step == '1'
def get_context_data(self, **kwargs):
context = super(WizardCreateView, self).get_context_data(**kwargs)
if self.is_second_step():
context['wizard_entry'] = self.get_selected_entry()
return context
def get_form(self, step=None, data=None, files=None):
if step is None:
step = self.steps.current
# We need to grab the page from pre-validated data so that the wizard
# has it to prepare the list of valid entries.
if data:
page_key = "{0}-page".format(step)
self.page_pk = data.get(page_key, None)
else:
self.page_pk = None
if self.is_second_step(step):
self.form_list[step] = self.get_step_2_form(step, data, files)
return super(WizardCreateView, self).get_form(step, data, files)
def get_form_kwargs(self, step=None):
"""This is called by self.get_form()"""
kwargs = super(WizardCreateView, self).get_form_kwargs()
kwargs['wizard_user'] = self.request.user
if self.is_second_step(step):
kwargs['wizard_page'] = self.get_origin_page()
kwargs['wizard_language'] = self.get_origin_language()
else:
page_pk = self.page_pk or self.request.GET.get('page', None)
if page_pk and page_pk != 'None':
kwargs['wizard_page'] = Page.objects.filter(pk=page_pk).first()
else:
kwargs['wizard_page'] = None
kwargs['wizard_language'] = get_site_language_from_request(
self.request,
site_id=self.site.pk,
)
return kwargs
def get_form_initial(self, step):
"""This is called by self.get_form()"""
initial = super(WizardCreateView, self).get_form_initial(step)
if self.is_first_step(step):
initial['page'] = self.request.GET.get('page')
initial['language'] = self.request.GET.get('language')
return initial
def get_step_2_form(self, step=None, data=None, files=None):
entry_form_class = self.get_selected_entry().form
step_2_base_form = self.get_step_2_base_form()
form = step2_form_factory(
mixin_cls=step_2_base_form,
entry_form_class=entry_form_class,
)
return form
def get_step_2_base_form(self):
"""
Returns the base form to be used for step 2.
This form is sub classed dynamically by the form defined per module.
"""
return WizardStep2BaseForm
def get_template_names(self):
if self.is_first_step():
template_name = self.template_name
else:
template_name = self.get_selected_entry().template_name
return template_name
def done(self, form_list, **kwargs):
"""
This step only runs if all forms are valid. Simply emits a simple
template that uses JS to redirect to the newly created object.
"""
form_one, form_two = list(form_list)
instance = form_two.save()
url = self.get_success_url(instance)
language = form_one.cleaned_data['language']
if not url:
page = self.get_origin_page()
if page:
try:
url = page.get_absolute_url(language)
except NoReverseMatch:
url = '/'
else:
url = '/'
return SimpleTemplateResponse("cms/wizards/done.html", {"url": url})
def get_selected_entry(self):
data = self.get_cleaned_data_for_step('0')
return wizard_pool.get_entry(data['entry'])
def get_origin_page(self):
data = self.get_cleaned_data_for_step('0')
return data.get('page')
def get_origin_language(self):
data = self.get_cleaned_data_for_step('0')
return data.get('language')
def get_success_url(self, instance):
entry = self.get_selected_entry()
language = self.get_origin_language()
success_url = entry.get_success_url(
obj=instance,
language=language,
)
return success_url
| WizardCreateView | identifier_name |
googleAnalyticsAdapter_spec.js | import ga from 'modules/googleAnalyticsAdapter.js';
var assert = require('assert');
describe('Ga', function () {
describe('enableAnalytics', function () {
var cpmDistribution = function(cpm) {
return cpm <= 1 ? '<= 1$' : '> 1$';
}
var config = { options: { trackerName: 'foo', enableDistribution: true, cpmDistribution: cpmDistribution } };
// enableAnalytics can only be called once
ga.enableAnalytics(config);
it('should accept a tracker name option and output prefixed send string', function () {
var output = ga.getTrackerSend(); |
it('should use the custom cpm distribution', function() {
assert.equal(ga.getCpmDistribution(0.5), '<= 1$');
assert.equal(ga.getCpmDistribution(1), '<= 1$');
assert.equal(ga.getCpmDistribution(2), '> 1$');
assert.equal(ga.getCpmDistribution(5.23), '> 1$');
});
});
}); | assert.equal(output, 'foo.send');
}); | random_line_split |
scaleselector.spec.js | // The MIT License (MIT)
//
// Copyright (c) 2015-2021 Camptocamp SA
//
// 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.
import angular from 'angular';
import olMap from 'ol/Map';
import olView from 'ol/View';
describe('ngeo.map.scaleselector', () => {
/** @type {JQuery<HTMLElement>} */
let element;
/** @type {import('ol/Map').default} */
let map;
beforeEach(() => {
map = new olMap({
view: new olView({
center: [0, 0],
zoom: 0,
}),
});
element = angular.element('<div ngeo-scaleselector ngeo-scaleselector-map="map"></div>');
// Silent warnings throw by the ngeo-scaleselector component.
const logWarnFn = console.warn;
console.warn = () => {};
angular.mock.inject(($rootScope, $compile, $sce) => {
$rootScope.map = map;
$compile(element)($rootScope);
$rootScope.$digest();
});
// Enable again warnings
console.warn = logWarnFn;
});
it('creates an element with expected number of li elements', () => {
const lis = element.find('li');
expect(lis.length).toBe(29);
expect(lis[0].innerText.trim()).toBe('1\u00a0:\u00a0500');
});
describe('calling setZoom in Angular context', () => {
it('does not throw', () => {
const scope = element.scope();
/**
*
*/
function | () {
scope.$apply(() => {
map.getView().setZoom(4);
});
}
expect(test).not.toThrow();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.currentScale).toBe(50000);
});
});
it('calls getScale', () => {
const scope = element.scope();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(0)).toBe(500);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(0.5)).toEqual(750);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(4)).toBe(50000);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(28)).toBe(2);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(28.1)).toBeUndefined();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(undefined)).toBeUndefined();
});
});
| test | identifier_name |
scaleselector.spec.js | // The MIT License (MIT)
//
// Copyright (c) 2015-2021 Camptocamp SA
//
// 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.
import angular from 'angular';
import olMap from 'ol/Map';
import olView from 'ol/View';
describe('ngeo.map.scaleselector', () => {
/** @type {JQuery<HTMLElement>} */
let element;
/** @type {import('ol/Map').default} */
let map;
beforeEach(() => {
map = new olMap({
view: new olView({
center: [0, 0],
zoom: 0,
}),
});
element = angular.element('<div ngeo-scaleselector ngeo-scaleselector-map="map"></div>');
// Silent warnings throw by the ngeo-scaleselector component.
const logWarnFn = console.warn;
console.warn = () => {};
angular.mock.inject(($rootScope, $compile, $sce) => {
$rootScope.map = map;
$compile(element)($rootScope);
$rootScope.$digest();
});
// Enable again warnings
console.warn = logWarnFn;
});
it('creates an element with expected number of li elements', () => {
const lis = element.find('li');
expect(lis.length).toBe(29);
expect(lis[0].innerText.trim()).toBe('1\u00a0:\u00a0500');
});
describe('calling setZoom in Angular context', () => {
it('does not throw', () => {
const scope = element.scope();
/**
*
*/
function test() |
expect(test).not.toThrow();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.currentScale).toBe(50000);
});
});
it('calls getScale', () => {
const scope = element.scope();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(0)).toBe(500);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(0.5)).toEqual(750);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(4)).toBe(50000);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(28)).toBe(2);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(28.1)).toBeUndefined();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(undefined)).toBeUndefined();
});
});
| {
scope.$apply(() => {
map.getView().setZoom(4);
});
} | identifier_body |
scaleselector.spec.js | // The MIT License (MIT)
//
// Copyright (c) 2015-2021 Camptocamp SA
//
// 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.
import angular from 'angular';
import olMap from 'ol/Map';
import olView from 'ol/View';
describe('ngeo.map.scaleselector', () => {
/** @type {JQuery<HTMLElement>} */
let element;
/** @type {import('ol/Map').default} */
let map;
beforeEach(() => { | }),
});
element = angular.element('<div ngeo-scaleselector ngeo-scaleselector-map="map"></div>');
// Silent warnings throw by the ngeo-scaleselector component.
const logWarnFn = console.warn;
console.warn = () => {};
angular.mock.inject(($rootScope, $compile, $sce) => {
$rootScope.map = map;
$compile(element)($rootScope);
$rootScope.$digest();
});
// Enable again warnings
console.warn = logWarnFn;
});
it('creates an element with expected number of li elements', () => {
const lis = element.find('li');
expect(lis.length).toBe(29);
expect(lis[0].innerText.trim()).toBe('1\u00a0:\u00a0500');
});
describe('calling setZoom in Angular context', () => {
it('does not throw', () => {
const scope = element.scope();
/**
*
*/
function test() {
scope.$apply(() => {
map.getView().setZoom(4);
});
}
expect(test).not.toThrow();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.currentScale).toBe(50000);
});
});
it('calls getScale', () => {
const scope = element.scope();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(0)).toBe(500);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(0.5)).toEqual(750);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(4)).toBe(50000);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(28)).toBe(2);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(28.1)).toBeUndefined();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(undefined)).toBeUndefined();
});
}); | map = new olMap({
view: new olView({
center: [0, 0],
zoom: 0, | random_line_split |
mac_os.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import platform as py_platform
from spack.architecture import OperatingSystem
from spack.version import Version
from spack.util.executable import Executable
# FIXME: store versions inside OperatingSystem as a Version instead of string
def | ():
"""temporary workaround to return a macOS version as a Version object
"""
return Version(py_platform.mac_ver()[0])
def macos_sdk_path():
"""Return SDK path
"""
xcrun = Executable('xcrun')
return xcrun('--show-sdk-path', output=str, error=str).rstrip()
class MacOs(OperatingSystem):
"""This class represents the macOS operating system. This will be
auto detected using the python platform.mac_ver. The macOS
platform will be represented using the major version operating
system name, i.e el capitan, yosemite...etc.
"""
def __init__(self):
"""Autodetects the mac version from a dictionary.
If the mac version is too old or too new for Spack to recognize,
will use a generic "macos" version string until Spack is updated.
"""
mac_releases = {
'10.0': 'cheetah',
'10.1': 'puma',
'10.2': 'jaguar',
'10.3': 'panther',
'10.4': 'tiger',
'10.5': 'leopard',
'10.6': 'snowleopard',
'10.7': 'lion',
'10.8': 'mountainlion',
'10.9': 'mavericks',
'10.10': 'yosemite',
'10.11': 'elcapitan',
'10.12': 'sierra',
'10.13': 'highsierra',
'10.14': 'mojave',
'10.15': 'catalina',
'10.16': 'bigsur',
'11': 'bigsur',
}
# Big Sur versions go 11.0, 11.0.1, 11.1 (vs. prior versions that
# only used the minor component)
part = 1 if macos_version() >= Version('11') else 2
mac_ver = str(macos_version().up_to(part))
name = mac_releases.get(mac_ver, "macos")
super(MacOs, self).__init__(name, mac_ver)
def __str__(self):
return self.name
| macos_version | identifier_name |
mac_os.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import platform as py_platform
from spack.architecture import OperatingSystem
from spack.version import Version
from spack.util.executable import Executable
# FIXME: store versions inside OperatingSystem as a Version instead of string
def macos_version():
"""temporary workaround to return a macOS version as a Version object
"""
return Version(py_platform.mac_ver()[0])
def macos_sdk_path():
"""Return SDK path
"""
xcrun = Executable('xcrun')
return xcrun('--show-sdk-path', output=str, error=str).rstrip()
class MacOs(OperatingSystem):
"""This class represents the macOS operating system. This will be
auto detected using the python platform.mac_ver. The macOS
platform will be represented using the major version operating
system name, i.e el capitan, yosemite...etc.
"""
def __init__(self):
"""Autodetects the mac version from a dictionary.
If the mac version is too old or too new for Spack to recognize,
will use a generic "macos" version string until Spack is updated.
"""
mac_releases = {
'10.0': 'cheetah',
'10.1': 'puma',
'10.2': 'jaguar',
'10.3': 'panther',
'10.4': 'tiger',
'10.5': 'leopard',
'10.6': 'snowleopard',
'10.7': 'lion',
'10.8': 'mountainlion',
'10.9': 'mavericks',
'10.10': 'yosemite',
'10.11': 'elcapitan',
'10.12': 'sierra',
'10.13': 'highsierra',
'10.14': 'mojave',
'10.15': 'catalina',
'10.16': 'bigsur',
'11': 'bigsur',
}
# Big Sur versions go 11.0, 11.0.1, 11.1 (vs. prior versions that
# only used the minor component)
part = 1 if macos_version() >= Version('11') else 2
mac_ver = str(macos_version().up_to(part))
name = mac_releases.get(mac_ver, "macos")
super(MacOs, self).__init__(name, mac_ver)
def __str__(self):
| return self.name | identifier_body | |
mac_os.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import platform as py_platform
from spack.architecture import OperatingSystem
from spack.version import Version
from spack.util.executable import Executable
# FIXME: store versions inside OperatingSystem as a Version instead of string
def macos_version():
"""temporary workaround to return a macOS version as a Version object
"""
return Version(py_platform.mac_ver()[0])
def macos_sdk_path():
"""Return SDK path | xcrun = Executable('xcrun')
return xcrun('--show-sdk-path', output=str, error=str).rstrip()
class MacOs(OperatingSystem):
"""This class represents the macOS operating system. This will be
auto detected using the python platform.mac_ver. The macOS
platform will be represented using the major version operating
system name, i.e el capitan, yosemite...etc.
"""
def __init__(self):
"""Autodetects the mac version from a dictionary.
If the mac version is too old or too new for Spack to recognize,
will use a generic "macos" version string until Spack is updated.
"""
mac_releases = {
'10.0': 'cheetah',
'10.1': 'puma',
'10.2': 'jaguar',
'10.3': 'panther',
'10.4': 'tiger',
'10.5': 'leopard',
'10.6': 'snowleopard',
'10.7': 'lion',
'10.8': 'mountainlion',
'10.9': 'mavericks',
'10.10': 'yosemite',
'10.11': 'elcapitan',
'10.12': 'sierra',
'10.13': 'highsierra',
'10.14': 'mojave',
'10.15': 'catalina',
'10.16': 'bigsur',
'11': 'bigsur',
}
# Big Sur versions go 11.0, 11.0.1, 11.1 (vs. prior versions that
# only used the minor component)
part = 1 if macos_version() >= Version('11') else 2
mac_ver = str(macos_version().up_to(part))
name = mac_releases.get(mac_ver, "macos")
super(MacOs, self).__init__(name, mac_ver)
def __str__(self):
return self.name | """ | random_line_split |
JwtTokenError.ts | /* tslint:disable */
/* eslint-disable */
/**
* OpenCraft Instance Manager
* API for OpenCraft Instance Manager
*
* The version of the OpenAPI document: api
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { exists, mapValues } from '../runtime';
/**
*
* @export
* @interface JwtTokenError
*/
export interface JwtTokenError {
/**
*
* @type {string}
* @memberof JwtTokenError
*/
detail?: string;
/**
*
* @type {string}
* @memberof JwtTokenError
*/
code?: string;
}
export function JwtTokenErrorFromJSON(json: any): JwtTokenError {
return JwtTokenErrorFromJSONTyped(json, false);
}
export function JwtTokenErrorFromJSONTyped(json: any, ignoreDiscriminator: boolean): JwtTokenError {
if ((json === undefined) || (json === null)) {
return json;
}
return {
'detail': !exists(json, 'detail') ? undefined : json['detail'],
'code': !exists(json, 'code') ? undefined : json['code'],
};
}
export function JwtTokenErrorToJSON(value?: JwtTokenError | null): any | {
if (value === undefined) {
return undefined;
}
if (value === null) {
return null;
}
return {
'detail': value.detail,
'code': value.code,
};
} | identifier_body | |
JwtTokenError.ts | /* tslint:disable */
/* eslint-disable */
/**
* OpenCraft Instance Manager
* API for OpenCraft Instance Manager
*
* The version of the OpenAPI document: api
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { exists, mapValues } from '../runtime';
/**
*
* @export
* @interface JwtTokenError
*/
export interface JwtTokenError {
/**
*
* @type {string}
* @memberof JwtTokenError
*/
detail?: string;
/**
*
* @type {string}
* @memberof JwtTokenError
*/
code?: string;
}
export function JwtTokenErrorFromJSON(json: any): JwtTokenError {
return JwtTokenErrorFromJSONTyped(json, false);
}
export function JwtTokenErrorFromJSONTyped(json: any, ignoreDiscriminator: boolean): JwtTokenError {
if ((json === undefined) || (json === null)) |
return {
'detail': !exists(json, 'detail') ? undefined : json['detail'],
'code': !exists(json, 'code') ? undefined : json['code'],
};
}
export function JwtTokenErrorToJSON(value?: JwtTokenError | null): any {
if (value === undefined) {
return undefined;
}
if (value === null) {
return null;
}
return {
'detail': value.detail,
'code': value.code,
};
}
| {
return json;
} | conditional_block |
JwtTokenError.ts | /* tslint:disable */
/* eslint-disable */
/**
* OpenCraft Instance Manager
* API for OpenCraft Instance Manager
*
* The version of the OpenAPI document: api
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { exists, mapValues } from '../runtime';
/**
*
* @export
* @interface JwtTokenError
*/
export interface JwtTokenError {
/**
*
* @type {string}
* @memberof JwtTokenError
*/
detail?: string;
/**
*
* @type {string}
* @memberof JwtTokenError
*/
code?: string;
}
export function JwtTokenErrorFromJSON(json: any): JwtTokenError {
return JwtTokenErrorFromJSONTyped(json, false);
}
export function | (json: any, ignoreDiscriminator: boolean): JwtTokenError {
if ((json === undefined) || (json === null)) {
return json;
}
return {
'detail': !exists(json, 'detail') ? undefined : json['detail'],
'code': !exists(json, 'code') ? undefined : json['code'],
};
}
export function JwtTokenErrorToJSON(value?: JwtTokenError | null): any {
if (value === undefined) {
return undefined;
}
if (value === null) {
return null;
}
return {
'detail': value.detail,
'code': value.code,
};
}
| JwtTokenErrorFromJSONTyped | identifier_name |
JwtTokenError.ts | /* tslint:disable */
/* eslint-disable */
/**
* OpenCraft Instance Manager
* API for OpenCraft Instance Manager
*
* The version of the OpenAPI document: api
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { exists, mapValues } from '../runtime';
/**
*
* @export
* @interface JwtTokenError
*/
export interface JwtTokenError {
/**
*
* @type {string}
* @memberof JwtTokenError
*/
detail?: string;
/**
*
* @type {string}
* @memberof JwtTokenError
*/
code?: string; |
export function JwtTokenErrorFromJSONTyped(json: any, ignoreDiscriminator: boolean): JwtTokenError {
if ((json === undefined) || (json === null)) {
return json;
}
return {
'detail': !exists(json, 'detail') ? undefined : json['detail'],
'code': !exists(json, 'code') ? undefined : json['code'],
};
}
export function JwtTokenErrorToJSON(value?: JwtTokenError | null): any {
if (value === undefined) {
return undefined;
}
if (value === null) {
return null;
}
return {
'detail': value.detail,
'code': value.code,
};
} | }
export function JwtTokenErrorFromJSON(json: any): JwtTokenError {
return JwtTokenErrorFromJSONTyped(json, false);
} | random_line_split |
index.js | import { request } from '@octokit/request';
import { getUserAgent } from 'universal-user-agent';
const VERSION = "4.5.6";
class GraphqlError extends Error {
constructor(request, response) {
const message = response.data.errors[0].message;
super(message);
Object.assign(this, response.data);
Object.assign(this, { headers: response.headers });
this.name = "GraphqlError";
this.request = request;
// Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
const NON_VARIABLE_OPTIONS = [
"method",
"baseUrl",
"url",
"headers",
"request",
"query",
"mediaType",
];
const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
function graphql(request, query, options) {
if (typeof query === "string" && options && "query" in options) {
return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
}
const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {
if (NON_VARIABLE_OPTIONS.includes(key)) {
result[key] = parsedOptions[key];
return result;
}
if (!result.variables) {
result.variables = {};
}
result.variables[key] = parsedOptions[key];
return result;
}, {});
// workaround for GitHub Enterprise baseUrl set with /api/v3 suffix
// https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451
const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;
if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
}
return request(requestOptions).then((response) => {
if (response.data.errors) |
return response.data.data;
});
}
function withDefaults(request$1, newDefaults) {
const newRequest = request$1.defaults(newDefaults);
const newApi = (query, options) => {
return graphql(newRequest, query, options);
};
return Object.assign(newApi, {
defaults: withDefaults.bind(null, newRequest),
endpoint: request.endpoint,
});
}
const graphql$1 = withDefaults(request, {
headers: {
"user-agent": `octokit-graphql.js/${VERSION} ${getUserAgent()}`,
},
method: "POST",
url: "/graphql",
});
function withCustomRequest(customRequest) {
return withDefaults(customRequest, {
method: "POST",
url: "/graphql",
});
}
export { graphql$1 as graphql, withCustomRequest };
//# sourceMappingURL=index.js.map
| {
const headers = {};
for (const key of Object.keys(response.headers)) {
headers[key] = response.headers[key];
}
throw new GraphqlError(requestOptions, {
headers,
data: response.data,
});
} | conditional_block |
index.js | import { request } from '@octokit/request';
import { getUserAgent } from 'universal-user-agent';
const VERSION = "4.5.6";
class GraphqlError extends Error {
constructor(request, response) {
const message = response.data.errors[0].message;
super(message);
Object.assign(this, response.data);
Object.assign(this, { headers: response.headers });
this.name = "GraphqlError";
this.request = request;
// Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
const NON_VARIABLE_OPTIONS = [
"method",
"baseUrl",
"url",
"headers",
"request",
"query",
"mediaType",
];
const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
function graphql(request, query, options) {
if (typeof query === "string" && options && "query" in options) {
return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
}
const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {
if (NON_VARIABLE_OPTIONS.includes(key)) {
result[key] = parsedOptions[key];
return result;
}
if (!result.variables) {
result.variables = {};
}
result.variables[key] = parsedOptions[key];
return result;
}, {});
// workaround for GitHub Enterprise baseUrl set with /api/v3 suffix
// https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451
const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;
if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
}
return request(requestOptions).then((response) => {
if (response.data.errors) {
const headers = {};
for (const key of Object.keys(response.headers)) {
headers[key] = response.headers[key];
}
throw new GraphqlError(requestOptions, {
headers,
data: response.data,
});
}
return response.data.data;
});
}
function withDefaults(request$1, newDefaults) {
const newRequest = request$1.defaults(newDefaults);
const newApi = (query, options) => {
return graphql(newRequest, query, options);
};
return Object.assign(newApi, {
defaults: withDefaults.bind(null, newRequest),
endpoint: request.endpoint,
});
}
const graphql$1 = withDefaults(request, {
headers: {
"user-agent": `octokit-graphql.js/${VERSION} ${getUserAgent()}`,
},
method: "POST",
url: "/graphql",
});
function withCustomRequest(customRequest) |
export { graphql$1 as graphql, withCustomRequest };
//# sourceMappingURL=index.js.map
| {
return withDefaults(customRequest, {
method: "POST",
url: "/graphql",
});
} | identifier_body |
index.js | import { request } from '@octokit/request';
import { getUserAgent } from 'universal-user-agent';
const VERSION = "4.5.6";
class GraphqlError extends Error {
| (request, response) {
const message = response.data.errors[0].message;
super(message);
Object.assign(this, response.data);
Object.assign(this, { headers: response.headers });
this.name = "GraphqlError";
this.request = request;
// Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
const NON_VARIABLE_OPTIONS = [
"method",
"baseUrl",
"url",
"headers",
"request",
"query",
"mediaType",
];
const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
function graphql(request, query, options) {
if (typeof query === "string" && options && "query" in options) {
return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
}
const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {
if (NON_VARIABLE_OPTIONS.includes(key)) {
result[key] = parsedOptions[key];
return result;
}
if (!result.variables) {
result.variables = {};
}
result.variables[key] = parsedOptions[key];
return result;
}, {});
// workaround for GitHub Enterprise baseUrl set with /api/v3 suffix
// https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451
const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;
if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
}
return request(requestOptions).then((response) => {
if (response.data.errors) {
const headers = {};
for (const key of Object.keys(response.headers)) {
headers[key] = response.headers[key];
}
throw new GraphqlError(requestOptions, {
headers,
data: response.data,
});
}
return response.data.data;
});
}
function withDefaults(request$1, newDefaults) {
const newRequest = request$1.defaults(newDefaults);
const newApi = (query, options) => {
return graphql(newRequest, query, options);
};
return Object.assign(newApi, {
defaults: withDefaults.bind(null, newRequest),
endpoint: request.endpoint,
});
}
const graphql$1 = withDefaults(request, {
headers: {
"user-agent": `octokit-graphql.js/${VERSION} ${getUserAgent()}`,
},
method: "POST",
url: "/graphql",
});
function withCustomRequest(customRequest) {
return withDefaults(customRequest, {
method: "POST",
url: "/graphql",
});
}
export { graphql$1 as graphql, withCustomRequest };
//# sourceMappingURL=index.js.map
| constructor | identifier_name |
index.js | import { request } from '@octokit/request';
import { getUserAgent } from 'universal-user-agent';
const VERSION = "4.5.6";
class GraphqlError extends Error {
constructor(request, response) {
const message = response.data.errors[0].message;
super(message);
Object.assign(this, response.data);
Object.assign(this, { headers: response.headers });
this.name = "GraphqlError";
this.request = request;
// Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
const NON_VARIABLE_OPTIONS = [
"method",
"baseUrl",
"url",
"headers",
"request",
"query",
"mediaType",
];
const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
function graphql(request, query, options) {
if (typeof query === "string" && options && "query" in options) {
return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
}
const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {
if (NON_VARIABLE_OPTIONS.includes(key)) {
result[key] = parsedOptions[key];
return result;
}
if (!result.variables) {
result.variables = {};
}
result.variables[key] = parsedOptions[key];
return result;
}, {});
// workaround for GitHub Enterprise baseUrl set with /api/v3 suffix | return request(requestOptions).then((response) => {
if (response.data.errors) {
const headers = {};
for (const key of Object.keys(response.headers)) {
headers[key] = response.headers[key];
}
throw new GraphqlError(requestOptions, {
headers,
data: response.data,
});
}
return response.data.data;
});
}
function withDefaults(request$1, newDefaults) {
const newRequest = request$1.defaults(newDefaults);
const newApi = (query, options) => {
return graphql(newRequest, query, options);
};
return Object.assign(newApi, {
defaults: withDefaults.bind(null, newRequest),
endpoint: request.endpoint,
});
}
const graphql$1 = withDefaults(request, {
headers: {
"user-agent": `octokit-graphql.js/${VERSION} ${getUserAgent()}`,
},
method: "POST",
url: "/graphql",
});
function withCustomRequest(customRequest) {
return withDefaults(customRequest, {
method: "POST",
url: "/graphql",
});
}
export { graphql$1 as graphql, withCustomRequest };
//# sourceMappingURL=index.js.map | // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451
const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;
if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
} | random_line_split |
Transform.js | import Mat23 from 'math/matrix/mat23/Build.js';
import Scale from 'math/transform/2d/components/Scale.js';
import Position from 'math/transform/2d/components/Position.js';
// A Minimal 2D Transform class
// Components: Position and Scale, baked to a Mat23
// Supports: Immediate or Deferred Updates, Interpolation.
export default class Transform {
constructor (x = 0, y = 0, scaleX = 1, scaleY = 1) {
this.position = new Position(this, x, y);
this.scale = new Scale(this, scaleX, scaleY);
this.local = Mat23(scaleX, 0, 0, scaleY, x, y);
this.interpolate = false;
this.immediate = false;
this.dirty = true;
}
// Inject the transform properties to the given target
addProperties (target) {
// Property getter/setter injection
this.position.addProperties(target);
// Component references
target.position = this.position;
target.scale = this.scale;
return target;
}
enableImmediateUpdates () {
this.immediate = true;
return this;
}
disableImmediateUpdates () {
this.immediate = false;
this.dirty = true;
return this;
}
enableInterpolation () {
this.interpolate = true;
this.position.reset(this.position.x, this.position.y);
this.scale.reset(this.scale.x, this.scale.y);
return this;
}
disableInterpolation () {
this.interpolate = false;
return this;
}
setDirty () {
if (this.immediate)
{
this.updateTransform();
}
else
{
this.dirty = true;
}
return this;
}
updateTransform (i = 1) {
this.local[0] = this.scale[0];
this.local[1] = 0;
this.local[2] = 0;
this.local[3] = this.scale[1];
if (this.interpolate)
{
this.local[4] = this.position.getDeltaX(i);
this.local[5] = this.position.getDeltaY(i);
}
else
|
this.dirty = false;
return this;
}
destroy () {
this.position.destroy();
this.scale.destroy();
this.local = undefined;
}
}
| {
this.local[4] = this.position[0];
this.local[5] = this.position[1];
} | conditional_block |
Transform.js | import Mat23 from 'math/matrix/mat23/Build.js';
import Scale from 'math/transform/2d/components/Scale.js';
import Position from 'math/transform/2d/components/Position.js';
// A Minimal 2D Transform class
// Components: Position and Scale, baked to a Mat23
// Supports: Immediate or Deferred Updates, Interpolation.
export default class Transform {
constructor (x = 0, y = 0, scaleX = 1, scaleY = 1) {
this.position = new Position(this, x, y);
this.scale = new Scale(this, scaleX, scaleY);
this.local = Mat23(scaleX, 0, 0, scaleY, x, y);
this.interpolate = false;
this.immediate = false;
this.dirty = true;
}
// Inject the transform properties to the given target
addProperties (target) {
// Property getter/setter injection
this.position.addProperties(target);
// Component references
target.position = this.position;
target.scale = this.scale;
return target;
}
enableImmediateUpdates () {
this.immediate = true;
return this;
}
disableImmediateUpdates () {
this.immediate = false;
this.dirty = true;
return this;
}
enableInterpolation () {
this.interpolate = true;
this.position.reset(this.position.x, this.position.y);
this.scale.reset(this.scale.x, this.scale.y);
return this;
}
disableInterpolation () {
this.interpolate = false;
return this;
}
| () {
if (this.immediate)
{
this.updateTransform();
}
else
{
this.dirty = true;
}
return this;
}
updateTransform (i = 1) {
this.local[0] = this.scale[0];
this.local[1] = 0;
this.local[2] = 0;
this.local[3] = this.scale[1];
if (this.interpolate)
{
this.local[4] = this.position.getDeltaX(i);
this.local[5] = this.position.getDeltaY(i);
}
else
{
this.local[4] = this.position[0];
this.local[5] = this.position[1];
}
this.dirty = false;
return this;
}
destroy () {
this.position.destroy();
this.scale.destroy();
this.local = undefined;
}
}
| setDirty | identifier_name |
Transform.js | import Mat23 from 'math/matrix/mat23/Build.js';
import Scale from 'math/transform/2d/components/Scale.js';
import Position from 'math/transform/2d/components/Position.js';
// A Minimal 2D Transform class
// Components: Position and Scale, baked to a Mat23
// Supports: Immediate or Deferred Updates, Interpolation.
export default class Transform {
constructor (x = 0, y = 0, scaleX = 1, scaleY = 1) {
this.position = new Position(this, x, y);
this.scale = new Scale(this, scaleX, scaleY);
this.local = Mat23(scaleX, 0, 0, scaleY, x, y);
this.interpolate = false;
this.immediate = false;
this.dirty = true;
}
// Inject the transform properties to the given target
addProperties (target) {
// Property getter/setter injection
this.position.addProperties(target);
// Component references
target.position = this.position;
target.scale = this.scale;
return target;
}
enableImmediateUpdates () |
disableImmediateUpdates () {
this.immediate = false;
this.dirty = true;
return this;
}
enableInterpolation () {
this.interpolate = true;
this.position.reset(this.position.x, this.position.y);
this.scale.reset(this.scale.x, this.scale.y);
return this;
}
disableInterpolation () {
this.interpolate = false;
return this;
}
setDirty () {
if (this.immediate)
{
this.updateTransform();
}
else
{
this.dirty = true;
}
return this;
}
updateTransform (i = 1) {
this.local[0] = this.scale[0];
this.local[1] = 0;
this.local[2] = 0;
this.local[3] = this.scale[1];
if (this.interpolate)
{
this.local[4] = this.position.getDeltaX(i);
this.local[5] = this.position.getDeltaY(i);
}
else
{
this.local[4] = this.position[0];
this.local[5] = this.position[1];
}
this.dirty = false;
return this;
}
destroy () {
this.position.destroy();
this.scale.destroy();
this.local = undefined;
}
}
| {
this.immediate = true;
return this;
} | identifier_body |
Transform.js | import Mat23 from 'math/matrix/mat23/Build.js';
import Scale from 'math/transform/2d/components/Scale.js';
import Position from 'math/transform/2d/components/Position.js';
// A Minimal 2D Transform class
// Components: Position and Scale, baked to a Mat23
// Supports: Immediate or Deferred Updates, Interpolation.
export default class Transform {
constructor (x = 0, y = 0, scaleX = 1, scaleY = 1) {
this.position = new Position(this, x, y);
this.scale = new Scale(this, scaleX, scaleY);
this.local = Mat23(scaleX, 0, 0, scaleY, x, y);
this.interpolate = false;
this.immediate = false;
this.dirty = true;
}
// Inject the transform properties to the given target
addProperties (target) {
// Property getter/setter injection
this.position.addProperties(target);
// Component references
target.position = this.position;
target.scale = this.scale;
return target;
}
enableImmediateUpdates () {
this.immediate = true;
return this;
}
disableImmediateUpdates () {
this.immediate = false;
this.dirty = true;
return this;
}
enableInterpolation () {
this.interpolate = true;
this.position.reset(this.position.x, this.position.y);
this.scale.reset(this.scale.x, this.scale.y);
return this;
}
| this.interpolate = false;
return this;
}
setDirty () {
if (this.immediate)
{
this.updateTransform();
}
else
{
this.dirty = true;
}
return this;
}
updateTransform (i = 1) {
this.local[0] = this.scale[0];
this.local[1] = 0;
this.local[2] = 0;
this.local[3] = this.scale[1];
if (this.interpolate)
{
this.local[4] = this.position.getDeltaX(i);
this.local[5] = this.position.getDeltaY(i);
}
else
{
this.local[4] = this.position[0];
this.local[5] = this.position[1];
}
this.dirty = false;
return this;
}
destroy () {
this.position.destroy();
this.scale.destroy();
this.local = undefined;
}
} | disableInterpolation () {
| random_line_split |
exceptions.py |
# Base exception classes
class PGError(Exception):
"""
Base class for all exceptions explicitly raised in PolyglotDB.
"""
def __init__(self, value):
self.value = value
def __repr__(self):
return '{}: {}'.format(type(self).__name__, self.value)
def __str__(self):
return self.value
# Context Manager exceptions
class PGContextError(PGError):
"""
Exception class for when context managers should be used and aren't.
"""
pass
# Corpus loading exceptions
class ParseError(PGError):
"""
Exception class for parsing errors
"""
pass
class PGOSError(PGError):
"""
Exception class for when files or directories that are expected are missing.
Wrapper for OSError.
"""
pass
class CorpusIntegrityError(PGError):
"""
Exception for when a problem arises while loading in the corpus.
"""
pass
class DelimiterError(PGError):
"""
Exception for mismatch between specified delimiter and the actual text
when loading in CSV files and transcriptions.
"""
pass
class ILGError(ParseError):
"""
Exception for general issues when loading interlinear gloss files.
"""
pass
class ILGWordMismatchError(ParseError):
"""
Exception for when interlinear gloss files have different numbers of
words across lines that should have a one-to-one mapping.
Parameters
----------
spelling_line : list
List of words in the spelling line
transcription_line : list
List of words in the transcription line
"""
def __init__(self, mismatching_lines):
self.main = "There doesn't appear to be equal numbers of words in one or more of the glosses."
self.information = ''
self.details = 'The following glosses did not have matching numbers of words:\n\n'
for ml in mismatching_lines:
line_inds, line = ml
self.details += 'From lines {} to {}:\n'.format(*line_inds)
for k, v in line.items():
|
class ILGLinesMismatchError(ParseError):
"""
Exception for when the number of lines in a interlinear gloss file
is not a multiple of the number of types of lines.
Parameters
----------
lines : list
List of the lines in the interlinear gloss file
"""
def __init__(self, lines):
self.main = "There doesn't appear to be equal numbers of orthography and transcription lines"
self.information = ''
self.details = 'The following is the contents of the file after initial preprocessing:\n\n'
for line in lines:
if isinstance(line, tuple):
self.details += '{}: {}\n'.format(*line)
else:
self.details += str(line) + '\n'
class TextGridError(ParseError):
"""
Exception class for parsing TextGrids
"""
pass
class TextGridTierError(TextGridError):
"""
Exception for when a specified tier was not found in a TextGrid.
Parameters
----------
tier_type : str
The type of tier looked for (such as spelling or transcription)
tier_name : str
The name of the tier specified
tiers : list
List of tiers in the TextGrid that were inspected
"""
def __init__(self, tier_type, tier_name, tiers):
self.main = 'The {} tier name was not found'.format(tier_type)
self.information = 'The tier name \'{}\' was not found in any tiers'.format(tier_name)
self.details = 'The tier name looked for (ignoring case) was \'{}\'.\n'.format(tier_name)
self.details += 'The following tiers were found:\n\n'
for t in tiers:
self.details += '{}\n'.format(t.name)
class BuckeyeParseError(ParseError):
"""
Exception class for parsing Buckeye formatted files
"""
def __init__(self, path, misparsed_lines):
if len(misparsed_lines) == 1:
self.main = 'One line in \'{}\' was not parsed correctly.'.format(path)
else:
self.main = '{} lines in \'{}\' were not parsed correctly.'.format(len(misparsed_lines), path)
self.information = 'The lines did not have enough fields to be parsed correctly.'
self.details = 'The following lines were missing entries:\n\n'
for t in misparsed_lines:
self.details += '{}\n'.format(t)
self.value = '\n'.join([self.main, self.details])
# Acoustic exceptions
class AcousticError(PGError):
"""
Exception class for errors in acoustic processing
"""
pass
class NoSoundFileError(AcousticError):
"""
Exception class for when no sound file exists
"""
pass
class GraphQueryError(PGError):
"""
Exception class for errors in querying the Neo4j database
"""
pass
class CorpusConfigError(PGError):
"""
Exception class for misconfigured CorpusContext objects
"""
pass
class SubannotationError(PGError):
"""
Exception class for subannotations
"""
pass
class GraphModelError(PGError):
"""
Exception class for generating Python objects from Neo4j queries
"""
pass
class ConnectionError(PGError):
"""
Exception class for connection failures
"""
pass
class AuthorizationError(PGError):
"""
Exception class for authentication failures
"""
pass
class NetworkAddressError(PGError):
"""
Exception class for malformed network addresses
"""
pass
class TemporaryConnectionError(PGError):
"""
Exception class for transient connection errors
"""
pass
class SubsetError(PGError):
"""
Exception class for not finding a specified subset
"""
pass
class HierarchyError(PGError):
"""
Exception class for Hierarchy errors
"""
pass
class ClientError(PGError):
"""
Exception class for connecting to remote/local ISCAN servers
"""
pass
class NodeAttributeError(GraphQueryError):
"""
Exception class for errors in attributes for base nodes in constructing queries
"""
pass
class SpeakerAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for speakers in constructing queries
"""
pass
class DiscourseAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for discourses in constructing queries
"""
pass
class AnnotationAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for annotations in constructing queries
"""
pass
class LexiconAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for type annotations in constructing queries
"""
pass
| self.details += '({}, {} words) '.format(k, len(v))
self.details += ' '.join(str(x) for x in v) + '\n' | conditional_block |
exceptions.py |
# Base exception classes
class PGError(Exception):
"""
Base class for all exceptions explicitly raised in PolyglotDB.
"""
def __init__(self, value):
self.value = value
def __repr__(self):
return '{}: {}'.format(type(self).__name__, self.value)
def __str__(self):
return self.value
# Context Manager exceptions
class PGContextError(PGError):
"""
Exception class for when context managers should be used and aren't.
"""
pass
# Corpus loading exceptions
class ParseError(PGError):
"""
Exception class for parsing errors
"""
pass
class PGOSError(PGError):
"""
Exception class for when files or directories that are expected are missing.
Wrapper for OSError.
"""
pass
class | (PGError):
"""
Exception for when a problem arises while loading in the corpus.
"""
pass
class DelimiterError(PGError):
"""
Exception for mismatch between specified delimiter and the actual text
when loading in CSV files and transcriptions.
"""
pass
class ILGError(ParseError):
"""
Exception for general issues when loading interlinear gloss files.
"""
pass
class ILGWordMismatchError(ParseError):
"""
Exception for when interlinear gloss files have different numbers of
words across lines that should have a one-to-one mapping.
Parameters
----------
spelling_line : list
List of words in the spelling line
transcription_line : list
List of words in the transcription line
"""
def __init__(self, mismatching_lines):
self.main = "There doesn't appear to be equal numbers of words in one or more of the glosses."
self.information = ''
self.details = 'The following glosses did not have matching numbers of words:\n\n'
for ml in mismatching_lines:
line_inds, line = ml
self.details += 'From lines {} to {}:\n'.format(*line_inds)
for k, v in line.items():
self.details += '({}, {} words) '.format(k, len(v))
self.details += ' '.join(str(x) for x in v) + '\n'
class ILGLinesMismatchError(ParseError):
"""
Exception for when the number of lines in a interlinear gloss file
is not a multiple of the number of types of lines.
Parameters
----------
lines : list
List of the lines in the interlinear gloss file
"""
def __init__(self, lines):
self.main = "There doesn't appear to be equal numbers of orthography and transcription lines"
self.information = ''
self.details = 'The following is the contents of the file after initial preprocessing:\n\n'
for line in lines:
if isinstance(line, tuple):
self.details += '{}: {}\n'.format(*line)
else:
self.details += str(line) + '\n'
class TextGridError(ParseError):
"""
Exception class for parsing TextGrids
"""
pass
class TextGridTierError(TextGridError):
"""
Exception for when a specified tier was not found in a TextGrid.
Parameters
----------
tier_type : str
The type of tier looked for (such as spelling or transcription)
tier_name : str
The name of the tier specified
tiers : list
List of tiers in the TextGrid that were inspected
"""
def __init__(self, tier_type, tier_name, tiers):
self.main = 'The {} tier name was not found'.format(tier_type)
self.information = 'The tier name \'{}\' was not found in any tiers'.format(tier_name)
self.details = 'The tier name looked for (ignoring case) was \'{}\'.\n'.format(tier_name)
self.details += 'The following tiers were found:\n\n'
for t in tiers:
self.details += '{}\n'.format(t.name)
class BuckeyeParseError(ParseError):
"""
Exception class for parsing Buckeye formatted files
"""
def __init__(self, path, misparsed_lines):
if len(misparsed_lines) == 1:
self.main = 'One line in \'{}\' was not parsed correctly.'.format(path)
else:
self.main = '{} lines in \'{}\' were not parsed correctly.'.format(len(misparsed_lines), path)
self.information = 'The lines did not have enough fields to be parsed correctly.'
self.details = 'The following lines were missing entries:\n\n'
for t in misparsed_lines:
self.details += '{}\n'.format(t)
self.value = '\n'.join([self.main, self.details])
# Acoustic exceptions
class AcousticError(PGError):
"""
Exception class for errors in acoustic processing
"""
pass
class NoSoundFileError(AcousticError):
"""
Exception class for when no sound file exists
"""
pass
class GraphQueryError(PGError):
"""
Exception class for errors in querying the Neo4j database
"""
pass
class CorpusConfigError(PGError):
"""
Exception class for misconfigured CorpusContext objects
"""
pass
class SubannotationError(PGError):
"""
Exception class for subannotations
"""
pass
class GraphModelError(PGError):
"""
Exception class for generating Python objects from Neo4j queries
"""
pass
class ConnectionError(PGError):
"""
Exception class for connection failures
"""
pass
class AuthorizationError(PGError):
"""
Exception class for authentication failures
"""
pass
class NetworkAddressError(PGError):
"""
Exception class for malformed network addresses
"""
pass
class TemporaryConnectionError(PGError):
"""
Exception class for transient connection errors
"""
pass
class SubsetError(PGError):
"""
Exception class for not finding a specified subset
"""
pass
class HierarchyError(PGError):
"""
Exception class for Hierarchy errors
"""
pass
class ClientError(PGError):
"""
Exception class for connecting to remote/local ISCAN servers
"""
pass
class NodeAttributeError(GraphQueryError):
"""
Exception class for errors in attributes for base nodes in constructing queries
"""
pass
class SpeakerAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for speakers in constructing queries
"""
pass
class DiscourseAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for discourses in constructing queries
"""
pass
class AnnotationAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for annotations in constructing queries
"""
pass
class LexiconAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for type annotations in constructing queries
"""
pass
| CorpusIntegrityError | identifier_name |
exceptions.py |
# Base exception classes
class PGError(Exception):
"""
Base class for all exceptions explicitly raised in PolyglotDB.
"""
def __init__(self, value):
self.value = value
def __repr__(self):
return '{}: {}'.format(type(self).__name__, self.value)
def __str__(self):
return self.value
# Context Manager exceptions
class PGContextError(PGError):
"""
Exception class for when context managers should be used and aren't.
"""
pass
# Corpus loading exceptions
class ParseError(PGError):
"""
Exception class for parsing errors
"""
pass
class PGOSError(PGError):
"""
Exception class for when files or directories that are expected are missing.
Wrapper for OSError.
"""
pass
class CorpusIntegrityError(PGError):
"""
Exception for when a problem arises while loading in the corpus.
"""
pass
class DelimiterError(PGError):
"""
Exception for mismatch between specified delimiter and the actual text
when loading in CSV files and transcriptions.
"""
pass
class ILGError(ParseError):
"""
Exception for general issues when loading interlinear gloss files.
"""
pass
class ILGWordMismatchError(ParseError):
"""
Exception for when interlinear gloss files have different numbers of
words across lines that should have a one-to-one mapping.
Parameters
----------
spelling_line : list
List of words in the spelling line
transcription_line : list
List of words in the transcription line
"""
def __init__(self, mismatching_lines):
self.main = "There doesn't appear to be equal numbers of words in one or more of the glosses."
self.information = ''
self.details = 'The following glosses did not have matching numbers of words:\n\n'
for ml in mismatching_lines:
line_inds, line = ml
self.details += 'From lines {} to {}:\n'.format(*line_inds)
for k, v in line.items():
self.details += '({}, {} words) '.format(k, len(v))
self.details += ' '.join(str(x) for x in v) + '\n'
class ILGLinesMismatchError(ParseError):
|
class TextGridError(ParseError):
"""
Exception class for parsing TextGrids
"""
pass
class TextGridTierError(TextGridError):
"""
Exception for when a specified tier was not found in a TextGrid.
Parameters
----------
tier_type : str
The type of tier looked for (such as spelling or transcription)
tier_name : str
The name of the tier specified
tiers : list
List of tiers in the TextGrid that were inspected
"""
def __init__(self, tier_type, tier_name, tiers):
self.main = 'The {} tier name was not found'.format(tier_type)
self.information = 'The tier name \'{}\' was not found in any tiers'.format(tier_name)
self.details = 'The tier name looked for (ignoring case) was \'{}\'.\n'.format(tier_name)
self.details += 'The following tiers were found:\n\n'
for t in tiers:
self.details += '{}\n'.format(t.name)
class BuckeyeParseError(ParseError):
"""
Exception class for parsing Buckeye formatted files
"""
def __init__(self, path, misparsed_lines):
if len(misparsed_lines) == 1:
self.main = 'One line in \'{}\' was not parsed correctly.'.format(path)
else:
self.main = '{} lines in \'{}\' were not parsed correctly.'.format(len(misparsed_lines), path)
self.information = 'The lines did not have enough fields to be parsed correctly.'
self.details = 'The following lines were missing entries:\n\n'
for t in misparsed_lines:
self.details += '{}\n'.format(t)
self.value = '\n'.join([self.main, self.details])
# Acoustic exceptions
class AcousticError(PGError):
"""
Exception class for errors in acoustic processing
"""
pass
class NoSoundFileError(AcousticError):
"""
Exception class for when no sound file exists
"""
pass
class GraphQueryError(PGError):
"""
Exception class for errors in querying the Neo4j database
"""
pass
class CorpusConfigError(PGError):
"""
Exception class for misconfigured CorpusContext objects
"""
pass
class SubannotationError(PGError):
"""
Exception class for subannotations
"""
pass
class GraphModelError(PGError):
"""
Exception class for generating Python objects from Neo4j queries
"""
pass
class ConnectionError(PGError):
"""
Exception class for connection failures
"""
pass
class AuthorizationError(PGError):
"""
Exception class for authentication failures
"""
pass
class NetworkAddressError(PGError):
"""
Exception class for malformed network addresses
"""
pass
class TemporaryConnectionError(PGError):
"""
Exception class for transient connection errors
"""
pass
class SubsetError(PGError):
"""
Exception class for not finding a specified subset
"""
pass
class HierarchyError(PGError):
"""
Exception class for Hierarchy errors
"""
pass
class ClientError(PGError):
"""
Exception class for connecting to remote/local ISCAN servers
"""
pass
class NodeAttributeError(GraphQueryError):
"""
Exception class for errors in attributes for base nodes in constructing queries
"""
pass
class SpeakerAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for speakers in constructing queries
"""
pass
class DiscourseAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for discourses in constructing queries
"""
pass
class AnnotationAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for annotations in constructing queries
"""
pass
class LexiconAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for type annotations in constructing queries
"""
pass
| """
Exception for when the number of lines in a interlinear gloss file
is not a multiple of the number of types of lines.
Parameters
----------
lines : list
List of the lines in the interlinear gloss file
"""
def __init__(self, lines):
self.main = "There doesn't appear to be equal numbers of orthography and transcription lines"
self.information = ''
self.details = 'The following is the contents of the file after initial preprocessing:\n\n'
for line in lines:
if isinstance(line, tuple):
self.details += '{}: {}\n'.format(*line)
else:
self.details += str(line) + '\n' | identifier_body |
exceptions.py | # Base exception classes
| Base class for all exceptions explicitly raised in PolyglotDB.
"""
def __init__(self, value):
self.value = value
def __repr__(self):
return '{}: {}'.format(type(self).__name__, self.value)
def __str__(self):
return self.value
# Context Manager exceptions
class PGContextError(PGError):
"""
Exception class for when context managers should be used and aren't.
"""
pass
# Corpus loading exceptions
class ParseError(PGError):
"""
Exception class for parsing errors
"""
pass
class PGOSError(PGError):
"""
Exception class for when files or directories that are expected are missing.
Wrapper for OSError.
"""
pass
class CorpusIntegrityError(PGError):
"""
Exception for when a problem arises while loading in the corpus.
"""
pass
class DelimiterError(PGError):
"""
Exception for mismatch between specified delimiter and the actual text
when loading in CSV files and transcriptions.
"""
pass
class ILGError(ParseError):
"""
Exception for general issues when loading interlinear gloss files.
"""
pass
class ILGWordMismatchError(ParseError):
"""
Exception for when interlinear gloss files have different numbers of
words across lines that should have a one-to-one mapping.
Parameters
----------
spelling_line : list
List of words in the spelling line
transcription_line : list
List of words in the transcription line
"""
def __init__(self, mismatching_lines):
self.main = "There doesn't appear to be equal numbers of words in one or more of the glosses."
self.information = ''
self.details = 'The following glosses did not have matching numbers of words:\n\n'
for ml in mismatching_lines:
line_inds, line = ml
self.details += 'From lines {} to {}:\n'.format(*line_inds)
for k, v in line.items():
self.details += '({}, {} words) '.format(k, len(v))
self.details += ' '.join(str(x) for x in v) + '\n'
class ILGLinesMismatchError(ParseError):
"""
Exception for when the number of lines in a interlinear gloss file
is not a multiple of the number of types of lines.
Parameters
----------
lines : list
List of the lines in the interlinear gloss file
"""
def __init__(self, lines):
self.main = "There doesn't appear to be equal numbers of orthography and transcription lines"
self.information = ''
self.details = 'The following is the contents of the file after initial preprocessing:\n\n'
for line in lines:
if isinstance(line, tuple):
self.details += '{}: {}\n'.format(*line)
else:
self.details += str(line) + '\n'
class TextGridError(ParseError):
"""
Exception class for parsing TextGrids
"""
pass
class TextGridTierError(TextGridError):
"""
Exception for when a specified tier was not found in a TextGrid.
Parameters
----------
tier_type : str
The type of tier looked for (such as spelling or transcription)
tier_name : str
The name of the tier specified
tiers : list
List of tiers in the TextGrid that were inspected
"""
def __init__(self, tier_type, tier_name, tiers):
self.main = 'The {} tier name was not found'.format(tier_type)
self.information = 'The tier name \'{}\' was not found in any tiers'.format(tier_name)
self.details = 'The tier name looked for (ignoring case) was \'{}\'.\n'.format(tier_name)
self.details += 'The following tiers were found:\n\n'
for t in tiers:
self.details += '{}\n'.format(t.name)
class BuckeyeParseError(ParseError):
"""
Exception class for parsing Buckeye formatted files
"""
def __init__(self, path, misparsed_lines):
if len(misparsed_lines) == 1:
self.main = 'One line in \'{}\' was not parsed correctly.'.format(path)
else:
self.main = '{} lines in \'{}\' were not parsed correctly.'.format(len(misparsed_lines), path)
self.information = 'The lines did not have enough fields to be parsed correctly.'
self.details = 'The following lines were missing entries:\n\n'
for t in misparsed_lines:
self.details += '{}\n'.format(t)
self.value = '\n'.join([self.main, self.details])
# Acoustic exceptions
class AcousticError(PGError):
"""
Exception class for errors in acoustic processing
"""
pass
class NoSoundFileError(AcousticError):
"""
Exception class for when no sound file exists
"""
pass
class GraphQueryError(PGError):
"""
Exception class for errors in querying the Neo4j database
"""
pass
class CorpusConfigError(PGError):
"""
Exception class for misconfigured CorpusContext objects
"""
pass
class SubannotationError(PGError):
"""
Exception class for subannotations
"""
pass
class GraphModelError(PGError):
"""
Exception class for generating Python objects from Neo4j queries
"""
pass
class ConnectionError(PGError):
"""
Exception class for connection failures
"""
pass
class AuthorizationError(PGError):
"""
Exception class for authentication failures
"""
pass
class NetworkAddressError(PGError):
"""
Exception class for malformed network addresses
"""
pass
class TemporaryConnectionError(PGError):
"""
Exception class for transient connection errors
"""
pass
class SubsetError(PGError):
"""
Exception class for not finding a specified subset
"""
pass
class HierarchyError(PGError):
"""
Exception class for Hierarchy errors
"""
pass
class ClientError(PGError):
"""
Exception class for connecting to remote/local ISCAN servers
"""
pass
class NodeAttributeError(GraphQueryError):
"""
Exception class for errors in attributes for base nodes in constructing queries
"""
pass
class SpeakerAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for speakers in constructing queries
"""
pass
class DiscourseAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for discourses in constructing queries
"""
pass
class AnnotationAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for annotations in constructing queries
"""
pass
class LexiconAttributeError(NodeAttributeError):
"""
Exception class for errors in attributes for type annotations in constructing queries
"""
pass | class PGError(Exception):
""" | random_line_split |
mod.rs | use memory::PAGE_SIZE;
// use memory::frame::Frame;
use memory::alloc::FrameAlloc;
pub const PRESENT: u64 = 1 << 0;
pub const WRITABLE: u64 = 1 << 1;
pub const USER_ACCESSIBLE: u64 = 1 << 2;
pub const WRITE_THROUGH_CACHING: u64 = 1 << 3;
pub const DISABLE_CACHE: u64 = 1 << 4;
pub const ACCESSED: u64 = 1 << 5;
pub const DIRTY: u64 = 1 << 6;
pub const HUGE: u64 = 1 << 7;
pub const GLOBAL: u64 = 1 << 8;
pub const NO_EXECUTE: u64 = 1 << 63;
pub const NO_FLAGS: u64 = 0o1777777777777777770000;
pub const ENTRY_COUNT: u64 = 512;
pub const ENTRY_SIZE: u64 = 8;
pub const P4: u64 = 0o1777777777777777770000;
pub struct Page {
number: u64,
}
impl Page {
pub fn new(number: u64) -> Self {
Page { number: number }
}
pub fn virt_addr(&self) -> u64 {
self.number * PAGE_SIZE
}
/// Returns index of page in P4 table
pub fn p4_index(&self) -> u64 {
(self.number >> 27) & 0o777
}
/// Returns index of page in P3 table
pub fn p3_index(&self) -> u64 {
(self.number >> 18) & 0o777
}
/// Returns index of page in P2 table
pub fn p2_index(&self) -> u64 {
(self.number >> 9) & 0o777
}
/// Returns index of page in P1 table
pub fn p1_index(&self) -> u64 {
self.number & 0o777
}
fn get_table(address: u64, index: isize) -> u64 {
unsafe { *(address as *mut u64).offset(index) }
}
fn get_table_mut(address: u64, index: isize) -> *mut u64 {
unsafe { (address as *mut u64).offset(index) } |
/// Tests if next table exists and allocates a new one if not
fn create_next_table<T: FrameAlloc>(allocator: &mut T, address: u64, index: isize) -> u64 {
let mut entry = Page::get_table(address, index);
if (entry & PRESENT) != 0 {
} else {
let frame = allocator.alloc();
unsafe {
*Page::get_table_mut(address, index) = (frame.unwrap().number * PAGE_SIZE) |
PRESENT |
WRITABLE;
}
entry = Page::get_table(address, index);
}
entry
}
/// Sets a page in a PT
fn create_page(physical_addr: u64, flags: u64, address: u64, index: isize) {
unsafe {
*Page::get_table_mut(address, index) = (physical_addr * PAGE_SIZE) | flags;
}
}
/// Create page tables and allocate page
///
/// This function walks through the page tables. If the next table is present, it jumps
/// to it and continues. Otherwise, it allocates a frame and writes its address to the entry.
/// Once it is done, it allocates the actual frame.
pub fn map_page<T: FrameAlloc>(&self, address: u64, allocator: &mut T) {
// Entry in P4 (P3 location)
let p4_entry = Page::create_next_table(allocator, P4, self.p4_index() as isize);
// Entry in P3 (P2 location)
let p3_entry = Page::create_next_table(allocator,
p4_entry & NO_FLAGS,
self.p3_index() as isize);
// Entry in P2 (P1 location)
let p2_entry = Page::create_next_table(allocator,
p3_entry & NO_FLAGS,
self.p2_index() as isize);
// Entry in P1 (Page or P0 location)
Page::create_page(address,
(PRESENT | WRITABLE),
p2_entry & NO_FLAGS,
self.p1_index() as isize);
}
} | } | random_line_split |
mod.rs | use memory::PAGE_SIZE;
// use memory::frame::Frame;
use memory::alloc::FrameAlloc;
pub const PRESENT: u64 = 1 << 0;
pub const WRITABLE: u64 = 1 << 1;
pub const USER_ACCESSIBLE: u64 = 1 << 2;
pub const WRITE_THROUGH_CACHING: u64 = 1 << 3;
pub const DISABLE_CACHE: u64 = 1 << 4;
pub const ACCESSED: u64 = 1 << 5;
pub const DIRTY: u64 = 1 << 6;
pub const HUGE: u64 = 1 << 7;
pub const GLOBAL: u64 = 1 << 8;
pub const NO_EXECUTE: u64 = 1 << 63;
pub const NO_FLAGS: u64 = 0o1777777777777777770000;
pub const ENTRY_COUNT: u64 = 512;
pub const ENTRY_SIZE: u64 = 8;
pub const P4: u64 = 0o1777777777777777770000;
pub struct Page {
number: u64,
}
impl Page {
pub fn new(number: u64) -> Self {
Page { number: number }
}
pub fn virt_addr(&self) -> u64 {
self.number * PAGE_SIZE
}
/// Returns index of page in P4 table
pub fn p4_index(&self) -> u64 {
(self.number >> 27) & 0o777
}
/// Returns index of page in P3 table
pub fn p3_index(&self) -> u64 {
(self.number >> 18) & 0o777
}
/// Returns index of page in P2 table
pub fn p2_index(&self) -> u64 {
(self.number >> 9) & 0o777
}
/// Returns index of page in P1 table
pub fn p1_index(&self) -> u64 {
self.number & 0o777
}
fn get_table(address: u64, index: isize) -> u64 {
unsafe { *(address as *mut u64).offset(index) }
}
fn get_table_mut(address: u64, index: isize) -> *mut u64 {
unsafe { (address as *mut u64).offset(index) }
}
/// Tests if next table exists and allocates a new one if not
fn create_next_table<T: FrameAlloc>(allocator: &mut T, address: u64, index: isize) -> u64 {
let mut entry = Page::get_table(address, index);
if (entry & PRESENT) != 0 | else {
let frame = allocator.alloc();
unsafe {
*Page::get_table_mut(address, index) = (frame.unwrap().number * PAGE_SIZE) |
PRESENT |
WRITABLE;
}
entry = Page::get_table(address, index);
}
entry
}
/// Sets a page in a PT
fn create_page(physical_addr: u64, flags: u64, address: u64, index: isize) {
unsafe {
*Page::get_table_mut(address, index) = (physical_addr * PAGE_SIZE) | flags;
}
}
/// Create page tables and allocate page
///
/// This function walks through the page tables. If the next table is present, it jumps
/// to it and continues. Otherwise, it allocates a frame and writes its address to the entry.
/// Once it is done, it allocates the actual frame.
pub fn map_page<T: FrameAlloc>(&self, address: u64, allocator: &mut T) {
// Entry in P4 (P3 location)
let p4_entry = Page::create_next_table(allocator, P4, self.p4_index() as isize);
// Entry in P3 (P2 location)
let p3_entry = Page::create_next_table(allocator,
p4_entry & NO_FLAGS,
self.p3_index() as isize);
// Entry in P2 (P1 location)
let p2_entry = Page::create_next_table(allocator,
p3_entry & NO_FLAGS,
self.p2_index() as isize);
// Entry in P1 (Page or P0 location)
Page::create_page(address,
(PRESENT | WRITABLE),
p2_entry & NO_FLAGS,
self.p1_index() as isize);
}
}
| {
} | conditional_block |
mod.rs | use memory::PAGE_SIZE;
// use memory::frame::Frame;
use memory::alloc::FrameAlloc;
pub const PRESENT: u64 = 1 << 0;
pub const WRITABLE: u64 = 1 << 1;
pub const USER_ACCESSIBLE: u64 = 1 << 2;
pub const WRITE_THROUGH_CACHING: u64 = 1 << 3;
pub const DISABLE_CACHE: u64 = 1 << 4;
pub const ACCESSED: u64 = 1 << 5;
pub const DIRTY: u64 = 1 << 6;
pub const HUGE: u64 = 1 << 7;
pub const GLOBAL: u64 = 1 << 8;
pub const NO_EXECUTE: u64 = 1 << 63;
pub const NO_FLAGS: u64 = 0o1777777777777777770000;
pub const ENTRY_COUNT: u64 = 512;
pub const ENTRY_SIZE: u64 = 8;
pub const P4: u64 = 0o1777777777777777770000;
pub struct Page {
number: u64,
}
impl Page {
pub fn new(number: u64) -> Self {
Page { number: number }
}
pub fn virt_addr(&self) -> u64 {
self.number * PAGE_SIZE
}
/// Returns index of page in P4 table
pub fn p4_index(&self) -> u64 {
(self.number >> 27) & 0o777
}
/// Returns index of page in P3 table
pub fn p3_index(&self) -> u64 {
(self.number >> 18) & 0o777
}
/// Returns index of page in P2 table
pub fn p2_index(&self) -> u64 {
(self.number >> 9) & 0o777
}
/// Returns index of page in P1 table
pub fn p1_index(&self) -> u64 {
self.number & 0o777
}
fn get_table(address: u64, index: isize) -> u64 {
unsafe { *(address as *mut u64).offset(index) }
}
fn get_table_mut(address: u64, index: isize) -> *mut u64 {
unsafe { (address as *mut u64).offset(index) }
}
/// Tests if next table exists and allocates a new one if not
fn create_next_table<T: FrameAlloc>(allocator: &mut T, address: u64, index: isize) -> u64 {
let mut entry = Page::get_table(address, index);
if (entry & PRESENT) != 0 {
} else {
let frame = allocator.alloc();
unsafe {
*Page::get_table_mut(address, index) = (frame.unwrap().number * PAGE_SIZE) |
PRESENT |
WRITABLE;
}
entry = Page::get_table(address, index);
}
entry
}
/// Sets a page in a PT
fn create_page(physical_addr: u64, flags: u64, address: u64, index: isize) {
unsafe {
*Page::get_table_mut(address, index) = (physical_addr * PAGE_SIZE) | flags;
}
}
/// Create page tables and allocate page
///
/// This function walks through the page tables. If the next table is present, it jumps
/// to it and continues. Otherwise, it allocates a frame and writes its address to the entry.
/// Once it is done, it allocates the actual frame.
pub fn map_page<T: FrameAlloc>(&self, address: u64, allocator: &mut T) |
}
| {
// Entry in P4 (P3 location)
let p4_entry = Page::create_next_table(allocator, P4, self.p4_index() as isize);
// Entry in P3 (P2 location)
let p3_entry = Page::create_next_table(allocator,
p4_entry & NO_FLAGS,
self.p3_index() as isize);
// Entry in P2 (P1 location)
let p2_entry = Page::create_next_table(allocator,
p3_entry & NO_FLAGS,
self.p2_index() as isize);
// Entry in P1 (Page or P0 location)
Page::create_page(address,
(PRESENT | WRITABLE),
p2_entry & NO_FLAGS,
self.p1_index() as isize);
} | identifier_body |
mod.rs | use memory::PAGE_SIZE;
// use memory::frame::Frame;
use memory::alloc::FrameAlloc;
pub const PRESENT: u64 = 1 << 0;
pub const WRITABLE: u64 = 1 << 1;
pub const USER_ACCESSIBLE: u64 = 1 << 2;
pub const WRITE_THROUGH_CACHING: u64 = 1 << 3;
pub const DISABLE_CACHE: u64 = 1 << 4;
pub const ACCESSED: u64 = 1 << 5;
pub const DIRTY: u64 = 1 << 6;
pub const HUGE: u64 = 1 << 7;
pub const GLOBAL: u64 = 1 << 8;
pub const NO_EXECUTE: u64 = 1 << 63;
pub const NO_FLAGS: u64 = 0o1777777777777777770000;
pub const ENTRY_COUNT: u64 = 512;
pub const ENTRY_SIZE: u64 = 8;
pub const P4: u64 = 0o1777777777777777770000;
pub struct Page {
number: u64,
}
impl Page {
pub fn new(number: u64) -> Self {
Page { number: number }
}
pub fn virt_addr(&self) -> u64 {
self.number * PAGE_SIZE
}
/// Returns index of page in P4 table
pub fn p4_index(&self) -> u64 {
(self.number >> 27) & 0o777
}
/// Returns index of page in P3 table
pub fn p3_index(&self) -> u64 {
(self.number >> 18) & 0o777
}
/// Returns index of page in P2 table
pub fn p2_index(&self) -> u64 {
(self.number >> 9) & 0o777
}
/// Returns index of page in P1 table
pub fn p1_index(&self) -> u64 {
self.number & 0o777
}
fn get_table(address: u64, index: isize) -> u64 {
unsafe { *(address as *mut u64).offset(index) }
}
fn get_table_mut(address: u64, index: isize) -> *mut u64 {
unsafe { (address as *mut u64).offset(index) }
}
/// Tests if next table exists and allocates a new one if not
fn create_next_table<T: FrameAlloc>(allocator: &mut T, address: u64, index: isize) -> u64 {
let mut entry = Page::get_table(address, index);
if (entry & PRESENT) != 0 {
} else {
let frame = allocator.alloc();
unsafe {
*Page::get_table_mut(address, index) = (frame.unwrap().number * PAGE_SIZE) |
PRESENT |
WRITABLE;
}
entry = Page::get_table(address, index);
}
entry
}
/// Sets a page in a PT
fn | (physical_addr: u64, flags: u64, address: u64, index: isize) {
unsafe {
*Page::get_table_mut(address, index) = (physical_addr * PAGE_SIZE) | flags;
}
}
/// Create page tables and allocate page
///
/// This function walks through the page tables. If the next table is present, it jumps
/// to it and continues. Otherwise, it allocates a frame and writes its address to the entry.
/// Once it is done, it allocates the actual frame.
pub fn map_page<T: FrameAlloc>(&self, address: u64, allocator: &mut T) {
// Entry in P4 (P3 location)
let p4_entry = Page::create_next_table(allocator, P4, self.p4_index() as isize);
// Entry in P3 (P2 location)
let p3_entry = Page::create_next_table(allocator,
p4_entry & NO_FLAGS,
self.p3_index() as isize);
// Entry in P2 (P1 location)
let p2_entry = Page::create_next_table(allocator,
p3_entry & NO_FLAGS,
self.p2_index() as isize);
// Entry in P1 (Page or P0 location)
Page::create_page(address,
(PRESENT | WRITABLE),
p2_entry & NO_FLAGS,
self.p1_index() as isize);
}
}
| create_page | identifier_name |
shared.py | # Copyright (C) 2014 - 2020 Eaton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#! \file shared.py
# \brief shared routines for CI tests written in python
# \author Michal Vyskocil <MichalVyskocil@Eaton.com>
import MySQLdb
def parse_ip_a_s(out):
"""
parse output of command ip a(ddr) s(how)
return - list of tuple (name, ipver, ipaddr, prefixlen: int, mac)
"""
state = "start"
header = list()
ret = list()
for line in out.split('\n'):
if line and line[0] != ' ':
state = "start"
header = list()
if not "state UP" in line:
continue
header = list()
nic_name = line.split(':')[1].strip()
header.append(nic_name)
state = "read-mac"
continue
# skip entries for 'lo'
if state == "start" and not header:
continue
if line.startswith(" link/"): | mac = line.split()[1]
except IndexError as e:
print(line)
print(e)
header.append(mac)
elif line.startswith(" inet"):
name, mac = header
ipver, ipaddr = line.split()[:2]
ipaddr, prefixlen = ipaddr.split('/')
ret.append((name, ipver, ipaddr, int(prefixlen), mac))
return ret
def connect_to_db():
return MySQLdb.connect(host="localhost", user="root", db="box_utf8") | try: | random_line_split |
shared.py | # Copyright (C) 2014 - 2020 Eaton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#! \file shared.py
# \brief shared routines for CI tests written in python
# \author Michal Vyskocil <MichalVyskocil@Eaton.com>
import MySQLdb
def parse_ip_a_s(out):
|
def connect_to_db():
return MySQLdb.connect(host="localhost", user="root", db="box_utf8")
| """
parse output of command ip a(ddr) s(how)
return - list of tuple (name, ipver, ipaddr, prefixlen: int, mac)
"""
state = "start"
header = list()
ret = list()
for line in out.split('\n'):
if line and line[0] != ' ':
state = "start"
header = list()
if not "state UP" in line:
continue
header = list()
nic_name = line.split(':')[1].strip()
header.append(nic_name)
state = "read-mac"
continue
# skip entries for 'lo'
if state == "start" and not header:
continue
if line.startswith(" link/"):
try:
mac = line.split()[1]
except IndexError as e:
print(line)
print(e)
header.append(mac)
elif line.startswith(" inet"):
name, mac = header
ipver, ipaddr = line.split()[:2]
ipaddr, prefixlen = ipaddr.split('/')
ret.append((name, ipver, ipaddr, int(prefixlen), mac))
return ret | identifier_body |
shared.py | # Copyright (C) 2014 - 2020 Eaton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#! \file shared.py
# \brief shared routines for CI tests written in python
# \author Michal Vyskocil <MichalVyskocil@Eaton.com>
import MySQLdb
def parse_ip_a_s(out):
"""
parse output of command ip a(ddr) s(how)
return - list of tuple (name, ipver, ipaddr, prefixlen: int, mac)
"""
state = "start"
header = list()
ret = list()
for line in out.split('\n'):
if line and line[0] != ' ':
state = "start"
header = list()
if not "state UP" in line:
continue
header = list()
nic_name = line.split(':')[1].strip()
header.append(nic_name)
state = "read-mac"
continue
# skip entries for 'lo'
if state == "start" and not header:
continue
if line.startswith(" link/"):
try:
mac = line.split()[1]
except IndexError as e:
print(line)
print(e)
header.append(mac)
elif line.startswith(" inet"):
name, mac = header
ipver, ipaddr = line.split()[:2]
ipaddr, prefixlen = ipaddr.split('/')
ret.append((name, ipver, ipaddr, int(prefixlen), mac))
return ret
def | ():
return MySQLdb.connect(host="localhost", user="root", db="box_utf8")
| connect_to_db | identifier_name |
shared.py | # Copyright (C) 2014 - 2020 Eaton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#! \file shared.py
# \brief shared routines for CI tests written in python
# \author Michal Vyskocil <MichalVyskocil@Eaton.com>
import MySQLdb
def parse_ip_a_s(out):
"""
parse output of command ip a(ddr) s(how)
return - list of tuple (name, ipver, ipaddr, prefixlen: int, mac)
"""
state = "start"
header = list()
ret = list()
for line in out.split('\n'):
if line and line[0] != ' ':
state = "start"
header = list()
if not "state UP" in line:
|
header = list()
nic_name = line.split(':')[1].strip()
header.append(nic_name)
state = "read-mac"
continue
# skip entries for 'lo'
if state == "start" and not header:
continue
if line.startswith(" link/"):
try:
mac = line.split()[1]
except IndexError as e:
print(line)
print(e)
header.append(mac)
elif line.startswith(" inet"):
name, mac = header
ipver, ipaddr = line.split()[:2]
ipaddr, prefixlen = ipaddr.split('/')
ret.append((name, ipver, ipaddr, int(prefixlen), mac))
return ret
def connect_to_db():
return MySQLdb.connect(host="localhost", user="root", db="box_utf8")
| continue | conditional_block |
utils.js | /*!
* Jade - utils
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Convert interpolation in the given string to JavaScript.
*
* @param {String} str
* @return {String}
* @api private
*/
var interpolate = exports.interpolate = function(str){
return str.replace(/(\\)?([#!]){(.*?)}/g, function(str, escape, flag, code){
return escape
? str.slice(1)
: "' + "
+ ('!' == flag ? '' : 'escape')
+ "((interp = " + code.replace(/\\'/g, "'")
+ ") == null ? '' : interp) + '";
});
};
/**
* Escape single quotes in `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
var escape = exports.escape = function(str) {
return str.replace(/'/g, "\\'");
};
/**
* Interpolate, and escape the given `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
exports.text = function(str){
return interpolate(escape(str));
};
/**
* Merge `b` into `a`.
*
* @param {Object} a
* @param {Object} b
* @return {Object}
* @api public | exports.merge = function(a, b) {
for (var key in b) a[key] = b[key];
return a;
}; | */
| random_line_split |
admin.py | from django.contrib import admin
from achievs.models import Achievement
# from achievs.models import Gold
# from achievs.models import Silver
# from achievs.models import Bronze
# from achievs.models import Platinum | # class PlatinumInline(admin.StackedInline):
# model=Platinum
# class GoldInline(admin.StackedInline):
# model=Gold
# class SilverInline(admin.StackedInline):
# model=Silver
# class BronzeInline(admin.StackedInline):
# model=Bronze
class LevelInline(admin.StackedInline):
model=Level
class AchievementAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['name']}),
('Date information', {'fields': ['pub_date']}),
]
#inlines=[GoldInline, SilverInline, BronzeInline, PlatinumInline]
inlines=[LevelInline]
list_display = ('name', 'pub_date')
list_filter=['pub_date']
search_fields=['name']
date_hierarchy='pub_date'
# admin.site.register(Gold)
# admin.site.register(Silver)
# admin.site.register(Bronze)
# admin.site.register(Platinum)
admin.site.register(Level)
admin.site.register(Achievement, AchievementAdmin) | from achievs.models import Level
| random_line_split |
admin.py | from django.contrib import admin
from achievs.models import Achievement
# from achievs.models import Gold
# from achievs.models import Silver
# from achievs.models import Bronze
# from achievs.models import Platinum
from achievs.models import Level
# class PlatinumInline(admin.StackedInline):
# model=Platinum
# class GoldInline(admin.StackedInline):
# model=Gold
# class SilverInline(admin.StackedInline):
# model=Silver
# class BronzeInline(admin.StackedInline):
# model=Bronze
class LevelInline(admin.StackedInline):
model=Level
class | (admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['name']}),
('Date information', {'fields': ['pub_date']}),
]
#inlines=[GoldInline, SilverInline, BronzeInline, PlatinumInline]
inlines=[LevelInline]
list_display = ('name', 'pub_date')
list_filter=['pub_date']
search_fields=['name']
date_hierarchy='pub_date'
# admin.site.register(Gold)
# admin.site.register(Silver)
# admin.site.register(Bronze)
# admin.site.register(Platinum)
admin.site.register(Level)
admin.site.register(Achievement, AchievementAdmin) | AchievementAdmin | identifier_name |
admin.py | from django.contrib import admin
from achievs.models import Achievement
# from achievs.models import Gold
# from achievs.models import Silver
# from achievs.models import Bronze
# from achievs.models import Platinum
from achievs.models import Level
# class PlatinumInline(admin.StackedInline):
# model=Platinum
# class GoldInline(admin.StackedInline):
# model=Gold
# class SilverInline(admin.StackedInline):
# model=Silver
# class BronzeInline(admin.StackedInline):
# model=Bronze
class LevelInline(admin.StackedInline):
model=Level
class AchievementAdmin(admin.ModelAdmin):
|
# admin.site.register(Gold)
# admin.site.register(Silver)
# admin.site.register(Bronze)
# admin.site.register(Platinum)
admin.site.register(Level)
admin.site.register(Achievement, AchievementAdmin) | fieldsets = [
(None, {'fields': ['name']}),
('Date information', {'fields': ['pub_date']}),
]
#inlines=[GoldInline, SilverInline, BronzeInline, PlatinumInline]
inlines=[LevelInline]
list_display = ('name', 'pub_date')
list_filter=['pub_date']
search_fields=['name']
date_hierarchy='pub_date' | identifier_body |
threatfox.py | import logging
from datetime import timedelta
from core import Feed
import pandas as pd
from core.observables import Ip, Observable
from core.errors import ObservableValidationError
class ThreatFox(Feed):
default_values = {
"frequency": timedelta(hours=1),
"name": "ThreatFox",
"source": "https://threatfox.abuse.ch/export/json/recent/",
"description": "Feed ThreatFox by Abuse.ch",
}
def update(self):
for index, line in self.update_json():
self.analyze(line)
def update_json(self):
|
def analyze(self, item):
first_seen = item["first_seen_utc"]
ioc_value = item["ioc_value"]
ioc_type = item["ioc_type"]
threat_type = item["threat_type"]
malware_alias = item["malware_alias"]
malware_printable = item["malware_printable"]
last_seen_utc = item["last_seen_utc"]
confidence_level = item["confidence_level"]
reference = item["reference"]
reporter = item["reporter"]
tags = []
context = {"source": self.name}
context["first_seen"] = first_seen
if reference:
context["reference"] = reference
else:
context["reference"] = "Unknown"
if reporter:
context["reporter"] = reporter
else:
context["reporter"] = "Unknown"
if threat_type:
context["threat_type"] = threat_type
if item["tags"]:
tags.extend(item["tags"].split(","))
if malware_printable:
tags.append(malware_printable)
if malware_alias:
context["malware_alias"] = malware_alias
if last_seen_utc:
context["last_seen_utc"] = last_seen_utc
if confidence_level:
context["confidence_level"] = confidence_level
value = None
obs = None
try:
if "ip" in ioc_type:
value, port = ioc_value.split(":")
context["port"] = port
obs = Ip.get_or_create(value=value)
else:
obs = Observable.add_text(ioc_value)
except ObservableValidationError as e:
logging.error(e)
return
if obs:
obs.add_context(context)
obs.add_source(self.name)
if tags:
obs.tag(tags)
if malware_printable:
obs.tags
| r = self._make_request(sort=False)
if r:
res = r.json()
values = [r[0] for r in res.values()]
df = pd.DataFrame(values)
df["first_seen_utc"] = pd.to_datetime(df["first_seen_utc"])
df["last_seen_utc"] = pd.to_datetime(df["last_seen_utc"])
if self.last_run:
df = df[df["first_seen_utc"] > self.last_run]
df.fillna("-", inplace=True)
return df.iterrows() | identifier_body |
threatfox.py | import logging
from datetime import timedelta
from core import Feed
import pandas as pd
from core.observables import Ip, Observable
from core.errors import ObservableValidationError
class | (Feed):
default_values = {
"frequency": timedelta(hours=1),
"name": "ThreatFox",
"source": "https://threatfox.abuse.ch/export/json/recent/",
"description": "Feed ThreatFox by Abuse.ch",
}
def update(self):
for index, line in self.update_json():
self.analyze(line)
def update_json(self):
r = self._make_request(sort=False)
if r:
res = r.json()
values = [r[0] for r in res.values()]
df = pd.DataFrame(values)
df["first_seen_utc"] = pd.to_datetime(df["first_seen_utc"])
df["last_seen_utc"] = pd.to_datetime(df["last_seen_utc"])
if self.last_run:
df = df[df["first_seen_utc"] > self.last_run]
df.fillna("-", inplace=True)
return df.iterrows()
def analyze(self, item):
first_seen = item["first_seen_utc"]
ioc_value = item["ioc_value"]
ioc_type = item["ioc_type"]
threat_type = item["threat_type"]
malware_alias = item["malware_alias"]
malware_printable = item["malware_printable"]
last_seen_utc = item["last_seen_utc"]
confidence_level = item["confidence_level"]
reference = item["reference"]
reporter = item["reporter"]
tags = []
context = {"source": self.name}
context["first_seen"] = first_seen
if reference:
context["reference"] = reference
else:
context["reference"] = "Unknown"
if reporter:
context["reporter"] = reporter
else:
context["reporter"] = "Unknown"
if threat_type:
context["threat_type"] = threat_type
if item["tags"]:
tags.extend(item["tags"].split(","))
if malware_printable:
tags.append(malware_printable)
if malware_alias:
context["malware_alias"] = malware_alias
if last_seen_utc:
context["last_seen_utc"] = last_seen_utc
if confidence_level:
context["confidence_level"] = confidence_level
value = None
obs = None
try:
if "ip" in ioc_type:
value, port = ioc_value.split(":")
context["port"] = port
obs = Ip.get_or_create(value=value)
else:
obs = Observable.add_text(ioc_value)
except ObservableValidationError as e:
logging.error(e)
return
if obs:
obs.add_context(context)
obs.add_source(self.name)
if tags:
obs.tag(tags)
if malware_printable:
obs.tags
| ThreatFox | identifier_name |
threatfox.py | import logging
from datetime import timedelta
from core import Feed
import pandas as pd
from core.observables import Ip, Observable
from core.errors import ObservableValidationError
class ThreatFox(Feed):
default_values = {
"frequency": timedelta(hours=1),
"name": "ThreatFox",
"source": "https://threatfox.abuse.ch/export/json/recent/",
"description": "Feed ThreatFox by Abuse.ch",
}
def update(self):
for index, line in self.update_json():
self.analyze(line)
def update_json(self):
r = self._make_request(sort=False)
if r:
res = r.json()
values = [r[0] for r in res.values()]
df = pd.DataFrame(values)
df["first_seen_utc"] = pd.to_datetime(df["first_seen_utc"])
df["last_seen_utc"] = pd.to_datetime(df["last_seen_utc"])
if self.last_run:
df = df[df["first_seen_utc"] > self.last_run]
df.fillna("-", inplace=True)
return df.iterrows()
def analyze(self, item):
first_seen = item["first_seen_utc"]
ioc_value = item["ioc_value"]
ioc_type = item["ioc_type"]
threat_type = item["threat_type"]
malware_alias = item["malware_alias"]
malware_printable = item["malware_printable"]
last_seen_utc = item["last_seen_utc"]
confidence_level = item["confidence_level"]
reference = item["reference"]
reporter = item["reporter"]
tags = []
context = {"source": self.name}
context["first_seen"] = first_seen
if reference:
context["reference"] = reference
else:
context["reference"] = "Unknown"
if reporter:
context["reporter"] = reporter
else:
context["reporter"] = "Unknown"
if threat_type:
context["threat_type"] = threat_type
if item["tags"]:
tags.extend(item["tags"].split(","))
if malware_printable:
tags.append(malware_printable)
if malware_alias:
context["malware_alias"] = malware_alias
if last_seen_utc:
context["last_seen_utc"] = last_seen_utc
if confidence_level:
context["confidence_level"] = confidence_level
value = None
obs = None
try:
if "ip" in ioc_type:
value, port = ioc_value.split(":")
context["port"] = port
obs = Ip.get_or_create(value=value)
else:
|
except ObservableValidationError as e:
logging.error(e)
return
if obs:
obs.add_context(context)
obs.add_source(self.name)
if tags:
obs.tag(tags)
if malware_printable:
obs.tags
| obs = Observable.add_text(ioc_value) | conditional_block |
threatfox.py | import logging
from datetime import timedelta
from core import Feed
import pandas as pd
from core.observables import Ip, Observable
from core.errors import ObservableValidationError
class ThreatFox(Feed):
default_values = {
"frequency": timedelta(hours=1),
"name": "ThreatFox",
"source": "https://threatfox.abuse.ch/export/json/recent/",
"description": "Feed ThreatFox by Abuse.ch",
}
def update(self):
for index, line in self.update_json():
self.analyze(line)
| if r:
res = r.json()
values = [r[0] for r in res.values()]
df = pd.DataFrame(values)
df["first_seen_utc"] = pd.to_datetime(df["first_seen_utc"])
df["last_seen_utc"] = pd.to_datetime(df["last_seen_utc"])
if self.last_run:
df = df[df["first_seen_utc"] > self.last_run]
df.fillna("-", inplace=True)
return df.iterrows()
def analyze(self, item):
first_seen = item["first_seen_utc"]
ioc_value = item["ioc_value"]
ioc_type = item["ioc_type"]
threat_type = item["threat_type"]
malware_alias = item["malware_alias"]
malware_printable = item["malware_printable"]
last_seen_utc = item["last_seen_utc"]
confidence_level = item["confidence_level"]
reference = item["reference"]
reporter = item["reporter"]
tags = []
context = {"source": self.name}
context["first_seen"] = first_seen
if reference:
context["reference"] = reference
else:
context["reference"] = "Unknown"
if reporter:
context["reporter"] = reporter
else:
context["reporter"] = "Unknown"
if threat_type:
context["threat_type"] = threat_type
if item["tags"]:
tags.extend(item["tags"].split(","))
if malware_printable:
tags.append(malware_printable)
if malware_alias:
context["malware_alias"] = malware_alias
if last_seen_utc:
context["last_seen_utc"] = last_seen_utc
if confidence_level:
context["confidence_level"] = confidence_level
value = None
obs = None
try:
if "ip" in ioc_type:
value, port = ioc_value.split(":")
context["port"] = port
obs = Ip.get_or_create(value=value)
else:
obs = Observable.add_text(ioc_value)
except ObservableValidationError as e:
logging.error(e)
return
if obs:
obs.add_context(context)
obs.add_source(self.name)
if tags:
obs.tag(tags)
if malware_printable:
obs.tags | def update_json(self):
r = self._make_request(sort=False)
| random_line_split |
info.py | from pygametk.color import Color
from pygametk.draw import crop
from pygametk.geometry import Rect
from pygametk.image import load_image
from pylaunchr.builder.factory import DialogFactory
from pylaunchr.builder.path import module_relative_path
from ..data import MpdPlayerStatusListener
from ..utils import get_player_status
class InfoDialogUpdater(MpdPlayerStatusListener):
def __init__(self, dialog, context):
self.status = get_player_status(context)
self.coverfetcher = context.services["coverfetcher"].handler
self.imagefilter = context.services["imagefilter"].handler
self.dialog = dialog
self.dialog.connect("dialog-finished", self._finish_dialog)
def _update_background_image(self, image, current):
def blur_callback(result, song):
if "image" in result and self.status.current == song:
shade = Color(0, 0, 0, 230)
self.dialog.set_background_image(result["image"], shade)
image_rect = Rect((0, 0), image.get_size())
screen_rect = Rect((0, 0), self.dialog.size)
cropped = crop(image, screen_rect.fit(image_rect))
self.imagefilter.blur(cropped, 15, blur_callback, [current])
| def _fetch_image(self, current):
albuminfo = {
"artist": current.albumartist,
"album": current.album,
"file": current.file
}
def callback(result, song):
if "filename" in result and self.status.current == song:
image = load_image(result["filename"])
self._update_background_image(image, song)
image_holder = self.dialog.get_widget("image")
image_holder.set(image)
self.coverfetcher.fetch(albuminfo, callback, [current])
def _clear_image(self):
self.dialog.get_widget("image").clear()
self.dialog.set_background_color(Color(0, 0, 0))
def _update(self):
if self.status.has_current_song():
self._fetch_image(self.status.current)
else:
self.dialog.cancel()
def init(self):
self.status.add_listener(self)
self._update()
def current_changed(self, mpd_status, current):
self._update()
def _finish_dialog(self):
self.status.remove_listener(self)
class MpdInfoDialogFactory(DialogFactory):
def create(self, element, widget_registry):
path = module_relative_path("info.xml")
dialog = self.context.dialog_registry.dialog_from_file(path)
updater = InfoDialogUpdater(dialog, self.context)
dialog.connect("dialog-started", updater.init)
return dialog | random_line_split | |
info.py | from pygametk.color import Color
from pygametk.draw import crop
from pygametk.geometry import Rect
from pygametk.image import load_image
from pylaunchr.builder.factory import DialogFactory
from pylaunchr.builder.path import module_relative_path
from ..data import MpdPlayerStatusListener
from ..utils import get_player_status
class InfoDialogUpdater(MpdPlayerStatusListener):
def __init__(self, dialog, context):
self.status = get_player_status(context)
self.coverfetcher = context.services["coverfetcher"].handler
self.imagefilter = context.services["imagefilter"].handler
self.dialog = dialog
self.dialog.connect("dialog-finished", self._finish_dialog)
def | (self, image, current):
def blur_callback(result, song):
if "image" in result and self.status.current == song:
shade = Color(0, 0, 0, 230)
self.dialog.set_background_image(result["image"], shade)
image_rect = Rect((0, 0), image.get_size())
screen_rect = Rect((0, 0), self.dialog.size)
cropped = crop(image, screen_rect.fit(image_rect))
self.imagefilter.blur(cropped, 15, blur_callback, [current])
def _fetch_image(self, current):
albuminfo = {
"artist": current.albumartist,
"album": current.album,
"file": current.file
}
def callback(result, song):
if "filename" in result and self.status.current == song:
image = load_image(result["filename"])
self._update_background_image(image, song)
image_holder = self.dialog.get_widget("image")
image_holder.set(image)
self.coverfetcher.fetch(albuminfo, callback, [current])
def _clear_image(self):
self.dialog.get_widget("image").clear()
self.dialog.set_background_color(Color(0, 0, 0))
def _update(self):
if self.status.has_current_song():
self._fetch_image(self.status.current)
else:
self.dialog.cancel()
def init(self):
self.status.add_listener(self)
self._update()
def current_changed(self, mpd_status, current):
self._update()
def _finish_dialog(self):
self.status.remove_listener(self)
class MpdInfoDialogFactory(DialogFactory):
def create(self, element, widget_registry):
path = module_relative_path("info.xml")
dialog = self.context.dialog_registry.dialog_from_file(path)
updater = InfoDialogUpdater(dialog, self.context)
dialog.connect("dialog-started", updater.init)
return dialog
| _update_background_image | identifier_name |
info.py | from pygametk.color import Color
from pygametk.draw import crop
from pygametk.geometry import Rect
from pygametk.image import load_image
from pylaunchr.builder.factory import DialogFactory
from pylaunchr.builder.path import module_relative_path
from ..data import MpdPlayerStatusListener
from ..utils import get_player_status
class InfoDialogUpdater(MpdPlayerStatusListener):
def __init__(self, dialog, context):
self.status = get_player_status(context)
self.coverfetcher = context.services["coverfetcher"].handler
self.imagefilter = context.services["imagefilter"].handler
self.dialog = dialog
self.dialog.connect("dialog-finished", self._finish_dialog)
def _update_background_image(self, image, current):
def blur_callback(result, song):
if "image" in result and self.status.current == song:
|
image_rect = Rect((0, 0), image.get_size())
screen_rect = Rect((0, 0), self.dialog.size)
cropped = crop(image, screen_rect.fit(image_rect))
self.imagefilter.blur(cropped, 15, blur_callback, [current])
def _fetch_image(self, current):
albuminfo = {
"artist": current.albumartist,
"album": current.album,
"file": current.file
}
def callback(result, song):
if "filename" in result and self.status.current == song:
image = load_image(result["filename"])
self._update_background_image(image, song)
image_holder = self.dialog.get_widget("image")
image_holder.set(image)
self.coverfetcher.fetch(albuminfo, callback, [current])
def _clear_image(self):
self.dialog.get_widget("image").clear()
self.dialog.set_background_color(Color(0, 0, 0))
def _update(self):
if self.status.has_current_song():
self._fetch_image(self.status.current)
else:
self.dialog.cancel()
def init(self):
self.status.add_listener(self)
self._update()
def current_changed(self, mpd_status, current):
self._update()
def _finish_dialog(self):
self.status.remove_listener(self)
class MpdInfoDialogFactory(DialogFactory):
def create(self, element, widget_registry):
path = module_relative_path("info.xml")
dialog = self.context.dialog_registry.dialog_from_file(path)
updater = InfoDialogUpdater(dialog, self.context)
dialog.connect("dialog-started", updater.init)
return dialog
| shade = Color(0, 0, 0, 230)
self.dialog.set_background_image(result["image"], shade) | conditional_block |
info.py | from pygametk.color import Color
from pygametk.draw import crop
from pygametk.geometry import Rect
from pygametk.image import load_image
from pylaunchr.builder.factory import DialogFactory
from pylaunchr.builder.path import module_relative_path
from ..data import MpdPlayerStatusListener
from ..utils import get_player_status
class InfoDialogUpdater(MpdPlayerStatusListener):
def __init__(self, dialog, context):
self.status = get_player_status(context)
self.coverfetcher = context.services["coverfetcher"].handler
self.imagefilter = context.services["imagefilter"].handler
self.dialog = dialog
self.dialog.connect("dialog-finished", self._finish_dialog)
def _update_background_image(self, image, current):
def blur_callback(result, song):
if "image" in result and self.status.current == song:
shade = Color(0, 0, 0, 230)
self.dialog.set_background_image(result["image"], shade)
image_rect = Rect((0, 0), image.get_size())
screen_rect = Rect((0, 0), self.dialog.size)
cropped = crop(image, screen_rect.fit(image_rect))
self.imagefilter.blur(cropped, 15, blur_callback, [current])
def _fetch_image(self, current):
albuminfo = {
"artist": current.albumartist,
"album": current.album,
"file": current.file
}
def callback(result, song):
if "filename" in result and self.status.current == song:
image = load_image(result["filename"])
self._update_background_image(image, song)
image_holder = self.dialog.get_widget("image")
image_holder.set(image)
self.coverfetcher.fetch(albuminfo, callback, [current])
def _clear_image(self):
self.dialog.get_widget("image").clear()
self.dialog.set_background_color(Color(0, 0, 0))
def _update(self):
if self.status.has_current_song():
self._fetch_image(self.status.current)
else:
self.dialog.cancel()
def init(self):
|
def current_changed(self, mpd_status, current):
self._update()
def _finish_dialog(self):
self.status.remove_listener(self)
class MpdInfoDialogFactory(DialogFactory):
def create(self, element, widget_registry):
path = module_relative_path("info.xml")
dialog = self.context.dialog_registry.dialog_from_file(path)
updater = InfoDialogUpdater(dialog, self.context)
dialog.connect("dialog-started", updater.init)
return dialog
| self.status.add_listener(self)
self._update() | identifier_body |
EffectComposer.js | /**
* @author alteredq / http://alteredqualia.com/
*/
THREE.EffectComposer = function ( renderer, renderTarget ) {
this.renderer = renderer;
if ( renderTarget === undefined ) {
var width = window.innerWidth || 1;
var height = window.innerHeight || 1;
var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat, stencilBuffer: false };
renderTarget = new THREE.WebGLRenderTarget( width, height, parameters );
}
this.renderTarget1 = renderTarget;
this.renderTarget2 = renderTarget.clone();
this.writeBuffer = this.renderTarget1;
this.readBuffer = this.renderTarget2;
this.passes = [];
if ( THREE.CopyShader === undefined )
console.error( "THREE.EffectComposer relies on THREE.CopyShader" );
this.copyPass = new THREE.ShaderPass( THREE.CopyShader );
};
THREE.EffectComposer.prototype = {
swapBuffers: function() {
var tmp = this.readBuffer;
this.readBuffer = this.writeBuffer;
this.writeBuffer = tmp;
}, |
},
insertPass: function ( pass, index ) {
this.passes.splice( index, 0, pass );
},
render: function ( delta ) {
this.writeBuffer = this.renderTarget1;
this.readBuffer = this.renderTarget2;
var maskActive = false;
var pass, i, il = this.passes.length;
for ( i = 0; i < il; i ++ ) {
pass = this.passes[ i ];
if ( !pass.enabled ) continue;
pass.render( this.renderer, this.writeBuffer, this.readBuffer, delta, maskActive );
if ( pass.needsSwap ) {
if ( maskActive ) {
var context = this.renderer.context;
context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );
this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, delta );
context.stencilFunc( context.EQUAL, 1, 0xffffffff );
}
this.swapBuffers();
}
if ( pass instanceof THREE.MaskPass ) {
maskActive = true;
} else if ( pass instanceof THREE.ClearMaskPass ) {
maskActive = false;
}
}
},
reset: function ( renderTarget ) {
if ( renderTarget === undefined ) {
renderTarget = this.renderTarget1.clone();
renderTarget.width = window.innerWidth;
renderTarget.height = window.innerHeight;
}
this.renderTarget1 = renderTarget;
this.renderTarget2 = renderTarget.clone();
this.writeBuffer = this.renderTarget1;
this.readBuffer = this.renderTarget2;
},
setSize: function ( width, height ) {
var renderTarget = this.renderTarget1.clone();
renderTarget.width = width;
renderTarget.height = height;
this.reset( renderTarget );
}
}; |
addPass: function ( pass ) {
this.passes.push( pass ); | random_line_split |
res_currency.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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/>.
#
##############################################################################
import re
import time
from openerp import tools
from openerp.osv import fields, osv
from openerp.tools import float_round, float_is_zero, float_compare
from openerp.tools.translate import _ |
CURRENCY_DISPLAY_PATTERN = re.compile(r'(\w+)\s*(?:\((.*)\))?')
class res_currency(osv.osv):
def _current_rate(self, cr, uid, ids, name, arg, context=None):
if context is None:
context = {}
res = {}
if 'date' in context:
date = context['date']
else:
date = time.strftime('%Y-%m-%d')
date = date or time.strftime('%Y-%m-%d')
# Convert False values to None ...
currency_rate_type = context.get('currency_rate_type_id') or None
# ... and use 'is NULL' instead of '= some-id'.
operator = '=' if currency_rate_type else 'is'
for id in ids:
cr.execute("SELECT currency_id, rate FROM res_currency_rate WHERE currency_id = %s AND name <= %s AND currency_rate_type_id " + operator +" %s ORDER BY name desc LIMIT 1" ,(id, date, currency_rate_type))
if cr.rowcount:
id, rate = cr.fetchall()[0]
res[id] = rate
else:
raise osv.except_osv(_('Error!'),_("No currency rate associated for currency %d for the given period" % (id)))
return res
_name = "res.currency"
_description = "Currency"
_columns = {
# Note: 'code' column was removed as of v6.0, the 'name' should now hold the ISO code.
'name': fields.char('Currency', size=32, required=True, help="Currency Code (ISO 4217)"),
'symbol': fields.char('Symbol', size=4, help="Currency sign, to be used when printing amounts."),
'rate': fields.function(_current_rate, string='Current Rate', digits=(12,6),
help='The rate of the currency to the currency of rate 1.'),
'rate_ids': fields.one2many('res.currency.rate', 'currency_id', 'Rates'),
'accuracy': fields.integer('Computational Accuracy'),
'rounding': fields.float('Rounding Factor', digits=(12,6)),
'active': fields.boolean('Active'),
'company_id':fields.many2one('res.company', 'Company'),
'date': fields.date('Date'),
'base': fields.boolean('Base'),
'position': fields.selection([('after','After Amount'),('before','Before Amount')], 'Symbol Position', help="Determines where the currency symbol should be placed after or before the amount.")
}
_defaults = {
'active': 1,
'position' : 'after',
'rounding': 0.01,
'accuracy': 4,
'company_id': False,
}
_sql_constraints = [
# this constraint does not cover all cases due to SQL NULL handling for company_id,
# so it is complemented with a unique index (see below). The constraint and index
# share the same prefix so that IntegrityError triggered by the index will be caught
# and reported to the user with the constraint's error message.
('unique_name_company_id', 'unique (name, company_id)', 'The currency code must be unique per company!'),
]
_order = "name"
def init(self, cr):
# CONSTRAINT/UNIQUE INDEX on (name,company_id)
# /!\ The unique constraint 'unique_name_company_id' is not sufficient, because SQL92
# only support field names in constraint definitions, and we need a function here:
# we need to special-case company_id to treat all NULL company_id as equal, otherwise
# we would allow duplicate "global" currencies (all having company_id == NULL)
cr.execute("""SELECT indexname FROM pg_indexes WHERE indexname = 'res_currency_unique_name_company_id_idx'""")
if not cr.fetchone():
cr.execute("""CREATE UNIQUE INDEX res_currency_unique_name_company_id_idx
ON res_currency
(name, (COALESCE(company_id,-1)))""")
def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
res = super(res_currency, self).read(cr, user, ids, fields, context, load)
currency_rate_obj = self.pool.get('res.currency.rate')
values = res
if not isinstance(values, list):
values = [values]
for r in values:
if r.__contains__('rate_ids'):
rates=r['rate_ids']
if rates:
currency_date = currency_rate_obj.read(cr, user, rates[0], ['name'])['name']
r['date'] = currency_date
return res
def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
if not args:
args = []
results = super(res_currency,self)\
.name_search(cr, user, name, args, operator=operator, context=context, limit=limit)
if not results:
name_match = CURRENCY_DISPLAY_PATTERN.match(name)
if name_match:
results = super(res_currency,self)\
.name_search(cr, user, name_match.group(1), args, operator=operator, context=context, limit=limit)
return results
def name_get(self, cr, uid, ids, context=None):
if not ids:
return []
if isinstance(ids, (int, long)):
ids = [ids]
reads = self.read(cr, uid, ids, ['name','symbol'], context=context, load='_classic_write')
return [(x['id'], tools.ustr(x['name'])) for x in reads]
def round(self, cr, uid, currency, amount):
"""Return ``amount`` rounded according to ``currency``'s
rounding rules.
:param browse_record currency: currency for which we are rounding
:param float amount: the amount to round
:return: rounded float
"""
return float_round(amount, precision_rounding=currency.rounding)
def compare_amounts(self, cr, uid, currency, amount1, amount2):
"""Compare ``amount1`` and ``amount2`` after rounding them according to the
given currency's precision..
An amount is considered lower/greater than another amount if their rounded
value is different. This is not the same as having a non-zero difference!
For example 1.432 and 1.431 are equal at 2 digits precision,
so this method would return 0.
However 0.006 and 0.002 are considered different (returns 1) because
they respectively round to 0.01 and 0.0, even though
0.006-0.002 = 0.004 which would be considered zero at 2 digits precision.
:param browse_record currency: currency for which we are rounding
:param float amount1: first amount to compare
:param float amount2: second amount to compare
:return: (resp.) -1, 0 or 1, if ``amount1`` is (resp.) lower than,
equal to, or greater than ``amount2``, according to
``currency``'s rounding.
"""
return float_compare(amount1, amount2, precision_rounding=currency.rounding)
def is_zero(self, cr, uid, currency, amount):
"""Returns true if ``amount`` is small enough to be treated as
zero according to ``currency``'s rounding rules.
Warning: ``is_zero(amount1-amount2)`` is not always equivalent to
``compare_amounts(amount1,amount2) == 0``, as the former will round after
computing the difference, while the latter will round before, giving
different results for e.g. 0.006 and 0.002 at 2 digits precision.
:param browse_record currency: currency for which we are rounding
:param float amount: amount to compare with currency's zero
"""
return float_is_zero(amount, precision_rounding=currency.rounding)
def _get_conversion_rate(self, cr, uid, from_currency, to_currency, context=None):
if context is None:
context = {}
ctx = context.copy()
ctx.update({'currency_rate_type_id': ctx.get('currency_rate_type_from')})
from_currency = self.browse(cr, uid, from_currency.id, context=ctx)
ctx.update({'currency_rate_type_id': ctx.get('currency_rate_type_to')})
to_currency = self.browse(cr, uid, to_currency.id, context=ctx)
if from_currency.rate == 0 or to_currency.rate == 0:
date = context.get('date', time.strftime('%Y-%m-%d'))
if from_currency.rate == 0:
currency_symbol = from_currency.symbol
else:
currency_symbol = to_currency.symbol
raise osv.except_osv(_('Error'), _('No rate found \n' \
'for the currency: %s \n' \
'at the date: %s') % (currency_symbol, date))
return to_currency.rate/from_currency.rate
def compute(self, cr, uid, from_currency_id, to_currency_id, from_amount,
round=True, currency_rate_type_from=False, currency_rate_type_to=False, context=None):
if not context:
context = {}
if not from_currency_id:
from_currency_id = to_currency_id
if not to_currency_id:
to_currency_id = from_currency_id
xc = self.browse(cr, uid, [from_currency_id,to_currency_id], context=context)
from_currency = (xc[0].id == from_currency_id and xc[0]) or xc[1]
to_currency = (xc[0].id == to_currency_id and xc[0]) or xc[1]
if (to_currency_id == from_currency_id) and (currency_rate_type_from == currency_rate_type_to):
if round:
return self.round(cr, uid, to_currency, from_amount)
else:
return from_amount
else:
context.update({'currency_rate_type_from': currency_rate_type_from, 'currency_rate_type_to': currency_rate_type_to})
rate = self._get_conversion_rate(cr, uid, from_currency, to_currency, context=context)
if round:
return self.round(cr, uid, to_currency, from_amount * rate)
else:
return from_amount * rate
res_currency()
class res_currency_rate_type(osv.osv):
_name = "res.currency.rate.type"
_description = "Currency Rate Type"
_columns = {
'name': fields.char('Name', size=64, required=True, translate=True),
}
res_currency_rate_type()
class res_currency_rate(osv.osv):
_name = "res.currency.rate"
_description = "Currency Rate"
_columns = {
'name': fields.date('Date', required=True, select=True),
'rate': fields.float('Rate', digits=(12,6), help='The rate of the currency to the currency of rate 1'),
'currency_id': fields.many2one('res.currency', 'Currency', readonly=True),
'currency_rate_type_id': fields.many2one('res.currency.rate.type', 'Currency Rate Type', help="Allow you to define your own currency rate types, like 'Average' or 'Year to Date'. Leave empty if you simply want to use the normal 'spot' rate type"),
}
_defaults = {
'name': lambda *a: time.strftime('%Y-%m-%d'),
}
_order = "name desc"
res_currency_rate()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | random_line_split | |
res_currency.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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/>.
#
##############################################################################
import re
import time
from openerp import tools
from openerp.osv import fields, osv
from openerp.tools import float_round, float_is_zero, float_compare
from openerp.tools.translate import _
CURRENCY_DISPLAY_PATTERN = re.compile(r'(\w+)\s*(?:\((.*)\))?')
class res_currency(osv.osv):
def _current_rate(self, cr, uid, ids, name, arg, context=None):
if context is None:
context = {}
res = {}
if 'date' in context:
date = context['date']
else:
date = time.strftime('%Y-%m-%d')
date = date or time.strftime('%Y-%m-%d')
# Convert False values to None ...
currency_rate_type = context.get('currency_rate_type_id') or None
# ... and use 'is NULL' instead of '= some-id'.
operator = '=' if currency_rate_type else 'is'
for id in ids:
cr.execute("SELECT currency_id, rate FROM res_currency_rate WHERE currency_id = %s AND name <= %s AND currency_rate_type_id " + operator +" %s ORDER BY name desc LIMIT 1" ,(id, date, currency_rate_type))
if cr.rowcount:
id, rate = cr.fetchall()[0]
res[id] = rate
else:
raise osv.except_osv(_('Error!'),_("No currency rate associated for currency %d for the given period" % (id)))
return res
_name = "res.currency"
_description = "Currency"
_columns = {
# Note: 'code' column was removed as of v6.0, the 'name' should now hold the ISO code.
'name': fields.char('Currency', size=32, required=True, help="Currency Code (ISO 4217)"),
'symbol': fields.char('Symbol', size=4, help="Currency sign, to be used when printing amounts."),
'rate': fields.function(_current_rate, string='Current Rate', digits=(12,6),
help='The rate of the currency to the currency of rate 1.'),
'rate_ids': fields.one2many('res.currency.rate', 'currency_id', 'Rates'),
'accuracy': fields.integer('Computational Accuracy'),
'rounding': fields.float('Rounding Factor', digits=(12,6)),
'active': fields.boolean('Active'),
'company_id':fields.many2one('res.company', 'Company'),
'date': fields.date('Date'),
'base': fields.boolean('Base'),
'position': fields.selection([('after','After Amount'),('before','Before Amount')], 'Symbol Position', help="Determines where the currency symbol should be placed after or before the amount.")
}
_defaults = {
'active': 1,
'position' : 'after',
'rounding': 0.01,
'accuracy': 4,
'company_id': False,
}
_sql_constraints = [
# this constraint does not cover all cases due to SQL NULL handling for company_id,
# so it is complemented with a unique index (see below). The constraint and index
# share the same prefix so that IntegrityError triggered by the index will be caught
# and reported to the user with the constraint's error message.
('unique_name_company_id', 'unique (name, company_id)', 'The currency code must be unique per company!'),
]
_order = "name"
def init(self, cr):
# CONSTRAINT/UNIQUE INDEX on (name,company_id)
# /!\ The unique constraint 'unique_name_company_id' is not sufficient, because SQL92
# only support field names in constraint definitions, and we need a function here:
# we need to special-case company_id to treat all NULL company_id as equal, otherwise
# we would allow duplicate "global" currencies (all having company_id == NULL)
cr.execute("""SELECT indexname FROM pg_indexes WHERE indexname = 'res_currency_unique_name_company_id_idx'""")
if not cr.fetchone():
cr.execute("""CREATE UNIQUE INDEX res_currency_unique_name_company_id_idx
ON res_currency
(name, (COALESCE(company_id,-1)))""")
def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
res = super(res_currency, self).read(cr, user, ids, fields, context, load)
currency_rate_obj = self.pool.get('res.currency.rate')
values = res
if not isinstance(values, list):
values = [values]
for r in values:
if r.__contains__('rate_ids'):
rates=r['rate_ids']
if rates:
currency_date = currency_rate_obj.read(cr, user, rates[0], ['name'])['name']
r['date'] = currency_date
return res
def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
if not args:
args = []
results = super(res_currency,self)\
.name_search(cr, user, name, args, operator=operator, context=context, limit=limit)
if not results:
name_match = CURRENCY_DISPLAY_PATTERN.match(name)
if name_match:
results = super(res_currency,self)\
.name_search(cr, user, name_match.group(1), args, operator=operator, context=context, limit=limit)
return results
def name_get(self, cr, uid, ids, context=None):
if not ids:
return []
if isinstance(ids, (int, long)):
ids = [ids]
reads = self.read(cr, uid, ids, ['name','symbol'], context=context, load='_classic_write')
return [(x['id'], tools.ustr(x['name'])) for x in reads]
def round(self, cr, uid, currency, amount):
"""Return ``amount`` rounded according to ``currency``'s
rounding rules.
:param browse_record currency: currency for which we are rounding
:param float amount: the amount to round
:return: rounded float
"""
return float_round(amount, precision_rounding=currency.rounding)
def compare_amounts(self, cr, uid, currency, amount1, amount2):
"""Compare ``amount1`` and ``amount2`` after rounding them according to the
given currency's precision..
An amount is considered lower/greater than another amount if their rounded
value is different. This is not the same as having a non-zero difference!
For example 1.432 and 1.431 are equal at 2 digits precision,
so this method would return 0.
However 0.006 and 0.002 are considered different (returns 1) because
they respectively round to 0.01 and 0.0, even though
0.006-0.002 = 0.004 which would be considered zero at 2 digits precision.
:param browse_record currency: currency for which we are rounding
:param float amount1: first amount to compare
:param float amount2: second amount to compare
:return: (resp.) -1, 0 or 1, if ``amount1`` is (resp.) lower than,
equal to, or greater than ``amount2``, according to
``currency``'s rounding.
"""
return float_compare(amount1, amount2, precision_rounding=currency.rounding)
def is_zero(self, cr, uid, currency, amount):
"""Returns true if ``amount`` is small enough to be treated as
zero according to ``currency``'s rounding rules.
Warning: ``is_zero(amount1-amount2)`` is not always equivalent to
``compare_amounts(amount1,amount2) == 0``, as the former will round after
computing the difference, while the latter will round before, giving
different results for e.g. 0.006 and 0.002 at 2 digits precision.
:param browse_record currency: currency for which we are rounding
:param float amount: amount to compare with currency's zero
"""
return float_is_zero(amount, precision_rounding=currency.rounding)
def _get_conversion_rate(self, cr, uid, from_currency, to_currency, context=None):
|
def compute(self, cr, uid, from_currency_id, to_currency_id, from_amount,
round=True, currency_rate_type_from=False, currency_rate_type_to=False, context=None):
if not context:
context = {}
if not from_currency_id:
from_currency_id = to_currency_id
if not to_currency_id:
to_currency_id = from_currency_id
xc = self.browse(cr, uid, [from_currency_id,to_currency_id], context=context)
from_currency = (xc[0].id == from_currency_id and xc[0]) or xc[1]
to_currency = (xc[0].id == to_currency_id and xc[0]) or xc[1]
if (to_currency_id == from_currency_id) and (currency_rate_type_from == currency_rate_type_to):
if round:
return self.round(cr, uid, to_currency, from_amount)
else:
return from_amount
else:
context.update({'currency_rate_type_from': currency_rate_type_from, 'currency_rate_type_to': currency_rate_type_to})
rate = self._get_conversion_rate(cr, uid, from_currency, to_currency, context=context)
if round:
return self.round(cr, uid, to_currency, from_amount * rate)
else:
return from_amount * rate
res_currency()
class res_currency_rate_type(osv.osv):
_name = "res.currency.rate.type"
_description = "Currency Rate Type"
_columns = {
'name': fields.char('Name', size=64, required=True, translate=True),
}
res_currency_rate_type()
class res_currency_rate(osv.osv):
_name = "res.currency.rate"
_description = "Currency Rate"
_columns = {
'name': fields.date('Date', required=True, select=True),
'rate': fields.float('Rate', digits=(12,6), help='The rate of the currency to the currency of rate 1'),
'currency_id': fields.many2one('res.currency', 'Currency', readonly=True),
'currency_rate_type_id': fields.many2one('res.currency.rate.type', 'Currency Rate Type', help="Allow you to define your own currency rate types, like 'Average' or 'Year to Date'. Leave empty if you simply want to use the normal 'spot' rate type"),
}
_defaults = {
'name': lambda *a: time.strftime('%Y-%m-%d'),
}
_order = "name desc"
res_currency_rate()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| if context is None:
context = {}
ctx = context.copy()
ctx.update({'currency_rate_type_id': ctx.get('currency_rate_type_from')})
from_currency = self.browse(cr, uid, from_currency.id, context=ctx)
ctx.update({'currency_rate_type_id': ctx.get('currency_rate_type_to')})
to_currency = self.browse(cr, uid, to_currency.id, context=ctx)
if from_currency.rate == 0 or to_currency.rate == 0:
date = context.get('date', time.strftime('%Y-%m-%d'))
if from_currency.rate == 0:
currency_symbol = from_currency.symbol
else:
currency_symbol = to_currency.symbol
raise osv.except_osv(_('Error'), _('No rate found \n' \
'for the currency: %s \n' \
'at the date: %s') % (currency_symbol, date))
return to_currency.rate/from_currency.rate | identifier_body |
res_currency.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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/>.
#
##############################################################################
import re
import time
from openerp import tools
from openerp.osv import fields, osv
from openerp.tools import float_round, float_is_zero, float_compare
from openerp.tools.translate import _
CURRENCY_DISPLAY_PATTERN = re.compile(r'(\w+)\s*(?:\((.*)\))?')
class res_currency(osv.osv):
def _current_rate(self, cr, uid, ids, name, arg, context=None):
if context is None:
context = {}
res = {}
if 'date' in context:
date = context['date']
else:
date = time.strftime('%Y-%m-%d')
date = date or time.strftime('%Y-%m-%d')
# Convert False values to None ...
currency_rate_type = context.get('currency_rate_type_id') or None
# ... and use 'is NULL' instead of '= some-id'.
operator = '=' if currency_rate_type else 'is'
for id in ids:
cr.execute("SELECT currency_id, rate FROM res_currency_rate WHERE currency_id = %s AND name <= %s AND currency_rate_type_id " + operator +" %s ORDER BY name desc LIMIT 1" ,(id, date, currency_rate_type))
if cr.rowcount:
id, rate = cr.fetchall()[0]
res[id] = rate
else:
raise osv.except_osv(_('Error!'),_("No currency rate associated for currency %d for the given period" % (id)))
return res
_name = "res.currency"
_description = "Currency"
_columns = {
# Note: 'code' column was removed as of v6.0, the 'name' should now hold the ISO code.
'name': fields.char('Currency', size=32, required=True, help="Currency Code (ISO 4217)"),
'symbol': fields.char('Symbol', size=4, help="Currency sign, to be used when printing amounts."),
'rate': fields.function(_current_rate, string='Current Rate', digits=(12,6),
help='The rate of the currency to the currency of rate 1.'),
'rate_ids': fields.one2many('res.currency.rate', 'currency_id', 'Rates'),
'accuracy': fields.integer('Computational Accuracy'),
'rounding': fields.float('Rounding Factor', digits=(12,6)),
'active': fields.boolean('Active'),
'company_id':fields.many2one('res.company', 'Company'),
'date': fields.date('Date'),
'base': fields.boolean('Base'),
'position': fields.selection([('after','After Amount'),('before','Before Amount')], 'Symbol Position', help="Determines where the currency symbol should be placed after or before the amount.")
}
_defaults = {
'active': 1,
'position' : 'after',
'rounding': 0.01,
'accuracy': 4,
'company_id': False,
}
_sql_constraints = [
# this constraint does not cover all cases due to SQL NULL handling for company_id,
# so it is complemented with a unique index (see below). The constraint and index
# share the same prefix so that IntegrityError triggered by the index will be caught
# and reported to the user with the constraint's error message.
('unique_name_company_id', 'unique (name, company_id)', 'The currency code must be unique per company!'),
]
_order = "name"
def init(self, cr):
# CONSTRAINT/UNIQUE INDEX on (name,company_id)
# /!\ The unique constraint 'unique_name_company_id' is not sufficient, because SQL92
# only support field names in constraint definitions, and we need a function here:
# we need to special-case company_id to treat all NULL company_id as equal, otherwise
# we would allow duplicate "global" currencies (all having company_id == NULL)
cr.execute("""SELECT indexname FROM pg_indexes WHERE indexname = 'res_currency_unique_name_company_id_idx'""")
if not cr.fetchone():
cr.execute("""CREATE UNIQUE INDEX res_currency_unique_name_company_id_idx
ON res_currency
(name, (COALESCE(company_id,-1)))""")
def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
res = super(res_currency, self).read(cr, user, ids, fields, context, load)
currency_rate_obj = self.pool.get('res.currency.rate')
values = res
if not isinstance(values, list):
values = [values]
for r in values:
if r.__contains__('rate_ids'):
rates=r['rate_ids']
if rates:
currency_date = currency_rate_obj.read(cr, user, rates[0], ['name'])['name']
r['date'] = currency_date
return res
def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
if not args:
args = []
results = super(res_currency,self)\
.name_search(cr, user, name, args, operator=operator, context=context, limit=limit)
if not results:
name_match = CURRENCY_DISPLAY_PATTERN.match(name)
if name_match:
results = super(res_currency,self)\
.name_search(cr, user, name_match.group(1), args, operator=operator, context=context, limit=limit)
return results
def name_get(self, cr, uid, ids, context=None):
if not ids:
return []
if isinstance(ids, (int, long)):
ids = [ids]
reads = self.read(cr, uid, ids, ['name','symbol'], context=context, load='_classic_write')
return [(x['id'], tools.ustr(x['name'])) for x in reads]
def round(self, cr, uid, currency, amount):
"""Return ``amount`` rounded according to ``currency``'s
rounding rules.
:param browse_record currency: currency for which we are rounding
:param float amount: the amount to round
:return: rounded float
"""
return float_round(amount, precision_rounding=currency.rounding)
def compare_amounts(self, cr, uid, currency, amount1, amount2):
"""Compare ``amount1`` and ``amount2`` after rounding them according to the
given currency's precision..
An amount is considered lower/greater than another amount if their rounded
value is different. This is not the same as having a non-zero difference!
For example 1.432 and 1.431 are equal at 2 digits precision,
so this method would return 0.
However 0.006 and 0.002 are considered different (returns 1) because
they respectively round to 0.01 and 0.0, even though
0.006-0.002 = 0.004 which would be considered zero at 2 digits precision.
:param browse_record currency: currency for which we are rounding
:param float amount1: first amount to compare
:param float amount2: second amount to compare
:return: (resp.) -1, 0 or 1, if ``amount1`` is (resp.) lower than,
equal to, or greater than ``amount2``, according to
``currency``'s rounding.
"""
return float_compare(amount1, amount2, precision_rounding=currency.rounding)
def is_zero(self, cr, uid, currency, amount):
"""Returns true if ``amount`` is small enough to be treated as
zero according to ``currency``'s rounding rules.
Warning: ``is_zero(amount1-amount2)`` is not always equivalent to
``compare_amounts(amount1,amount2) == 0``, as the former will round after
computing the difference, while the latter will round before, giving
different results for e.g. 0.006 and 0.002 at 2 digits precision.
:param browse_record currency: currency for which we are rounding
:param float amount: amount to compare with currency's zero
"""
return float_is_zero(amount, precision_rounding=currency.rounding)
def _get_conversion_rate(self, cr, uid, from_currency, to_currency, context=None):
if context is None:
context = {}
ctx = context.copy()
ctx.update({'currency_rate_type_id': ctx.get('currency_rate_type_from')})
from_currency = self.browse(cr, uid, from_currency.id, context=ctx)
ctx.update({'currency_rate_type_id': ctx.get('currency_rate_type_to')})
to_currency = self.browse(cr, uid, to_currency.id, context=ctx)
if from_currency.rate == 0 or to_currency.rate == 0:
date = context.get('date', time.strftime('%Y-%m-%d'))
if from_currency.rate == 0:
currency_symbol = from_currency.symbol
else:
|
raise osv.except_osv(_('Error'), _('No rate found \n' \
'for the currency: %s \n' \
'at the date: %s') % (currency_symbol, date))
return to_currency.rate/from_currency.rate
def compute(self, cr, uid, from_currency_id, to_currency_id, from_amount,
round=True, currency_rate_type_from=False, currency_rate_type_to=False, context=None):
if not context:
context = {}
if not from_currency_id:
from_currency_id = to_currency_id
if not to_currency_id:
to_currency_id = from_currency_id
xc = self.browse(cr, uid, [from_currency_id,to_currency_id], context=context)
from_currency = (xc[0].id == from_currency_id and xc[0]) or xc[1]
to_currency = (xc[0].id == to_currency_id and xc[0]) or xc[1]
if (to_currency_id == from_currency_id) and (currency_rate_type_from == currency_rate_type_to):
if round:
return self.round(cr, uid, to_currency, from_amount)
else:
return from_amount
else:
context.update({'currency_rate_type_from': currency_rate_type_from, 'currency_rate_type_to': currency_rate_type_to})
rate = self._get_conversion_rate(cr, uid, from_currency, to_currency, context=context)
if round:
return self.round(cr, uid, to_currency, from_amount * rate)
else:
return from_amount * rate
res_currency()
class res_currency_rate_type(osv.osv):
_name = "res.currency.rate.type"
_description = "Currency Rate Type"
_columns = {
'name': fields.char('Name', size=64, required=True, translate=True),
}
res_currency_rate_type()
class res_currency_rate(osv.osv):
_name = "res.currency.rate"
_description = "Currency Rate"
_columns = {
'name': fields.date('Date', required=True, select=True),
'rate': fields.float('Rate', digits=(12,6), help='The rate of the currency to the currency of rate 1'),
'currency_id': fields.many2one('res.currency', 'Currency', readonly=True),
'currency_rate_type_id': fields.many2one('res.currency.rate.type', 'Currency Rate Type', help="Allow you to define your own currency rate types, like 'Average' or 'Year to Date'. Leave empty if you simply want to use the normal 'spot' rate type"),
}
_defaults = {
'name': lambda *a: time.strftime('%Y-%m-%d'),
}
_order = "name desc"
res_currency_rate()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| currency_symbol = to_currency.symbol | conditional_block |
res_currency.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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/>.
#
##############################################################################
import re
import time
from openerp import tools
from openerp.osv import fields, osv
from openerp.tools import float_round, float_is_zero, float_compare
from openerp.tools.translate import _
CURRENCY_DISPLAY_PATTERN = re.compile(r'(\w+)\s*(?:\((.*)\))?')
class res_currency(osv.osv):
def _current_rate(self, cr, uid, ids, name, arg, context=None):
if context is None:
context = {}
res = {}
if 'date' in context:
date = context['date']
else:
date = time.strftime('%Y-%m-%d')
date = date or time.strftime('%Y-%m-%d')
# Convert False values to None ...
currency_rate_type = context.get('currency_rate_type_id') or None
# ... and use 'is NULL' instead of '= some-id'.
operator = '=' if currency_rate_type else 'is'
for id in ids:
cr.execute("SELECT currency_id, rate FROM res_currency_rate WHERE currency_id = %s AND name <= %s AND currency_rate_type_id " + operator +" %s ORDER BY name desc LIMIT 1" ,(id, date, currency_rate_type))
if cr.rowcount:
id, rate = cr.fetchall()[0]
res[id] = rate
else:
raise osv.except_osv(_('Error!'),_("No currency rate associated for currency %d for the given period" % (id)))
return res
_name = "res.currency"
_description = "Currency"
_columns = {
# Note: 'code' column was removed as of v6.0, the 'name' should now hold the ISO code.
'name': fields.char('Currency', size=32, required=True, help="Currency Code (ISO 4217)"),
'symbol': fields.char('Symbol', size=4, help="Currency sign, to be used when printing amounts."),
'rate': fields.function(_current_rate, string='Current Rate', digits=(12,6),
help='The rate of the currency to the currency of rate 1.'),
'rate_ids': fields.one2many('res.currency.rate', 'currency_id', 'Rates'),
'accuracy': fields.integer('Computational Accuracy'),
'rounding': fields.float('Rounding Factor', digits=(12,6)),
'active': fields.boolean('Active'),
'company_id':fields.many2one('res.company', 'Company'),
'date': fields.date('Date'),
'base': fields.boolean('Base'),
'position': fields.selection([('after','After Amount'),('before','Before Amount')], 'Symbol Position', help="Determines where the currency symbol should be placed after or before the amount.")
}
_defaults = {
'active': 1,
'position' : 'after',
'rounding': 0.01,
'accuracy': 4,
'company_id': False,
}
_sql_constraints = [
# this constraint does not cover all cases due to SQL NULL handling for company_id,
# so it is complemented with a unique index (see below). The constraint and index
# share the same prefix so that IntegrityError triggered by the index will be caught
# and reported to the user with the constraint's error message.
('unique_name_company_id', 'unique (name, company_id)', 'The currency code must be unique per company!'),
]
_order = "name"
def | (self, cr):
# CONSTRAINT/UNIQUE INDEX on (name,company_id)
# /!\ The unique constraint 'unique_name_company_id' is not sufficient, because SQL92
# only support field names in constraint definitions, and we need a function here:
# we need to special-case company_id to treat all NULL company_id as equal, otherwise
# we would allow duplicate "global" currencies (all having company_id == NULL)
cr.execute("""SELECT indexname FROM pg_indexes WHERE indexname = 'res_currency_unique_name_company_id_idx'""")
if not cr.fetchone():
cr.execute("""CREATE UNIQUE INDEX res_currency_unique_name_company_id_idx
ON res_currency
(name, (COALESCE(company_id,-1)))""")
def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
res = super(res_currency, self).read(cr, user, ids, fields, context, load)
currency_rate_obj = self.pool.get('res.currency.rate')
values = res
if not isinstance(values, list):
values = [values]
for r in values:
if r.__contains__('rate_ids'):
rates=r['rate_ids']
if rates:
currency_date = currency_rate_obj.read(cr, user, rates[0], ['name'])['name']
r['date'] = currency_date
return res
def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
if not args:
args = []
results = super(res_currency,self)\
.name_search(cr, user, name, args, operator=operator, context=context, limit=limit)
if not results:
name_match = CURRENCY_DISPLAY_PATTERN.match(name)
if name_match:
results = super(res_currency,self)\
.name_search(cr, user, name_match.group(1), args, operator=operator, context=context, limit=limit)
return results
def name_get(self, cr, uid, ids, context=None):
if not ids:
return []
if isinstance(ids, (int, long)):
ids = [ids]
reads = self.read(cr, uid, ids, ['name','symbol'], context=context, load='_classic_write')
return [(x['id'], tools.ustr(x['name'])) for x in reads]
def round(self, cr, uid, currency, amount):
"""Return ``amount`` rounded according to ``currency``'s
rounding rules.
:param browse_record currency: currency for which we are rounding
:param float amount: the amount to round
:return: rounded float
"""
return float_round(amount, precision_rounding=currency.rounding)
def compare_amounts(self, cr, uid, currency, amount1, amount2):
"""Compare ``amount1`` and ``amount2`` after rounding them according to the
given currency's precision..
An amount is considered lower/greater than another amount if their rounded
value is different. This is not the same as having a non-zero difference!
For example 1.432 and 1.431 are equal at 2 digits precision,
so this method would return 0.
However 0.006 and 0.002 are considered different (returns 1) because
they respectively round to 0.01 and 0.0, even though
0.006-0.002 = 0.004 which would be considered zero at 2 digits precision.
:param browse_record currency: currency for which we are rounding
:param float amount1: first amount to compare
:param float amount2: second amount to compare
:return: (resp.) -1, 0 or 1, if ``amount1`` is (resp.) lower than,
equal to, or greater than ``amount2``, according to
``currency``'s rounding.
"""
return float_compare(amount1, amount2, precision_rounding=currency.rounding)
def is_zero(self, cr, uid, currency, amount):
"""Returns true if ``amount`` is small enough to be treated as
zero according to ``currency``'s rounding rules.
Warning: ``is_zero(amount1-amount2)`` is not always equivalent to
``compare_amounts(amount1,amount2) == 0``, as the former will round after
computing the difference, while the latter will round before, giving
different results for e.g. 0.006 and 0.002 at 2 digits precision.
:param browse_record currency: currency for which we are rounding
:param float amount: amount to compare with currency's zero
"""
return float_is_zero(amount, precision_rounding=currency.rounding)
def _get_conversion_rate(self, cr, uid, from_currency, to_currency, context=None):
if context is None:
context = {}
ctx = context.copy()
ctx.update({'currency_rate_type_id': ctx.get('currency_rate_type_from')})
from_currency = self.browse(cr, uid, from_currency.id, context=ctx)
ctx.update({'currency_rate_type_id': ctx.get('currency_rate_type_to')})
to_currency = self.browse(cr, uid, to_currency.id, context=ctx)
if from_currency.rate == 0 or to_currency.rate == 0:
date = context.get('date', time.strftime('%Y-%m-%d'))
if from_currency.rate == 0:
currency_symbol = from_currency.symbol
else:
currency_symbol = to_currency.symbol
raise osv.except_osv(_('Error'), _('No rate found \n' \
'for the currency: %s \n' \
'at the date: %s') % (currency_symbol, date))
return to_currency.rate/from_currency.rate
def compute(self, cr, uid, from_currency_id, to_currency_id, from_amount,
round=True, currency_rate_type_from=False, currency_rate_type_to=False, context=None):
if not context:
context = {}
if not from_currency_id:
from_currency_id = to_currency_id
if not to_currency_id:
to_currency_id = from_currency_id
xc = self.browse(cr, uid, [from_currency_id,to_currency_id], context=context)
from_currency = (xc[0].id == from_currency_id and xc[0]) or xc[1]
to_currency = (xc[0].id == to_currency_id and xc[0]) or xc[1]
if (to_currency_id == from_currency_id) and (currency_rate_type_from == currency_rate_type_to):
if round:
return self.round(cr, uid, to_currency, from_amount)
else:
return from_amount
else:
context.update({'currency_rate_type_from': currency_rate_type_from, 'currency_rate_type_to': currency_rate_type_to})
rate = self._get_conversion_rate(cr, uid, from_currency, to_currency, context=context)
if round:
return self.round(cr, uid, to_currency, from_amount * rate)
else:
return from_amount * rate
res_currency()
class res_currency_rate_type(osv.osv):
_name = "res.currency.rate.type"
_description = "Currency Rate Type"
_columns = {
'name': fields.char('Name', size=64, required=True, translate=True),
}
res_currency_rate_type()
class res_currency_rate(osv.osv):
_name = "res.currency.rate"
_description = "Currency Rate"
_columns = {
'name': fields.date('Date', required=True, select=True),
'rate': fields.float('Rate', digits=(12,6), help='The rate of the currency to the currency of rate 1'),
'currency_id': fields.many2one('res.currency', 'Currency', readonly=True),
'currency_rate_type_id': fields.many2one('res.currency.rate.type', 'Currency Rate Type', help="Allow you to define your own currency rate types, like 'Average' or 'Year to Date'. Leave empty if you simply want to use the normal 'spot' rate type"),
}
_defaults = {
'name': lambda *a: time.strftime('%Y-%m-%d'),
}
_order = "name desc"
res_currency_rate()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| init | identifier_name |
test_xor_clasification_demo_v2.py | # Dependencias Internas
import numpy as np
import matplotlib.pyplot as plt
# Dependencias Externas
from cupydle.dnn.NeuralNetwork import NeuralNetwork
from cupydle.dnn.data import LabeledDataSet as dataSet
# Seteo de los parametros
capa_entrada = 2
capa_oculta_1 = 3
capa_salida = 2
capas = [capa_entrada, capa_oculta_1, capa_salida]
net = NeuralNetwork(list_layers=capas, clasificacion=True, funcion_error="CROSS_ENTROPY",
funcion_activacion="Sigmoid", w=None, b=None)
# -------------------------------- DATASET --------------------------------------------#
print("Cargando la base de datos...")
data_trn = dataSet('cupydle/data/XOR_trn.csv', delimiter=',')
print("Entrenamiento: " + str(data_trn.data.shape))
entrada_trn, salida_trn = data_trn.split_data(3)
# corregir los valores de los labels, deben estar entre 0 y 1 "clases"
salida_trn_tmp = np.zeros((1, len(salida_trn)))
for l in range(0, len(salida_trn)):
if salida_trn[l] < 0.0:
salida_trn_tmp[0][l] = 0.0
else:
salida_trn_tmp[0][l] = 1.0
datos_trn = [(x, y) for x, y in zip(entrada_trn, salida_trn_tmp.transpose())]
data_tst = dataSet('cupydle/data/XOR_tst.csv', delimiter=',')
print("Testeo: " + str(data_tst.data.shape))
entrada_tst, salida_tst = data_tst.split_data(3)
# corregir los valores de los labels, deben estar entre 0 y 1 "clases"
salida_tst_tmp = np.zeros((1, len(salida_tst)))
for l in range(0, len(salida_tst)):
if salida_tst[l] < 0.0:
salida_tst_tmp[0][l] = 0.0
else: |
# -------------------------------- ENTRENAMIENTO --------------------------------------------#
tmp = datos_trn
cantidad = len(tmp)
porcentaje = 80
datos_trn = tmp[0: int(cantidad * porcentaje / 100)]
datos_vld = tmp[int(cantidad * porcentaje / 100 + 1):]
print("Training Data size: " + str(len(datos_trn)))
print("Validating Data size: " + str(len(datos_vld)))
print("Testing Data size: " + str(len(datos_tst)))
loss, error = net.fit(train=datos_trn, valid=datos_vld, test=datos_tst, batch_size=10, epocas=100, tasa_apren=0.2, momentum=0.1)
fig2 = plt.figure()
plt.clf()
plt3 = fig2.add_subplot(1, 1, 1)
m_l = max(loss)
m_e = max(error)
loss = [x/m_l for x in loss]
error = [x/m_e for x in error]
plt3.plot(range(0, len(loss)), loss, c='b', marker='.')
plt3.plot(range(0, len(loss)), error, c='r', marker='o')
plt3.set_xlabel('EPOCH')
plt3.set_ylabel('COSTO')
plt3.set_title("COSTO vs. EPOCA")
plt.show() | salida_tst_tmp[0][l] = 1.0
datos_tst = [(x, y) for x, y in zip(entrada_tst, salida_tst_tmp.transpose())] | random_line_split |
test_xor_clasification_demo_v2.py | # Dependencias Internas
import numpy as np
import matplotlib.pyplot as plt
# Dependencias Externas
from cupydle.dnn.NeuralNetwork import NeuralNetwork
from cupydle.dnn.data import LabeledDataSet as dataSet
# Seteo de los parametros
capa_entrada = 2
capa_oculta_1 = 3
capa_salida = 2
capas = [capa_entrada, capa_oculta_1, capa_salida]
net = NeuralNetwork(list_layers=capas, clasificacion=True, funcion_error="CROSS_ENTROPY",
funcion_activacion="Sigmoid", w=None, b=None)
# -------------------------------- DATASET --------------------------------------------#
print("Cargando la base de datos...")
data_trn = dataSet('cupydle/data/XOR_trn.csv', delimiter=',')
print("Entrenamiento: " + str(data_trn.data.shape))
entrada_trn, salida_trn = data_trn.split_data(3)
# corregir los valores de los labels, deben estar entre 0 y 1 "clases"
salida_trn_tmp = np.zeros((1, len(salida_trn)))
for l in range(0, len(salida_trn)):
if salida_trn[l] < 0.0:
salida_trn_tmp[0][l] = 0.0
else:
salida_trn_tmp[0][l] = 1.0
datos_trn = [(x, y) for x, y in zip(entrada_trn, salida_trn_tmp.transpose())]
data_tst = dataSet('cupydle/data/XOR_tst.csv', delimiter=',')
print("Testeo: " + str(data_tst.data.shape))
entrada_tst, salida_tst = data_tst.split_data(3)
# corregir los valores de los labels, deben estar entre 0 y 1 "clases"
salida_tst_tmp = np.zeros((1, len(salida_tst)))
for l in range(0, len(salida_tst)):
|
datos_tst = [(x, y) for x, y in zip(entrada_tst, salida_tst_tmp.transpose())]
# -------------------------------- ENTRENAMIENTO --------------------------------------------#
tmp = datos_trn
cantidad = len(tmp)
porcentaje = 80
datos_trn = tmp[0: int(cantidad * porcentaje / 100)]
datos_vld = tmp[int(cantidad * porcentaje / 100 + 1):]
print("Training Data size: " + str(len(datos_trn)))
print("Validating Data size: " + str(len(datos_vld)))
print("Testing Data size: " + str(len(datos_tst)))
loss, error = net.fit(train=datos_trn, valid=datos_vld, test=datos_tst, batch_size=10, epocas=100, tasa_apren=0.2, momentum=0.1)
fig2 = plt.figure()
plt.clf()
plt3 = fig2.add_subplot(1, 1, 1)
m_l = max(loss)
m_e = max(error)
loss = [x/m_l for x in loss]
error = [x/m_e for x in error]
plt3.plot(range(0, len(loss)), loss, c='b', marker='.')
plt3.plot(range(0, len(loss)), error, c='r', marker='o')
plt3.set_xlabel('EPOCH')
plt3.set_ylabel('COSTO')
plt3.set_title("COSTO vs. EPOCA")
plt.show()
| if salida_tst[l] < 0.0:
salida_tst_tmp[0][l] = 0.0
else:
salida_tst_tmp[0][l] = 1.0 | conditional_block |
Header.styles.ts | import { CSSObject } from '@emotion/react';
import { theme } from '../../theme';
const styles: Record<string, CSSObject> = {
root: {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
overflow: 'hidden',
borderBottom: `1px solid ${theme.color.border}`,
height: 36,
lineHeight: '36px',
fontFamily: theme.typography.content,
color: theme.color.link,
userSelect: 'none',
backgroundColor: theme.color.section,
'& a': {
textDecoration: 'none',
color: 'inherit',
outline: 'none',
transition: 'color 150ms ease-out',
'&:hover, &:focus': {
color: theme.color.linkActive,
outline: 'none'
}
},
[theme.breakpoints.tabletUp]: {
height: 50, | lineHeight: '50px'
}
},
title: {
display: 'block',
margin: 0,
padding: '0 10px',
fontSize: 16,
fontFamily: theme.typography.content,
color: theme.color.headings,
whiteSpace: 'nowrap',
letterSpacing: 0,
textTransform: 'none',
textShadow: 'none',
[theme.breakpoints.tabletUp]: {
padding: '0 15px',
fontSize: 24
}
},
options: {
display: 'flex',
paddingRight: 5,
[theme.breakpoints.tabletUp]: {
paddingRight: 15
}
},
option: {
position: 'relative',
display: 'flex',
alignItems: 'center',
paddingRight: 5,
fontFamily: theme.typography.content,
color: theme.color.link,
fontSize: 12,
cursor: 'pointer',
transition: 'color 150ms ease-out',
'&:hover, &:focus': {
color: theme.color.linkActive,
outline: 'none'
},
[theme.breakpoints.tabletUp]: {
marginLeft: 10,
fontSize: 16
}
},
optionActive: {
color: theme.color.linkActive
}
};
export { styles }; | random_line_split | |
script_task.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The script task is the task that owns the DOM in memory, runs JavaScript, and spawns parsing
//! and layout tasks.
use dom::bindings::codegen::RegisterBindings;
use dom::bindings::codegen::InheritTypes::{EventTargetCast, NodeCast, EventCast};
use dom::bindings::js::{JS, JSRef, RootCollection, Temporary, OptionalSettable};
use dom::bindings::js::OptionalRootable;
use dom::bindings::utils::Reflectable;
use dom::bindings::utils::{wrap_for_same_compartment, pre_wrap};
use dom::document::{Document, HTMLDocument, DocumentHelpers};
use dom::element::{Element};
use dom::event::{Event_, ResizeEvent, ReflowEvent, ClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent};
use dom::event::Event;
use dom::uievent::UIEvent;
use dom::eventtarget::{EventTarget, EventTargetHelpers};
use dom::node;
use dom::node::{Node, NodeHelpers};
use dom::window::{TimerId, Window, WindowHelpers};
use dom::xmlhttprequest::{TrustedXHRAddress, XMLHttpRequest, XHRProgress};
use html::hubbub_html_parser::HtmlParserResult;
use html::hubbub_html_parser::{HtmlDiscoveredStyle, HtmlDiscoveredScript};
use html::hubbub_html_parser;
use layout_interface::AddStylesheetMsg;
use layout_interface::{LayoutChan, MatchSelectorsDocumentDamage};
use layout_interface::{ReflowDocumentDamage, ReflowForDisplay};
use layout_interface::ContentChangedDocumentDamage;
use layout_interface;
use page::{Page, IterablePage, Frame};
use geom::point::Point2D;
use js::jsapi::JS_CallFunctionValue;
use js::jsapi::{JS_SetWrapObjectCallbacks, JS_SetGCZeal, JS_DEFAULT_ZEAL_FREQ, JS_GC};
use js::jsapi::{JSContext, JSRuntime};
use js::jsval::NullValue;
use js::rust::{Cx, RtUtils};
use js::rust::with_compartment;
use js;
use servo_msg::compositor_msg::{FinishedLoading, LayerId, Loading};
use servo_msg::compositor_msg::{ScriptListener};
use servo_msg::constellation_msg::{ConstellationChan, LoadCompleteMsg, LoadUrlMsg, NavigationDirection};
use servo_msg::constellation_msg::{PipelineId, SubpageId, Failure, FailureMsg, WindowSizeData};
use servo_msg::constellation_msg;
use servo_net::image_cache_task::ImageCacheTask;
use servo_net::resource_task::ResourceTask;
use servo_util::geometry::to_frac_px;
use servo_util::task::send_on_failure;
use std::cell::RefCell;
use std::comm::{channel, Sender, Receiver};
use std::mem::replace;
use std::ptr;
use std::rc::Rc;
use std::task::TaskBuilder;
use url::Url;
use serialize::{Encoder, Encodable};
local_data_key!(pub StackRoots: *RootCollection)
/// Messages used to control the script task.
pub enum ScriptMsg {
/// Loads a new URL on the specified pipeline.
LoadMsg(PipelineId, Url),
/// Acts on a fragment URL load on the specified pipeline.
TriggerFragmentMsg(PipelineId, Url),
/// Begins a content-initiated load on the specified pipeline.
TriggerLoadMsg(PipelineId, Url),
/// Gives a channel and ID to a layout task, as well as the ID of that layout's parent
AttachLayoutMsg(NewLayoutInfo),
/// Instructs the script task to send a navigate message to the constellation.
NavigateMsg(NavigationDirection),
/// Sends a DOM event.
SendEventMsg(PipelineId, Event_),
/// Window resized. Sends a DOM event eventually, but first we combine events.
ResizeMsg(PipelineId, WindowSizeData),
/// Fires a JavaScript timeout.
FireTimerMsg(PipelineId, TimerId),
/// Notifies script that reflow is finished.
ReflowCompleteMsg(PipelineId, uint),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactiveMsg(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipelineMsg(PipelineId),
/// Notifies the script that a window associated with a particular pipeline should be closed.
ExitWindowMsg(PipelineId),
/// Notifies the script of progress on a fetch
XHRProgressMsg(TrustedXHRAddress, XHRProgress)
}
pub struct NewLayoutInfo {
pub old_pipeline_id: PipelineId,
pub new_pipeline_id: PipelineId,
pub subpage_id: SubpageId,
pub layout_chan: LayoutChan,
}
/// Encapsulates external communication with the script task.
#[deriving(Clone)]
pub struct ScriptChan(pub Sender<ScriptMsg>);
impl<S: Encoder<E>, E> Encodable<S, E> for ScriptChan {
fn encode(&self, _s: &mut S) -> Result<(), E> {
Ok(())
}
}
impl ScriptChan {
/// Creates a new script chan.
pub fn new() -> (Receiver<ScriptMsg>, ScriptChan) {
let (chan, port) = channel();
(port, ScriptChan(chan))
}
}
struct StackRootTLS;
impl StackRootTLS {
fn new(roots: &RootCollection) -> StackRootTLS {
StackRoots.replace(Some(roots as *RootCollection));
StackRootTLS
}
}
impl Drop for StackRootTLS {
fn drop(&mut self) {
let _ = StackRoots.replace(None);
}
}
/// Information for an entire page. Pages are top-level browsing contexts and can contain multiple
/// frames.
///
/// FIXME: Rename to `Page`, following WebKit?
pub struct ScriptTask {
/// A handle to the information pertaining to page layout
page: RefCell<Rc<Page>>,
/// A handle to the image cache task.
image_cache_task: ImageCacheTask,
/// A handle to the resource task.
resource_task: ResourceTask,
/// The port on which the script task receives messages (load URL, exit, etc.)
port: Receiver<ScriptMsg>,
/// A channel to hand out when some other task needs to be able to respond to a message from
/// the script task.
chan: ScriptChan,
/// For communicating load url messages to the constellation
constellation_chan: ConstellationChan,
/// A handle to the compositor for communicating ready state messages.
compositor: Box<ScriptListener>,
/// The JavaScript runtime.
js_runtime: js::rust::rt,
/// The JSContext.
js_context: RefCell<Option<Rc<Cx>>>,
mouse_over_targets: RefCell<Option<Vec<JS<Node>>>>
}
/// In the event of task failure, all data on the stack runs its destructor. However, there
/// are no reachable, owning pointers to the DOM memory, so it never gets freed by default
/// when the script task fails. The ScriptMemoryFailsafe uses the destructor bomb pattern
/// to forcibly tear down the JS compartments for pages associated with the failing ScriptTask.
struct ScriptMemoryFailsafe<'a> {
owner: Option<&'a ScriptTask>,
}
impl<'a> ScriptMemoryFailsafe<'a> {
fn neuter(&mut self) {
self.owner = None;
}
fn new(owner: &'a ScriptTask) -> ScriptMemoryFailsafe<'a> {
ScriptMemoryFailsafe {
owner: Some(owner),
}
}
}
#[unsafe_destructor]
impl<'a> Drop for ScriptMemoryFailsafe<'a> {
fn drop(&mut self) {
match self.owner {
Some(owner) => {
let mut page = owner.page.borrow_mut();
for page in page.iter() {
*page.mut_js_info() = None;
}
*owner.js_context.borrow_mut() = None;
}
None => (),
}
}
}
impl ScriptTask {
/// Creates a new script task.
pub fn new(id: PipelineId,
compositor: Box<ScriptListener>,
layout_chan: LayoutChan,
port: Receiver<ScriptMsg>,
chan: ScriptChan,
constellation_chan: ConstellationChan,
resource_task: ResourceTask,
img_cache_task: ImageCacheTask,
window_size: WindowSizeData)
-> Rc<ScriptTask> {
let (js_runtime, js_context) = ScriptTask::new_rt_and_cx();
let page = Page::new(id, None, layout_chan, window_size,
resource_task.clone(),
constellation_chan.clone(),
js_context.clone());
Rc::new(ScriptTask {
page: RefCell::new(Rc::new(page)),
image_cache_task: img_cache_task,
resource_task: resource_task,
port: port,
chan: chan,
constellation_chan: constellation_chan,
compositor: compositor,
js_runtime: js_runtime,
js_context: RefCell::new(Some(js_context)),
mouse_over_targets: RefCell::new(None)
})
}
fn new_rt_and_cx() -> (js::rust::rt, Rc<Cx>) {
let js_runtime = js::rust::rt();
assert!({
let ptr: *mut JSRuntime = (*js_runtime).ptr;
ptr.is_not_null()
});
unsafe {
// JS_SetWrapObjectCallbacks clobbers the existing wrap callback,
// and JSCompartment::wrap crashes if that happens. The only way
// to retrieve the default callback is as the result of
// JS_SetWrapObjectCallbacks, which is why we call it twice.
let callback = JS_SetWrapObjectCallbacks((*js_runtime).ptr,
None,
Some(wrap_for_same_compartment),
None);
JS_SetWrapObjectCallbacks((*js_runtime).ptr,
callback,
Some(wrap_for_same_compartment),
Some(pre_wrap));
}
let js_context = js_runtime.cx();
assert!({
let ptr: *mut JSContext = (*js_context).ptr;
ptr.is_not_null()
});
js_context.set_default_options_and_version();
js_context.set_logging_error_reporter();
unsafe {
JS_SetGCZeal((*js_context).ptr, 0, JS_DEFAULT_ZEAL_FREQ);
}
(js_runtime, js_context)
}
pub fn get_cx(&self) -> *mut JSContext {
(**self.js_context.borrow().get_ref()).ptr
}
/// Starts the script task. After calling this method, the script task will loop receiving
/// messages on its port.
pub fn start(&self) {
while self.handle_msgs() {
// Go on...
}
}
pub fn create<C:ScriptListener + Send>(
id: PipelineId,
compositor: Box<C>,
layout_chan: LayoutChan,
port: Receiver<ScriptMsg>,
chan: ScriptChan,
constellation_chan: ConstellationChan,
failure_msg: Failure,
resource_task: ResourceTask,
image_cache_task: ImageCacheTask,
window_size: WindowSizeData) {
let mut builder = TaskBuilder::new().named("ScriptTask");
let ConstellationChan(const_chan) = constellation_chan.clone();
send_on_failure(&mut builder, FailureMsg(failure_msg), const_chan);
builder.spawn(proc() {
let script_task = ScriptTask::new(id,
compositor as Box<ScriptListener>,
layout_chan,
port,
chan,
constellation_chan,
resource_task,
image_cache_task,
window_size);
let mut failsafe = ScriptMemoryFailsafe::new(&*script_task);
script_task.start();
// This must always be the very last operation performed before the task completes
failsafe.neuter();
});
}
/// Handle incoming control messages.
fn handle_msgs(&self) -> bool {
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
// Handle pending resize events.
// Gather them first to avoid a double mut borrow on self.
let mut resizes = vec!();
{
let mut page = self.page.borrow_mut();
for page in page.iter() {
// Only process a resize if layout is idle.
let layout_join_port = page.layout_join_port.deref().borrow();
if layout_join_port.is_none() {
let mut resize_event = page.resize_event.deref().get();
match resize_event.take() {
Some(size) => resizes.push((page.id, size)),
None => ()
}
page.resize_event.deref().set(None);
}
}
}
for (id, size) in resizes.move_iter() {
self.handle_event(id, ResizeEvent(size));
}
// Store new resizes, and gather all other events.
let mut sequential = vec!();
// Receive at least one message so we don't spinloop.
let mut event = self.port.recv();
loop {
match event {
ResizeMsg(id, size) => {
let mut page = self.page.borrow_mut();
let page = page.find(id).expect("resize sent to nonexistent pipeline");
page.resize_event.deref().set(Some(size));
}
_ => {
sequential.push(event);
}
}
match self.port.try_recv() {
Err(_) => break,
Ok(ev) => event = ev,
}
}
// Process the gathered events.
for msg in sequential.move_iter() {
match msg {
// TODO(tkuehn) need to handle auxiliary layouts for iframes
AttachLayoutMsg(new_layout_info) => self.handle_new_layout(new_layout_info),
LoadMsg(id, url) => self.load(id, url),
TriggerLoadMsg(id, url) => self.trigger_load(id, url),
TriggerFragmentMsg(id, url) => self.trigger_fragment(id, url),
SendEventMsg(id, event) => self.handle_event(id, event),
FireTimerMsg(id, timer_id) => self.handle_fire_timer_msg(id, timer_id),
NavigateMsg(direction) => self.handle_navigate_msg(direction),
ReflowCompleteMsg(id, reflow_id) => self.handle_reflow_complete_msg(id, reflow_id),
ResizeInactiveMsg(id, new_size) => self.handle_resize_inactive_msg(id, new_size),
ExitPipelineMsg(id) => if self.handle_exit_pipeline_msg(id) { return false },
ExitWindowMsg(id) => self.handle_exit_window_msg(id),
ResizeMsg(..) => fail!("should have handled ResizeMsg already"),
XHRProgressMsg(addr, progress) => XMLHttpRequest::handle_xhr_progress(addr, progress),
}
}
true
}
fn handle_new_layout(&self, new_layout_info: NewLayoutInfo) |
/// Handles a timer that fired.
fn handle_fire_timer_msg(&self, id: PipelineId, timer_id: TimerId) {
let mut page = self.page.borrow_mut();
let page = page.find(id).expect("ScriptTask: received fire timer msg for a
pipeline ID not associated with this script task. This is a bug.");
let frame = page.frame();
let window = frame.get_ref().window.root();
let this_value = window.deref().reflector().get_jsobject();
let data = match window.deref().active_timers.deref().borrow().find(&timer_id) {
None => return,
Some(timer_handle) => timer_handle.data,
};
// TODO: Support extra arguments. This requires passing a `*JSVal` array as `argv`.
let cx = self.get_cx();
with_compartment(cx, this_value, || {
let mut rval = NullValue();
unsafe {
JS_CallFunctionValue(cx, this_value, *data.funval,
0, ptr::mut_null(), &mut rval);
}
});
if !data.is_interval {
window.deref().active_timers.deref().borrow_mut().remove(&timer_id);
}
}
/// Handles a notification that reflow completed.
fn handle_reflow_complete_msg(&self, pipeline_id: PipelineId, reflow_id: uint) {
debug!("Script: Reflow {:?} complete for {:?}", reflow_id, pipeline_id);
let mut page = self.page.borrow_mut();
let page = page.find(pipeline_id).expect(
"ScriptTask: received a load message for a layout channel that is not associated \
with this script task. This is a bug.");
let last_reflow_id = page.last_reflow_id.deref().get();
if last_reflow_id == reflow_id {
let mut layout_join_port = page.layout_join_port.deref().borrow_mut();
*layout_join_port = None;
}
self.compositor.set_ready_state(FinishedLoading);
}
/// Handles a navigate forward or backward message.
/// TODO(tkuehn): is it ever possible to navigate only on a subframe?
fn handle_navigate_msg(&self, direction: NavigationDirection) {
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(constellation_msg::NavigateMsg(direction));
}
/// Window was resized, but this script was not active, so don't reflow yet
fn handle_resize_inactive_msg(&self, id: PipelineId, new_size: WindowSizeData) {
let mut page = self.page.borrow_mut();
let page = page.find(id).expect("Received resize message for PipelineId not associated
with a page in the page tree. This is a bug.");
page.window_size.deref().set(new_size);
let mut page_url = page.mut_url();
let last_loaded_url = replace(&mut *page_url, None);
for url in last_loaded_url.iter() {
*page_url = Some((url.ref0().clone(), true));
}
}
/// We have gotten a window.close from script, which we pass on to the compositor.
/// We do not shut down the script task now, because the compositor will ask the
/// constellation to shut down the pipeline, which will clean everything up
/// normally. If we do exit, we will tear down the DOM nodes, possibly at a point
/// where layout is still accessing them.
fn handle_exit_window_msg(&self, _: PipelineId) {
debug!("script task handling exit window msg");
// TODO(tkuehn): currently there is only one window,
// so this can afford to be naive and just shut down the
// compositor. In the future it'll need to be smarter.
self.compositor.close();
}
/// Handles a request to exit the script task and shut down layout.
/// Returns true if the script task should shut down and false otherwise.
fn handle_exit_pipeline_msg(&self, id: PipelineId) -> bool {
// If root is being exited, shut down all pages
let mut page = self.page.borrow_mut();
if page.id == id {
debug!("shutting down layout for root page {:?}", id);
*self.js_context.borrow_mut() = None;
shut_down_layout(&*page, (*self.js_runtime).ptr);
return true
}
// otherwise find just the matching page and exit all sub-pages
match page.remove(id) {
Some(ref mut page) => {
shut_down_layout(&*page, (*self.js_runtime).ptr);
false
}
// TODO(tkuehn): pipeline closing is currently duplicated across
// script and constellation, which can cause this to happen. Constellation
// needs to be smarter about exiting pipelines.
None => false,
}
}
/// The entry point to document loading. Defines bindings, sets up the window and document
/// objects, parses HTML and CSS, and kicks off initial layout.
fn load(&self, pipeline_id: PipelineId, url: Url) {
debug!("ScriptTask: loading {:?} on page {:?}", url, pipeline_id);
let mut page = self.page.borrow_mut();
let page = page.find(pipeline_id).expect("ScriptTask: received a load
message for a layout channel that is not associated with this script task. This
is a bug.");
let last_loaded_url = replace(&mut *page.mut_url(), None);
match last_loaded_url {
Some((ref loaded, needs_reflow)) if *loaded == url => {
*page.mut_url() = Some((loaded.clone(), false));
if needs_reflow {
page.damage(ContentChangedDocumentDamage);
page.reflow(ReflowForDisplay, self.chan.clone(), self.compositor);
}
return;
},
_ => (),
}
let cx = self.js_context.borrow();
let cx = cx.get_ref();
// Create the window and document objects.
let window = Window::new(cx.deref().ptr,
page.clone(),
self.chan.clone(),
self.compositor.dup(),
self.image_cache_task.clone()).root();
let document = Document::new(&*window, Some(url.clone()), HTMLDocument, None).root();
window.deref().init_browser_context(&*document);
with_compartment((**cx).ptr, window.reflector().get_jsobject(), || {
let mut js_info = page.mut_js_info();
RegisterBindings::Register(&*window, js_info.get_mut_ref());
});
self.compositor.set_ready_state(Loading);
// Parse HTML.
//
// Note: We can parse the next document in parallel with any previous documents.
let html_parsing_result = hubbub_html_parser::parse_html(&*page,
&*document,
url.clone(),
self.resource_task.clone());
let HtmlParserResult {
discovery_port
} = html_parsing_result;
{
// Create the root frame.
let mut frame = page.mut_frame();
*frame = Some(Frame {
document: JS::from_rooted(document.deref()),
window: JS::from_rooted(window.deref()),
});
}
// Send style sheets over to layout.
//
// FIXME: These should be streamed to layout as they're parsed. We don't need to stop here
// in the script task.
let mut js_scripts = None;
loop {
match discovery_port.recv_opt() {
Ok(HtmlDiscoveredScript(scripts)) => {
assert!(js_scripts.is_none());
js_scripts = Some(scripts);
}
Ok(HtmlDiscoveredStyle(sheet)) => {
let LayoutChan(ref chan) = *page.layout_chan;
chan.send(AddStylesheetMsg(sheet));
}
Err(()) => break
}
}
// Kick off the initial reflow of the page.
document.deref().content_changed();
let fragment = url.fragment.as_ref().map(|ref fragment| fragment.to_string());
{
// No more reflow required
let mut page_url = page.mut_url();
*page_url = Some((url.clone(), false));
}
// Receive the JavaScript scripts.
assert!(js_scripts.is_some());
let js_scripts = js_scripts.take_unwrap();
debug!("js_scripts: {:?}", js_scripts);
with_compartment((**cx).ptr, window.reflector().get_jsobject(), || {
// Evaluate every script in the document.
for file in js_scripts.iter() {
let global_obj = window.reflector().get_jsobject();
//FIXME: this should have some kind of error handling, or explicitly
// drop an exception on the floor.
match cx.evaluate_script(global_obj, file.data.clone(), file.url.to_str(), 1) {
Ok(_) => (),
Err(_) => println!("evaluate_script failed")
}
}
});
// We have no concept of a document loader right now, so just dispatch the
// "load" event as soon as we've finished executing all scripts parsed during
// the initial load.
let event = Event::new(&*window, "load".to_string(), false, false).root();
let doctarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&*document);
let wintarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&*window);
let _ = wintarget.dispatch_event_with_target(Some((*doctarget).clone()),
&*event);
page.fragment_node.assign(fragment.map_or(None, |fragid| page.find_fragment_node(fragid)));
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(LoadCompleteMsg(page.id, url));
}
fn scroll_fragment_point(&self, pipeline_id: PipelineId, node: &JSRef<Element>) {
let node: &JSRef<Node> = NodeCast::from_ref(node);
let rect = node.get_bounding_content_box();
let point = Point2D(to_frac_px(rect.origin.x).to_f32().unwrap(),
to_frac_px(rect.origin.y).to_f32().unwrap());
// FIXME(#2003, pcwalton): This is pretty bogus when multiple layers are involved.
// Really what needs to happen is that this needs to go through layout to ask which
// layer the element belongs to, and have it send the scroll message to the
// compositor.
self.compositor.scroll_fragment_point(pipeline_id, LayerId::null(), point);
}
/// This is the main entry point for receiving and dispatching DOM events.
///
/// TODO: Actually perform DOM event dispatch.
fn handle_event(&self, pipeline_id: PipelineId, event: Event_) {
match event {
ResizeEvent(new_size) => {
debug!("script got resize event: {:?}", new_size);
let window = {
let page = get_page(&*self.page.borrow(), pipeline_id);
page.window_size.deref().set(new_size);
let frame = page.frame();
if frame.is_some() {
page.damage(ReflowDocumentDamage);
page.reflow(ReflowForDisplay, self.chan.clone(), self.compositor)
}
let mut fragment_node = page.fragment_node.get();
match fragment_node.take().map(|node| node.root()) {
Some(node) => self.scroll_fragment_point(pipeline_id, &*node),
None => {}
}
frame.as_ref().map(|frame| Temporary::new(frame.window.clone()))
};
match window.root() {
Some(window) => {
// http://dev.w3.org/csswg/cssom-view/#resizing-viewports
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-resize
let uievent = UIEvent::new(&window.clone(),
"resize".to_string(), false,
false, Some(window.clone()),
0i32).root();
let event: &JSRef<Event> = EventCast::from_ref(&*uievent);
let wintarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&*window);
let _ = wintarget.dispatch_event_with_target(None, event);
}
None => ()
}
}
// FIXME(pcwalton): This reflows the entire document and is not incremental-y.
ReflowEvent => {
debug!("script got reflow event");
let page = get_page(&*self.page.borrow(), pipeline_id);
let frame = page.frame();
if frame.is_some() {
page.damage(MatchSelectorsDocumentDamage);
page.reflow(ReflowForDisplay, self.chan.clone(), self.compositor)
}
}
ClickEvent(_button, point) => {
debug!("ClickEvent: clicked at {:?}", point);
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.hit_test(&point) {
Some(node_address) => {
debug!("node address is {:?}", node_address);
let temp_node =
node::from_untrusted_node_address(
self.js_runtime.deref().ptr, node_address);
let maybe_node = temp_node.root().ancestors().find(|node| node.is_element());
match maybe_node {
Some(node) => {
debug!("clicked on {:s}", node.debug_str());
match *page.frame() {
Some(ref frame) => {
let window = frame.window.root();
let event =
Event::new(&*window,
"click".to_string(),
true, true).root();
let eventtarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&node);
let _ = eventtarget.dispatch_event_with_target(None, &*event);
}
None => {}
}
}
None => {}
}
}
None => {}
}
}
MouseDownEvent(..) => {}
MouseUpEvent(..) => {}
MouseMoveEvent(point) => {
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.get_nodes_under_mouse(&point) {
Some(node_address) => {
let mut target_list = vec!();
let mut target_compare = false;
let mouse_over_targets = &mut *self.mouse_over_targets.borrow_mut();
match *mouse_over_targets {
Some(ref mut mouse_over_targets) => {
for node in mouse_over_targets.mut_iter() {
let node = node.root();
node.deref().set_hover_state(false);
}
}
None => {}
}
for node_address in node_address.iter() {
let temp_node =
node::from_untrusted_node_address(
self.js_runtime.deref().ptr, *node_address);
let maybe_node = temp_node.root().ancestors().find(|node| node.is_element());
match maybe_node {
Some(node) => {
node.set_hover_state(true);
match *mouse_over_targets {
Some(ref mouse_over_targets) => {
if !target_compare {
target_compare = !mouse_over_targets.contains(&JS::from_rooted(&node));
}
}
None => {}
}
target_list.push(JS::from_rooted(&node));
}
None => {}
}
}
match *mouse_over_targets {
Some(ref mouse_over_targets) => {
if mouse_over_targets.len() != target_list.len() {
target_compare = true;
}
}
None => { target_compare = true; }
}
if target_compare {
if mouse_over_targets.is_some() {
page.damage(MatchSelectorsDocumentDamage);
page.reflow(ReflowForDisplay, self.chan.clone(), self.compositor);
}
*mouse_over_targets = Some(target_list);
}
}
None => {}
}
}
}
}
/// The entry point for content to notify that a new load has been requested
/// for the given pipeline.
fn trigger_load(&self, pipeline_id: PipelineId, url: Url) {
let ConstellationChan(ref const_chan) = self.constellation_chan;
const_chan.send(LoadUrlMsg(pipeline_id, url));
}
/// The entry point for content to notify that a fragment url has been requested
/// for the given pipeline.
fn trigger_fragment(&self, pipeline_id: PipelineId, url: Url) {
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.find_fragment_node(url.fragment.unwrap()).root() {
Some(node) => {
self.scroll_fragment_point(pipeline_id, &*node);
}
None => {}
}
}
}
/// Shuts down layout for the given page tree.
fn shut_down_layout(page_tree: &Rc<Page>, rt: *mut JSRuntime) {
for page in page_tree.iter() {
page.join_layout();
// Tell the layout task to begin shutting down, and wait until it
// processed this message.
let (response_chan, response_port) = channel();
let LayoutChan(ref chan) = *page.layout_chan;
chan.send(layout_interface::PrepareToExitMsg(response_chan));
response_port.recv();
}
// Remove our references to the DOM objects in this page tree.
for page in page_tree.iter() {
*page.mut_frame() = None;
}
// Drop our references to the JSContext, potentially triggering a GC.
for page in page_tree.iter() {
*page.mut_js_info() = None;
}
// Force a GC to make sure that our DOM reflectors are released before we tell
// layout to exit.
unsafe {
JS_GC(rt);
}
// Destroy the layout task. If there were node leaks, layout will now crash safely.
for page in page_tree.iter() {
let LayoutChan(ref chan) = *page.layout_chan;
chan.send(layout_interface::ExitNowMsg);
}
}
fn get_page(page: &Rc<Page>, pipeline_id: PipelineId) -> Rc<Page> {
page.find(pipeline_id).expect("ScriptTask: received an event \
message for a layout channel that is not associated with this script task.\
This is a bug.")
}
| {
debug!("Script: new layout: {:?}", new_layout_info);
let NewLayoutInfo {
old_pipeline_id,
new_pipeline_id,
subpage_id,
layout_chan
} = new_layout_info;
let mut page = self.page.borrow_mut();
let parent_page = page.find(old_pipeline_id).expect("ScriptTask: received a layout
whose parent has a PipelineId which does not correspond to a pipeline in the script
task's page tree. This is a bug.");
let new_page = {
let window_size = parent_page.window_size.deref().get();
Page::new(new_pipeline_id, Some(subpage_id), layout_chan, window_size,
parent_page.resource_task.deref().clone(),
self.constellation_chan.clone(),
self.js_context.borrow().get_ref().clone())
};
parent_page.children.deref().borrow_mut().push(Rc::new(new_page));
} | identifier_body |
script_task.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The script task is the task that owns the DOM in memory, runs JavaScript, and spawns parsing
//! and layout tasks.
use dom::bindings::codegen::RegisterBindings;
use dom::bindings::codegen::InheritTypes::{EventTargetCast, NodeCast, EventCast};
use dom::bindings::js::{JS, JSRef, RootCollection, Temporary, OptionalSettable};
use dom::bindings::js::OptionalRootable;
use dom::bindings::utils::Reflectable;
use dom::bindings::utils::{wrap_for_same_compartment, pre_wrap};
use dom::document::{Document, HTMLDocument, DocumentHelpers};
use dom::element::{Element};
use dom::event::{Event_, ResizeEvent, ReflowEvent, ClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent};
use dom::event::Event;
use dom::uievent::UIEvent;
use dom::eventtarget::{EventTarget, EventTargetHelpers};
use dom::node;
use dom::node::{Node, NodeHelpers};
use dom::window::{TimerId, Window, WindowHelpers};
use dom::xmlhttprequest::{TrustedXHRAddress, XMLHttpRequest, XHRProgress};
use html::hubbub_html_parser::HtmlParserResult;
use html::hubbub_html_parser::{HtmlDiscoveredStyle, HtmlDiscoveredScript};
use html::hubbub_html_parser;
use layout_interface::AddStylesheetMsg;
use layout_interface::{LayoutChan, MatchSelectorsDocumentDamage};
use layout_interface::{ReflowDocumentDamage, ReflowForDisplay};
use layout_interface::ContentChangedDocumentDamage;
use layout_interface;
use page::{Page, IterablePage, Frame};
use geom::point::Point2D;
use js::jsapi::JS_CallFunctionValue;
use js::jsapi::{JS_SetWrapObjectCallbacks, JS_SetGCZeal, JS_DEFAULT_ZEAL_FREQ, JS_GC};
use js::jsapi::{JSContext, JSRuntime};
use js::jsval::NullValue;
use js::rust::{Cx, RtUtils};
use js::rust::with_compartment;
use js;
use servo_msg::compositor_msg::{FinishedLoading, LayerId, Loading};
use servo_msg::compositor_msg::{ScriptListener};
use servo_msg::constellation_msg::{ConstellationChan, LoadCompleteMsg, LoadUrlMsg, NavigationDirection};
use servo_msg::constellation_msg::{PipelineId, SubpageId, Failure, FailureMsg, WindowSizeData};
use servo_msg::constellation_msg;
use servo_net::image_cache_task::ImageCacheTask;
use servo_net::resource_task::ResourceTask;
use servo_util::geometry::to_frac_px;
use servo_util::task::send_on_failure;
use std::cell::RefCell;
use std::comm::{channel, Sender, Receiver};
use std::mem::replace;
use std::ptr;
use std::rc::Rc;
use std::task::TaskBuilder;
use url::Url;
use serialize::{Encoder, Encodable};
local_data_key!(pub StackRoots: *RootCollection)
/// Messages used to control the script task.
pub enum ScriptMsg {
/// Loads a new URL on the specified pipeline.
LoadMsg(PipelineId, Url),
/// Acts on a fragment URL load on the specified pipeline.
TriggerFragmentMsg(PipelineId, Url),
/// Begins a content-initiated load on the specified pipeline.
TriggerLoadMsg(PipelineId, Url),
/// Gives a channel and ID to a layout task, as well as the ID of that layout's parent
AttachLayoutMsg(NewLayoutInfo),
/// Instructs the script task to send a navigate message to the constellation.
NavigateMsg(NavigationDirection),
/// Sends a DOM event.
SendEventMsg(PipelineId, Event_),
/// Window resized. Sends a DOM event eventually, but first we combine events.
ResizeMsg(PipelineId, WindowSizeData),
/// Fires a JavaScript timeout.
FireTimerMsg(PipelineId, TimerId),
/// Notifies script that reflow is finished.
ReflowCompleteMsg(PipelineId, uint),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactiveMsg(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipelineMsg(PipelineId),
/// Notifies the script that a window associated with a particular pipeline should be closed.
ExitWindowMsg(PipelineId),
/// Notifies the script of progress on a fetch
XHRProgressMsg(TrustedXHRAddress, XHRProgress)
}
pub struct NewLayoutInfo {
pub old_pipeline_id: PipelineId,
pub new_pipeline_id: PipelineId,
pub subpage_id: SubpageId,
pub layout_chan: LayoutChan,
}
/// Encapsulates external communication with the script task.
#[deriving(Clone)]
pub struct ScriptChan(pub Sender<ScriptMsg>);
impl<S: Encoder<E>, E> Encodable<S, E> for ScriptChan {
fn encode(&self, _s: &mut S) -> Result<(), E> {
Ok(())
}
}
impl ScriptChan {
/// Creates a new script chan.
pub fn new() -> (Receiver<ScriptMsg>, ScriptChan) {
let (chan, port) = channel();
(port, ScriptChan(chan))
}
}
struct StackRootTLS;
impl StackRootTLS {
fn new(roots: &RootCollection) -> StackRootTLS {
StackRoots.replace(Some(roots as *RootCollection));
StackRootTLS
}
}
impl Drop for StackRootTLS {
fn drop(&mut self) {
let _ = StackRoots.replace(None);
}
}
/// Information for an entire page. Pages are top-level browsing contexts and can contain multiple
/// frames.
///
/// FIXME: Rename to `Page`, following WebKit?
pub struct ScriptTask {
/// A handle to the information pertaining to page layout
page: RefCell<Rc<Page>>,
/// A handle to the image cache task.
image_cache_task: ImageCacheTask,
/// A handle to the resource task.
resource_task: ResourceTask,
/// The port on which the script task receives messages (load URL, exit, etc.)
port: Receiver<ScriptMsg>,
/// A channel to hand out when some other task needs to be able to respond to a message from
/// the script task.
chan: ScriptChan,
/// For communicating load url messages to the constellation
constellation_chan: ConstellationChan,
/// A handle to the compositor for communicating ready state messages.
compositor: Box<ScriptListener>,
/// The JavaScript runtime.
js_runtime: js::rust::rt,
/// The JSContext.
js_context: RefCell<Option<Rc<Cx>>>,
mouse_over_targets: RefCell<Option<Vec<JS<Node>>>>
}
/// In the event of task failure, all data on the stack runs its destructor. However, there
/// are no reachable, owning pointers to the DOM memory, so it never gets freed by default
/// when the script task fails. The ScriptMemoryFailsafe uses the destructor bomb pattern
/// to forcibly tear down the JS compartments for pages associated with the failing ScriptTask.
struct ScriptMemoryFailsafe<'a> {
owner: Option<&'a ScriptTask>,
}
impl<'a> ScriptMemoryFailsafe<'a> {
fn neuter(&mut self) {
self.owner = None;
}
fn new(owner: &'a ScriptTask) -> ScriptMemoryFailsafe<'a> {
ScriptMemoryFailsafe {
owner: Some(owner),
}
}
}
#[unsafe_destructor]
impl<'a> Drop for ScriptMemoryFailsafe<'a> {
fn drop(&mut self) {
match self.owner {
Some(owner) => {
let mut page = owner.page.borrow_mut();
for page in page.iter() {
*page.mut_js_info() = None;
}
*owner.js_context.borrow_mut() = None;
}
None => (),
}
}
}
impl ScriptTask {
/// Creates a new script task.
pub fn new(id: PipelineId,
compositor: Box<ScriptListener>,
layout_chan: LayoutChan,
port: Receiver<ScriptMsg>,
chan: ScriptChan,
constellation_chan: ConstellationChan,
resource_task: ResourceTask,
img_cache_task: ImageCacheTask,
window_size: WindowSizeData)
-> Rc<ScriptTask> {
let (js_runtime, js_context) = ScriptTask::new_rt_and_cx();
let page = Page::new(id, None, layout_chan, window_size,
resource_task.clone(),
constellation_chan.clone(),
js_context.clone());
Rc::new(ScriptTask {
page: RefCell::new(Rc::new(page)),
image_cache_task: img_cache_task,
resource_task: resource_task,
port: port,
chan: chan,
constellation_chan: constellation_chan,
compositor: compositor,
js_runtime: js_runtime,
js_context: RefCell::new(Some(js_context)),
mouse_over_targets: RefCell::new(None)
})
}
fn new_rt_and_cx() -> (js::rust::rt, Rc<Cx>) {
let js_runtime = js::rust::rt();
assert!({
let ptr: *mut JSRuntime = (*js_runtime).ptr;
ptr.is_not_null()
});
unsafe {
// JS_SetWrapObjectCallbacks clobbers the existing wrap callback,
// and JSCompartment::wrap crashes if that happens. The only way
// to retrieve the default callback is as the result of
// JS_SetWrapObjectCallbacks, which is why we call it twice.
let callback = JS_SetWrapObjectCallbacks((*js_runtime).ptr,
None,
Some(wrap_for_same_compartment),
None);
JS_SetWrapObjectCallbacks((*js_runtime).ptr,
callback,
Some(wrap_for_same_compartment),
Some(pre_wrap));
}
let js_context = js_runtime.cx();
assert!({
let ptr: *mut JSContext = (*js_context).ptr;
ptr.is_not_null()
});
js_context.set_default_options_and_version();
js_context.set_logging_error_reporter();
unsafe {
JS_SetGCZeal((*js_context).ptr, 0, JS_DEFAULT_ZEAL_FREQ);
}
(js_runtime, js_context)
}
pub fn get_cx(&self) -> *mut JSContext {
(**self.js_context.borrow().get_ref()).ptr
}
/// Starts the script task. After calling this method, the script task will loop receiving
/// messages on its port.
pub fn start(&self) {
while self.handle_msgs() {
// Go on...
}
}
pub fn create<C:ScriptListener + Send>(
id: PipelineId,
compositor: Box<C>,
layout_chan: LayoutChan,
port: Receiver<ScriptMsg>,
chan: ScriptChan,
constellation_chan: ConstellationChan,
failure_msg: Failure,
resource_task: ResourceTask,
image_cache_task: ImageCacheTask,
window_size: WindowSizeData) {
let mut builder = TaskBuilder::new().named("ScriptTask");
let ConstellationChan(const_chan) = constellation_chan.clone();
send_on_failure(&mut builder, FailureMsg(failure_msg), const_chan);
builder.spawn(proc() {
let script_task = ScriptTask::new(id,
compositor as Box<ScriptListener>,
layout_chan,
port,
chan,
constellation_chan,
resource_task,
image_cache_task,
window_size);
let mut failsafe = ScriptMemoryFailsafe::new(&*script_task);
script_task.start();
// This must always be the very last operation performed before the task completes
failsafe.neuter();
});
}
/// Handle incoming control messages.
fn handle_msgs(&self) -> bool {
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
// Handle pending resize events.
// Gather them first to avoid a double mut borrow on self.
let mut resizes = vec!();
{
let mut page = self.page.borrow_mut();
for page in page.iter() {
// Only process a resize if layout is idle.
let layout_join_port = page.layout_join_port.deref().borrow();
if layout_join_port.is_none() {
let mut resize_event = page.resize_event.deref().get();
match resize_event.take() {
Some(size) => resizes.push((page.id, size)),
None => ()
}
page.resize_event.deref().set(None);
}
}
}
for (id, size) in resizes.move_iter() {
self.handle_event(id, ResizeEvent(size));
}
// Store new resizes, and gather all other events.
let mut sequential = vec!();
// Receive at least one message so we don't spinloop.
let mut event = self.port.recv();
loop {
match event {
ResizeMsg(id, size) => {
let mut page = self.page.borrow_mut();
let page = page.find(id).expect("resize sent to nonexistent pipeline");
page.resize_event.deref().set(Some(size));
}
_ => {
sequential.push(event);
}
}
match self.port.try_recv() {
Err(_) => break,
Ok(ev) => event = ev,
}
}
// Process the gathered events.
for msg in sequential.move_iter() {
match msg {
// TODO(tkuehn) need to handle auxiliary layouts for iframes
AttachLayoutMsg(new_layout_info) => self.handle_new_layout(new_layout_info),
LoadMsg(id, url) => self.load(id, url),
TriggerLoadMsg(id, url) => self.trigger_load(id, url),
TriggerFragmentMsg(id, url) => self.trigger_fragment(id, url),
SendEventMsg(id, event) => self.handle_event(id, event),
FireTimerMsg(id, timer_id) => self.handle_fire_timer_msg(id, timer_id),
NavigateMsg(direction) => self.handle_navigate_msg(direction),
ReflowCompleteMsg(id, reflow_id) => self.handle_reflow_complete_msg(id, reflow_id),
ResizeInactiveMsg(id, new_size) => self.handle_resize_inactive_msg(id, new_size),
ExitPipelineMsg(id) => if self.handle_exit_pipeline_msg(id) { return false },
ExitWindowMsg(id) => self.handle_exit_window_msg(id),
ResizeMsg(..) => fail!("should have handled ResizeMsg already"),
XHRProgressMsg(addr, progress) => XMLHttpRequest::handle_xhr_progress(addr, progress),
}
}
true
}
fn handle_new_layout(&self, new_layout_info: NewLayoutInfo) {
debug!("Script: new layout: {:?}", new_layout_info);
let NewLayoutInfo {
old_pipeline_id,
new_pipeline_id,
subpage_id,
layout_chan
} = new_layout_info;
let mut page = self.page.borrow_mut();
let parent_page = page.find(old_pipeline_id).expect("ScriptTask: received a layout
whose parent has a PipelineId which does not correspond to a pipeline in the script
task's page tree. This is a bug.");
let new_page = {
let window_size = parent_page.window_size.deref().get();
Page::new(new_pipeline_id, Some(subpage_id), layout_chan, window_size,
parent_page.resource_task.deref().clone(),
self.constellation_chan.clone(),
self.js_context.borrow().get_ref().clone())
};
parent_page.children.deref().borrow_mut().push(Rc::new(new_page));
}
/// Handles a timer that fired.
fn handle_fire_timer_msg(&self, id: PipelineId, timer_id: TimerId) {
let mut page = self.page.borrow_mut();
let page = page.find(id).expect("ScriptTask: received fire timer msg for a
pipeline ID not associated with this script task. This is a bug.");
let frame = page.frame();
let window = frame.get_ref().window.root();
let this_value = window.deref().reflector().get_jsobject();
let data = match window.deref().active_timers.deref().borrow().find(&timer_id) {
None => return,
Some(timer_handle) => timer_handle.data,
};
// TODO: Support extra arguments. This requires passing a `*JSVal` array as `argv`.
let cx = self.get_cx();
with_compartment(cx, this_value, || {
let mut rval = NullValue();
unsafe {
JS_CallFunctionValue(cx, this_value, *data.funval,
0, ptr::mut_null(), &mut rval);
}
});
if !data.is_interval {
window.deref().active_timers.deref().borrow_mut().remove(&timer_id);
}
}
/// Handles a notification that reflow completed.
fn handle_reflow_complete_msg(&self, pipeline_id: PipelineId, reflow_id: uint) {
debug!("Script: Reflow {:?} complete for {:?}", reflow_id, pipeline_id);
let mut page = self.page.borrow_mut();
let page = page.find(pipeline_id).expect(
"ScriptTask: received a load message for a layout channel that is not associated \
with this script task. This is a bug.");
let last_reflow_id = page.last_reflow_id.deref().get();
if last_reflow_id == reflow_id {
let mut layout_join_port = page.layout_join_port.deref().borrow_mut();
*layout_join_port = None;
}
self.compositor.set_ready_state(FinishedLoading);
}
/// Handles a navigate forward or backward message.
/// TODO(tkuehn): is it ever possible to navigate only on a subframe?
fn handle_navigate_msg(&self, direction: NavigationDirection) {
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(constellation_msg::NavigateMsg(direction));
}
/// Window was resized, but this script was not active, so don't reflow yet
fn handle_resize_inactive_msg(&self, id: PipelineId, new_size: WindowSizeData) {
let mut page = self.page.borrow_mut();
let page = page.find(id).expect("Received resize message for PipelineId not associated
with a page in the page tree. This is a bug.");
page.window_size.deref().set(new_size);
let mut page_url = page.mut_url();
let last_loaded_url = replace(&mut *page_url, None);
for url in last_loaded_url.iter() {
*page_url = Some((url.ref0().clone(), true));
}
}
/// We have gotten a window.close from script, which we pass on to the compositor.
/// We do not shut down the script task now, because the compositor will ask the
/// constellation to shut down the pipeline, which will clean everything up
/// normally. If we do exit, we will tear down the DOM nodes, possibly at a point
/// where layout is still accessing them.
fn | (&self, _: PipelineId) {
debug!("script task handling exit window msg");
// TODO(tkuehn): currently there is only one window,
// so this can afford to be naive and just shut down the
// compositor. In the future it'll need to be smarter.
self.compositor.close();
}
/// Handles a request to exit the script task and shut down layout.
/// Returns true if the script task should shut down and false otherwise.
fn handle_exit_pipeline_msg(&self, id: PipelineId) -> bool {
// If root is being exited, shut down all pages
let mut page = self.page.borrow_mut();
if page.id == id {
debug!("shutting down layout for root page {:?}", id);
*self.js_context.borrow_mut() = None;
shut_down_layout(&*page, (*self.js_runtime).ptr);
return true
}
// otherwise find just the matching page and exit all sub-pages
match page.remove(id) {
Some(ref mut page) => {
shut_down_layout(&*page, (*self.js_runtime).ptr);
false
}
// TODO(tkuehn): pipeline closing is currently duplicated across
// script and constellation, which can cause this to happen. Constellation
// needs to be smarter about exiting pipelines.
None => false,
}
}
/// The entry point to document loading. Defines bindings, sets up the window and document
/// objects, parses HTML and CSS, and kicks off initial layout.
fn load(&self, pipeline_id: PipelineId, url: Url) {
debug!("ScriptTask: loading {:?} on page {:?}", url, pipeline_id);
let mut page = self.page.borrow_mut();
let page = page.find(pipeline_id).expect("ScriptTask: received a load
message for a layout channel that is not associated with this script task. This
is a bug.");
let last_loaded_url = replace(&mut *page.mut_url(), None);
match last_loaded_url {
Some((ref loaded, needs_reflow)) if *loaded == url => {
*page.mut_url() = Some((loaded.clone(), false));
if needs_reflow {
page.damage(ContentChangedDocumentDamage);
page.reflow(ReflowForDisplay, self.chan.clone(), self.compositor);
}
return;
},
_ => (),
}
let cx = self.js_context.borrow();
let cx = cx.get_ref();
// Create the window and document objects.
let window = Window::new(cx.deref().ptr,
page.clone(),
self.chan.clone(),
self.compositor.dup(),
self.image_cache_task.clone()).root();
let document = Document::new(&*window, Some(url.clone()), HTMLDocument, None).root();
window.deref().init_browser_context(&*document);
with_compartment((**cx).ptr, window.reflector().get_jsobject(), || {
let mut js_info = page.mut_js_info();
RegisterBindings::Register(&*window, js_info.get_mut_ref());
});
self.compositor.set_ready_state(Loading);
// Parse HTML.
//
// Note: We can parse the next document in parallel with any previous documents.
let html_parsing_result = hubbub_html_parser::parse_html(&*page,
&*document,
url.clone(),
self.resource_task.clone());
let HtmlParserResult {
discovery_port
} = html_parsing_result;
{
// Create the root frame.
let mut frame = page.mut_frame();
*frame = Some(Frame {
document: JS::from_rooted(document.deref()),
window: JS::from_rooted(window.deref()),
});
}
// Send style sheets over to layout.
//
// FIXME: These should be streamed to layout as they're parsed. We don't need to stop here
// in the script task.
let mut js_scripts = None;
loop {
match discovery_port.recv_opt() {
Ok(HtmlDiscoveredScript(scripts)) => {
assert!(js_scripts.is_none());
js_scripts = Some(scripts);
}
Ok(HtmlDiscoveredStyle(sheet)) => {
let LayoutChan(ref chan) = *page.layout_chan;
chan.send(AddStylesheetMsg(sheet));
}
Err(()) => break
}
}
// Kick off the initial reflow of the page.
document.deref().content_changed();
let fragment = url.fragment.as_ref().map(|ref fragment| fragment.to_string());
{
// No more reflow required
let mut page_url = page.mut_url();
*page_url = Some((url.clone(), false));
}
// Receive the JavaScript scripts.
assert!(js_scripts.is_some());
let js_scripts = js_scripts.take_unwrap();
debug!("js_scripts: {:?}", js_scripts);
with_compartment((**cx).ptr, window.reflector().get_jsobject(), || {
// Evaluate every script in the document.
for file in js_scripts.iter() {
let global_obj = window.reflector().get_jsobject();
//FIXME: this should have some kind of error handling, or explicitly
// drop an exception on the floor.
match cx.evaluate_script(global_obj, file.data.clone(), file.url.to_str(), 1) {
Ok(_) => (),
Err(_) => println!("evaluate_script failed")
}
}
});
// We have no concept of a document loader right now, so just dispatch the
// "load" event as soon as we've finished executing all scripts parsed during
// the initial load.
let event = Event::new(&*window, "load".to_string(), false, false).root();
let doctarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&*document);
let wintarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&*window);
let _ = wintarget.dispatch_event_with_target(Some((*doctarget).clone()),
&*event);
page.fragment_node.assign(fragment.map_or(None, |fragid| page.find_fragment_node(fragid)));
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(LoadCompleteMsg(page.id, url));
}
fn scroll_fragment_point(&self, pipeline_id: PipelineId, node: &JSRef<Element>) {
let node: &JSRef<Node> = NodeCast::from_ref(node);
let rect = node.get_bounding_content_box();
let point = Point2D(to_frac_px(rect.origin.x).to_f32().unwrap(),
to_frac_px(rect.origin.y).to_f32().unwrap());
// FIXME(#2003, pcwalton): This is pretty bogus when multiple layers are involved.
// Really what needs to happen is that this needs to go through layout to ask which
// layer the element belongs to, and have it send the scroll message to the
// compositor.
self.compositor.scroll_fragment_point(pipeline_id, LayerId::null(), point);
}
/// This is the main entry point for receiving and dispatching DOM events.
///
/// TODO: Actually perform DOM event dispatch.
fn handle_event(&self, pipeline_id: PipelineId, event: Event_) {
match event {
ResizeEvent(new_size) => {
debug!("script got resize event: {:?}", new_size);
let window = {
let page = get_page(&*self.page.borrow(), pipeline_id);
page.window_size.deref().set(new_size);
let frame = page.frame();
if frame.is_some() {
page.damage(ReflowDocumentDamage);
page.reflow(ReflowForDisplay, self.chan.clone(), self.compositor)
}
let mut fragment_node = page.fragment_node.get();
match fragment_node.take().map(|node| node.root()) {
Some(node) => self.scroll_fragment_point(pipeline_id, &*node),
None => {}
}
frame.as_ref().map(|frame| Temporary::new(frame.window.clone()))
};
match window.root() {
Some(window) => {
// http://dev.w3.org/csswg/cssom-view/#resizing-viewports
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-resize
let uievent = UIEvent::new(&window.clone(),
"resize".to_string(), false,
false, Some(window.clone()),
0i32).root();
let event: &JSRef<Event> = EventCast::from_ref(&*uievent);
let wintarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&*window);
let _ = wintarget.dispatch_event_with_target(None, event);
}
None => ()
}
}
// FIXME(pcwalton): This reflows the entire document and is not incremental-y.
ReflowEvent => {
debug!("script got reflow event");
let page = get_page(&*self.page.borrow(), pipeline_id);
let frame = page.frame();
if frame.is_some() {
page.damage(MatchSelectorsDocumentDamage);
page.reflow(ReflowForDisplay, self.chan.clone(), self.compositor)
}
}
ClickEvent(_button, point) => {
debug!("ClickEvent: clicked at {:?}", point);
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.hit_test(&point) {
Some(node_address) => {
debug!("node address is {:?}", node_address);
let temp_node =
node::from_untrusted_node_address(
self.js_runtime.deref().ptr, node_address);
let maybe_node = temp_node.root().ancestors().find(|node| node.is_element());
match maybe_node {
Some(node) => {
debug!("clicked on {:s}", node.debug_str());
match *page.frame() {
Some(ref frame) => {
let window = frame.window.root();
let event =
Event::new(&*window,
"click".to_string(),
true, true).root();
let eventtarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&node);
let _ = eventtarget.dispatch_event_with_target(None, &*event);
}
None => {}
}
}
None => {}
}
}
None => {}
}
}
MouseDownEvent(..) => {}
MouseUpEvent(..) => {}
MouseMoveEvent(point) => {
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.get_nodes_under_mouse(&point) {
Some(node_address) => {
let mut target_list = vec!();
let mut target_compare = false;
let mouse_over_targets = &mut *self.mouse_over_targets.borrow_mut();
match *mouse_over_targets {
Some(ref mut mouse_over_targets) => {
for node in mouse_over_targets.mut_iter() {
let node = node.root();
node.deref().set_hover_state(false);
}
}
None => {}
}
for node_address in node_address.iter() {
let temp_node =
node::from_untrusted_node_address(
self.js_runtime.deref().ptr, *node_address);
let maybe_node = temp_node.root().ancestors().find(|node| node.is_element());
match maybe_node {
Some(node) => {
node.set_hover_state(true);
match *mouse_over_targets {
Some(ref mouse_over_targets) => {
if !target_compare {
target_compare = !mouse_over_targets.contains(&JS::from_rooted(&node));
}
}
None => {}
}
target_list.push(JS::from_rooted(&node));
}
None => {}
}
}
match *mouse_over_targets {
Some(ref mouse_over_targets) => {
if mouse_over_targets.len() != target_list.len() {
target_compare = true;
}
}
None => { target_compare = true; }
}
if target_compare {
if mouse_over_targets.is_some() {
page.damage(MatchSelectorsDocumentDamage);
page.reflow(ReflowForDisplay, self.chan.clone(), self.compositor);
}
*mouse_over_targets = Some(target_list);
}
}
None => {}
}
}
}
}
/// The entry point for content to notify that a new load has been requested
/// for the given pipeline.
fn trigger_load(&self, pipeline_id: PipelineId, url: Url) {
let ConstellationChan(ref const_chan) = self.constellation_chan;
const_chan.send(LoadUrlMsg(pipeline_id, url));
}
/// The entry point for content to notify that a fragment url has been requested
/// for the given pipeline.
fn trigger_fragment(&self, pipeline_id: PipelineId, url: Url) {
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.find_fragment_node(url.fragment.unwrap()).root() {
Some(node) => {
self.scroll_fragment_point(pipeline_id, &*node);
}
None => {}
}
}
}
/// Shuts down layout for the given page tree.
fn shut_down_layout(page_tree: &Rc<Page>, rt: *mut JSRuntime) {
for page in page_tree.iter() {
page.join_layout();
// Tell the layout task to begin shutting down, and wait until it
// processed this message.
let (response_chan, response_port) = channel();
let LayoutChan(ref chan) = *page.layout_chan;
chan.send(layout_interface::PrepareToExitMsg(response_chan));
response_port.recv();
}
// Remove our references to the DOM objects in this page tree.
for page in page_tree.iter() {
*page.mut_frame() = None;
}
// Drop our references to the JSContext, potentially triggering a GC.
for page in page_tree.iter() {
*page.mut_js_info() = None;
}
// Force a GC to make sure that our DOM reflectors are released before we tell
// layout to exit.
unsafe {
JS_GC(rt);
}
// Destroy the layout task. If there were node leaks, layout will now crash safely.
for page in page_tree.iter() {
let LayoutChan(ref chan) = *page.layout_chan;
chan.send(layout_interface::ExitNowMsg);
}
}
fn get_page(page: &Rc<Page>, pipeline_id: PipelineId) -> Rc<Page> {
page.find(pipeline_id).expect("ScriptTask: received an event \
message for a layout channel that is not associated with this script task.\
This is a bug.")
}
| handle_exit_window_msg | identifier_name |
script_task.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The script task is the task that owns the DOM in memory, runs JavaScript, and spawns parsing
//! and layout tasks.
use dom::bindings::codegen::RegisterBindings;
use dom::bindings::codegen::InheritTypes::{EventTargetCast, NodeCast, EventCast};
use dom::bindings::js::{JS, JSRef, RootCollection, Temporary, OptionalSettable};
use dom::bindings::js::OptionalRootable;
use dom::bindings::utils::Reflectable;
use dom::bindings::utils::{wrap_for_same_compartment, pre_wrap};
use dom::document::{Document, HTMLDocument, DocumentHelpers};
use dom::element::{Element};
use dom::event::{Event_, ResizeEvent, ReflowEvent, ClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent};
use dom::event::Event;
use dom::uievent::UIEvent;
use dom::eventtarget::{EventTarget, EventTargetHelpers};
use dom::node;
use dom::node::{Node, NodeHelpers};
use dom::window::{TimerId, Window, WindowHelpers};
use dom::xmlhttprequest::{TrustedXHRAddress, XMLHttpRequest, XHRProgress};
use html::hubbub_html_parser::HtmlParserResult;
use html::hubbub_html_parser::{HtmlDiscoveredStyle, HtmlDiscoveredScript};
use html::hubbub_html_parser;
use layout_interface::AddStylesheetMsg;
use layout_interface::{LayoutChan, MatchSelectorsDocumentDamage};
use layout_interface::{ReflowDocumentDamage, ReflowForDisplay};
use layout_interface::ContentChangedDocumentDamage;
use layout_interface;
use page::{Page, IterablePage, Frame};
use geom::point::Point2D;
use js::jsapi::JS_CallFunctionValue;
use js::jsapi::{JS_SetWrapObjectCallbacks, JS_SetGCZeal, JS_DEFAULT_ZEAL_FREQ, JS_GC};
use js::jsapi::{JSContext, JSRuntime};
use js::jsval::NullValue;
use js::rust::{Cx, RtUtils};
use js::rust::with_compartment;
use js;
use servo_msg::compositor_msg::{FinishedLoading, LayerId, Loading};
use servo_msg::compositor_msg::{ScriptListener};
use servo_msg::constellation_msg::{ConstellationChan, LoadCompleteMsg, LoadUrlMsg, NavigationDirection};
use servo_msg::constellation_msg::{PipelineId, SubpageId, Failure, FailureMsg, WindowSizeData};
use servo_msg::constellation_msg;
use servo_net::image_cache_task::ImageCacheTask;
use servo_net::resource_task::ResourceTask;
use servo_util::geometry::to_frac_px;
use servo_util::task::send_on_failure;
use std::cell::RefCell;
use std::comm::{channel, Sender, Receiver};
use std::mem::replace;
use std::ptr;
use std::rc::Rc;
use std::task::TaskBuilder;
use url::Url;
use serialize::{Encoder, Encodable};
local_data_key!(pub StackRoots: *RootCollection)
/// Messages used to control the script task.
pub enum ScriptMsg {
/// Loads a new URL on the specified pipeline.
LoadMsg(PipelineId, Url),
/// Acts on a fragment URL load on the specified pipeline.
TriggerFragmentMsg(PipelineId, Url),
/// Begins a content-initiated load on the specified pipeline.
TriggerLoadMsg(PipelineId, Url),
/// Gives a channel and ID to a layout task, as well as the ID of that layout's parent
AttachLayoutMsg(NewLayoutInfo),
/// Instructs the script task to send a navigate message to the constellation.
NavigateMsg(NavigationDirection),
/// Sends a DOM event.
SendEventMsg(PipelineId, Event_),
/// Window resized. Sends a DOM event eventually, but first we combine events.
ResizeMsg(PipelineId, WindowSizeData),
/// Fires a JavaScript timeout.
FireTimerMsg(PipelineId, TimerId),
/// Notifies script that reflow is finished.
ReflowCompleteMsg(PipelineId, uint),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactiveMsg(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipelineMsg(PipelineId),
/// Notifies the script that a window associated with a particular pipeline should be closed.
ExitWindowMsg(PipelineId),
/// Notifies the script of progress on a fetch
XHRProgressMsg(TrustedXHRAddress, XHRProgress)
}
pub struct NewLayoutInfo {
pub old_pipeline_id: PipelineId,
pub new_pipeline_id: PipelineId,
pub subpage_id: SubpageId,
pub layout_chan: LayoutChan,
}
/// Encapsulates external communication with the script task.
#[deriving(Clone)]
pub struct ScriptChan(pub Sender<ScriptMsg>);
impl<S: Encoder<E>, E> Encodable<S, E> for ScriptChan {
fn encode(&self, _s: &mut S) -> Result<(), E> {
Ok(())
}
}
impl ScriptChan {
/// Creates a new script chan.
pub fn new() -> (Receiver<ScriptMsg>, ScriptChan) {
let (chan, port) = channel();
(port, ScriptChan(chan))
}
}
struct StackRootTLS;
impl StackRootTLS {
fn new(roots: &RootCollection) -> StackRootTLS {
StackRoots.replace(Some(roots as *RootCollection));
StackRootTLS
}
}
impl Drop for StackRootTLS {
fn drop(&mut self) {
let _ = StackRoots.replace(None);
}
}
/// Information for an entire page. Pages are top-level browsing contexts and can contain multiple
/// frames.
///
/// FIXME: Rename to `Page`, following WebKit?
pub struct ScriptTask {
/// A handle to the information pertaining to page layout
page: RefCell<Rc<Page>>,
/// A handle to the image cache task.
image_cache_task: ImageCacheTask,
/// A handle to the resource task.
resource_task: ResourceTask,
/// The port on which the script task receives messages (load URL, exit, etc.)
port: Receiver<ScriptMsg>,
/// A channel to hand out when some other task needs to be able to respond to a message from
/// the script task.
chan: ScriptChan,
/// For communicating load url messages to the constellation
constellation_chan: ConstellationChan,
/// A handle to the compositor for communicating ready state messages.
compositor: Box<ScriptListener>,
/// The JavaScript runtime.
js_runtime: js::rust::rt,
/// The JSContext.
js_context: RefCell<Option<Rc<Cx>>>,
mouse_over_targets: RefCell<Option<Vec<JS<Node>>>>
}
/// In the event of task failure, all data on the stack runs its destructor. However, there
/// are no reachable, owning pointers to the DOM memory, so it never gets freed by default
/// when the script task fails. The ScriptMemoryFailsafe uses the destructor bomb pattern
/// to forcibly tear down the JS compartments for pages associated with the failing ScriptTask.
struct ScriptMemoryFailsafe<'a> {
owner: Option<&'a ScriptTask>,
}
impl<'a> ScriptMemoryFailsafe<'a> {
fn neuter(&mut self) {
self.owner = None;
}
fn new(owner: &'a ScriptTask) -> ScriptMemoryFailsafe<'a> {
ScriptMemoryFailsafe {
owner: Some(owner),
}
}
}
#[unsafe_destructor]
impl<'a> Drop for ScriptMemoryFailsafe<'a> {
fn drop(&mut self) {
match self.owner {
Some(owner) => {
let mut page = owner.page.borrow_mut();
for page in page.iter() {
*page.mut_js_info() = None;
}
*owner.js_context.borrow_mut() = None;
}
None => (),
}
}
}
impl ScriptTask {
/// Creates a new script task.
pub fn new(id: PipelineId,
compositor: Box<ScriptListener>,
layout_chan: LayoutChan,
port: Receiver<ScriptMsg>,
chan: ScriptChan,
constellation_chan: ConstellationChan,
resource_task: ResourceTask,
img_cache_task: ImageCacheTask,
window_size: WindowSizeData)
-> Rc<ScriptTask> {
let (js_runtime, js_context) = ScriptTask::new_rt_and_cx();
let page = Page::new(id, None, layout_chan, window_size,
resource_task.clone(),
constellation_chan.clone(),
js_context.clone());
Rc::new(ScriptTask {
page: RefCell::new(Rc::new(page)),
image_cache_task: img_cache_task,
resource_task: resource_task,
port: port,
chan: chan,
constellation_chan: constellation_chan,
compositor: compositor,
js_runtime: js_runtime,
js_context: RefCell::new(Some(js_context)),
mouse_over_targets: RefCell::new(None)
})
}
fn new_rt_and_cx() -> (js::rust::rt, Rc<Cx>) {
let js_runtime = js::rust::rt();
assert!({
let ptr: *mut JSRuntime = (*js_runtime).ptr;
ptr.is_not_null()
});
unsafe {
// JS_SetWrapObjectCallbacks clobbers the existing wrap callback,
// and JSCompartment::wrap crashes if that happens. The only way
// to retrieve the default callback is as the result of
// JS_SetWrapObjectCallbacks, which is why we call it twice.
let callback = JS_SetWrapObjectCallbacks((*js_runtime).ptr,
None,
Some(wrap_for_same_compartment),
None);
JS_SetWrapObjectCallbacks((*js_runtime).ptr,
callback,
Some(wrap_for_same_compartment),
Some(pre_wrap));
}
let js_context = js_runtime.cx();
assert!({
let ptr: *mut JSContext = (*js_context).ptr;
ptr.is_not_null()
});
js_context.set_default_options_and_version();
js_context.set_logging_error_reporter();
unsafe {
JS_SetGCZeal((*js_context).ptr, 0, JS_DEFAULT_ZEAL_FREQ);
}
(js_runtime, js_context)
}
pub fn get_cx(&self) -> *mut JSContext {
(**self.js_context.borrow().get_ref()).ptr
}
/// Starts the script task. After calling this method, the script task will loop receiving
/// messages on its port.
pub fn start(&self) {
while self.handle_msgs() {
// Go on...
}
}
pub fn create<C:ScriptListener + Send>(
id: PipelineId,
compositor: Box<C>,
layout_chan: LayoutChan,
port: Receiver<ScriptMsg>,
chan: ScriptChan,
constellation_chan: ConstellationChan,
failure_msg: Failure,
resource_task: ResourceTask,
image_cache_task: ImageCacheTask,
window_size: WindowSizeData) {
let mut builder = TaskBuilder::new().named("ScriptTask");
let ConstellationChan(const_chan) = constellation_chan.clone();
send_on_failure(&mut builder, FailureMsg(failure_msg), const_chan);
builder.spawn(proc() {
let script_task = ScriptTask::new(id,
compositor as Box<ScriptListener>,
layout_chan,
port,
chan,
constellation_chan,
resource_task,
image_cache_task,
window_size);
let mut failsafe = ScriptMemoryFailsafe::new(&*script_task);
script_task.start();
// This must always be the very last operation performed before the task completes
failsafe.neuter();
});
}
/// Handle incoming control messages.
fn handle_msgs(&self) -> bool {
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
// Handle pending resize events.
// Gather them first to avoid a double mut borrow on self.
let mut resizes = vec!();
{
let mut page = self.page.borrow_mut();
for page in page.iter() {
// Only process a resize if layout is idle.
let layout_join_port = page.layout_join_port.deref().borrow();
if layout_join_port.is_none() {
let mut resize_event = page.resize_event.deref().get();
match resize_event.take() {
Some(size) => resizes.push((page.id, size)),
None => ()
}
page.resize_event.deref().set(None);
}
}
}
for (id, size) in resizes.move_iter() {
self.handle_event(id, ResizeEvent(size));
}
// Store new resizes, and gather all other events.
let mut sequential = vec!();
// Receive at least one message so we don't spinloop.
let mut event = self.port.recv();
loop {
match event {
ResizeMsg(id, size) => {
let mut page = self.page.borrow_mut();
let page = page.find(id).expect("resize sent to nonexistent pipeline");
page.resize_event.deref().set(Some(size));
}
_ => {
sequential.push(event);
}
}
match self.port.try_recv() {
Err(_) => break,
Ok(ev) => event = ev,
}
}
// Process the gathered events.
for msg in sequential.move_iter() {
match msg {
// TODO(tkuehn) need to handle auxiliary layouts for iframes
AttachLayoutMsg(new_layout_info) => self.handle_new_layout(new_layout_info),
LoadMsg(id, url) => self.load(id, url),
TriggerLoadMsg(id, url) => self.trigger_load(id, url),
TriggerFragmentMsg(id, url) => self.trigger_fragment(id, url),
SendEventMsg(id, event) => self.handle_event(id, event),
FireTimerMsg(id, timer_id) => self.handle_fire_timer_msg(id, timer_id),
NavigateMsg(direction) => self.handle_navigate_msg(direction),
ReflowCompleteMsg(id, reflow_id) => self.handle_reflow_complete_msg(id, reflow_id),
ResizeInactiveMsg(id, new_size) => self.handle_resize_inactive_msg(id, new_size),
ExitPipelineMsg(id) => if self.handle_exit_pipeline_msg(id) { return false },
ExitWindowMsg(id) => self.handle_exit_window_msg(id),
ResizeMsg(..) => fail!("should have handled ResizeMsg already"),
XHRProgressMsg(addr, progress) => XMLHttpRequest::handle_xhr_progress(addr, progress),
}
}
true
}
fn handle_new_layout(&self, new_layout_info: NewLayoutInfo) {
debug!("Script: new layout: {:?}", new_layout_info);
let NewLayoutInfo {
old_pipeline_id,
new_pipeline_id,
subpage_id,
layout_chan
} = new_layout_info;
let mut page = self.page.borrow_mut();
let parent_page = page.find(old_pipeline_id).expect("ScriptTask: received a layout
whose parent has a PipelineId which does not correspond to a pipeline in the script
task's page tree. This is a bug.");
let new_page = {
let window_size = parent_page.window_size.deref().get();
Page::new(new_pipeline_id, Some(subpage_id), layout_chan, window_size,
parent_page.resource_task.deref().clone(),
self.constellation_chan.clone(),
self.js_context.borrow().get_ref().clone())
};
parent_page.children.deref().borrow_mut().push(Rc::new(new_page));
}
/// Handles a timer that fired.
fn handle_fire_timer_msg(&self, id: PipelineId, timer_id: TimerId) {
let mut page = self.page.borrow_mut();
let page = page.find(id).expect("ScriptTask: received fire timer msg for a
pipeline ID not associated with this script task. This is a bug.");
let frame = page.frame();
let window = frame.get_ref().window.root();
let this_value = window.deref().reflector().get_jsobject();
let data = match window.deref().active_timers.deref().borrow().find(&timer_id) {
None => return,
Some(timer_handle) => timer_handle.data,
};
// TODO: Support extra arguments. This requires passing a `*JSVal` array as `argv`.
let cx = self.get_cx();
with_compartment(cx, this_value, || {
let mut rval = NullValue();
unsafe {
JS_CallFunctionValue(cx, this_value, *data.funval,
0, ptr::mut_null(), &mut rval);
}
});
if !data.is_interval {
window.deref().active_timers.deref().borrow_mut().remove(&timer_id);
}
}
/// Handles a notification that reflow completed.
fn handle_reflow_complete_msg(&self, pipeline_id: PipelineId, reflow_id: uint) {
debug!("Script: Reflow {:?} complete for {:?}", reflow_id, pipeline_id);
let mut page = self.page.borrow_mut();
let page = page.find(pipeline_id).expect(
"ScriptTask: received a load message for a layout channel that is not associated \
with this script task. This is a bug.");
let last_reflow_id = page.last_reflow_id.deref().get();
if last_reflow_id == reflow_id {
let mut layout_join_port = page.layout_join_port.deref().borrow_mut();
*layout_join_port = None;
}
self.compositor.set_ready_state(FinishedLoading);
}
/// Handles a navigate forward or backward message.
/// TODO(tkuehn): is it ever possible to navigate only on a subframe?
fn handle_navigate_msg(&self, direction: NavigationDirection) {
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(constellation_msg::NavigateMsg(direction));
}
/// Window was resized, but this script was not active, so don't reflow yet
fn handle_resize_inactive_msg(&self, id: PipelineId, new_size: WindowSizeData) {
let mut page = self.page.borrow_mut();
let page = page.find(id).expect("Received resize message for PipelineId not associated
with a page in the page tree. This is a bug.");
page.window_size.deref().set(new_size);
let mut page_url = page.mut_url();
let last_loaded_url = replace(&mut *page_url, None);
for url in last_loaded_url.iter() {
*page_url = Some((url.ref0().clone(), true));
}
}
/// We have gotten a window.close from script, which we pass on to the compositor.
/// We do not shut down the script task now, because the compositor will ask the
/// constellation to shut down the pipeline, which will clean everything up
/// normally. If we do exit, we will tear down the DOM nodes, possibly at a point
/// where layout is still accessing them.
fn handle_exit_window_msg(&self, _: PipelineId) {
debug!("script task handling exit window msg");
// TODO(tkuehn): currently there is only one window,
// so this can afford to be naive and just shut down the
// compositor. In the future it'll need to be smarter.
self.compositor.close();
}
/// Handles a request to exit the script task and shut down layout.
/// Returns true if the script task should shut down and false otherwise.
fn handle_exit_pipeline_msg(&self, id: PipelineId) -> bool {
// If root is being exited, shut down all pages
let mut page = self.page.borrow_mut();
if page.id == id {
debug!("shutting down layout for root page {:?}", id);
*self.js_context.borrow_mut() = None;
shut_down_layout(&*page, (*self.js_runtime).ptr);
return true
}
// otherwise find just the matching page and exit all sub-pages
match page.remove(id) {
Some(ref mut page) => {
shut_down_layout(&*page, (*self.js_runtime).ptr);
false
}
// TODO(tkuehn): pipeline closing is currently duplicated across
// script and constellation, which can cause this to happen. Constellation
// needs to be smarter about exiting pipelines.
None => false,
}
}
/// The entry point to document loading. Defines bindings, sets up the window and document
/// objects, parses HTML and CSS, and kicks off initial layout.
fn load(&self, pipeline_id: PipelineId, url: Url) {
debug!("ScriptTask: loading {:?} on page {:?}", url, pipeline_id);
let mut page = self.page.borrow_mut();
let page = page.find(pipeline_id).expect("ScriptTask: received a load
message for a layout channel that is not associated with this script task. This
is a bug.");
let last_loaded_url = replace(&mut *page.mut_url(), None);
match last_loaded_url {
Some((ref loaded, needs_reflow)) if *loaded == url => {
*page.mut_url() = Some((loaded.clone(), false));
if needs_reflow {
page.damage(ContentChangedDocumentDamage);
page.reflow(ReflowForDisplay, self.chan.clone(), self.compositor);
}
return;
},
_ => (),
}
let cx = self.js_context.borrow();
let cx = cx.get_ref();
// Create the window and document objects.
let window = Window::new(cx.deref().ptr,
page.clone(),
self.chan.clone(),
self.compositor.dup(),
self.image_cache_task.clone()).root();
let document = Document::new(&*window, Some(url.clone()), HTMLDocument, None).root();
window.deref().init_browser_context(&*document);
with_compartment((**cx).ptr, window.reflector().get_jsobject(), || {
let mut js_info = page.mut_js_info();
RegisterBindings::Register(&*window, js_info.get_mut_ref());
});
self.compositor.set_ready_state(Loading);
// Parse HTML.
//
// Note: We can parse the next document in parallel with any previous documents.
let html_parsing_result = hubbub_html_parser::parse_html(&*page,
&*document,
url.clone(),
self.resource_task.clone());
let HtmlParserResult {
discovery_port
} = html_parsing_result;
{
// Create the root frame.
let mut frame = page.mut_frame();
*frame = Some(Frame {
document: JS::from_rooted(document.deref()),
window: JS::from_rooted(window.deref()),
});
}
// Send style sheets over to layout.
//
// FIXME: These should be streamed to layout as they're parsed. We don't need to stop here
// in the script task.
let mut js_scripts = None;
loop {
match discovery_port.recv_opt() {
Ok(HtmlDiscoveredScript(scripts)) => {
assert!(js_scripts.is_none());
js_scripts = Some(scripts);
}
Ok(HtmlDiscoveredStyle(sheet)) => {
let LayoutChan(ref chan) = *page.layout_chan;
chan.send(AddStylesheetMsg(sheet));
}
Err(()) => break
}
}
// Kick off the initial reflow of the page.
document.deref().content_changed();
let fragment = url.fragment.as_ref().map(|ref fragment| fragment.to_string());
{
// No more reflow required
let mut page_url = page.mut_url();
*page_url = Some((url.clone(), false));
}
// Receive the JavaScript scripts.
assert!(js_scripts.is_some());
let js_scripts = js_scripts.take_unwrap();
debug!("js_scripts: {:?}", js_scripts);
with_compartment((**cx).ptr, window.reflector().get_jsobject(), || {
// Evaluate every script in the document.
for file in js_scripts.iter() {
let global_obj = window.reflector().get_jsobject();
//FIXME: this should have some kind of error handling, or explicitly
// drop an exception on the floor.
match cx.evaluate_script(global_obj, file.data.clone(), file.url.to_str(), 1) {
Ok(_) => (),
Err(_) => println!("evaluate_script failed")
}
}
});
// We have no concept of a document loader right now, so just dispatch the
// "load" event as soon as we've finished executing all scripts parsed during
// the initial load.
let event = Event::new(&*window, "load".to_string(), false, false).root();
let doctarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&*document);
let wintarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&*window);
let _ = wintarget.dispatch_event_with_target(Some((*doctarget).clone()),
&*event);
page.fragment_node.assign(fragment.map_or(None, |fragid| page.find_fragment_node(fragid)));
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(LoadCompleteMsg(page.id, url));
}
fn scroll_fragment_point(&self, pipeline_id: PipelineId, node: &JSRef<Element>) {
let node: &JSRef<Node> = NodeCast::from_ref(node);
let rect = node.get_bounding_content_box();
let point = Point2D(to_frac_px(rect.origin.x).to_f32().unwrap(),
to_frac_px(rect.origin.y).to_f32().unwrap());
// FIXME(#2003, pcwalton): This is pretty bogus when multiple layers are involved.
// Really what needs to happen is that this needs to go through layout to ask which
// layer the element belongs to, and have it send the scroll message to the
// compositor.
self.compositor.scroll_fragment_point(pipeline_id, LayerId::null(), point);
}
/// This is the main entry point for receiving and dispatching DOM events.
///
/// TODO: Actually perform DOM event dispatch.
fn handle_event(&self, pipeline_id: PipelineId, event: Event_) {
match event {
ResizeEvent(new_size) => {
debug!("script got resize event: {:?}", new_size);
let window = {
let page = get_page(&*self.page.borrow(), pipeline_id);
page.window_size.deref().set(new_size);
let frame = page.frame();
if frame.is_some() {
page.damage(ReflowDocumentDamage);
page.reflow(ReflowForDisplay, self.chan.clone(), self.compositor)
}
let mut fragment_node = page.fragment_node.get();
match fragment_node.take().map(|node| node.root()) {
Some(node) => self.scroll_fragment_point(pipeline_id, &*node),
None => {}
}
frame.as_ref().map(|frame| Temporary::new(frame.window.clone()))
};
match window.root() {
Some(window) => {
// http://dev.w3.org/csswg/cssom-view/#resizing-viewports
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-resize
let uievent = UIEvent::new(&window.clone(),
"resize".to_string(), false,
false, Some(window.clone()),
0i32).root();
let event: &JSRef<Event> = EventCast::from_ref(&*uievent);
let wintarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&*window);
let _ = wintarget.dispatch_event_with_target(None, event);
}
None => ()
}
}
// FIXME(pcwalton): This reflows the entire document and is not incremental-y.
ReflowEvent => {
debug!("script got reflow event");
let page = get_page(&*self.page.borrow(), pipeline_id);
let frame = page.frame();
if frame.is_some() {
page.damage(MatchSelectorsDocumentDamage);
page.reflow(ReflowForDisplay, self.chan.clone(), self.compositor)
}
}
ClickEvent(_button, point) => {
debug!("ClickEvent: clicked at {:?}", point);
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.hit_test(&point) {
Some(node_address) => {
debug!("node address is {:?}", node_address);
let temp_node =
node::from_untrusted_node_address(
self.js_runtime.deref().ptr, node_address);
let maybe_node = temp_node.root().ancestors().find(|node| node.is_element());
match maybe_node {
Some(node) => {
debug!("clicked on {:s}", node.debug_str());
match *page.frame() {
Some(ref frame) => {
let window = frame.window.root();
let event =
Event::new(&*window,
"click".to_string(),
true, true).root();
let eventtarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&node);
let _ = eventtarget.dispatch_event_with_target(None, &*event);
}
None => {}
}
}
None => {}
}
}
None => {}
}
}
MouseDownEvent(..) => {}
MouseUpEvent(..) => {}
MouseMoveEvent(point) => {
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.get_nodes_under_mouse(&point) {
Some(node_address) => {
let mut target_list = vec!();
let mut target_compare = false;
let mouse_over_targets = &mut *self.mouse_over_targets.borrow_mut();
match *mouse_over_targets {
Some(ref mut mouse_over_targets) => {
for node in mouse_over_targets.mut_iter() {
let node = node.root(); | }
for node_address in node_address.iter() {
let temp_node =
node::from_untrusted_node_address(
self.js_runtime.deref().ptr, *node_address);
let maybe_node = temp_node.root().ancestors().find(|node| node.is_element());
match maybe_node {
Some(node) => {
node.set_hover_state(true);
match *mouse_over_targets {
Some(ref mouse_over_targets) => {
if !target_compare {
target_compare = !mouse_over_targets.contains(&JS::from_rooted(&node));
}
}
None => {}
}
target_list.push(JS::from_rooted(&node));
}
None => {}
}
}
match *mouse_over_targets {
Some(ref mouse_over_targets) => {
if mouse_over_targets.len() != target_list.len() {
target_compare = true;
}
}
None => { target_compare = true; }
}
if target_compare {
if mouse_over_targets.is_some() {
page.damage(MatchSelectorsDocumentDamage);
page.reflow(ReflowForDisplay, self.chan.clone(), self.compositor);
}
*mouse_over_targets = Some(target_list);
}
}
None => {}
}
}
}
}
/// The entry point for content to notify that a new load has been requested
/// for the given pipeline.
fn trigger_load(&self, pipeline_id: PipelineId, url: Url) {
let ConstellationChan(ref const_chan) = self.constellation_chan;
const_chan.send(LoadUrlMsg(pipeline_id, url));
}
/// The entry point for content to notify that a fragment url has been requested
/// for the given pipeline.
fn trigger_fragment(&self, pipeline_id: PipelineId, url: Url) {
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.find_fragment_node(url.fragment.unwrap()).root() {
Some(node) => {
self.scroll_fragment_point(pipeline_id, &*node);
}
None => {}
}
}
}
/// Shuts down layout for the given page tree.
fn shut_down_layout(page_tree: &Rc<Page>, rt: *mut JSRuntime) {
for page in page_tree.iter() {
page.join_layout();
// Tell the layout task to begin shutting down, and wait until it
// processed this message.
let (response_chan, response_port) = channel();
let LayoutChan(ref chan) = *page.layout_chan;
chan.send(layout_interface::PrepareToExitMsg(response_chan));
response_port.recv();
}
// Remove our references to the DOM objects in this page tree.
for page in page_tree.iter() {
*page.mut_frame() = None;
}
// Drop our references to the JSContext, potentially triggering a GC.
for page in page_tree.iter() {
*page.mut_js_info() = None;
}
// Force a GC to make sure that our DOM reflectors are released before we tell
// layout to exit.
unsafe {
JS_GC(rt);
}
// Destroy the layout task. If there were node leaks, layout will now crash safely.
for page in page_tree.iter() {
let LayoutChan(ref chan) = *page.layout_chan;
chan.send(layout_interface::ExitNowMsg);
}
}
fn get_page(page: &Rc<Page>, pipeline_id: PipelineId) -> Rc<Page> {
page.find(pipeline_id).expect("ScriptTask: received an event \
message for a layout channel that is not associated with this script task.\
This is a bug.")
} | node.deref().set_hover_state(false);
}
}
None => {} | random_line_split |
app.js | 'use strict';
/*
* Defining the Package
*/
var Module = require('meanio').Module,
favicon = require('serve-favicon'),
express = require('express');
var System = new Module('system');
/*
* All MEAN packages require registration
* Dependency injection is used to define required modules
*/
System.register(function(app, auth, database) {
//We enable routing. By default the Package Object is passed to the routes
System.routes(app, auth, database);
System.aggregateAsset('css', 'common.css');
// The middleware in config/express will run before this code
// Set views path, template engine and default layout
app.set('views', __dirname + '/server/views');
// Setting the favicon and static folder
app.use(favicon(__dirname + '/public/assets/img/favicon.ico'));
// Adding robots and humans txt
app.use(express.static(__dirname + '/public/assets/static'));
app.use(express.static(__dirname + '/public/assets/img'));
return System; | }); | random_line_split | |
LocaleReceiver.tsx | import * as React from 'react';
import defaultLocaleData from './default';
import LocaleContext from './context';
import { Locale } from '.';
export type LocaleComponentName = Exclude<keyof Locale, 'locale'>;
export interface LocaleReceiverProps<C extends LocaleComponentName = LocaleComponentName> {
componentName: C;
defaultLocale?: Locale[C] | (() => Locale[C]);
children: (
locale: Exclude<Locale[C], undefined>,
localeCode?: string,
fullLocale?: object,
) => React.ReactNode;
}
export default class LocaleReceiver<
C extends LocaleComponentName = LocaleComponentName,
> extends React.Component<LocaleReceiverProps<C>> {
static defaultProps = {
componentName: 'global',
};
static contextType = LocaleContext;
getLocale(): Exclude<Locale[C], undefined> {
const { componentName, defaultLocale } = this.props;
const locale = defaultLocale || defaultLocaleData[componentName ?? 'global'];
const antLocale = this.context;
const localeFromContext = componentName && antLocale ? antLocale[componentName] : {};
return {
...(locale instanceof Function ? locale() : locale),
...(localeFromContext || {}),
};
}
getLocaleCode() {
const antLocale = this.context;
const localeCode = antLocale && antLocale.locale;
// Had use LocaleProvide but didn't set locale
if (antLocale && antLocale.exist && !localeCode) |
return localeCode;
}
render() {
return this.props.children(this.getLocale(), this.getLocaleCode(), this.context);
}
}
export function useLocaleReceiver<T extends LocaleComponentName>(
componentName: T,
defaultLocale?: Locale[T] | Function,
): [Locale[T]] {
const antLocale = React.useContext(LocaleContext);
const componentLocale = React.useMemo(() => {
const locale = defaultLocale || defaultLocaleData[componentName || 'global'];
const localeFromContext = componentName && antLocale ? antLocale[componentName] : {};
return {
...(typeof locale === 'function' ? (locale as Function)() : locale),
...(localeFromContext || {}),
};
}, [componentName, defaultLocale, antLocale]);
return [componentLocale];
}
| {
return defaultLocaleData.locale;
} | conditional_block |
LocaleReceiver.tsx | import * as React from 'react';
import defaultLocaleData from './default';
import LocaleContext from './context';
import { Locale } from '.';
export type LocaleComponentName = Exclude<keyof Locale, 'locale'>;
export interface LocaleReceiverProps<C extends LocaleComponentName = LocaleComponentName> {
componentName: C;
defaultLocale?: Locale[C] | (() => Locale[C]);
children: (
locale: Exclude<Locale[C], undefined>,
localeCode?: string,
fullLocale?: object,
) => React.ReactNode;
}
export default class LocaleReceiver<
C extends LocaleComponentName = LocaleComponentName,
> extends React.Component<LocaleReceiverProps<C>> {
static defaultProps = {
componentName: 'global',
};
static contextType = LocaleContext;
getLocale(): Exclude<Locale[C], undefined> {
const { componentName, defaultLocale } = this.props;
const locale = defaultLocale || defaultLocaleData[componentName ?? 'global'];
const antLocale = this.context;
const localeFromContext = componentName && antLocale ? antLocale[componentName] : {};
return {
...(locale instanceof Function ? locale() : locale),
...(localeFromContext || {}),
};
}
getLocaleCode() {
const antLocale = this.context;
const localeCode = antLocale && antLocale.locale;
// Had use LocaleProvide but didn't set locale
if (antLocale && antLocale.exist && !localeCode) {
return defaultLocaleData.locale;
}
return localeCode;
}
render() {
return this.props.children(this.getLocale(), this.getLocaleCode(), this.context);
}
}
export function useLocaleReceiver<T extends LocaleComponentName>(
componentName: T,
defaultLocale?: Locale[T] | Function,
): [Locale[T]] | {
const antLocale = React.useContext(LocaleContext);
const componentLocale = React.useMemo(() => {
const locale = defaultLocale || defaultLocaleData[componentName || 'global'];
const localeFromContext = componentName && antLocale ? antLocale[componentName] : {};
return {
...(typeof locale === 'function' ? (locale as Function)() : locale),
...(localeFromContext || {}),
};
}, [componentName, defaultLocale, antLocale]);
return [componentLocale];
} | identifier_body | |
LocaleReceiver.tsx | import * as React from 'react';
import defaultLocaleData from './default';
import LocaleContext from './context';
import { Locale } from '.';
export type LocaleComponentName = Exclude<keyof Locale, 'locale'>;
export interface LocaleReceiverProps<C extends LocaleComponentName = LocaleComponentName> {
componentName: C;
defaultLocale?: Locale[C] | (() => Locale[C]);
children: (
locale: Exclude<Locale[C], undefined>,
localeCode?: string,
fullLocale?: object,
) => React.ReactNode;
}
export default class LocaleReceiver<
C extends LocaleComponentName = LocaleComponentName,
> extends React.Component<LocaleReceiverProps<C>> {
static defaultProps = {
componentName: 'global',
};
static contextType = LocaleContext;
getLocale(): Exclude<Locale[C], undefined> {
const { componentName, defaultLocale } = this.props;
const locale = defaultLocale || defaultLocaleData[componentName ?? 'global'];
const antLocale = this.context;
const localeFromContext = componentName && antLocale ? antLocale[componentName] : {};
return {
...(locale instanceof Function ? locale() : locale),
...(localeFromContext || {}),
};
}
getLocaleCode() {
const antLocale = this.context;
const localeCode = antLocale && antLocale.locale;
// Had use LocaleProvide but didn't set locale
if (antLocale && antLocale.exist && !localeCode) { | return defaultLocaleData.locale;
}
return localeCode;
}
render() {
return this.props.children(this.getLocale(), this.getLocaleCode(), this.context);
}
}
export function useLocaleReceiver<T extends LocaleComponentName>(
componentName: T,
defaultLocale?: Locale[T] | Function,
): [Locale[T]] {
const antLocale = React.useContext(LocaleContext);
const componentLocale = React.useMemo(() => {
const locale = defaultLocale || defaultLocaleData[componentName || 'global'];
const localeFromContext = componentName && antLocale ? antLocale[componentName] : {};
return {
...(typeof locale === 'function' ? (locale as Function)() : locale),
...(localeFromContext || {}),
};
}, [componentName, defaultLocale, antLocale]);
return [componentLocale];
} | random_line_split | |
LocaleReceiver.tsx | import * as React from 'react';
import defaultLocaleData from './default';
import LocaleContext from './context';
import { Locale } from '.';
export type LocaleComponentName = Exclude<keyof Locale, 'locale'>;
export interface LocaleReceiverProps<C extends LocaleComponentName = LocaleComponentName> {
componentName: C;
defaultLocale?: Locale[C] | (() => Locale[C]);
children: (
locale: Exclude<Locale[C], undefined>,
localeCode?: string,
fullLocale?: object,
) => React.ReactNode;
}
export default class LocaleReceiver<
C extends LocaleComponentName = LocaleComponentName,
> extends React.Component<LocaleReceiverProps<C>> {
static defaultProps = {
componentName: 'global',
};
static contextType = LocaleContext;
getLocale(): Exclude<Locale[C], undefined> {
const { componentName, defaultLocale } = this.props;
const locale = defaultLocale || defaultLocaleData[componentName ?? 'global'];
const antLocale = this.context;
const localeFromContext = componentName && antLocale ? antLocale[componentName] : {};
return {
...(locale instanceof Function ? locale() : locale),
...(localeFromContext || {}),
};
}
| () {
const antLocale = this.context;
const localeCode = antLocale && antLocale.locale;
// Had use LocaleProvide but didn't set locale
if (antLocale && antLocale.exist && !localeCode) {
return defaultLocaleData.locale;
}
return localeCode;
}
render() {
return this.props.children(this.getLocale(), this.getLocaleCode(), this.context);
}
}
export function useLocaleReceiver<T extends LocaleComponentName>(
componentName: T,
defaultLocale?: Locale[T] | Function,
): [Locale[T]] {
const antLocale = React.useContext(LocaleContext);
const componentLocale = React.useMemo(() => {
const locale = defaultLocale || defaultLocaleData[componentName || 'global'];
const localeFromContext = componentName && antLocale ? antLocale[componentName] : {};
return {
...(typeof locale === 'function' ? (locale as Function)() : locale),
...(localeFromContext || {}),
};
}, [componentName, defaultLocale, antLocale]);
return [componentLocale];
}
| getLocaleCode | identifier_name |
ansible_api.py | #!/usr/bin/python2
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase
from DJBot.config import Config
from datetime import datetime
import threading
import json
import os
Options = namedtuple('Options', ['connection', 'module_path', 'forks',
'remote_user', 'private_key_file',
'ssh_common_args', 'ssh_extra_args',
'sftp_extra_args', 'scp_extra_args',
'become', 'become_method',
'become_user', 'verbosity', 'check'])
# Creat a callback object so we can capture the output
class ResultsCollector(CallbackBase):
def __init__(self, *args, **kwargs):
super(ResultsCollector, self).__init__(*args, **kwargs)
self.host_ok = {}
self.host_unreachable = {}
self.host_failed = {}
self.condition = threading.Semaphore(0)
def v2_runner_on_unreachable(self, result):
self.host_unreachable[result._host.get_name()] = result._result
def v2_runner_on_ok(self, result, *args, **kwargs):
try:
self.host_ok[result._host.get_name()]
except:
self.host_ok[result._host.get_name()] = []
self.host_ok[result._host.get_name()].append(result._result)
def v2_runner_on_failed(self, result, *args, **kwargs):
self.host_failed[result._host.get_name()] = result._result
def get_all(self):
return {'ok': self.host_ok,
'unreachable': self.host_unreachable,
'failed': self.host_failed}
class Runner(object):
"""I wrote this to make a response with flask to avoid the timeout
But I neet to check if it's really usefull,
maybe the way of Runner is enought.
"""
def __init__(self, inventory, remote_user='root',
private_key_file=None, ssh_extra_args=None,
become=None):
# initialize needed objects
ansible_path = '/usr/local/lib/python2.7/site-packages/ansible'
self.callback = ResultsCollector()
self.vmanager = VariableManager()
self.loader = DataLoader()
self.remote_user = remote_user
self.inventory = Inventory(loader=self.loader,
variable_manager=self.vmanager,
host_list=inventory)
self.vmanager.set_inventory(self.inventory)
self.options = Options(connection='smart',
module_path=ansible_path,
forks=100, remote_user=remote_user,
private_key_file=private_key_file,
ssh_common_args=None,
ssh_extra_args=ssh_extra_args,
sftp_extra_args=None,
scp_extra_args=None,
become=become, become_method=None,
become_user=None, verbosity=None,
check=False)
# create inventory and pass to var manager
self.passwords = dict(vault_pass='secret')
self.plays = {}
self.hosts_results = {}
def add_setup(self, hosts):
self.play_source = dict(
name='setup',
hosts=', '.join(hosts),
tasks=[dict(action='setup')]
# args=(dict(filter='ansible_[a,d,h,l,m,p,][a,e,i,o,r,s]*'))
)
self.plays['setup'] = Play().load(self.play_source,
variable_manager=self.vmanager,
loader=self.loader)
self.plays['setup'].gather_facts = False
def add_plays(self, name='undefined', hosts=[], tasks=[]):
""" add tasks to play"""
self.play_source = dict(
name=name,
hosts=', '.join(hosts),
tasks=tasks
)
self.plays[name] = Play().load(self.play_source,
variable_manager=self.vmanager,
loader=self.loader)
self.plays[name].gather_facts = False
def run(self):
tqm = None
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.vmanager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback=self.callback,
)
for name, play in self.plays.items():
tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
class ThreadRunner(threading.Thread):
def __init__(self, machines, playbook, user, room, username,
private_key="id_rsa",
setup=False):
threading.Thread.__init__(self)
self.room = room
self.username = username
self.machines = machines
self.user = user
self.private_key = Config.KEYS + private_key
self.playbook = Runner(self.machines, self.user,
self.private_key)
if setup:
self.playbook.add_setup(self.machines)
self.playbook.add_plays(playbook['name'], self.machines,
playbook['modules'])
self.task = playbook
def run(self):
self.playbook.run()
results = self.playbook.callback.get_all()
results['datetime'] = datetime.now().isoformat(' ')[:-7]
results['playbook'] = self.task['name']
results['room'] = self.room
results['tasks'] = self.task
results['username'] = self.username
name_log = '-'.join(self.task['name'].split(' ')) + \
'@' + '-'.join(self.room.split(' '))
name_log += '@' + self.username
name_log += '@' + '-'.join(results['datetime'].split(' '))
name = os.getenv("LOGS") + '/' + name_log + '.json'
with open(name, 'w') as record:
json.dump(results, record)
def ansible_status(hosts, user="root", private_key_file=None):
"""run ansible setup on hosts"""
key = Config.KEYS + private_key_file
ansible_game = Runner(hosts, remote_user=user,
private_key_file=key)
ansible_game.add_setup(hosts)
ansible_game.run()
response = ansible_game.callback.get_all()
response['tasks'] = {
'modules': [{
'action': {
'module': 'setup',
'args': {
'filter': 'ansible_[a,d,h,l,m,p,][a,e,i,o,r,s]*',
}
}
}],
'name': 'Get host info',
}
return response
def copy_key(hosts, key, user, password):
key = Config.KEYS + key + ".pub"
key = "{{ lookup('file', '" + key + "' ) }}"
ansible_api = Runner(hosts, user)
ansible_api.passwords = {'conn_pass': password}
authorized_key = [{'action': u'authorized_key',
'args': {
u'user': unicode(user),
u'state': u'present',
u'key': unicode(key)
},
}]
ansible_api.add_plays('Add ssh key', hosts, authorized_key)
ansible_api.run()
response = ansible_api.callback.get_all()
response['tasks'] = {'name': 'Add ssh key'}
response['tasks'].update(authorized_key[0])
return response
if __name__ == '__main__':
| inventory = ['172.18.0.2']
ansible_api = Runner(inventory, 'krahser')
ansible_api.add_setup(inventory)
ansible_api.passwords = {'conn_pass': 'root'}
ansible_api.add_plays('Add ssh key', inventory, [
{'action': u'authorized_key',
'args':
{
u'user': u'root',
u'state': u'present',
u'key': u"{{ lookup('file', '/home/krahser/.ssh/id_rsa.pub') }}",
},
}
]
)
ansible_api.run()
print ansible_api.callback.get_all() | conditional_block | |
ansible_api.py | #!/usr/bin/python2
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase
from DJBot.config import Config
from datetime import datetime
import threading
import json
import os
Options = namedtuple('Options', ['connection', 'module_path', 'forks',
'remote_user', 'private_key_file',
'ssh_common_args', 'ssh_extra_args',
'sftp_extra_args', 'scp_extra_args',
'become', 'become_method',
'become_user', 'verbosity', 'check'])
# Creat a callback object so we can capture the output
class ResultsCollector(CallbackBase):
def __init__(self, *args, **kwargs):
super(ResultsCollector, self).__init__(*args, **kwargs)
self.host_ok = {}
self.host_unreachable = {}
self.host_failed = {}
self.condition = threading.Semaphore(0)
def v2_runner_on_unreachable(self, result):
self.host_unreachable[result._host.get_name()] = result._result
def v2_runner_on_ok(self, result, *args, **kwargs):
try:
self.host_ok[result._host.get_name()]
except:
self.host_ok[result._host.get_name()] = []
self.host_ok[result._host.get_name()].append(result._result)
def v2_runner_on_failed(self, result, *args, **kwargs):
self.host_failed[result._host.get_name()] = result._result
def get_all(self):
return {'ok': self.host_ok,
'unreachable': self.host_unreachable,
'failed': self.host_failed}
class Runner(object):
"""I wrote this to make a response with flask to avoid the timeout
But I neet to check if it's really usefull,
maybe the way of Runner is enought.
"""
def __init__(self, inventory, remote_user='root',
private_key_file=None, ssh_extra_args=None,
become=None):
# initialize needed objects
ansible_path = '/usr/local/lib/python2.7/site-packages/ansible'
self.callback = ResultsCollector()
self.vmanager = VariableManager()
self.loader = DataLoader()
self.remote_user = remote_user
self.inventory = Inventory(loader=self.loader,
variable_manager=self.vmanager,
host_list=inventory)
self.vmanager.set_inventory(self.inventory)
self.options = Options(connection='smart',
module_path=ansible_path,
forks=100, remote_user=remote_user,
private_key_file=private_key_file,
ssh_common_args=None,
ssh_extra_args=ssh_extra_args,
sftp_extra_args=None,
scp_extra_args=None,
become=become, become_method=None,
become_user=None, verbosity=None,
check=False)
# create inventory and pass to var manager
self.passwords = dict(vault_pass='secret')
self.plays = {}
self.hosts_results = {}
def add_setup(self, hosts):
self.play_source = dict(
name='setup',
hosts=', '.join(hosts),
tasks=[dict(action='setup')]
# args=(dict(filter='ansible_[a,d,h,l,m,p,][a,e,i,o,r,s]*'))
)
self.plays['setup'] = Play().load(self.play_source,
variable_manager=self.vmanager,
loader=self.loader)
self.plays['setup'].gather_facts = False
def add_plays(self, name='undefined', hosts=[], tasks=[]):
""" add tasks to play"""
self.play_source = dict(
name=name,
hosts=', '.join(hosts),
tasks=tasks
)
self.plays[name] = Play().load(self.play_source,
variable_manager=self.vmanager,
loader=self.loader)
self.plays[name].gather_facts = False
def run(self):
tqm = None
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.vmanager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback=self.callback,
)
for name, play in self.plays.items():
tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
class ThreadRunner(threading.Thread):
def __init__(self, machines, playbook, user, room, username,
private_key="id_rsa",
setup=False):
threading.Thread.__init__(self)
self.room = room
self.username = username
self.machines = machines
self.user = user
self.private_key = Config.KEYS + private_key
self.playbook = Runner(self.machines, self.user,
self.private_key)
if setup:
self.playbook.add_setup(self.machines)
self.playbook.add_plays(playbook['name'], self.machines,
playbook['modules'])
self.task = playbook
def run(self):
self.playbook.run()
results = self.playbook.callback.get_all()
results['datetime'] = datetime.now().isoformat(' ')[:-7]
results['playbook'] = self.task['name']
results['room'] = self.room
results['tasks'] = self.task
results['username'] = self.username
name_log = '-'.join(self.task['name'].split(' ')) + \
'@' + '-'.join(self.room.split(' '))
name_log += '@' + self.username
name_log += '@' + '-'.join(results['datetime'].split(' '))
name = os.getenv("LOGS") + '/' + name_log + '.json'
with open(name, 'w') as record:
json.dump(results, record)
def ansible_status(hosts, user="root", private_key_file=None):
"""run ansible setup on hosts"""
key = Config.KEYS + private_key_file
ansible_game = Runner(hosts, remote_user=user,
private_key_file=key)
ansible_game.add_setup(hosts)
ansible_game.run()
response = ansible_game.callback.get_all()
response['tasks'] = {
'modules': [{
'action': {
'module': 'setup',
'args': {
'filter': 'ansible_[a,d,h,l,m,p,][a,e,i,o,r,s]*',
}
}
}],
'name': 'Get host info',
}
return response
| authorized_key = [{'action': u'authorized_key',
'args': {
u'user': unicode(user),
u'state': u'present',
u'key': unicode(key)
},
}]
ansible_api.add_plays('Add ssh key', hosts, authorized_key)
ansible_api.run()
response = ansible_api.callback.get_all()
response['tasks'] = {'name': 'Add ssh key'}
response['tasks'].update(authorized_key[0])
return response
if __name__ == '__main__':
inventory = ['172.18.0.2']
ansible_api = Runner(inventory, 'krahser')
ansible_api.add_setup(inventory)
ansible_api.passwords = {'conn_pass': 'root'}
ansible_api.add_plays('Add ssh key', inventory, [
{'action': u'authorized_key',
'args':
{
u'user': u'root',
u'state': u'present',
u'key': u"{{ lookup('file', '/home/krahser/.ssh/id_rsa.pub') }}",
},
}
]
)
ansible_api.run()
print ansible_api.callback.get_all() | def copy_key(hosts, key, user, password):
key = Config.KEYS + key + ".pub"
key = "{{ lookup('file', '" + key + "' ) }}"
ansible_api = Runner(hosts, user)
ansible_api.passwords = {'conn_pass': password} | random_line_split |
ansible_api.py | #!/usr/bin/python2
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase
from DJBot.config import Config
from datetime import datetime
import threading
import json
import os
Options = namedtuple('Options', ['connection', 'module_path', 'forks',
'remote_user', 'private_key_file',
'ssh_common_args', 'ssh_extra_args',
'sftp_extra_args', 'scp_extra_args',
'become', 'become_method',
'become_user', 'verbosity', 'check'])
# Creat a callback object so we can capture the output
class ResultsCollector(CallbackBase):
def __init__(self, *args, **kwargs):
super(ResultsCollector, self).__init__(*args, **kwargs)
self.host_ok = {}
self.host_unreachable = {}
self.host_failed = {}
self.condition = threading.Semaphore(0)
def v2_runner_on_unreachable(self, result):
self.host_unreachable[result._host.get_name()] = result._result
def v2_runner_on_ok(self, result, *args, **kwargs):
try:
self.host_ok[result._host.get_name()]
except:
self.host_ok[result._host.get_name()] = []
self.host_ok[result._host.get_name()].append(result._result)
def v2_runner_on_failed(self, result, *args, **kwargs):
self.host_failed[result._host.get_name()] = result._result
def get_all(self):
return {'ok': self.host_ok,
'unreachable': self.host_unreachable,
'failed': self.host_failed}
class Runner(object):
"""I wrote this to make a response with flask to avoid the timeout
But I neet to check if it's really usefull,
maybe the way of Runner is enought.
"""
def __init__(self, inventory, remote_user='root',
private_key_file=None, ssh_extra_args=None,
become=None):
# initialize needed objects
ansible_path = '/usr/local/lib/python2.7/site-packages/ansible'
self.callback = ResultsCollector()
self.vmanager = VariableManager()
self.loader = DataLoader()
self.remote_user = remote_user
self.inventory = Inventory(loader=self.loader,
variable_manager=self.vmanager,
host_list=inventory)
self.vmanager.set_inventory(self.inventory)
self.options = Options(connection='smart',
module_path=ansible_path,
forks=100, remote_user=remote_user,
private_key_file=private_key_file,
ssh_common_args=None,
ssh_extra_args=ssh_extra_args,
sftp_extra_args=None,
scp_extra_args=None,
become=become, become_method=None,
become_user=None, verbosity=None,
check=False)
# create inventory and pass to var manager
self.passwords = dict(vault_pass='secret')
self.plays = {}
self.hosts_results = {}
def add_setup(self, hosts):
self.play_source = dict(
name='setup',
hosts=', '.join(hosts),
tasks=[dict(action='setup')]
# args=(dict(filter='ansible_[a,d,h,l,m,p,][a,e,i,o,r,s]*'))
)
self.plays['setup'] = Play().load(self.play_source,
variable_manager=self.vmanager,
loader=self.loader)
self.plays['setup'].gather_facts = False
def add_plays(self, name='undefined', hosts=[], tasks=[]):
""" add tasks to play"""
self.play_source = dict(
name=name,
hosts=', '.join(hosts),
tasks=tasks
)
self.plays[name] = Play().load(self.play_source,
variable_manager=self.vmanager,
loader=self.loader)
self.plays[name].gather_facts = False
def run(self):
tqm = None
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.vmanager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback=self.callback,
)
for name, play in self.plays.items():
tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
class ThreadRunner(threading.Thread):
def __init__(self, machines, playbook, user, room, username,
private_key="id_rsa",
setup=False):
threading.Thread.__init__(self)
self.room = room
self.username = username
self.machines = machines
self.user = user
self.private_key = Config.KEYS + private_key
self.playbook = Runner(self.machines, self.user,
self.private_key)
if setup:
self.playbook.add_setup(self.machines)
self.playbook.add_plays(playbook['name'], self.machines,
playbook['modules'])
self.task = playbook
def run(self):
self.playbook.run()
results = self.playbook.callback.get_all()
results['datetime'] = datetime.now().isoformat(' ')[:-7]
results['playbook'] = self.task['name']
results['room'] = self.room
results['tasks'] = self.task
results['username'] = self.username
name_log = '-'.join(self.task['name'].split(' ')) + \
'@' + '-'.join(self.room.split(' '))
name_log += '@' + self.username
name_log += '@' + '-'.join(results['datetime'].split(' '))
name = os.getenv("LOGS") + '/' + name_log + '.json'
with open(name, 'w') as record:
json.dump(results, record)
def | (hosts, user="root", private_key_file=None):
"""run ansible setup on hosts"""
key = Config.KEYS + private_key_file
ansible_game = Runner(hosts, remote_user=user,
private_key_file=key)
ansible_game.add_setup(hosts)
ansible_game.run()
response = ansible_game.callback.get_all()
response['tasks'] = {
'modules': [{
'action': {
'module': 'setup',
'args': {
'filter': 'ansible_[a,d,h,l,m,p,][a,e,i,o,r,s]*',
}
}
}],
'name': 'Get host info',
}
return response
def copy_key(hosts, key, user, password):
key = Config.KEYS + key + ".pub"
key = "{{ lookup('file', '" + key + "' ) }}"
ansible_api = Runner(hosts, user)
ansible_api.passwords = {'conn_pass': password}
authorized_key = [{'action': u'authorized_key',
'args': {
u'user': unicode(user),
u'state': u'present',
u'key': unicode(key)
},
}]
ansible_api.add_plays('Add ssh key', hosts, authorized_key)
ansible_api.run()
response = ansible_api.callback.get_all()
response['tasks'] = {'name': 'Add ssh key'}
response['tasks'].update(authorized_key[0])
return response
if __name__ == '__main__':
inventory = ['172.18.0.2']
ansible_api = Runner(inventory, 'krahser')
ansible_api.add_setup(inventory)
ansible_api.passwords = {'conn_pass': 'root'}
ansible_api.add_plays('Add ssh key', inventory, [
{'action': u'authorized_key',
'args':
{
u'user': u'root',
u'state': u'present',
u'key': u"{{ lookup('file', '/home/krahser/.ssh/id_rsa.pub') }}",
},
}
]
)
ansible_api.run()
print ansible_api.callback.get_all()
| ansible_status | identifier_name |
ansible_api.py | #!/usr/bin/python2
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase
from DJBot.config import Config
from datetime import datetime
import threading
import json
import os
Options = namedtuple('Options', ['connection', 'module_path', 'forks',
'remote_user', 'private_key_file',
'ssh_common_args', 'ssh_extra_args',
'sftp_extra_args', 'scp_extra_args',
'become', 'become_method',
'become_user', 'verbosity', 'check'])
# Creat a callback object so we can capture the output
class ResultsCollector(CallbackBase):
def __init__(self, *args, **kwargs):
super(ResultsCollector, self).__init__(*args, **kwargs)
self.host_ok = {}
self.host_unreachable = {}
self.host_failed = {}
self.condition = threading.Semaphore(0)
def v2_runner_on_unreachable(self, result):
self.host_unreachable[result._host.get_name()] = result._result
def v2_runner_on_ok(self, result, *args, **kwargs):
try:
self.host_ok[result._host.get_name()]
except:
self.host_ok[result._host.get_name()] = []
self.host_ok[result._host.get_name()].append(result._result)
def v2_runner_on_failed(self, result, *args, **kwargs):
self.host_failed[result._host.get_name()] = result._result
def get_all(self):
return {'ok': self.host_ok,
'unreachable': self.host_unreachable,
'failed': self.host_failed}
class Runner(object):
"""I wrote this to make a response with flask to avoid the timeout
But I neet to check if it's really usefull,
maybe the way of Runner is enought.
"""
def __init__(self, inventory, remote_user='root',
private_key_file=None, ssh_extra_args=None,
become=None):
# initialize needed objects
ansible_path = '/usr/local/lib/python2.7/site-packages/ansible'
self.callback = ResultsCollector()
self.vmanager = VariableManager()
self.loader = DataLoader()
self.remote_user = remote_user
self.inventory = Inventory(loader=self.loader,
variable_manager=self.vmanager,
host_list=inventory)
self.vmanager.set_inventory(self.inventory)
self.options = Options(connection='smart',
module_path=ansible_path,
forks=100, remote_user=remote_user,
private_key_file=private_key_file,
ssh_common_args=None,
ssh_extra_args=ssh_extra_args,
sftp_extra_args=None,
scp_extra_args=None,
become=become, become_method=None,
become_user=None, verbosity=None,
check=False)
# create inventory and pass to var manager
self.passwords = dict(vault_pass='secret')
self.plays = {}
self.hosts_results = {}
def add_setup(self, hosts):
self.play_source = dict(
name='setup',
hosts=', '.join(hosts),
tasks=[dict(action='setup')]
# args=(dict(filter='ansible_[a,d,h,l,m,p,][a,e,i,o,r,s]*'))
)
self.plays['setup'] = Play().load(self.play_source,
variable_manager=self.vmanager,
loader=self.loader)
self.plays['setup'].gather_facts = False
def add_plays(self, name='undefined', hosts=[], tasks=[]):
""" add tasks to play"""
self.play_source = dict(
name=name,
hosts=', '.join(hosts),
tasks=tasks
)
self.plays[name] = Play().load(self.play_source,
variable_manager=self.vmanager,
loader=self.loader)
self.plays[name].gather_facts = False
def run(self):
|
class ThreadRunner(threading.Thread):
def __init__(self, machines, playbook, user, room, username,
private_key="id_rsa",
setup=False):
threading.Thread.__init__(self)
self.room = room
self.username = username
self.machines = machines
self.user = user
self.private_key = Config.KEYS + private_key
self.playbook = Runner(self.machines, self.user,
self.private_key)
if setup:
self.playbook.add_setup(self.machines)
self.playbook.add_plays(playbook['name'], self.machines,
playbook['modules'])
self.task = playbook
def run(self):
self.playbook.run()
results = self.playbook.callback.get_all()
results['datetime'] = datetime.now().isoformat(' ')[:-7]
results['playbook'] = self.task['name']
results['room'] = self.room
results['tasks'] = self.task
results['username'] = self.username
name_log = '-'.join(self.task['name'].split(' ')) + \
'@' + '-'.join(self.room.split(' '))
name_log += '@' + self.username
name_log += '@' + '-'.join(results['datetime'].split(' '))
name = os.getenv("LOGS") + '/' + name_log + '.json'
with open(name, 'w') as record:
json.dump(results, record)
def ansible_status(hosts, user="root", private_key_file=None):
"""run ansible setup on hosts"""
key = Config.KEYS + private_key_file
ansible_game = Runner(hosts, remote_user=user,
private_key_file=key)
ansible_game.add_setup(hosts)
ansible_game.run()
response = ansible_game.callback.get_all()
response['tasks'] = {
'modules': [{
'action': {
'module': 'setup',
'args': {
'filter': 'ansible_[a,d,h,l,m,p,][a,e,i,o,r,s]*',
}
}
}],
'name': 'Get host info',
}
return response
def copy_key(hosts, key, user, password):
key = Config.KEYS + key + ".pub"
key = "{{ lookup('file', '" + key + "' ) }}"
ansible_api = Runner(hosts, user)
ansible_api.passwords = {'conn_pass': password}
authorized_key = [{'action': u'authorized_key',
'args': {
u'user': unicode(user),
u'state': u'present',
u'key': unicode(key)
},
}]
ansible_api.add_plays('Add ssh key', hosts, authorized_key)
ansible_api.run()
response = ansible_api.callback.get_all()
response['tasks'] = {'name': 'Add ssh key'}
response['tasks'].update(authorized_key[0])
return response
if __name__ == '__main__':
inventory = ['172.18.0.2']
ansible_api = Runner(inventory, 'krahser')
ansible_api.add_setup(inventory)
ansible_api.passwords = {'conn_pass': 'root'}
ansible_api.add_plays('Add ssh key', inventory, [
{'action': u'authorized_key',
'args':
{
u'user': u'root',
u'state': u'present',
u'key': u"{{ lookup('file', '/home/krahser/.ssh/id_rsa.pub') }}",
},
}
]
)
ansible_api.run()
print ansible_api.callback.get_all()
| tqm = None
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.vmanager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback=self.callback,
)
for name, play in self.plays.items():
tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup() | identifier_body |
ckb-IR.js | /**
* @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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n) {
if (n === 1)
return 1;
return 5;
}
export default [
'ckb-IR',
[
['ب.ن', 'د.ن'],
,
],
,
[
['ی', 'د', 'س', 'چ', 'پ', 'ھ', 'ش'],
[
'یەکشەممە', 'دووشەممە', 'سێشەممە', 'چوارشەممە',
'پێنجشەممە', 'ھەینی', 'شەممە'
],
,
['١ش', '٢ش', '٣ش', '٤ش', '٥ش', 'ھ', 'ش']
],
,
[
['ک', 'ش', 'ئ', 'ن', 'ئ', 'ح', 'ت', 'ئ', 'ئ', 'ت', 'ت', 'ک'],
[
'کانوونی دووەم', 'شوبات', 'ئازار', 'نیسان', 'ئایار',
'حوزەیران', 'تەمووز', 'ئاب', 'ئەیلوول', 'تشرینی یەکەم',
'تشرینی دووەم', 'کانونی یەکەم'
],
],
,
[
['پێش زایین', 'زایینی'],
,
],
6, [5, 5], ['y-MM-dd', 'y MMM d', 'dی MMMMی y', 'y MMMM d, EEEE'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
[
'{1} {0}',
, | ,
],
['.', ',', ';', '%', '\u200e+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'IRR', 'IRR', plural
];
//# sourceMappingURL=ckb-IR.js.map | random_line_split | |
ckb-IR.js | /**
* @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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n) |
export default [
'ckb-IR',
[
['ب.ن', 'د.ن'],
,
],
,
[
['ی', 'د', 'س', 'چ', 'پ', 'ھ', 'ش'],
[
'یەکشەممە', 'دووشەممە', 'سێشەممە', 'چوارشەممە',
'پێنجشەممە', 'ھەینی', 'شەممە'
],
,
['١ش', '٢ش', '٣ش', '٤ش', '٥ش', 'ھ', 'ش']
],
,
[
['ک', 'ش', 'ئ', 'ن', 'ئ', 'ح', 'ت', 'ئ', 'ئ', 'ت', 'ت', 'ک'],
[
'کانوونی دووەم', 'شوبات', 'ئازار', 'نیسان', 'ئایار',
'حوزەیران', 'تەمووز', 'ئاب', 'ئەیلوول', 'تشرینی یەکەم',
'تشرینی دووەم', 'کانونی یەکەم'
],
],
,
[
['پێش زایین', 'زایینی'],
,
],
6, [5, 5], ['y-MM-dd', 'y MMM d', 'dی MMMMی y', 'y MMMM d, EEEE'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
[
'{1} {0}',
,
,
],
['.', ',', ';', '%', '\u200e+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'IRR', 'IRR', plural
];
//# sourceMappingURL=ckb-IR.js.map | {
if (n === 1)
return 1;
return 5;
} | identifier_body |
ckb-IR.js | /**
* @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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function | (n) {
if (n === 1)
return 1;
return 5;
}
export default [
'ckb-IR',
[
['ب.ن', 'د.ن'],
,
],
,
[
['ی', 'د', 'س', 'چ', 'پ', 'ھ', 'ش'],
[
'یەکشەممە', 'دووشەممە', 'سێشەممە', 'چوارشەممە',
'پێنجشەممە', 'ھەینی', 'شەممە'
],
,
['١ش', '٢ش', '٣ش', '٤ش', '٥ش', 'ھ', 'ش']
],
,
[
['ک', 'ش', 'ئ', 'ن', 'ئ', 'ح', 'ت', 'ئ', 'ئ', 'ت', 'ت', 'ک'],
[
'کانوونی دووەم', 'شوبات', 'ئازار', 'نیسان', 'ئایار',
'حوزەیران', 'تەمووز', 'ئاب', 'ئەیلوول', 'تشرینی یەکەم',
'تشرینی دووەم', 'کانونی یەکەم'
],
],
,
[
['پێش زایین', 'زایینی'],
,
],
6, [5, 5], ['y-MM-dd', 'y MMM d', 'dی MMMMی y', 'y MMMM d, EEEE'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
[
'{1} {0}',
,
,
],
['.', ',', ';', '%', '\u200e+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'IRR', 'IRR', plural
];
//# sourceMappingURL=ckb-IR.js.map | plural | identifier_name |
ja-JP.ts | import callingOptions from 'ringcentral-integration/modules/CallingSettings/callingOptions';
export default {
title: '通話',
[callingOptions.softphone]: '{brand} for Desktop',
[callingOptions.myphone]: '自分の{brand}電話',
[callingOptions.otherphone]: 'その他の電話',
[callingOptions.customphone]: 'カスタム電話',
[callingOptions.browser]: 'ブラウザー',
makeCallsWith: '通話発信に使用する電話',
ringoutHint: '最初に自分の場所で自身を呼び出した後、通話相手に接続する',
myLocationLabel: '自分の場所',
press1ToStartCallLabel:
'通話接続前に「1」をダイヤルするように指示するメッセージを受け取る',
[`${callingOptions.browser}Tooltip`]: '通話の発着信にコンピューターのマイクロフォンとスピーカーを使用するには、このオプションを使用します。',
[`${callingOptions.softphone}Tooltip`]: '通話の発着信に{brand} for Desktopアプリを使用するには、このオプションを使用します。',
[`${callingOptions.myphone}Tooltip`]: '{brand}電話を使用して電話をかけるには、このオプションを使用します。',
[`${callingOptions.myphone}Tooltip1`]: '電話をかけた場合、最初に自分の{brand}電話が鳴ってから、通話相手の電話が鳴ります。',
[`${callingOptions.otherphone}Tooltip`]: '{brand}の内線に追加した自宅電話や携帯電話など、他の電話を使用して電話をかけるには、このオプションを使用します。',
[`${callingOptions.otherphone}Tooltip1`]: '電話をかけた場合、最初にこの電話が鳴ってから、通話相手の電話が鳴ります。',
[`${callingOptions.customphone}Tooltip`]: '以下のフィールドに有効な電話番号を入力することで任意の電話を使用して電話をかけるには、このオプションを使用します。',
[`${callingOptions.customphone}Tooltip1`]: '電話をかけた場合、最初にこの電話が鳴ってから、通話相手の電話が鳴ります。',
};
// @key: @#@"title"@#@ @source: @#@"Calling"@#@
// @key: @#@"[callingOptions.softphone]"@#@ @source: @#@"{brand} for Desktop"@#@
// @key: @#@"[callingOptions.myphone]"@#@ @source: @#@"My {brand} Phone"@#@
// @key: @#@"[callingOptions.otherphone]"@#@ @source: @#@"Other Phone"@#@
// @key: @#@"[callingOptions.customphone]"@#@ @source: @#@"Custom Phone"@#@
// @key: @#@"[callingOptions.browser]"@#@ @source: @#@"Browser"@#@
// @key: @#@"makeCallsWith"@#@ @source: @#@"Make my calls with"@#@ | // @key: @#@"ringoutHint"@#@ @source: @#@"Ring me at my location first, then connect the called party"@#@
// @key: @#@"myLocationLabel"@#@ @source: @#@"My Location"@#@
// @key: @#@"press1ToStartCallLabel"@#@ @source: @#@"Prompt me to dial 1 before connecting the call"@#@
// @key: @#@"[`${callingOptions.browser}Tooltip`]"@#@ @source: @#@"Use this option to make and receive calls using your computer’s microphone and speaker."@#@
// @key: @#@"[`${callingOptions.softphone}Tooltip`]"@#@ @source: @#@"Use this option to make and receive calls using your {brand} for Desktop app."@#@
// @key: @#@"[`${callingOptions.myphone}Tooltip`]"@#@ @source: @#@"Use this option to make calls using your {brand} phone."@#@
// @key: @#@"[`${callingOptions.myphone}Tooltip1`]"@#@ @source: @#@"For the call you make, your {brand} phone will ring first then the party you called."@#@
// @key: @#@"[`${callingOptions.otherphone}Tooltip`]"@#@ @source: @#@"Use this option to make calls using your other phones such as home or cell phones that you have added in your {brand} Extension."@#@
// @key: @#@"[`${callingOptions.otherphone}Tooltip1`]"@#@ @source: @#@"For the call you make, this phone will ring first then the party you called."@#@
// @key: @#@"[`${callingOptions.customphone}Tooltip`]"@#@ @source: @#@"Use this option to make calls using any phone of your choice by entering a valid phone number in the field below."@#@
// @key: @#@"[`${callingOptions.customphone}Tooltip1`]"@#@ @source: @#@"For the call you make, this phone will ring first then the party you called."@#@ | random_line_split | |
game.py | import pygame
import src.graphics as graphics
import src.colours as colours
import src.config as config
import src.scenes.scenebase as scene_base
from src.minigames.hunt.input_handler import InputHandler
from src.gui.clickable import Clickable
from src.resolution_asset_sizer import ResolutionAssetSizer
from src.tiled_map import TiledMap
from src.game_object.deadly_area import DeadlyArea
from src.minigames.hunt.player import Player
from src.minigames.hunt.collectible import Collectible
class Hunt(scene_base.SceneBase):
"""The Hunt minigame...pretty much snake"""
def __init__(self, previous, current_stage=1):
self.current_stage = current_stage
self.file = './assets/game-data/levels/minigames/hunt/minigame-hunt-' + str(self.current_stage) + '.tmx'
self.surface = graphics.get_window_surface()
self.tiled_map = TiledMap(self.file, self.surface)
self.sprites = self.tiled_map.sprites
self.player = self.get_player()
self.collectibles = pygame.sprite.Group([sprite for sprite in self.sprites if isinstance(sprite, Collectible)])
self.collideables = pygame.sprite.Group([sprite for sprite in self.sprites if isinstance(sprite, DeadlyArea)])
scene_base.SceneBase.__init__(
self,
InputHandler(self),
graphics.get_controller()
)
self.previous = previous
self.width, self.height = pygame.display.get_window_size()
def update(self, delta_time):
self.sprites.update(delta_time, self.tiled_map)
self.player.handle_collision(self.collectibles, self.collideables)
if not self.player.alive():
self.reset()
if self.has_completed_minigame():
self.previous.open_secured_door()
self.switch_to_scene(self.previous)
elif self.has_won():
self.next_stage()
def has_won(self):
has_no_enemies = True
for sprite in self.sprites:
if isinstance(sprite, Collectible):
|
return has_no_enemies
def has_completed_minigame(self):
return self.has_won() and self.current_stage == 3
def render(self):
self.surface.fill(colours.RED)
self.sprites.draw(self.surface)
def get_player(self):
for sprite in self.sprites:
if isinstance(sprite, Player):
return sprite
def reset(self):
self.__init__(self.previous, self.current_stage)
def next_stage(self):
self.current_stage += 1
self.__init__(self.previous, self.current_stage)
| has_no_enemies = False | conditional_block |
game.py | import pygame
import src.graphics as graphics
import src.colours as colours
import src.config as config
import src.scenes.scenebase as scene_base
from src.minigames.hunt.input_handler import InputHandler
from src.gui.clickable import Clickable
from src.resolution_asset_sizer import ResolutionAssetSizer
from src.tiled_map import TiledMap
from src.game_object.deadly_area import DeadlyArea
from src.minigames.hunt.player import Player
from src.minigames.hunt.collectible import Collectible
class Hunt(scene_base.SceneBase):
"""The Hunt minigame...pretty much snake"""
def __init__(self, previous, current_stage=1):
self.current_stage = current_stage
self.file = './assets/game-data/levels/minigames/hunt/minigame-hunt-' + str(self.current_stage) + '.tmx'
self.surface = graphics.get_window_surface()
self.tiled_map = TiledMap(self.file, self.surface)
self.sprites = self.tiled_map.sprites
self.player = self.get_player()
self.collectibles = pygame.sprite.Group([sprite for sprite in self.sprites if isinstance(sprite, Collectible)])
self.collideables = pygame.sprite.Group([sprite for sprite in self.sprites if isinstance(sprite, DeadlyArea)])
scene_base.SceneBase.__init__(
self,
InputHandler(self),
graphics.get_controller()
)
self.previous = previous
self.width, self.height = pygame.display.get_window_size()
def update(self, delta_time):
self.sprites.update(delta_time, self.tiled_map)
self.player.handle_collision(self.collectibles, self.collideables)
if not self.player.alive():
self.reset()
if self.has_completed_minigame():
self.previous.open_secured_door()
self.switch_to_scene(self.previous)
elif self.has_won():
self.next_stage()
def has_won(self):
has_no_enemies = True
for sprite in self.sprites:
if isinstance(sprite, Collectible):
has_no_enemies = False
return has_no_enemies
def has_completed_minigame(self):
return self.has_won() and self.current_stage == 3
def render(self):
self.surface.fill(colours.RED)
self.sprites.draw(self.surface)
def | (self):
for sprite in self.sprites:
if isinstance(sprite, Player):
return sprite
def reset(self):
self.__init__(self.previous, self.current_stage)
def next_stage(self):
self.current_stage += 1
self.__init__(self.previous, self.current_stage)
| get_player | identifier_name |
game.py | import pygame
import src.graphics as graphics
import src.colours as colours
import src.config as config
import src.scenes.scenebase as scene_base
from src.minigames.hunt.input_handler import InputHandler
from src.gui.clickable import Clickable
from src.resolution_asset_sizer import ResolutionAssetSizer
from src.tiled_map import TiledMap
from src.game_object.deadly_area import DeadlyArea
from src.minigames.hunt.player import Player
from src.minigames.hunt.collectible import Collectible
class Hunt(scene_base.SceneBase):
"""The Hunt minigame...pretty much snake"""
def __init__(self, previous, current_stage=1):
self.current_stage = current_stage
self.file = './assets/game-data/levels/minigames/hunt/minigame-hunt-' + str(self.current_stage) + '.tmx'
self.surface = graphics.get_window_surface()
self.tiled_map = TiledMap(self.file, self.surface)
self.sprites = self.tiled_map.sprites
self.player = self.get_player()
self.collectibles = pygame.sprite.Group([sprite for sprite in self.sprites if isinstance(sprite, Collectible)])
self.collideables = pygame.sprite.Group([sprite for sprite in self.sprites if isinstance(sprite, DeadlyArea)])
scene_base.SceneBase.__init__(
self,
InputHandler(self),
graphics.get_controller()
)
self.previous = previous
self.width, self.height = pygame.display.get_window_size()
def update(self, delta_time):
self.sprites.update(delta_time, self.tiled_map)
self.player.handle_collision(self.collectibles, self.collideables)
if not self.player.alive():
self.reset()
if self.has_completed_minigame():
self.previous.open_secured_door()
self.switch_to_scene(self.previous)
elif self.has_won():
self.next_stage()
def has_won(self):
has_no_enemies = True
for sprite in self.sprites:
if isinstance(sprite, Collectible):
has_no_enemies = False
return has_no_enemies
def has_completed_minigame(self):
return self.has_won() and self.current_stage == 3
def render(self):
self.surface.fill(colours.RED)
self.sprites.draw(self.surface)
def get_player(self):
for sprite in self.sprites: |
def next_stage(self):
self.current_stage += 1
self.__init__(self.previous, self.current_stage) | if isinstance(sprite, Player):
return sprite
def reset(self):
self.__init__(self.previous, self.current_stage) | random_line_split |
game.py | import pygame
import src.graphics as graphics
import src.colours as colours
import src.config as config
import src.scenes.scenebase as scene_base
from src.minigames.hunt.input_handler import InputHandler
from src.gui.clickable import Clickable
from src.resolution_asset_sizer import ResolutionAssetSizer
from src.tiled_map import TiledMap
from src.game_object.deadly_area import DeadlyArea
from src.minigames.hunt.player import Player
from src.minigames.hunt.collectible import Collectible
class Hunt(scene_base.SceneBase):
"""The Hunt minigame...pretty much snake"""
def __init__(self, previous, current_stage=1):
self.current_stage = current_stage
self.file = './assets/game-data/levels/minigames/hunt/minigame-hunt-' + str(self.current_stage) + '.tmx'
self.surface = graphics.get_window_surface()
self.tiled_map = TiledMap(self.file, self.surface)
self.sprites = self.tiled_map.sprites
self.player = self.get_player()
self.collectibles = pygame.sprite.Group([sprite for sprite in self.sprites if isinstance(sprite, Collectible)])
self.collideables = pygame.sprite.Group([sprite for sprite in self.sprites if isinstance(sprite, DeadlyArea)])
scene_base.SceneBase.__init__(
self,
InputHandler(self),
graphics.get_controller()
)
self.previous = previous
self.width, self.height = pygame.display.get_window_size()
def update(self, delta_time):
|
def has_won(self):
has_no_enemies = True
for sprite in self.sprites:
if isinstance(sprite, Collectible):
has_no_enemies = False
return has_no_enemies
def has_completed_minigame(self):
return self.has_won() and self.current_stage == 3
def render(self):
self.surface.fill(colours.RED)
self.sprites.draw(self.surface)
def get_player(self):
for sprite in self.sprites:
if isinstance(sprite, Player):
return sprite
def reset(self):
self.__init__(self.previous, self.current_stage)
def next_stage(self):
self.current_stage += 1
self.__init__(self.previous, self.current_stage)
| self.sprites.update(delta_time, self.tiled_map)
self.player.handle_collision(self.collectibles, self.collideables)
if not self.player.alive():
self.reset()
if self.has_completed_minigame():
self.previous.open_secured_door()
self.switch_to_scene(self.previous)
elif self.has_won():
self.next_stage() | identifier_body |
ledger.py | # -*- coding: utf-8 -*-
class Ledger(object):
def __init__(self, db):
self.db = db
def balance(self, token):
cursor = self.db.cursor()
cursor.execute("""SELECT * FROM balances WHERE TOKEN = %s""", [token])
row = cursor.fetchone()
return 0 if row is None else row[2]
def deposit(self, token, amount):
cursor = self.db.cursor()
cursor.execute(
"""INSERT INTO balances (token, amount)
SELECT %s, 0
WHERE NOT EXISTS (SELECT 1 FROM balances WHERE token = %s)""",
[token, token])
cursor.execute(
"""UPDATE balances SET amount = amount + %s WHERE token = %s""",
[amount, token])
cursor.execute(
"""INSERT INTO movements (token, amount) VALUES(%s, %s)""",
[token, amount])
self.db.commit()
return True
def withdraw(self, token, amount):
"""Remove the given amount from the token's balance."""
cursor = self.db.cursor()
cursor.execute("""
UPDATE balances
SET amount = amount - %s
WHERE token = %s AND amount >= %s""",
[amount, token, amount])
success = (cursor.rowcount == 1)
if success:
|
self.db.commit()
return success
| cursor.execute(
"""INSERT INTO movements (token, amount) VALUES(%s, %s)""",
[token, -amount]) | conditional_block |
ledger.py | # -*- coding: utf-8 -*-
class Ledger(object):
def __init__(self, db):
self.db = db
def balance(self, token):
cursor = self.db.cursor()
cursor.execute("""SELECT * FROM balances WHERE TOKEN = %s""", [token])
row = cursor.fetchone()
return 0 if row is None else row[2]
def | (self, token, amount):
cursor = self.db.cursor()
cursor.execute(
"""INSERT INTO balances (token, amount)
SELECT %s, 0
WHERE NOT EXISTS (SELECT 1 FROM balances WHERE token = %s)""",
[token, token])
cursor.execute(
"""UPDATE balances SET amount = amount + %s WHERE token = %s""",
[amount, token])
cursor.execute(
"""INSERT INTO movements (token, amount) VALUES(%s, %s)""",
[token, amount])
self.db.commit()
return True
def withdraw(self, token, amount):
"""Remove the given amount from the token's balance."""
cursor = self.db.cursor()
cursor.execute("""
UPDATE balances
SET amount = amount - %s
WHERE token = %s AND amount >= %s""",
[amount, token, amount])
success = (cursor.rowcount == 1)
if success:
cursor.execute(
"""INSERT INTO movements (token, amount) VALUES(%s, %s)""",
[token, -amount])
self.db.commit()
return success
| deposit | identifier_name |
ledger.py | # -*- coding: utf-8 -*-
class Ledger(object):
def __init__(self, db):
self.db = db
def balance(self, token):
cursor = self.db.cursor()
cursor.execute("""SELECT * FROM balances WHERE TOKEN = %s""", [token])
row = cursor.fetchone()
return 0 if row is None else row[2]
def deposit(self, token, amount):
|
def withdraw(self, token, amount):
"""Remove the given amount from the token's balance."""
cursor = self.db.cursor()
cursor.execute("""
UPDATE balances
SET amount = amount - %s
WHERE token = %s AND amount >= %s""",
[amount, token, amount])
success = (cursor.rowcount == 1)
if success:
cursor.execute(
"""INSERT INTO movements (token, amount) VALUES(%s, %s)""",
[token, -amount])
self.db.commit()
return success
| cursor = self.db.cursor()
cursor.execute(
"""INSERT INTO balances (token, amount)
SELECT %s, 0
WHERE NOT EXISTS (SELECT 1 FROM balances WHERE token = %s)""",
[token, token])
cursor.execute(
"""UPDATE balances SET amount = amount + %s WHERE token = %s""",
[amount, token])
cursor.execute(
"""INSERT INTO movements (token, amount) VALUES(%s, %s)""",
[token, amount])
self.db.commit()
return True | identifier_body |
ledger.py | # -*- coding: utf-8 -*-
class Ledger(object):
def __init__(self, db):
self.db = db
def balance(self, token):
cursor = self.db.cursor()
cursor.execute("""SELECT * FROM balances WHERE TOKEN = %s""", [token])
row = cursor.fetchone()
return 0 if row is None else row[2]
def deposit(self, token, amount):
cursor = self.db.cursor()
cursor.execute(
"""INSERT INTO balances (token, amount)
SELECT %s, 0
WHERE NOT EXISTS (SELECT 1 FROM balances WHERE token = %s)""",
[token, token])
cursor.execute(
"""UPDATE balances SET amount = amount + %s WHERE token = %s""",
[amount, token])
cursor.execute(
"""INSERT INTO movements (token, amount) VALUES(%s, %s)""",
[token, amount])
self.db.commit()
return True
def withdraw(self, token, amount):
"""Remove the given amount from the token's balance.""" | UPDATE balances
SET amount = amount - %s
WHERE token = %s AND amount >= %s""",
[amount, token, amount])
success = (cursor.rowcount == 1)
if success:
cursor.execute(
"""INSERT INTO movements (token, amount) VALUES(%s, %s)""",
[token, -amount])
self.db.commit()
return success |
cursor = self.db.cursor()
cursor.execute(""" | random_line_split |
blocks.py | import json
import sys
if sys.version_info >= (3, 0):
from urllib.request import urlopen
else:
from urllib2 import urlopen
class Blocks:
def __init__(self):
self.version = None
self.block_hash = None
def load_info(self, block_number):
raise NotImplementError
def read_url(self, url):
try:
return urlopen(url).read().decode('utf-8')
except:
print('Error trying to read: ' + url +\
' / Try to open in a browser to see what the error is.')
sys.exit(0)
class Block_Toshi(Blocks):
def __init__(self): |
def load_info(self, block_number):
json_block = json.loads(self.read_url(self.url.format(str(block_number))))
self.version = json_block['version']
self.block_hash = json_block['hash']
class Block_BlockR(Blocks):
def __init__(self):
BLOCKR_API = 'https://btc.blockr.io/api/'
self.url = BLOCKR_API + 'v1/block/info/{}'
def load_info(self, block_number):
json_block = json.loads(self.read_url(self.url.format(str(block_number))))
block_info = json_block['data']
self.version = block_info['version']
self.block_hash = block_info['hash'] | TOSHI_API = 'https://bitcoin.toshi.io/api'
self.url = TOSHI_API + "/v0/blocks/{}" | random_line_split |
blocks.py | import json
import sys
if sys.version_info >= (3, 0):
from urllib.request import urlopen
else:
from urllib2 import urlopen
class Blocks:
def __init__(self):
self.version = None
self.block_hash = None
def load_info(self, block_number):
raise NotImplementError
def read_url(self, url):
try:
return urlopen(url).read().decode('utf-8')
except:
print('Error trying to read: ' + url +\
' / Try to open in a browser to see what the error is.')
sys.exit(0)
class Block_Toshi(Blocks):
def __init__(self):
TOSHI_API = 'https://bitcoin.toshi.io/api'
self.url = TOSHI_API + "/v0/blocks/{}"
def load_info(self, block_number):
json_block = json.loads(self.read_url(self.url.format(str(block_number))))
self.version = json_block['version']
self.block_hash = json_block['hash']
class Block_BlockR(Blocks):
| def __init__(self):
BLOCKR_API = 'https://btc.blockr.io/api/'
self.url = BLOCKR_API + 'v1/block/info/{}'
def load_info(self, block_number):
json_block = json.loads(self.read_url(self.url.format(str(block_number))))
block_info = json_block['data']
self.version = block_info['version']
self.block_hash = block_info['hash'] | identifier_body | |
blocks.py | import json
import sys
if sys.version_info >= (3, 0):
from urllib.request import urlopen
else:
from urllib2 import urlopen
class Blocks:
def __init__(self):
self.version = None
self.block_hash = None
def load_info(self, block_number):
raise NotImplementError
def read_url(self, url):
try:
return urlopen(url).read().decode('utf-8')
except:
print('Error trying to read: ' + url +\
' / Try to open in a browser to see what the error is.')
sys.exit(0)
class Block_Toshi(Blocks):
def __init__(self):
TOSHI_API = 'https://bitcoin.toshi.io/api'
self.url = TOSHI_API + "/v0/blocks/{}"
def load_info(self, block_number):
json_block = json.loads(self.read_url(self.url.format(str(block_number))))
self.version = json_block['version']
self.block_hash = json_block['hash']
class Block_BlockR(Blocks):
def | (self):
BLOCKR_API = 'https://btc.blockr.io/api/'
self.url = BLOCKR_API + 'v1/block/info/{}'
def load_info(self, block_number):
json_block = json.loads(self.read_url(self.url.format(str(block_number))))
block_info = json_block['data']
self.version = block_info['version']
self.block_hash = block_info['hash']
| __init__ | identifier_name |
blocks.py | import json
import sys
if sys.version_info >= (3, 0):
|
else:
from urllib2 import urlopen
class Blocks:
def __init__(self):
self.version = None
self.block_hash = None
def load_info(self, block_number):
raise NotImplementError
def read_url(self, url):
try:
return urlopen(url).read().decode('utf-8')
except:
print('Error trying to read: ' + url +\
' / Try to open in a browser to see what the error is.')
sys.exit(0)
class Block_Toshi(Blocks):
def __init__(self):
TOSHI_API = 'https://bitcoin.toshi.io/api'
self.url = TOSHI_API + "/v0/blocks/{}"
def load_info(self, block_number):
json_block = json.loads(self.read_url(self.url.format(str(block_number))))
self.version = json_block['version']
self.block_hash = json_block['hash']
class Block_BlockR(Blocks):
def __init__(self):
BLOCKR_API = 'https://btc.blockr.io/api/'
self.url = BLOCKR_API + 'v1/block/info/{}'
def load_info(self, block_number):
json_block = json.loads(self.read_url(self.url.format(str(block_number))))
block_info = json_block['data']
self.version = block_info['version']
self.block_hash = block_info['hash']
| from urllib.request import urlopen | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.