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 |
---|---|---|---|---|
test_deprecations.py | import logging
import pytest
from traitlets.config import Config
from dockerspawner import DockerSpawner
def test_deprecated_config(caplog):
cfg = Config()
cfg.DockerSpawner.image_whitelist = {"1.0": "jupyterhub/singleuser:1.0"}
log = logging.getLogger("testlog")
spawner = DockerSpawner(config=cfg, log=log)
assert caplog.record_tuples == [
(
log.name,
logging.WARNING,
'DockerSpawner.image_whitelist is deprecated in DockerSpawner 12.0, use '
'DockerSpawner.allowed_images instead',
)
]
assert spawner.allowed_images == {"1.0": "jupyterhub/singleuser:1.0"}
async def test_deprecated_methods():
| cfg = Config()
cfg.DockerSpawner.image_whitelist = {"1.0": "jupyterhub/singleuser:1.0"}
spawner = DockerSpawner(config=cfg)
assert await spawner.check_allowed("1.0")
with pytest.deprecated_call():
assert await spawner.check_image_whitelist("1.0") | identifier_body |
|
test_deprecations.py | import logging
import pytest
from traitlets.config import Config
from dockerspawner import DockerSpawner
def test_deprecated_config(caplog):
cfg = Config()
cfg.DockerSpawner.image_whitelist = {"1.0": "jupyterhub/singleuser:1.0"}
| logging.WARNING,
'DockerSpawner.image_whitelist is deprecated in DockerSpawner 12.0, use '
'DockerSpawner.allowed_images instead',
)
]
assert spawner.allowed_images == {"1.0": "jupyterhub/singleuser:1.0"}
async def test_deprecated_methods():
cfg = Config()
cfg.DockerSpawner.image_whitelist = {"1.0": "jupyterhub/singleuser:1.0"}
spawner = DockerSpawner(config=cfg)
assert await spawner.check_allowed("1.0")
with pytest.deprecated_call():
assert await spawner.check_image_whitelist("1.0") | log = logging.getLogger("testlog")
spawner = DockerSpawner(config=cfg, log=log)
assert caplog.record_tuples == [
(
log.name, | random_line_split |
generic_type_does_not_live_long_enough.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(existential_type)]
fn main() {
let y = 42;
let x = wrong_generic(&y);
let z: i32 = x; //~ ERROR mismatched types
}
existential type WrongGeneric<T>: 'static;
//~^ ERROR the parameter type `T` may not live long enough
fn wrong_generic<T>(t: T) -> WrongGeneric<T> {
t | } | random_line_split |
|
generic_type_does_not_live_long_enough.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(existential_type)]
fn main() |
existential type WrongGeneric<T>: 'static;
//~^ ERROR the parameter type `T` may not live long enough
fn wrong_generic<T>(t: T) -> WrongGeneric<T> {
t
}
| {
let y = 42;
let x = wrong_generic(&y);
let z: i32 = x; //~ ERROR mismatched types
} | identifier_body |
generic_type_does_not_live_long_enough.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(existential_type)]
fn | () {
let y = 42;
let x = wrong_generic(&y);
let z: i32 = x; //~ ERROR mismatched types
}
existential type WrongGeneric<T>: 'static;
//~^ ERROR the parameter type `T` may not live long enough
fn wrong_generic<T>(t: T) -> WrongGeneric<T> {
t
}
| main | identifier_name |
sectionalize_pass.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Breaks rustdocs into sections according to their headers
use astsrv;
use doc::ItemUtils;
use doc;
use fold::Fold;
use fold;
use pass::Pass;
use std::iterator::IteratorUtil;
pub fn mk_pass() -> Pass {
Pass {
name: ~"sectionalize",
f: run
}
}
pub fn run(_srv: astsrv::Srv, doc: doc::Doc) -> doc::Doc {
let fold = Fold {
fold_item: fold_item,
fold_trait: fold_trait,
fold_impl: fold_impl,
.. fold::default_any_fold(())
};
(fold.fold_doc)(&fold, doc)
}
fn fold_item(fold: &fold::Fold<()>, doc: doc::ItemDoc) -> doc::ItemDoc {
let doc = fold::default_seq_fold_item(fold, doc);
let (desc, sections) = sectionalize(copy doc.desc);
doc::ItemDoc {
desc: desc,
sections: sections,
.. doc
}
}
fn fold_trait(fold: &fold::Fold<()>, doc: doc::TraitDoc) -> doc::TraitDoc {
let doc = fold::default_seq_fold_trait(fold, doc);
doc::TraitDoc {
methods: do doc.methods.map |method| {
let (desc, sections) = sectionalize(copy method.desc);
doc::MethodDoc {
desc: desc,
sections: sections,
.. copy *method
}
},
.. doc
}
}
fn fold_impl(fold: &fold::Fold<()>, doc: doc::ImplDoc) -> doc::ImplDoc {
let doc = fold::default_seq_fold_impl(fold, doc);
doc::ImplDoc {
methods: do doc.methods.map |method| {
let (desc, sections) = sectionalize(copy method.desc);
doc::MethodDoc {
desc: desc,
sections: sections,
.. copy *method
}
},
.. doc
}
}
fn sectionalize(desc: Option<~str>) -> (Option<~str>, ~[doc::Section]) {
/*!
* Take a description of the form
*
* General text
*
* # Section header
*
* Section text
*
* # Section header
*
* Section text
*
* and remove each header and accompanying text into section records.
*/
if desc.is_none() {
return (None, ~[]);
}
let mut new_desc = None::<~str>;
let mut current_section = None;
let mut sections = ~[];
for desc.get_ref().any_line_iter().advance |line| {
match parse_header(line) {
Some(header) => {
if current_section.is_some() {
sections.push(copy *current_section.get_ref());
}
current_section = Some(doc::Section {
header: header.to_owned(),
body: ~""
});
}
None => {
match copy current_section {
Some(section) => {
current_section = Some(doc::Section {
body: fmt!("%s\n%s", section.body, line),
.. section
});
}
None => {
new_desc = match copy new_desc {
Some(desc) => {
Some(fmt!("%s\n%s", desc, line))
}
None => {
Some(line.to_owned())
}
};
}
}
}
}
}
if current_section.is_some() {
sections.push(current_section.unwrap());
}
(new_desc, sections)
}
fn parse_header<'a>(line: &'a str) -> Option<&'a str> {
if line.starts_with("# ") {
Some(line.slice_from(2))
} else {
None
}
}
#[cfg(test)]
mod test {
use astsrv;
use attr_pass;
use doc;
use extract;
use prune_hidden_pass;
use sectionalize_pass::run;
fn mk_doc(source: ~str) -> doc::Doc {
do astsrv::from_str(copy source) |srv| {
let doc = extract::from_srv(srv.clone(), ~"");
let doc = (attr_pass::mk_pass().f)(srv.clone(), doc);
let doc = (prune_hidden_pass::mk_pass().f)(srv.clone(), doc);
run(srv.clone(), doc)
}
}
#[test]
fn should_create_section_headers() {
let doc = mk_doc(
~"#[doc = \"\
# Header\n\
Body\"]\
mod a {
}");
assert!(doc.cratemod().mods()[0].item.sections[0].header.contains("Header"));
}
#[test]
fn should_create_section_bodies() {
let doc = mk_doc(
~"#[doc = \"\
# Header\n\
Body\"]\
mod a { | fn should_not_create_sections_from_indented_headers() {
let doc = mk_doc(
~"#[doc = \"\n\
Text\n # Header\n\
Body\"]\
mod a {
}");
assert!(doc.cratemod().mods()[0].item.sections.is_empty());
}
#[test]
fn should_remove_section_text_from_main_desc() {
let doc = mk_doc(
~"#[doc = \"\
Description\n\n\
# Header\n\
Body\"]\
mod a {
}");
assert!(!doc.cratemod().mods()[0].desc().get().contains("Header"));
assert!(!doc.cratemod().mods()[0].desc().get().contains("Body"));
}
#[test]
fn should_eliminate_desc_if_it_is_just_whitespace() {
let doc = mk_doc(
~"#[doc = \"\
# Header\n\
Body\"]\
mod a {
}");
assert_eq!(doc.cratemod().mods()[0].desc(), None);
}
#[test]
fn should_sectionalize_trait_methods() {
let doc = mk_doc(
~"trait i {
#[doc = \"\
# Header\n\
Body\"]\
fn a(); }");
assert_eq!(doc.cratemod().traits()[0].methods[0].sections.len(), 1u);
}
#[test]
fn should_sectionalize_impl_methods() {
let doc = mk_doc(
~"impl bool {
#[doc = \"\
# Header\n\
Body\"]\
fn a() { } }");
assert_eq!(doc.cratemod().impls()[0].methods[0].sections.len(), 1u);
}
} | }");
assert!(doc.cratemod().mods()[0].item.sections[0].body.contains("Body"));
}
#[test] | random_line_split |
sectionalize_pass.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Breaks rustdocs into sections according to their headers
use astsrv;
use doc::ItemUtils;
use doc;
use fold::Fold;
use fold;
use pass::Pass;
use std::iterator::IteratorUtil;
pub fn mk_pass() -> Pass {
Pass {
name: ~"sectionalize",
f: run
}
}
pub fn run(_srv: astsrv::Srv, doc: doc::Doc) -> doc::Doc {
let fold = Fold {
fold_item: fold_item,
fold_trait: fold_trait,
fold_impl: fold_impl,
.. fold::default_any_fold(())
};
(fold.fold_doc)(&fold, doc)
}
fn fold_item(fold: &fold::Fold<()>, doc: doc::ItemDoc) -> doc::ItemDoc |
fn fold_trait(fold: &fold::Fold<()>, doc: doc::TraitDoc) -> doc::TraitDoc {
let doc = fold::default_seq_fold_trait(fold, doc);
doc::TraitDoc {
methods: do doc.methods.map |method| {
let (desc, sections) = sectionalize(copy method.desc);
doc::MethodDoc {
desc: desc,
sections: sections,
.. copy *method
}
},
.. doc
}
}
fn fold_impl(fold: &fold::Fold<()>, doc: doc::ImplDoc) -> doc::ImplDoc {
let doc = fold::default_seq_fold_impl(fold, doc);
doc::ImplDoc {
methods: do doc.methods.map |method| {
let (desc, sections) = sectionalize(copy method.desc);
doc::MethodDoc {
desc: desc,
sections: sections,
.. copy *method
}
},
.. doc
}
}
fn sectionalize(desc: Option<~str>) -> (Option<~str>, ~[doc::Section]) {
/*!
* Take a description of the form
*
* General text
*
* # Section header
*
* Section text
*
* # Section header
*
* Section text
*
* and remove each header and accompanying text into section records.
*/
if desc.is_none() {
return (None, ~[]);
}
let mut new_desc = None::<~str>;
let mut current_section = None;
let mut sections = ~[];
for desc.get_ref().any_line_iter().advance |line| {
match parse_header(line) {
Some(header) => {
if current_section.is_some() {
sections.push(copy *current_section.get_ref());
}
current_section = Some(doc::Section {
header: header.to_owned(),
body: ~""
});
}
None => {
match copy current_section {
Some(section) => {
current_section = Some(doc::Section {
body: fmt!("%s\n%s", section.body, line),
.. section
});
}
None => {
new_desc = match copy new_desc {
Some(desc) => {
Some(fmt!("%s\n%s", desc, line))
}
None => {
Some(line.to_owned())
}
};
}
}
}
}
}
if current_section.is_some() {
sections.push(current_section.unwrap());
}
(new_desc, sections)
}
fn parse_header<'a>(line: &'a str) -> Option<&'a str> {
if line.starts_with("# ") {
Some(line.slice_from(2))
} else {
None
}
}
#[cfg(test)]
mod test {
use astsrv;
use attr_pass;
use doc;
use extract;
use prune_hidden_pass;
use sectionalize_pass::run;
fn mk_doc(source: ~str) -> doc::Doc {
do astsrv::from_str(copy source) |srv| {
let doc = extract::from_srv(srv.clone(), ~"");
let doc = (attr_pass::mk_pass().f)(srv.clone(), doc);
let doc = (prune_hidden_pass::mk_pass().f)(srv.clone(), doc);
run(srv.clone(), doc)
}
}
#[test]
fn should_create_section_headers() {
let doc = mk_doc(
~"#[doc = \"\
# Header\n\
Body\"]\
mod a {
}");
assert!(doc.cratemod().mods()[0].item.sections[0].header.contains("Header"));
}
#[test]
fn should_create_section_bodies() {
let doc = mk_doc(
~"#[doc = \"\
# Header\n\
Body\"]\
mod a {
}");
assert!(doc.cratemod().mods()[0].item.sections[0].body.contains("Body"));
}
#[test]
fn should_not_create_sections_from_indented_headers() {
let doc = mk_doc(
~"#[doc = \"\n\
Text\n # Header\n\
Body\"]\
mod a {
}");
assert!(doc.cratemod().mods()[0].item.sections.is_empty());
}
#[test]
fn should_remove_section_text_from_main_desc() {
let doc = mk_doc(
~"#[doc = \"\
Description\n\n\
# Header\n\
Body\"]\
mod a {
}");
assert!(!doc.cratemod().mods()[0].desc().get().contains("Header"));
assert!(!doc.cratemod().mods()[0].desc().get().contains("Body"));
}
#[test]
fn should_eliminate_desc_if_it_is_just_whitespace() {
let doc = mk_doc(
~"#[doc = \"\
# Header\n\
Body\"]\
mod a {
}");
assert_eq!(doc.cratemod().mods()[0].desc(), None);
}
#[test]
fn should_sectionalize_trait_methods() {
let doc = mk_doc(
~"trait i {
#[doc = \"\
# Header\n\
Body\"]\
fn a(); }");
assert_eq!(doc.cratemod().traits()[0].methods[0].sections.len(), 1u);
}
#[test]
fn should_sectionalize_impl_methods() {
let doc = mk_doc(
~"impl bool {
#[doc = \"\
# Header\n\
Body\"]\
fn a() { } }");
assert_eq!(doc.cratemod().impls()[0].methods[0].sections.len(), 1u);
}
}
| {
let doc = fold::default_seq_fold_item(fold, doc);
let (desc, sections) = sectionalize(copy doc.desc);
doc::ItemDoc {
desc: desc,
sections: sections,
.. doc
}
} | identifier_body |
sectionalize_pass.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Breaks rustdocs into sections according to their headers
use astsrv;
use doc::ItemUtils;
use doc;
use fold::Fold;
use fold;
use pass::Pass;
use std::iterator::IteratorUtil;
pub fn mk_pass() -> Pass {
Pass {
name: ~"sectionalize",
f: run
}
}
pub fn run(_srv: astsrv::Srv, doc: doc::Doc) -> doc::Doc {
let fold = Fold {
fold_item: fold_item,
fold_trait: fold_trait,
fold_impl: fold_impl,
.. fold::default_any_fold(())
};
(fold.fold_doc)(&fold, doc)
}
fn fold_item(fold: &fold::Fold<()>, doc: doc::ItemDoc) -> doc::ItemDoc {
let doc = fold::default_seq_fold_item(fold, doc);
let (desc, sections) = sectionalize(copy doc.desc);
doc::ItemDoc {
desc: desc,
sections: sections,
.. doc
}
}
fn fold_trait(fold: &fold::Fold<()>, doc: doc::TraitDoc) -> doc::TraitDoc {
let doc = fold::default_seq_fold_trait(fold, doc);
doc::TraitDoc {
methods: do doc.methods.map |method| {
let (desc, sections) = sectionalize(copy method.desc);
doc::MethodDoc {
desc: desc,
sections: sections,
.. copy *method
}
},
.. doc
}
}
fn fold_impl(fold: &fold::Fold<()>, doc: doc::ImplDoc) -> doc::ImplDoc {
let doc = fold::default_seq_fold_impl(fold, doc);
doc::ImplDoc {
methods: do doc.methods.map |method| {
let (desc, sections) = sectionalize(copy method.desc);
doc::MethodDoc {
desc: desc,
sections: sections,
.. copy *method
}
},
.. doc
}
}
fn | (desc: Option<~str>) -> (Option<~str>, ~[doc::Section]) {
/*!
* Take a description of the form
*
* General text
*
* # Section header
*
* Section text
*
* # Section header
*
* Section text
*
* and remove each header and accompanying text into section records.
*/
if desc.is_none() {
return (None, ~[]);
}
let mut new_desc = None::<~str>;
let mut current_section = None;
let mut sections = ~[];
for desc.get_ref().any_line_iter().advance |line| {
match parse_header(line) {
Some(header) => {
if current_section.is_some() {
sections.push(copy *current_section.get_ref());
}
current_section = Some(doc::Section {
header: header.to_owned(),
body: ~""
});
}
None => {
match copy current_section {
Some(section) => {
current_section = Some(doc::Section {
body: fmt!("%s\n%s", section.body, line),
.. section
});
}
None => {
new_desc = match copy new_desc {
Some(desc) => {
Some(fmt!("%s\n%s", desc, line))
}
None => {
Some(line.to_owned())
}
};
}
}
}
}
}
if current_section.is_some() {
sections.push(current_section.unwrap());
}
(new_desc, sections)
}
fn parse_header<'a>(line: &'a str) -> Option<&'a str> {
if line.starts_with("# ") {
Some(line.slice_from(2))
} else {
None
}
}
#[cfg(test)]
mod test {
use astsrv;
use attr_pass;
use doc;
use extract;
use prune_hidden_pass;
use sectionalize_pass::run;
fn mk_doc(source: ~str) -> doc::Doc {
do astsrv::from_str(copy source) |srv| {
let doc = extract::from_srv(srv.clone(), ~"");
let doc = (attr_pass::mk_pass().f)(srv.clone(), doc);
let doc = (prune_hidden_pass::mk_pass().f)(srv.clone(), doc);
run(srv.clone(), doc)
}
}
#[test]
fn should_create_section_headers() {
let doc = mk_doc(
~"#[doc = \"\
# Header\n\
Body\"]\
mod a {
}");
assert!(doc.cratemod().mods()[0].item.sections[0].header.contains("Header"));
}
#[test]
fn should_create_section_bodies() {
let doc = mk_doc(
~"#[doc = \"\
# Header\n\
Body\"]\
mod a {
}");
assert!(doc.cratemod().mods()[0].item.sections[0].body.contains("Body"));
}
#[test]
fn should_not_create_sections_from_indented_headers() {
let doc = mk_doc(
~"#[doc = \"\n\
Text\n # Header\n\
Body\"]\
mod a {
}");
assert!(doc.cratemod().mods()[0].item.sections.is_empty());
}
#[test]
fn should_remove_section_text_from_main_desc() {
let doc = mk_doc(
~"#[doc = \"\
Description\n\n\
# Header\n\
Body\"]\
mod a {
}");
assert!(!doc.cratemod().mods()[0].desc().get().contains("Header"));
assert!(!doc.cratemod().mods()[0].desc().get().contains("Body"));
}
#[test]
fn should_eliminate_desc_if_it_is_just_whitespace() {
let doc = mk_doc(
~"#[doc = \"\
# Header\n\
Body\"]\
mod a {
}");
assert_eq!(doc.cratemod().mods()[0].desc(), None);
}
#[test]
fn should_sectionalize_trait_methods() {
let doc = mk_doc(
~"trait i {
#[doc = \"\
# Header\n\
Body\"]\
fn a(); }");
assert_eq!(doc.cratemod().traits()[0].methods[0].sections.len(), 1u);
}
#[test]
fn should_sectionalize_impl_methods() {
let doc = mk_doc(
~"impl bool {
#[doc = \"\
# Header\n\
Body\"]\
fn a() { } }");
assert_eq!(doc.cratemod().impls()[0].methods[0].sections.len(), 1u);
}
}
| sectionalize | identifier_name |
sectionalize_pass.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Breaks rustdocs into sections according to their headers
use astsrv;
use doc::ItemUtils;
use doc;
use fold::Fold;
use fold;
use pass::Pass;
use std::iterator::IteratorUtil;
pub fn mk_pass() -> Pass {
Pass {
name: ~"sectionalize",
f: run
}
}
pub fn run(_srv: astsrv::Srv, doc: doc::Doc) -> doc::Doc {
let fold = Fold {
fold_item: fold_item,
fold_trait: fold_trait,
fold_impl: fold_impl,
.. fold::default_any_fold(())
};
(fold.fold_doc)(&fold, doc)
}
fn fold_item(fold: &fold::Fold<()>, doc: doc::ItemDoc) -> doc::ItemDoc {
let doc = fold::default_seq_fold_item(fold, doc);
let (desc, sections) = sectionalize(copy doc.desc);
doc::ItemDoc {
desc: desc,
sections: sections,
.. doc
}
}
fn fold_trait(fold: &fold::Fold<()>, doc: doc::TraitDoc) -> doc::TraitDoc {
let doc = fold::default_seq_fold_trait(fold, doc);
doc::TraitDoc {
methods: do doc.methods.map |method| {
let (desc, sections) = sectionalize(copy method.desc);
doc::MethodDoc {
desc: desc,
sections: sections,
.. copy *method
}
},
.. doc
}
}
fn fold_impl(fold: &fold::Fold<()>, doc: doc::ImplDoc) -> doc::ImplDoc {
let doc = fold::default_seq_fold_impl(fold, doc);
doc::ImplDoc {
methods: do doc.methods.map |method| {
let (desc, sections) = sectionalize(copy method.desc);
doc::MethodDoc {
desc: desc,
sections: sections,
.. copy *method
}
},
.. doc
}
}
fn sectionalize(desc: Option<~str>) -> (Option<~str>, ~[doc::Section]) {
/*!
* Take a description of the form
*
* General text
*
* # Section header
*
* Section text
*
* # Section header
*
* Section text
*
* and remove each header and accompanying text into section records.
*/
if desc.is_none() {
return (None, ~[]);
}
let mut new_desc = None::<~str>;
let mut current_section = None;
let mut sections = ~[];
for desc.get_ref().any_line_iter().advance |line| {
match parse_header(line) {
Some(header) => {
if current_section.is_some() {
sections.push(copy *current_section.get_ref());
}
current_section = Some(doc::Section {
header: header.to_owned(),
body: ~""
});
}
None => {
match copy current_section {
Some(section) => {
current_section = Some(doc::Section {
body: fmt!("%s\n%s", section.body, line),
.. section
});
}
None => {
new_desc = match copy new_desc {
Some(desc) => {
Some(fmt!("%s\n%s", desc, line))
}
None => {
Some(line.to_owned())
}
};
}
}
}
}
}
if current_section.is_some() |
(new_desc, sections)
}
fn parse_header<'a>(line: &'a str) -> Option<&'a str> {
if line.starts_with("# ") {
Some(line.slice_from(2))
} else {
None
}
}
#[cfg(test)]
mod test {
use astsrv;
use attr_pass;
use doc;
use extract;
use prune_hidden_pass;
use sectionalize_pass::run;
fn mk_doc(source: ~str) -> doc::Doc {
do astsrv::from_str(copy source) |srv| {
let doc = extract::from_srv(srv.clone(), ~"");
let doc = (attr_pass::mk_pass().f)(srv.clone(), doc);
let doc = (prune_hidden_pass::mk_pass().f)(srv.clone(), doc);
run(srv.clone(), doc)
}
}
#[test]
fn should_create_section_headers() {
let doc = mk_doc(
~"#[doc = \"\
# Header\n\
Body\"]\
mod a {
}");
assert!(doc.cratemod().mods()[0].item.sections[0].header.contains("Header"));
}
#[test]
fn should_create_section_bodies() {
let doc = mk_doc(
~"#[doc = \"\
# Header\n\
Body\"]\
mod a {
}");
assert!(doc.cratemod().mods()[0].item.sections[0].body.contains("Body"));
}
#[test]
fn should_not_create_sections_from_indented_headers() {
let doc = mk_doc(
~"#[doc = \"\n\
Text\n # Header\n\
Body\"]\
mod a {
}");
assert!(doc.cratemod().mods()[0].item.sections.is_empty());
}
#[test]
fn should_remove_section_text_from_main_desc() {
let doc = mk_doc(
~"#[doc = \"\
Description\n\n\
# Header\n\
Body\"]\
mod a {
}");
assert!(!doc.cratemod().mods()[0].desc().get().contains("Header"));
assert!(!doc.cratemod().mods()[0].desc().get().contains("Body"));
}
#[test]
fn should_eliminate_desc_if_it_is_just_whitespace() {
let doc = mk_doc(
~"#[doc = \"\
# Header\n\
Body\"]\
mod a {
}");
assert_eq!(doc.cratemod().mods()[0].desc(), None);
}
#[test]
fn should_sectionalize_trait_methods() {
let doc = mk_doc(
~"trait i {
#[doc = \"\
# Header\n\
Body\"]\
fn a(); }");
assert_eq!(doc.cratemod().traits()[0].methods[0].sections.len(), 1u);
}
#[test]
fn should_sectionalize_impl_methods() {
let doc = mk_doc(
~"impl bool {
#[doc = \"\
# Header\n\
Body\"]\
fn a() { } }");
assert_eq!(doc.cratemod().impls()[0].methods[0].sections.len(), 1u);
}
}
| {
sections.push(current_section.unwrap());
} | conditional_block |
androgui.py | #!/usr/bin/env python2
'''Androguard Gui'''
import argparse
import sys
from androguard.core import androconf
from androguard.session import Session
from androguard.gui.mainwindow import MainWindow
from androguard.misc import init_print_colors
from PySide import QtCore, QtGui
from threading import Thread
class IpythonConsole(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
|
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Androguard GUI")
parser.add_argument("-d", "--debug", action="store_true", default=False)
parser.add_argument("-i", "--input_file", default=None)
parser.add_argument("-c", "--console", action="store_true", default=False)
args = parser.parse_args()
if args.debug:
androconf.set_debug()
# We need that to save huge sessions when leaving and avoid
# RuntimeError: maximum recursion depth exceeded while pickling an object
# or
# RuntimeError: maximum recursion depth exceeded in cmp
# http://stackoverflow.com/questions/2134706/hitting-maximum-recursion-depth-using-pythons-pickle-cpickle
sys.setrecursionlimit(50000)
session = Session(export_ipython=args.console)
console = None
if args.console:
console = IpythonConsole()
console.start()
app = QtGui.QApplication(sys.argv)
window = MainWindow(session=session, input_file=args.input_file)
window.resize(1024, 768)
window.show()
sys.exit(app.exec_())
| from IPython.terminal.embed import InteractiveShellEmbed
from traitlets.config import Config
cfg = Config()
ipshell = InteractiveShellEmbed(
config=cfg,
banner1="Androguard version %s" % androconf.ANDROGUARD_VERSION)
init_print_colors()
ipshell() | identifier_body |
androgui.py | #!/usr/bin/env python2
'''Androguard Gui'''
import argparse
import sys
from androguard.core import androconf
from androguard.session import Session
from androguard.gui.mainwindow import MainWindow
from androguard.misc import init_print_colors
from PySide import QtCore, QtGui
from threading import Thread
class | (Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
from IPython.terminal.embed import InteractiveShellEmbed
from traitlets.config import Config
cfg = Config()
ipshell = InteractiveShellEmbed(
config=cfg,
banner1="Androguard version %s" % androconf.ANDROGUARD_VERSION)
init_print_colors()
ipshell()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Androguard GUI")
parser.add_argument("-d", "--debug", action="store_true", default=False)
parser.add_argument("-i", "--input_file", default=None)
parser.add_argument("-c", "--console", action="store_true", default=False)
args = parser.parse_args()
if args.debug:
androconf.set_debug()
# We need that to save huge sessions when leaving and avoid
# RuntimeError: maximum recursion depth exceeded while pickling an object
# or
# RuntimeError: maximum recursion depth exceeded in cmp
# http://stackoverflow.com/questions/2134706/hitting-maximum-recursion-depth-using-pythons-pickle-cpickle
sys.setrecursionlimit(50000)
session = Session(export_ipython=args.console)
console = None
if args.console:
console = IpythonConsole()
console.start()
app = QtGui.QApplication(sys.argv)
window = MainWindow(session=session, input_file=args.input_file)
window.resize(1024, 768)
window.show()
sys.exit(app.exec_())
| IpythonConsole | identifier_name |
androgui.py | #!/usr/bin/env python2
'''Androguard Gui'''
import argparse
import sys
from androguard.core import androconf
from androguard.session import Session
from androguard.gui.mainwindow import MainWindow
from androguard.misc import init_print_colors
from PySide import QtCore, QtGui
from threading import Thread
class IpythonConsole(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
from IPython.terminal.embed import InteractiveShellEmbed
from traitlets.config import Config
cfg = Config()
ipshell = InteractiveShellEmbed(
config=cfg,
banner1="Androguard version %s" % androconf.ANDROGUARD_VERSION)
init_print_colors()
ipshell()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Androguard GUI")
parser.add_argument("-d", "--debug", action="store_true", default=False)
parser.add_argument("-i", "--input_file", default=None)
parser.add_argument("-c", "--console", action="store_true", default=False)
args = parser.parse_args()
if args.debug:
androconf.set_debug()
# We need that to save huge sessions when leaving and avoid
# RuntimeError: maximum recursion depth exceeded while pickling an object
# or
# RuntimeError: maximum recursion depth exceeded in cmp
# http://stackoverflow.com/questions/2134706/hitting-maximum-recursion-depth-using-pythons-pickle-cpickle
sys.setrecursionlimit(50000)
session = Session(export_ipython=args.console)
console = None
if args.console:
console = IpythonConsole()
console.start() |
app = QtGui.QApplication(sys.argv)
window = MainWindow(session=session, input_file=args.input_file)
window.resize(1024, 768)
window.show()
sys.exit(app.exec_()) | random_line_split |
|
androgui.py | #!/usr/bin/env python2
'''Androguard Gui'''
import argparse
import sys
from androguard.core import androconf
from androguard.session import Session
from androguard.gui.mainwindow import MainWindow
from androguard.misc import init_print_colors
from PySide import QtCore, QtGui
from threading import Thread
class IpythonConsole(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
from IPython.terminal.embed import InteractiveShellEmbed
from traitlets.config import Config
cfg = Config()
ipshell = InteractiveShellEmbed(
config=cfg,
banner1="Androguard version %s" % androconf.ANDROGUARD_VERSION)
init_print_colors()
ipshell()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Androguard GUI")
parser.add_argument("-d", "--debug", action="store_true", default=False)
parser.add_argument("-i", "--input_file", default=None)
parser.add_argument("-c", "--console", action="store_true", default=False)
args = parser.parse_args()
if args.debug:
|
# We need that to save huge sessions when leaving and avoid
# RuntimeError: maximum recursion depth exceeded while pickling an object
# or
# RuntimeError: maximum recursion depth exceeded in cmp
# http://stackoverflow.com/questions/2134706/hitting-maximum-recursion-depth-using-pythons-pickle-cpickle
sys.setrecursionlimit(50000)
session = Session(export_ipython=args.console)
console = None
if args.console:
console = IpythonConsole()
console.start()
app = QtGui.QApplication(sys.argv)
window = MainWindow(session=session, input_file=args.input_file)
window.resize(1024, 768)
window.show()
sys.exit(app.exec_())
| androconf.set_debug() | conditional_block |
sepcomp-unwind.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-bitrig
// compile-flags: -C codegen-units=3
// Test unwinding through multiple compilation units.
// According to acrichto, in the distant past `ld -r` (which is used during
// linking when codegen-units > 1) was known to produce object files with
// damaged unwinding tables. This may be related to GNU binutils bug #6893
// ("Partial linking results in corrupt .eh_frame_hdr"), but I'm not certain.
// In any case, this test should let us know if enabling parallel codegen ever
// breaks unwinding.
use std::thread;
fn | () -> usize { 0 }
mod a {
pub fn f() {
panic!();
}
}
mod b {
pub fn g() {
::a::f();
}
}
fn main() {
thread::spawn(move|| { ::b::g() }).join().err().unwrap();
}
| pad | identifier_name |
sepcomp-unwind.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-bitrig
// compile-flags: -C codegen-units=3
// Test unwinding through multiple compilation units.
// According to acrichto, in the distant past `ld -r` (which is used during
// linking when codegen-units > 1) was known to produce object files with
// damaged unwinding tables. This may be related to GNU binutils bug #6893
// ("Partial linking results in corrupt .eh_frame_hdr"), but I'm not certain.
// In any case, this test should let us know if enabling parallel codegen ever
// breaks unwinding.
use std::thread;
fn pad() -> usize { 0 }
mod a {
pub fn f() {
panic!();
}
}
mod b {
pub fn g() {
::a::f();
}
}
| fn main() {
thread::spawn(move|| { ::b::g() }).join().err().unwrap();
} | random_line_split |
|
sepcomp-unwind.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-bitrig
// compile-flags: -C codegen-units=3
// Test unwinding through multiple compilation units.
// According to acrichto, in the distant past `ld -r` (which is used during
// linking when codegen-units > 1) was known to produce object files with
// damaged unwinding tables. This may be related to GNU binutils bug #6893
// ("Partial linking results in corrupt .eh_frame_hdr"), but I'm not certain.
// In any case, this test should let us know if enabling parallel codegen ever
// breaks unwinding.
use std::thread;
fn pad() -> usize { 0 }
mod a {
pub fn f() {
panic!();
}
}
mod b {
pub fn g() {
::a::f();
}
}
fn main() | {
thread::spawn(move|| { ::b::g() }).join().err().unwrap();
} | identifier_body |
|
partner_events.py | # -*- coding: UTF-8 -*-
import haystack
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from conference import models
from conference.templatetags.conference import fare_blob
from collections import defaultdict
from datetime import datetime
from xml.sax.saxutils import escape
class Command(BaseCommand):
"""
"""
@transaction.commit_on_success
def | (self, *args, **options):
try:
conference = args[0]
except IndexError:
raise CommandError('conference missing')
partner_events = defaultdict(list)
for f in models.Fare.objects.available(conference=conference).filter(ticket_type='partner'):
try:
date = datetime.strptime(fare_blob(f, 'data').split(',')[0][:-2] + ' 2011', '%B %d %Y').date()
time = datetime.strptime(fare_blob(f, 'departure'), '%H:%M').time()
except ValueError:
continue
partner_events[date].append((f, time))
for sch in models.Schedule.objects.filter(conference=conference):
events = list(models.Event.objects.filter(schedule=sch))
for fare, time in partner_events[sch.date]:
track_id = 'f%s' % fare.id
for e in events:
if track_id in e.get_all_tracks_names():
event = e
break
else:
event = models.Event(schedule=sch, talk=None)
event.track = 'partner-program ' + track_id
event.custom = escape(fare.name)
event.start_time = time
if time.hour < 13:
d = (13 - time.hour) * 60
else:
d = (19 - time.hour) * 60
event.duration = d
event.save()
| handle | identifier_name |
partner_events.py | # -*- coding: UTF-8 -*-
import haystack
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from conference import models
from conference.templatetags.conference import fare_blob
from collections import defaultdict
from datetime import datetime
from xml.sax.saxutils import escape
class Command(BaseCommand):
"""
"""
@transaction.commit_on_success
def handle(self, *args, **options):
try:
conference = args[0]
except IndexError:
raise CommandError('conference missing')
partner_events = defaultdict(list)
for f in models.Fare.objects.available(conference=conference).filter(ticket_type='partner'):
try:
date = datetime.strptime(fare_blob(f, 'data').split(',')[0][:-2] + ' 2011', '%B %d %Y').date()
time = datetime.strptime(fare_blob(f, 'departure'), '%H:%M').time()
except ValueError:
continue
partner_events[date].append((f, time))
for sch in models.Schedule.objects.filter(conference=conference):
events = list(models.Event.objects.filter(schedule=sch))
for fare, time in partner_events[sch.date]:
track_id = 'f%s' % fare.id
for e in events:
if track_id in e.get_all_tracks_names():
event = e
break
else:
event = models.Event(schedule=sch, talk=None)
event.track = 'partner-program ' + track_id
event.custom = escape(fare.name)
event.start_time = time
if time.hour < 13:
|
else:
d = (19 - time.hour) * 60
event.duration = d
event.save()
| d = (13 - time.hour) * 60 | conditional_block |
partner_events.py | # -*- coding: UTF-8 -*-
import haystack
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from conference import models
from conference.templatetags.conference import fare_blob
from collections import defaultdict
from datetime import datetime
from xml.sax.saxutils import escape
class Command(BaseCommand):
"""
"""
@transaction.commit_on_success
def handle(self, *args, **options):
| try:
conference = args[0]
except IndexError:
raise CommandError('conference missing')
partner_events = defaultdict(list)
for f in models.Fare.objects.available(conference=conference).filter(ticket_type='partner'):
try:
date = datetime.strptime(fare_blob(f, 'data').split(',')[0][:-2] + ' 2011', '%B %d %Y').date()
time = datetime.strptime(fare_blob(f, 'departure'), '%H:%M').time()
except ValueError:
continue
partner_events[date].append((f, time))
for sch in models.Schedule.objects.filter(conference=conference):
events = list(models.Event.objects.filter(schedule=sch))
for fare, time in partner_events[sch.date]:
track_id = 'f%s' % fare.id
for e in events:
if track_id in e.get_all_tracks_names():
event = e
break
else:
event = models.Event(schedule=sch, talk=None)
event.track = 'partner-program ' + track_id
event.custom = escape(fare.name)
event.start_time = time
if time.hour < 13:
d = (13 - time.hour) * 60
else:
d = (19 - time.hour) * 60
event.duration = d
event.save() | identifier_body |
|
partner_events.py | # -*- coding: UTF-8 -*-
import haystack
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from conference import models
from conference.templatetags.conference import fare_blob
from collections import defaultdict
from datetime import datetime
from xml.sax.saxutils import escape
class Command(BaseCommand):
"""
"""
@transaction.commit_on_success
def handle(self, *args, **options):
try:
conference = args[0]
except IndexError:
raise CommandError('conference missing')
partner_events = defaultdict(list)
for f in models.Fare.objects.available(conference=conference).filter(ticket_type='partner'):
try:
date = datetime.strptime(fare_blob(f, 'data').split(',')[0][:-2] + ' 2011', '%B %d %Y').date()
time = datetime.strptime(fare_blob(f, 'departure'), '%H:%M').time()
except ValueError:
continue
partner_events[date].append((f, time)) | for fare, time in partner_events[sch.date]:
track_id = 'f%s' % fare.id
for e in events:
if track_id in e.get_all_tracks_names():
event = e
break
else:
event = models.Event(schedule=sch, talk=None)
event.track = 'partner-program ' + track_id
event.custom = escape(fare.name)
event.start_time = time
if time.hour < 13:
d = (13 - time.hour) * 60
else:
d = (19 - time.hour) * 60
event.duration = d
event.save() |
for sch in models.Schedule.objects.filter(conference=conference):
events = list(models.Event.objects.filter(schedule=sch)) | random_line_split |
dbutils.py | # -*- coding: UTF-8 -*-
"""
Database utilities.
@author: Aurélien Gâteau <[email protected]>
@author: Sébastien Renard <[email protected]>
@license: GPL v3 or later
"""
from datetime import datetime, timedelta
import os
from sqlobject.dberrors import DuplicateEntryError
from sqlobject import SQLObjectNotFound
from yokadi.ycli import tui
from yokadi.core.db import Keyword, Project, Task, TaskLock
from yokadi.core.yokadiexception import YokadiException
def addTask(projectName, title, keywordDict=None, interactive=True):
"""Adds a task based on title and keywordDict.
@param projectName: name of project as a string
@param title: task title as a string
@param keywordDict: dictionary of keywords (name : value)
@param interactive: Ask user before creating project (this is the default)
@type interactive: Bool
@returns : Task instance on success, None if cancelled."""
if keywordDict is None:
keywordDict = {}
# Create missing keywords
if not createMissingKeywords(keywordDict.keys(), interactive=interactive):
return None
# Create missing project
project = getOrCreateProject(projectName, interactive=interactive)
if not project:
return None
# Create task
try:
task = Task(creationDate=datetime.now(), project=project, title=title, description="", status="new")
task.setKeywordDict(keywordDict)
except DuplicateEntryError:
raise YokadiException("A task named %s already exists in this project. Please find another name" % title)
return task
def updateTask(task, projectName, title, keywordDict):
"""
Update an existing task, returns True if it went well, False if user
canceled the update
"""
if not createMissingKeywords(keywordDict.keys()):
return False
project = getOrCreateProject(projectName)
if not project:
return False
task.project = project
task.title = title
task.setKeywordDict(keywordDict)
return True
def getTaskFromId(tid, parameterName="id"):
"""Returns a task given its id, or raise a YokadiException if it does not
exist.
@param tid: taskId string
@param parameterName: name of the parameter to mention in exception
@return: Task instance or None if existingTask is False"""
# We do not use line.isdigit() because it returns True if line is '¹'!
try:
taskId = int(tid)
except ValueError:
raise YokadiException("<%s> should be a number" % parameterName)
try:
task = Task.get(taskId)
except SQLObjectNotFound:
raise YokadiException("Task %s does not exist. Use t_list to see all tasks" % taskId)
return task
# TODO: factorize the two following functions and make a generic one
def getOrCreateKeyword(keywordName, interactive=True): | @param keywordName: keyword name as a string
@param interactive: Ask user before creating keyword (this is the default)
@type interactive: Bool
@return: Keyword instance or None if user cancel creation"""
result = Keyword.selectBy(name=keywordName)
result = list(result)
if len(result):
return result[0]
if interactive and not tui.confirm("Keyword '%s' does not exist, create it" % keywordName):
return None
keyword = Keyword(name=keywordName)
print "Added keyword '%s'" % keywordName
return keyword
def getOrCreateProject(projectName, interactive=True, createIfNeeded=True):
"""Get a project by its name. Create it if needed
@param projectName: project name as a string
@param interactive: Ask user before creating project (this is the default)
@type interactive: Bool
@param createIfNeeded: create project if it does not exist (this is the default)
@type createIfNeeded: Bool
@return: Project instance or None if user cancel creation or createIfNeeded is False"""
result = Project.selectBy(name=projectName)
result = list(result)
if len(result):
return result[0]
if not createIfNeeded:
return None
if interactive and not tui.confirm("Project '%s' does not exist, create it" % projectName):
return None
project = Project(name=projectName)
print "Added project '%s'" % projectName
return project
def createMissingKeywords(lst, interactive=True):
"""Create all keywords from lst which does not exist
@param lst: list of keyword
@return: True, if ok, False if user canceled"""
for keywordName in lst:
if not getOrCreateKeyword(keywordName, interactive=interactive):
return False
return True
def getKeywordFromName(name):
"""Returns a keyword from its name, which may start with "@"
raises a YokadiException if not found
@param name: the keyword name
@return: The keyword"""
if not name:
raise YokadiException("No keyword supplied")
if name.startswith("@"):
name = name[1:]
lst = list(Keyword.selectBy(name=name))
if len(lst) == 0:
raise YokadiException("No keyword named '%s' found" % name)
return lst[0]
class TaskLockManager:
"""Handle a lock to prevent concurrent editing of the same task"""
def __init__(self, task):
"""@param task: a Task instance"""
self.task = task
def _getLock(self):
"""Retrieve the task lock if it exists (else None)"""
try:
return TaskLock.select(TaskLock.q.task == self.task).getOne()
except SQLObjectNotFound:
return None
def acquire(self):
"""Acquire a lock for that task and remove any previous stale lock"""
lock = self._getLock()
if lock:
if lock.updateDate < datetime.now() - 2 * timedelta(seconds=tui.MTIME_POLL_INTERVAL):
# Stale lock, removing
TaskLock.delete(lock.id)
else:
raise YokadiException("Task %s is already locked by process %s" % (lock.task.id, lock.pid))
TaskLock(task=self.task, pid=os.getpid(), updateDate=datetime.now())
def update(self):
"""Update lock timestamp to avoid it to expire"""
lock = self._getLock()
lock.updateDate = datetime.now()
def release(self):
"""Release the lock for that task"""
# Only release our lock
lock = self._getLock()
if lock and lock.pid == os.getpid():
TaskLock.delete(lock.id)
# vi: ts=4 sw=4 et | """Get a keyword by its name. Create it if needed | random_line_split |
dbutils.py | # -*- coding: UTF-8 -*-
"""
Database utilities.
@author: Aurélien Gâteau <[email protected]>
@author: Sébastien Renard <[email protected]>
@license: GPL v3 or later
"""
from datetime import datetime, timedelta
import os
from sqlobject.dberrors import DuplicateEntryError
from sqlobject import SQLObjectNotFound
from yokadi.ycli import tui
from yokadi.core.db import Keyword, Project, Task, TaskLock
from yokadi.core.yokadiexception import YokadiException
def addTask(projectName, title, keywordDict=None, interactive=True):
"""Adds a task based on title and keywordDict.
@param projectName: name of project as a string
@param title: task title as a string
@param keywordDict: dictionary of keywords (name : value)
@param interactive: Ask user before creating project (this is the default)
@type interactive: Bool
@returns : Task instance on success, None if cancelled."""
if keywordDict is None:
keywordDict = {}
# Create missing keywords
if not createMissingKeywords(keywordDict.keys(), interactive=interactive):
return None
# Create missing project
project = getOrCreateProject(projectName, interactive=interactive)
if not project:
return None
# Create task
try:
task = Task(creationDate=datetime.now(), project=project, title=title, description="", status="new")
task.setKeywordDict(keywordDict)
except DuplicateEntryError:
raise YokadiException("A task named %s already exists in this project. Please find another name" % title)
return task
def updateTask(task, projectName, title, keywordDict):
"""
Update an existing task, returns True if it went well, False if user
canceled the update
"""
if not createMissingKeywords(keywordDict.keys()):
return False
project = getOrCreateProject(projectName)
if not project:
return False
task.project = project
task.title = title
task.setKeywordDict(keywordDict)
return True
def getTaskFromId(tid, parameterName="id"):
"""Returns a task given its id, or raise a YokadiException if it does not
exist.
@param tid: taskId string
@param parameterName: name of the parameter to mention in exception
@return: Task instance or None if existingTask is False"""
# We do not use line.isdigit() because it returns True if line is '¹'!
try:
taskId = int(tid)
except ValueError:
raise YokadiException("<%s> should be a number" % parameterName)
try:
task = Task.get(taskId)
except SQLObjectNotFound:
raise YokadiException("Task %s does not exist. Use t_list to see all tasks" % taskId)
return task
# TODO: factorize the two following functions and make a generic one
def getOrCreateKeyword(keywordName, interactive=True):
"""Get a keyword by its name. Create it if needed
@param keywordName: keyword name as a string
@param interactive: Ask user before creating keyword (this is the default)
@type interactive: Bool
@return: Keyword instance or None if user cancel creation"""
result = Keyword.selectBy(name=keywordName)
result = list(result)
if len(result):
return result[0]
if interactive and not tui.confirm("Keyword '%s' does not exist, create it" % keywordName):
return None
keyword = Keyword(name=keywordName)
print "Added keyword '%s'" % keywordName
return keyword
def getOrCreateProject(projectName, interactive=True, createIfNeeded=True):
"""Get a project by its name. Create it if needed
@param projectName: project name as a string
@param interactive: Ask user before creating project (this is the default)
@type interactive: Bool
@param createIfNeeded: create project if it does not exist (this is the default)
@type createIfNeeded: Bool
@return: Project instance or None if user cancel creation or createIfNeeded is False"""
result = Project.selectBy(name=projectName)
result = list(result)
if len(result):
return result[0]
if not createIfNeeded:
return None
if interactive and not tui.confirm("Project '%s' does not exist, create it" % projectName):
return None
project = Project(name=projectName)
print "Added project '%s'" % projectName
return project
def createMissingKeywords(lst, interactive=True):
"""Create all keywords from lst which does not exist
@param lst: list of keyword
@return: True, if ok, False if user canceled"""
for keywordName in lst:
if not getOrCreateKeyword(keywordName, interactive=interactive):
return False
return True
def getKeywordFromName(name):
"""Returns a keyword from its name, which may start with "@"
raises a YokadiException if not found
@param name: the keyword name
@return: The keyword"""
if not name:
rais | if name.startswith("@"):
name = name[1:]
lst = list(Keyword.selectBy(name=name))
if len(lst) == 0:
raise YokadiException("No keyword named '%s' found" % name)
return lst[0]
class TaskLockManager:
"""Handle a lock to prevent concurrent editing of the same task"""
def __init__(self, task):
"""@param task: a Task instance"""
self.task = task
def _getLock(self):
"""Retrieve the task lock if it exists (else None)"""
try:
return TaskLock.select(TaskLock.q.task == self.task).getOne()
except SQLObjectNotFound:
return None
def acquire(self):
"""Acquire a lock for that task and remove any previous stale lock"""
lock = self._getLock()
if lock:
if lock.updateDate < datetime.now() - 2 * timedelta(seconds=tui.MTIME_POLL_INTERVAL):
# Stale lock, removing
TaskLock.delete(lock.id)
else:
raise YokadiException("Task %s is already locked by process %s" % (lock.task.id, lock.pid))
TaskLock(task=self.task, pid=os.getpid(), updateDate=datetime.now())
def update(self):
"""Update lock timestamp to avoid it to expire"""
lock = self._getLock()
lock.updateDate = datetime.now()
def release(self):
"""Release the lock for that task"""
# Only release our lock
lock = self._getLock()
if lock and lock.pid == os.getpid():
TaskLock.delete(lock.id)
# vi: ts=4 sw=4 et
| e YokadiException("No keyword supplied")
| conditional_block |
dbutils.py | # -*- coding: UTF-8 -*-
"""
Database utilities.
@author: Aurélien Gâteau <[email protected]>
@author: Sébastien Renard <[email protected]>
@license: GPL v3 or later
"""
from datetime import datetime, timedelta
import os
from sqlobject.dberrors import DuplicateEntryError
from sqlobject import SQLObjectNotFound
from yokadi.ycli import tui
from yokadi.core.db import Keyword, Project, Task, TaskLock
from yokadi.core.yokadiexception import YokadiException
def addTask(projectName, title, keywordDict=None, interactive=True):
"""Adds a task based on title and keywordDict.
@param projectName: name of project as a string
@param title: task title as a string
@param keywordDict: dictionary of keywords (name : value)
@param interactive: Ask user before creating project (this is the default)
@type interactive: Bool
@returns : Task instance on success, None if cancelled."""
if keywordDict is None:
keywordDict = {}
# Create missing keywords
if not createMissingKeywords(keywordDict.keys(), interactive=interactive):
return None
# Create missing project
project = getOrCreateProject(projectName, interactive=interactive)
if not project:
return None
# Create task
try:
task = Task(creationDate=datetime.now(), project=project, title=title, description="", status="new")
task.setKeywordDict(keywordDict)
except DuplicateEntryError:
raise YokadiException("A task named %s already exists in this project. Please find another name" % title)
return task
def updateTask(task, projectName, title, keywordDict):
"""
Update an existing task, returns True if it went well, False if user
canceled the update
"""
if not createMissingKeywords(keywordDict.keys()):
return False
project = getOrCreateProject(projectName)
if not project:
return False
task.project = project
task.title = title
task.setKeywordDict(keywordDict)
return True
def getTaskFromId(tid, parameterName="id"):
"""Returns a task given its id, or raise a YokadiException if it does not
exist.
@param tid: taskId string
@param parameterName: name of the parameter to mention in exception
@return: Task instance or None if existingTask is False"""
# We do not use line.isdigit() because it returns True if line is '¹'!
try:
taskId = int(tid)
except ValueError:
raise YokadiException("<%s> should be a number" % parameterName)
try:
task = Task.get(taskId)
except SQLObjectNotFound:
raise YokadiException("Task %s does not exist. Use t_list to see all tasks" % taskId)
return task
# TODO: factorize the two following functions and make a generic one
def getOrCreateKeyword(keywordName, interactive=True):
"""Get a keyword by its name. Create it if needed
@param keywordName: keyword name as a string
@param interactive: Ask user before creating keyword (this is the default)
@type interactive: Bool
@return: Keyword instance or None if user cancel creation"""
result = Keyword.selectBy(name=keywordName)
result = list(result)
if len(result):
return result[0]
if interactive and not tui.confirm("Keyword '%s' does not exist, create it" % keywordName):
return None
keyword = Keyword(name=keywordName)
print "Added keyword '%s'" % keywordName
return keyword
def getOrCreateProject(projectName, interactive=True, createIfNeeded=True):
"""Get a project by its name. Create it if needed
@param projectName: project name as a string
@param interactive: Ask user before creating project (this is the default)
@type interactive: Bool
@param createIfNeeded: create project if it does not exist (this is the default)
@type createIfNeeded: Bool
@return: Project instance or None if user cancel creation or createIfNeeded is False"""
result = Project.selectBy(name=projectName)
result = list(result)
if len(result):
return result[0]
if not createIfNeeded:
return None
if interactive and not tui.confirm("Project '%s' does not exist, create it" % projectName):
return None
project = Project(name=projectName)
print "Added project '%s'" % projectName
return project
def createMissingKeywords(lst, interactive=True):
"""Create all keywords from lst which does not exist
@param lst: list of keyword
@return: True, if ok, False if user canceled"""
for keywordName in lst:
if not getOrCreateKeyword(keywordName, interactive=interactive):
return False
return True
def getKeywordFromName(name):
"""Returns a keyword from its name, which may start with "@"
raises a YokadiException if not found
@param name: the keyword name
@return: The keyword"""
if not name:
raise YokadiException("No keyword supplied")
if name.startswith("@"):
name = name[1:]
lst = list(Keyword.selectBy(name=name))
if len(lst) == 0:
raise YokadiException("No keyword named '%s' found" % name)
return lst[0]
class TaskLockManager:
"""Handle a lock to prevent concurrent editing of the same task"""
def __init__(self, task):
"""@param task: a Task instance"""
self.task = task
def _getLock(self):
"""Retrieve the task lock if it exists (else None)"""
try:
return TaskLock.select(TaskLock.q.task == self.task).getOne()
except SQLObjectNotFound:
return None
def acquire(self):
"""Acquire a lock for that task and remove any previous stale lock"""
lock = self._getLock()
if lock:
if lock.updateDate < datetime.now() - 2 * timedelta(seconds=tui.MTIME_POLL_INTERVAL):
# Stale lock, removing
TaskLock.delete(lock.id)
else:
raise YokadiException("Task %s is already locked by process %s" % (lock.task.id, lock.pid))
TaskLock(task=self.task, pid=os.getpid(), updateDate=datetime.now())
def update(self):
"""U | def release(self):
"""Release the lock for that task"""
# Only release our lock
lock = self._getLock()
if lock and lock.pid == os.getpid():
TaskLock.delete(lock.id)
# vi: ts=4 sw=4 et
| pdate lock timestamp to avoid it to expire"""
lock = self._getLock()
lock.updateDate = datetime.now()
| identifier_body |
dbutils.py | # -*- coding: UTF-8 -*-
"""
Database utilities.
@author: Aurélien Gâteau <[email protected]>
@author: Sébastien Renard <[email protected]>
@license: GPL v3 or later
"""
from datetime import datetime, timedelta
import os
from sqlobject.dberrors import DuplicateEntryError
from sqlobject import SQLObjectNotFound
from yokadi.ycli import tui
from yokadi.core.db import Keyword, Project, Task, TaskLock
from yokadi.core.yokadiexception import YokadiException
def addTask(projectName, title, keywordDict=None, interactive=True):
"""Adds a task based on title and keywordDict.
@param projectName: name of project as a string
@param title: task title as a string
@param keywordDict: dictionary of keywords (name : value)
@param interactive: Ask user before creating project (this is the default)
@type interactive: Bool
@returns : Task instance on success, None if cancelled."""
if keywordDict is None:
keywordDict = {}
# Create missing keywords
if not createMissingKeywords(keywordDict.keys(), interactive=interactive):
return None
# Create missing project
project = getOrCreateProject(projectName, interactive=interactive)
if not project:
return None
# Create task
try:
task = Task(creationDate=datetime.now(), project=project, title=title, description="", status="new")
task.setKeywordDict(keywordDict)
except DuplicateEntryError:
raise YokadiException("A task named %s already exists in this project. Please find another name" % title)
return task
def updateTask(task, projectName, title, keywordDict):
"""
Update an existing task, returns True if it went well, False if user
canceled the update
"""
if not createMissingKeywords(keywordDict.keys()):
return False
project = getOrCreateProject(projectName)
if not project:
return False
task.project = project
task.title = title
task.setKeywordDict(keywordDict)
return True
def getTaskFromId(tid, parameterName="id"):
"""Returns a task given its id, or raise a YokadiException if it does not
exist.
@param tid: taskId string
@param parameterName: name of the parameter to mention in exception
@return: Task instance or None if existingTask is False"""
# We do not use line.isdigit() because it returns True if line is '¹'!
try:
taskId = int(tid)
except ValueError:
raise YokadiException("<%s> should be a number" % parameterName)
try:
task = Task.get(taskId)
except SQLObjectNotFound:
raise YokadiException("Task %s does not exist. Use t_list to see all tasks" % taskId)
return task
# TODO: factorize the two following functions and make a generic one
def getO | wordName, interactive=True):
"""Get a keyword by its name. Create it if needed
@param keywordName: keyword name as a string
@param interactive: Ask user before creating keyword (this is the default)
@type interactive: Bool
@return: Keyword instance or None if user cancel creation"""
result = Keyword.selectBy(name=keywordName)
result = list(result)
if len(result):
return result[0]
if interactive and not tui.confirm("Keyword '%s' does not exist, create it" % keywordName):
return None
keyword = Keyword(name=keywordName)
print "Added keyword '%s'" % keywordName
return keyword
def getOrCreateProject(projectName, interactive=True, createIfNeeded=True):
"""Get a project by its name. Create it if needed
@param projectName: project name as a string
@param interactive: Ask user before creating project (this is the default)
@type interactive: Bool
@param createIfNeeded: create project if it does not exist (this is the default)
@type createIfNeeded: Bool
@return: Project instance or None if user cancel creation or createIfNeeded is False"""
result = Project.selectBy(name=projectName)
result = list(result)
if len(result):
return result[0]
if not createIfNeeded:
return None
if interactive and not tui.confirm("Project '%s' does not exist, create it" % projectName):
return None
project = Project(name=projectName)
print "Added project '%s'" % projectName
return project
def createMissingKeywords(lst, interactive=True):
"""Create all keywords from lst which does not exist
@param lst: list of keyword
@return: True, if ok, False if user canceled"""
for keywordName in lst:
if not getOrCreateKeyword(keywordName, interactive=interactive):
return False
return True
def getKeywordFromName(name):
"""Returns a keyword from its name, which may start with "@"
raises a YokadiException if not found
@param name: the keyword name
@return: The keyword"""
if not name:
raise YokadiException("No keyword supplied")
if name.startswith("@"):
name = name[1:]
lst = list(Keyword.selectBy(name=name))
if len(lst) == 0:
raise YokadiException("No keyword named '%s' found" % name)
return lst[0]
class TaskLockManager:
"""Handle a lock to prevent concurrent editing of the same task"""
def __init__(self, task):
"""@param task: a Task instance"""
self.task = task
def _getLock(self):
"""Retrieve the task lock if it exists (else None)"""
try:
return TaskLock.select(TaskLock.q.task == self.task).getOne()
except SQLObjectNotFound:
return None
def acquire(self):
"""Acquire a lock for that task and remove any previous stale lock"""
lock = self._getLock()
if lock:
if lock.updateDate < datetime.now() - 2 * timedelta(seconds=tui.MTIME_POLL_INTERVAL):
# Stale lock, removing
TaskLock.delete(lock.id)
else:
raise YokadiException("Task %s is already locked by process %s" % (lock.task.id, lock.pid))
TaskLock(task=self.task, pid=os.getpid(), updateDate=datetime.now())
def update(self):
"""Update lock timestamp to avoid it to expire"""
lock = self._getLock()
lock.updateDate = datetime.now()
def release(self):
"""Release the lock for that task"""
# Only release our lock
lock = self._getLock()
if lock and lock.pid == os.getpid():
TaskLock.delete(lock.id)
# vi: ts=4 sw=4 et
| rCreateKeyword(key | identifier_name |
messages.test.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import {formatExecError, formatResultsErrors} from '..';
const unixStackTrace =
` ` +
`at stack (../jest-jasmine2/build/jasmine-2.4.1.js:1580:17)
at Object.addResult (../jest-jasmine2/build/jasmine-2.4.1.js:1550:14)
at jasmine.addResult (../jest-jasmine2/build/index.js:82:44)
at Spec.Env.factory (../jest-jasmine2/build/jasmine-2.4.1.js:641:18)
at Spec.addResult (../jest-jasmine2/build/jasmine-2.4.1.js:333:34)
at Expectation.addResult (../jest-jasmine2/build/jasmine-2.4.1.js:591:21)
at Expectation.toBe (../jest-jasmine2/build/jasmine-2.4.1.js:1504:12)
at Object.it (build/__tests__/messages-test.js:45:41)
at Object.<anonymous> (../jest-jasmine2/build/jasmine-pit.js:35:32)
at attemptAsync (../jest-jasmine2/build/jasmine-2.4.1.js:1919:24)`;
const assertionStack =
' ' +
`
Expected value to be of type:
"number"
Received:
""
type:
"string"
at Object.it (__tests__/test.js:8:14)
at Object.asyncFn (node_modules/jest-jasmine2/build/jasmine_async.js:124:345)
at resolve (node_modules/jest-jasmine2/build/queue_runner.js:46:12)
at Promise (<anonymous>)
at mapper (node_modules/jest-jasmine2/build/queue_runner.js:34:499)
at promise.then (node_modules/jest-jasmine2/build/queue_runner.js:74:39)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
at internal/process/next_tick.js:188:7
`;
const vendorStack =
' ' +
`
Expected value to be of type:
"number"
Received:
""
type:
"string"
at Object.it (__tests__/vendor/cool_test.js:6:666)
at Object.asyncFn (__tests__/vendor/sulu/node_modules/sulu-content-bundle/best_component.js:1:5)
`;
const babelStack =
' ' +
`
packages/react/src/forwardRef.js: Unexpected token, expected , (20:10)
\u001b[0m \u001b[90m 18 | \u001b[39m \u001b[36mfalse\u001b[39m\u001b[33m,\u001b[39m
\u001b[90m 19 | \u001b[39m \u001b[32m'forwardRef requires a render function but received a \`memo\` '\u001b[39m
\u001b[31m\u001b[1m>\u001b[22m\u001b[39m\u001b[90m 20 | \u001b[39m \u001b[32m'component. Instead of forwardRef(memo(...)), use '\u001b[39m \u001b[33m+\u001b[39m
\u001b[90m | \u001b[39m \u001b[31m\u001b[1m^\u001b[22m\u001b[39m
\u001b[90m 21 | \u001b[39m \u001b[32m'memo(forwardRef(...)).'\u001b[39m\u001b[33m,\u001b[39m
\u001b[90m 22 | \u001b[39m )\u001b[33m;\u001b[39m
\u001b[90m 23 | \u001b[39m } \u001b[36melse\u001b[39m \u001b[36mif\u001b[39m (\u001b[36mtypeof\u001b[39m render \u001b[33m!==\u001b[39m \u001b[32m'function'\u001b[39m) {\u001b[0m
`;
it('should exclude jasmine from stack trace for Unix paths.', () => {
const messages = formatResultsErrors(
[
{
ancestorTitles: [],
failureMessages: [unixStackTrace],
fullName: 'full name',
location: null,
numPassingAsserts: 0,
status: 'failed',
title: 'Unix test',
},
],
{
rootDir: '',
testMatch: [],
},
{
noStackTrace: false,
},
);
expect(messages).toMatchSnapshot();
});
it('.formatExecError()', () => {
const message = formatExecError(
{
message: 'Whoops!',
stack: '',
},
{
rootDir: '',
testMatch: [],
},
{
noStackTrace: false,
},
'path_test',
);
expect(message).toMatchSnapshot();
});
it('formatStackTrace should strip node internals', () => {
const messages = formatResultsErrors(
[
{
ancestorTitles: [],
failureMessages: [assertionStack],
fullName: 'full name',
location: null,
numPassingAsserts: 0,
status: 'failed',
title: 'Unix test',
},
],
{
rootDir: '',
testMatch: [],
},
{
noStackTrace: false,
},
);
expect(messages).toMatchSnapshot();
});
it('should not exclude vendor from stack trace', () => {
const messages = formatResultsErrors(
[
{
ancestorTitles: [],
failureMessages: [vendorStack],
fullName: 'full name',
location: null,
numPassingAsserts: 0,
status: 'failed',
title: 'Vendor test',
},
],
{
rootDir: '',
testMatch: [],
},
{
noStackTrace: false,
},
);
expect(messages).toMatchSnapshot();
});
it('retains message in babel code frame error', () => {
const messages = formatResultsErrors(
[
{
ancestorTitles: [],
failureMessages: [babelStack],
fullName: 'full name',
location: null,
numPassingAsserts: 0,
status: 'failed',
title: 'Babel test',
},
],
{
rootDir: '',
testMatch: [],
},
{ | },
);
expect(messages).toMatchSnapshot();
}); | noStackTrace: false, | random_line_split |
__init__.py | #!/usr/bin/env python
""" Python SCSS parser. """
import operator
from . import compat
VERSION_INFO = (0, 8, 73)
__project__ = "scss"
__version__ = "0.8.73"
__author__ = "Kirill Klenov <[email protected]>"
__license__ = "GNU LGPL"
CONV = {
'size': {
'em': 13.0,
'px': 1.0},
'length': {
'mm': 1.0,
'cm': 10.0,
'in': 25.4,
'pt': 25.4 / 72,
'pc': 25.4 / 6},
'time': {
'ms': 1.0,
's': 1000.0},
'freq': {
'hz': 1.0,
'khz': 1000.0},
'any': {
'%': 1.0 / 100,
'deg': 1.0 / 360,
's': 1.0 / 60}}
CONV_TYPE = {}
CONV_FACTOR = {}
for t, m in CONV.items():
for k, f in m.items():
CONV_TYPE[k] = t
CONV_FACTOR[k] = f
OPRT = {
'^': operator.__pow__,
'+': operator.__add__,
'-': operator.__sub__,
'*': operator.__mul__,
'/': compat.div,
'!': operator.__neg__,
'<': operator.__lt__,
'<=': operator.__le__,
'>': operator.__gt__,
'>=': operator.__ge__,
'==': operator.__eq__,
'=': operator.__eq__,
'!=': operator.__ne__,
'&': operator.__and__,
'|': operator.__or__,
'and': lambda x, y: x and y,
'or': lambda x, y: x or y,
}
ELEMENTS_OF_TYPE = {
'block': (
"address, article, aside, blockquote, center, dd, dialog, dir, div, dl, dt, fieldset, "
"figure, footer, form, frameset, h1, h2, h3, h4, h5, h6, header, hgroup, hr, isindex, "
"menu, nav, noframes, noscript, ol, p, pre, section, ul"),
'inline': (
"a, abbr, acronym, b, basefont, bdo, big, br, cite, code, dfn, em, font, i, img, input, "
"kbd, label, q, s, samp, select, small, span, strike, strong, sub, sup, textarea, tt, u, "
"var"),
'table': 'table', 'list-item': 'li', 'table-row-group': 'tbody',
'table-header-group': 'thead', 'table-footer-group': 'tfoot', 'table-row':
'tr', 'table-cell': 'td, th', }
COLORS = {
'aliceblue': '#f0f8ff',
'antiquewhite': '#faebd7',
'aqua': '#00ffff',
'aquamarine': '#7fffd4',
'azure': '#f0ffff',
'beige': '#f5f5dc',
'bisque': '#ffe4c4',
'black': '#000000',
'blanchedalmond': '#ffebcd',
'blue': '#0000ff',
'blueviolet': '#8a2be2',
'brown': '#a52a2a',
'burlywood': '#deb887',
'cadetblue': '#5f9ea0',
'chartreuse': '#7fff00',
'chocolate': '#d2691e',
'coral': '#ff7f50',
'cornflowerblue': '#6495ed',
'cornsilk': '#fff8dc',
'crimson': '#dc143c',
'cyan': '#00ffff',
'darkblue': '#00008b',
'darkcyan': '#008b8b',
'darkgoldenrod': '#b8860b',
'darkgray': '#a9a9a9',
'darkgreen': '#006400',
'darkkhaki': '#bdb76b',
'darkmagenta': '#8b008b',
'darkolivegreen': '#556b2f',
'darkorange': '#ff8c00',
'darkorchid': '#9932cc',
'darkred': '#8b0000',
'darksalmon': '#e9967a',
'darkseagreen': '#8fbc8f',
'darkslateblue': '#483d8b',
'darkslategray': '#2f4f4f',
'darkturquoise': '#00ced1',
'darkviolet': '#9400d3',
'deeppink': '#ff1493',
'deepskyblue': '#00bfff',
'dimgray': '#696969',
'dodgerblue': '#1e90ff',
'firebrick': '#b22222',
'floralwhite': '#fffaf0',
'forestgreen': '#228b22',
'fuchsia': '#ff00ff',
'gainsboro': '#dcdcdc',
'ghostwhite': '#f8f8ff',
'gold': '#ffd700',
'goldenrod': '#daa520',
'gray': '#808080',
'green': '#008000',
'greenyellow': '#adff2f',
'honeydew': '#f0fff0',
'hotpink': '#ff69b4',
'indianred': '#cd5c5c',
'indigo': '#4b0082',
'ivory': '#fffff0',
'khaki': '#f0e68c',
'lavender': '#e6e6fa',
'lavenderblush': '#fff0f5',
'lawngreen': '#7cfc00',
'lemonchiffon': '#fffacd',
'lightblue': '#add8e6',
'lightcoral': '#f08080',
'lightcyan': '#e0ffff',
'lightgoldenrodyellow': '#fafad2',
'lightgreen': '#90ee90',
'lightgrey': '#d3d3d3',
'lightpink': '#ffb6c1',
'lightsalmon': '#ffa07a',
'lightseagreen': '#20b2aa',
'lightskyblue': '#87cefa',
'lightslategray': '#778899',
'lightsteelblue': '#b0c4de',
'lightyellow': '#ffffe0',
'lime': '#00ff00',
'limegreen': '#32cd32',
'linen': '#faf0e6',
'magenta': '#ff00ff',
'maroon': '#800000',
'mediumaquamarine': '#66cdaa',
'mediumblue': '#0000cd',
'mediumorchid': '#ba55d3',
'mediumpurple': '#9370db',
'mediumseagreen': '#3cb371',
'mediumslateblue': '#7b68ee',
'mediumspringgreen': '#00fa9a',
'mediumturquoise': '#48d1cc',
'mediumvioletred': '#c71585',
'midnightblue': '#191970',
'mintcream': '#f5fffa',
'mistyrose': '#ffe4e1',
'moccasin': '#ffe4b5',
'navajowhite': '#ffdead',
'navy': '#000080',
'oldlace': '#fdf5e6',
'olive': '#808000',
'olivedrab': '#6b8e23',
'orange': '#ffa500',
'orangered': '#ff4500',
'orchid': '#da70d6',
'palegoldenrod': '#eee8aa',
'palegreen': '#98fb98',
'paleturquoise': '#afeeee',
'palevioletred': '#db7093',
'papayawhip': '#ffefd5',
'peachpuff': '#ffdab9',
'peru': '#cd853f',
'pink': '#ffc0cb',
'plum': '#dda0dd',
'powderblue': '#b0e0e6',
'purple': '#800080',
'red': '#ff0000',
'rosybrown': '#bc8f8f',
'royalblue': '#4169e1',
'saddlebrown': '#8b4513',
'salmon': '#fa8072',
'sandybrown': '#f4a460',
'seagreen': '#2e8b57',
'seashell': '#fff5ee',
'sienna': '#a0522d',
'silver': '#c0c0c0',
'skyblue': '#87ceeb',
'slateblue': '#6a5acd',
'slategray': '#708090',
'snow': '#fffafa',
'springgreen': '#00ff7f',
'steelblue': '#4682b4',
'tan': '#d2b48c',
'teal': '#008080',
'thistle': '#d8bfd8',
'tomato': '#ff6347',
'turquoise': '#40e0d0',
'violet': '#ee82ee',
'wheat': '#f5deb3',
'white': '#ffffff',
'whitesmoke': '#f5f5f5',
'yellow': '#ffff00',
'yellowgreen': '#9acd32'
}
SORTING = dict((v, k) for k, v in enumerate((
# Positioning
'position',
'top',
'right',
'bottom',
'left',
'z-index',
# Box behavior and properties
'float',
'clear',
'display',
'visibility',
'overflow',
'overflow-x',
'overflow-y',
'overflow-style',
'zoom',
'clip',
'box-sizing',
'box-shadow',
# Sizing
'margin',
'margin-top',
'margin-right',
'margin-bottom',
'margin-left',
'padding',
'padding-top',
'padding-right',
'padding-bottom',
'padding-left',
'width',
'height',
'max-width',
'max-height',
'min-width',
'min-height',
# Color appearance
'outline',
'outline-offset',
'outline-width',
'outline-style',
'outline-color',
'border',
'border-break',
'border-collapse',
'border-color',
'border-image',
'border-top-image',
'border-right-image',
'border-bottom-image',
'border-left-image',
'border-corner-image',
'border-top-left-image',
'border-top-right-image',
'border-bottom-right-image',
'border-bottom-left-image',
'border-fit',
'border-length',
'border-spacing',
'border-style',
'border-width',
'border-top',
'border-top-width',
'border-top-style',
'border-top-color',
'border-right',
'border-right-width',
'border-right-style',
'border-right-color',
'border-bottom',
'border-bottom-width',
'border-bottom-style',
'border-bottom-color',
'border-left',
'border-left-width',
'border-left-style',
'border-left-color',
'border-radius',
'border-top-right-radius',
'border-top-left-radius',
'border-bottom-right-radius',
'border-bottom-left-radius',
'background',
'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader',
'background-color',
'background-image',
'background-repeat',
'background-attachment',
'background-position',
'background-position-x',
'background-position-y',
'background-break',
'background-clip',
'background-origin',
'background-size',
'color',
# Special content types
'table-layout',
'caption-side',
'empty-cells',
'list-style',
'list-style-position',
'list-style-type',
'list-style-image',
'quotes',
'content',
'counter-increment',
'counter-reset',
# Text
'direction',
'vertical-align',
'text-align',
'text-align-last',
'text-decoration',
'text-emphasis',
'text-height',
'text-indent',
'text-justify',
'text-outline',
'text-replace',
'text-transform',
'text-wrap',
'text-shadow',
'line-height',
'white-space',
'white-space-collapse',
'word-break',
'word-spacing',
'word-wrap',
'letter-spacing',
'font',
'font-weight',
'font-style',
'font-variant',
'font-size',
'font-size-adjust',
'font-family',
'font-effect',
'font-emphasize',
'font-emphasize-position',
'font-emphasize-style',
'font-smooth',
'font-stretch',
'src',
# Visual properties
'opacity',
'filter:progid:DXImageTransform.Microsoft.Alpha',
'-ms-filter:progid:DXImageTransform.Microsoft.Alpha',
'transitions',
'resize',
'cursor',
# Print
'page-break-before',
'page-break-inside',
'page-break-after',
'orphans',
'widows',
# Transfom
'transition',
'transition-delay',
'transition-duration',
'transition-property',
'transition-timing-function',
)))
class | (Exception):
""" Raise SCSS exception. """
pass
| ScssException | identifier_name |
__init__.py | #!/usr/bin/env python
""" Python SCSS parser. """
import operator
from . import compat
VERSION_INFO = (0, 8, 73)
__project__ = "scss"
__version__ = "0.8.73"
__author__ = "Kirill Klenov <[email protected]>"
__license__ = "GNU LGPL"
CONV = {
'size': {
'em': 13.0,
'px': 1.0},
'length': {
'mm': 1.0,
'cm': 10.0,
'in': 25.4,
'pt': 25.4 / 72,
'pc': 25.4 / 6},
'time': {
'ms': 1.0,
's': 1000.0},
'freq': {
'hz': 1.0,
'khz': 1000.0},
'any': {
'%': 1.0 / 100,
'deg': 1.0 / 360,
's': 1.0 / 60}}
CONV_TYPE = {}
CONV_FACTOR = {}
for t, m in CONV.items():
for k, f in m.items():
CONV_TYPE[k] = t
CONV_FACTOR[k] = f
OPRT = {
'^': operator.__pow__,
'+': operator.__add__,
'-': operator.__sub__,
'*': operator.__mul__,
'/': compat.div,
'!': operator.__neg__,
'<': operator.__lt__,
'<=': operator.__le__,
'>': operator.__gt__,
'>=': operator.__ge__,
'==': operator.__eq__,
'=': operator.__eq__,
'!=': operator.__ne__,
'&': operator.__and__,
'|': operator.__or__,
'and': lambda x, y: x and y,
'or': lambda x, y: x or y,
}
ELEMENTS_OF_TYPE = {
'block': (
"address, article, aside, blockquote, center, dd, dialog, dir, div, dl, dt, fieldset, "
"figure, footer, form, frameset, h1, h2, h3, h4, h5, h6, header, hgroup, hr, isindex, "
"menu, nav, noframes, noscript, ol, p, pre, section, ul"),
'inline': (
"a, abbr, acronym, b, basefont, bdo, big, br, cite, code, dfn, em, font, i, img, input, "
"kbd, label, q, s, samp, select, small, span, strike, strong, sub, sup, textarea, tt, u, "
"var"),
'table': 'table', 'list-item': 'li', 'table-row-group': 'tbody',
'table-header-group': 'thead', 'table-footer-group': 'tfoot', 'table-row':
'tr', 'table-cell': 'td, th', }
COLORS = {
'aliceblue': '#f0f8ff',
'antiquewhite': '#faebd7',
'aqua': '#00ffff',
'aquamarine': '#7fffd4',
'azure': '#f0ffff',
'beige': '#f5f5dc',
'bisque': '#ffe4c4',
'black': '#000000',
'blanchedalmond': '#ffebcd',
'blue': '#0000ff',
'blueviolet': '#8a2be2',
'brown': '#a52a2a',
'burlywood': '#deb887',
'cadetblue': '#5f9ea0',
'chartreuse': '#7fff00',
'chocolate': '#d2691e',
'coral': '#ff7f50',
'cornflowerblue': '#6495ed',
'cornsilk': '#fff8dc',
'crimson': '#dc143c',
'cyan': '#00ffff',
'darkblue': '#00008b',
'darkcyan': '#008b8b',
'darkgoldenrod': '#b8860b',
'darkgray': '#a9a9a9',
'darkgreen': '#006400',
'darkkhaki': '#bdb76b',
'darkmagenta': '#8b008b',
'darkolivegreen': '#556b2f',
'darkorange': '#ff8c00',
'darkorchid': '#9932cc',
'darkred': '#8b0000',
'darksalmon': '#e9967a',
'darkseagreen': '#8fbc8f',
'darkslateblue': '#483d8b',
'darkslategray': '#2f4f4f',
'darkturquoise': '#00ced1',
'darkviolet': '#9400d3',
'deeppink': '#ff1493',
'deepskyblue': '#00bfff',
'dimgray': '#696969',
'dodgerblue': '#1e90ff',
'firebrick': '#b22222',
'floralwhite': '#fffaf0',
'forestgreen': '#228b22',
'fuchsia': '#ff00ff',
'gainsboro': '#dcdcdc',
'ghostwhite': '#f8f8ff',
'gold': '#ffd700',
'goldenrod': '#daa520',
'gray': '#808080',
'green': '#008000',
'greenyellow': '#adff2f',
'honeydew': '#f0fff0',
'hotpink': '#ff69b4',
'indianred': '#cd5c5c',
'indigo': '#4b0082',
'ivory': '#fffff0',
'khaki': '#f0e68c',
'lavender': '#e6e6fa',
'lavenderblush': '#fff0f5',
'lawngreen': '#7cfc00',
'lemonchiffon': '#fffacd',
'lightblue': '#add8e6',
'lightcoral': '#f08080',
'lightcyan': '#e0ffff',
'lightgoldenrodyellow': '#fafad2',
'lightgreen': '#90ee90',
'lightgrey': '#d3d3d3',
'lightpink': '#ffb6c1',
'lightsalmon': '#ffa07a',
'lightseagreen': '#20b2aa',
'lightskyblue': '#87cefa',
'lightslategray': '#778899',
'lightsteelblue': '#b0c4de',
'lightyellow': '#ffffe0',
'lime': '#00ff00',
'limegreen': '#32cd32',
'linen': '#faf0e6',
'magenta': '#ff00ff',
'maroon': '#800000',
'mediumaquamarine': '#66cdaa',
'mediumblue': '#0000cd',
'mediumorchid': '#ba55d3',
'mediumpurple': '#9370db',
'mediumseagreen': '#3cb371',
'mediumslateblue': '#7b68ee',
'mediumspringgreen': '#00fa9a',
'mediumturquoise': '#48d1cc',
'mediumvioletred': '#c71585',
'midnightblue': '#191970',
'mintcream': '#f5fffa',
'mistyrose': '#ffe4e1',
'moccasin': '#ffe4b5',
'navajowhite': '#ffdead',
'navy': '#000080',
'oldlace': '#fdf5e6',
'olive': '#808000',
'olivedrab': '#6b8e23',
'orange': '#ffa500',
'orangered': '#ff4500',
'orchid': '#da70d6',
'palegoldenrod': '#eee8aa',
'palegreen': '#98fb98',
'paleturquoise': '#afeeee',
'palevioletred': '#db7093',
'papayawhip': '#ffefd5',
'peachpuff': '#ffdab9',
'peru': '#cd853f',
'pink': '#ffc0cb',
'plum': '#dda0dd',
'powderblue': '#b0e0e6',
'purple': '#800080',
'red': '#ff0000',
'rosybrown': '#bc8f8f',
'royalblue': '#4169e1',
'saddlebrown': '#8b4513',
'salmon': '#fa8072',
'sandybrown': '#f4a460',
'seagreen': '#2e8b57',
'seashell': '#fff5ee',
'sienna': '#a0522d',
'silver': '#c0c0c0',
'skyblue': '#87ceeb',
'slateblue': '#6a5acd',
'slategray': '#708090',
'snow': '#fffafa',
'springgreen': '#00ff7f',
'steelblue': '#4682b4',
'tan': '#d2b48c',
'teal': '#008080',
'thistle': '#d8bfd8',
'tomato': '#ff6347',
'turquoise': '#40e0d0',
'violet': '#ee82ee',
'wheat': '#f5deb3',
'white': '#ffffff',
'whitesmoke': '#f5f5f5',
'yellow': '#ffff00',
'yellowgreen': '#9acd32'
}
SORTING = dict((v, k) for k, v in enumerate((
# Positioning
'position',
'top',
'right',
'bottom',
'left',
'z-index',
# Box behavior and properties
'float',
'clear',
'display',
'visibility',
'overflow',
'overflow-x',
'overflow-y',
'overflow-style',
'zoom',
'clip',
'box-sizing',
'box-shadow',
# Sizing
'margin',
'margin-top',
'margin-right',
'margin-bottom',
'margin-left',
'padding',
'padding-top',
'padding-right',
'padding-bottom',
'padding-left',
'width',
'height',
'max-width',
'max-height',
'min-width',
'min-height',
# Color appearance
'outline',
'outline-offset',
'outline-width',
'outline-style',
'outline-color',
'border',
'border-break',
'border-collapse',
'border-color',
'border-image',
'border-top-image',
'border-right-image',
'border-bottom-image',
'border-left-image', | 'border-corner-image',
'border-top-left-image',
'border-top-right-image',
'border-bottom-right-image',
'border-bottom-left-image',
'border-fit',
'border-length',
'border-spacing',
'border-style',
'border-width',
'border-top',
'border-top-width',
'border-top-style',
'border-top-color',
'border-right',
'border-right-width',
'border-right-style',
'border-right-color',
'border-bottom',
'border-bottom-width',
'border-bottom-style',
'border-bottom-color',
'border-left',
'border-left-width',
'border-left-style',
'border-left-color',
'border-radius',
'border-top-right-radius',
'border-top-left-radius',
'border-bottom-right-radius',
'border-bottom-left-radius',
'background',
'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader',
'background-color',
'background-image',
'background-repeat',
'background-attachment',
'background-position',
'background-position-x',
'background-position-y',
'background-break',
'background-clip',
'background-origin',
'background-size',
'color',
# Special content types
'table-layout',
'caption-side',
'empty-cells',
'list-style',
'list-style-position',
'list-style-type',
'list-style-image',
'quotes',
'content',
'counter-increment',
'counter-reset',
# Text
'direction',
'vertical-align',
'text-align',
'text-align-last',
'text-decoration',
'text-emphasis',
'text-height',
'text-indent',
'text-justify',
'text-outline',
'text-replace',
'text-transform',
'text-wrap',
'text-shadow',
'line-height',
'white-space',
'white-space-collapse',
'word-break',
'word-spacing',
'word-wrap',
'letter-spacing',
'font',
'font-weight',
'font-style',
'font-variant',
'font-size',
'font-size-adjust',
'font-family',
'font-effect',
'font-emphasize',
'font-emphasize-position',
'font-emphasize-style',
'font-smooth',
'font-stretch',
'src',
# Visual properties
'opacity',
'filter:progid:DXImageTransform.Microsoft.Alpha',
'-ms-filter:progid:DXImageTransform.Microsoft.Alpha',
'transitions',
'resize',
'cursor',
# Print
'page-break-before',
'page-break-inside',
'page-break-after',
'orphans',
'widows',
# Transfom
'transition',
'transition-delay',
'transition-duration',
'transition-property',
'transition-timing-function',
)))
class ScssException(Exception):
""" Raise SCSS exception. """
pass | random_line_split |
|
__init__.py | #!/usr/bin/env python
""" Python SCSS parser. """
import operator
from . import compat
VERSION_INFO = (0, 8, 73)
__project__ = "scss"
__version__ = "0.8.73"
__author__ = "Kirill Klenov <[email protected]>"
__license__ = "GNU LGPL"
CONV = {
'size': {
'em': 13.0,
'px': 1.0},
'length': {
'mm': 1.0,
'cm': 10.0,
'in': 25.4,
'pt': 25.4 / 72,
'pc': 25.4 / 6},
'time': {
'ms': 1.0,
's': 1000.0},
'freq': {
'hz': 1.0,
'khz': 1000.0},
'any': {
'%': 1.0 / 100,
'deg': 1.0 / 360,
's': 1.0 / 60}}
CONV_TYPE = {}
CONV_FACTOR = {}
for t, m in CONV.items():
for k, f in m.items():
CONV_TYPE[k] = t
CONV_FACTOR[k] = f
OPRT = {
'^': operator.__pow__,
'+': operator.__add__,
'-': operator.__sub__,
'*': operator.__mul__,
'/': compat.div,
'!': operator.__neg__,
'<': operator.__lt__,
'<=': operator.__le__,
'>': operator.__gt__,
'>=': operator.__ge__,
'==': operator.__eq__,
'=': operator.__eq__,
'!=': operator.__ne__,
'&': operator.__and__,
'|': operator.__or__,
'and': lambda x, y: x and y,
'or': lambda x, y: x or y,
}
ELEMENTS_OF_TYPE = {
'block': (
"address, article, aside, blockquote, center, dd, dialog, dir, div, dl, dt, fieldset, "
"figure, footer, form, frameset, h1, h2, h3, h4, h5, h6, header, hgroup, hr, isindex, "
"menu, nav, noframes, noscript, ol, p, pre, section, ul"),
'inline': (
"a, abbr, acronym, b, basefont, bdo, big, br, cite, code, dfn, em, font, i, img, input, "
"kbd, label, q, s, samp, select, small, span, strike, strong, sub, sup, textarea, tt, u, "
"var"),
'table': 'table', 'list-item': 'li', 'table-row-group': 'tbody',
'table-header-group': 'thead', 'table-footer-group': 'tfoot', 'table-row':
'tr', 'table-cell': 'td, th', }
COLORS = {
'aliceblue': '#f0f8ff',
'antiquewhite': '#faebd7',
'aqua': '#00ffff',
'aquamarine': '#7fffd4',
'azure': '#f0ffff',
'beige': '#f5f5dc',
'bisque': '#ffe4c4',
'black': '#000000',
'blanchedalmond': '#ffebcd',
'blue': '#0000ff',
'blueviolet': '#8a2be2',
'brown': '#a52a2a',
'burlywood': '#deb887',
'cadetblue': '#5f9ea0',
'chartreuse': '#7fff00',
'chocolate': '#d2691e',
'coral': '#ff7f50',
'cornflowerblue': '#6495ed',
'cornsilk': '#fff8dc',
'crimson': '#dc143c',
'cyan': '#00ffff',
'darkblue': '#00008b',
'darkcyan': '#008b8b',
'darkgoldenrod': '#b8860b',
'darkgray': '#a9a9a9',
'darkgreen': '#006400',
'darkkhaki': '#bdb76b',
'darkmagenta': '#8b008b',
'darkolivegreen': '#556b2f',
'darkorange': '#ff8c00',
'darkorchid': '#9932cc',
'darkred': '#8b0000',
'darksalmon': '#e9967a',
'darkseagreen': '#8fbc8f',
'darkslateblue': '#483d8b',
'darkslategray': '#2f4f4f',
'darkturquoise': '#00ced1',
'darkviolet': '#9400d3',
'deeppink': '#ff1493',
'deepskyblue': '#00bfff',
'dimgray': '#696969',
'dodgerblue': '#1e90ff',
'firebrick': '#b22222',
'floralwhite': '#fffaf0',
'forestgreen': '#228b22',
'fuchsia': '#ff00ff',
'gainsboro': '#dcdcdc',
'ghostwhite': '#f8f8ff',
'gold': '#ffd700',
'goldenrod': '#daa520',
'gray': '#808080',
'green': '#008000',
'greenyellow': '#adff2f',
'honeydew': '#f0fff0',
'hotpink': '#ff69b4',
'indianred': '#cd5c5c',
'indigo': '#4b0082',
'ivory': '#fffff0',
'khaki': '#f0e68c',
'lavender': '#e6e6fa',
'lavenderblush': '#fff0f5',
'lawngreen': '#7cfc00',
'lemonchiffon': '#fffacd',
'lightblue': '#add8e6',
'lightcoral': '#f08080',
'lightcyan': '#e0ffff',
'lightgoldenrodyellow': '#fafad2',
'lightgreen': '#90ee90',
'lightgrey': '#d3d3d3',
'lightpink': '#ffb6c1',
'lightsalmon': '#ffa07a',
'lightseagreen': '#20b2aa',
'lightskyblue': '#87cefa',
'lightslategray': '#778899',
'lightsteelblue': '#b0c4de',
'lightyellow': '#ffffe0',
'lime': '#00ff00',
'limegreen': '#32cd32',
'linen': '#faf0e6',
'magenta': '#ff00ff',
'maroon': '#800000',
'mediumaquamarine': '#66cdaa',
'mediumblue': '#0000cd',
'mediumorchid': '#ba55d3',
'mediumpurple': '#9370db',
'mediumseagreen': '#3cb371',
'mediumslateblue': '#7b68ee',
'mediumspringgreen': '#00fa9a',
'mediumturquoise': '#48d1cc',
'mediumvioletred': '#c71585',
'midnightblue': '#191970',
'mintcream': '#f5fffa',
'mistyrose': '#ffe4e1',
'moccasin': '#ffe4b5',
'navajowhite': '#ffdead',
'navy': '#000080',
'oldlace': '#fdf5e6',
'olive': '#808000',
'olivedrab': '#6b8e23',
'orange': '#ffa500',
'orangered': '#ff4500',
'orchid': '#da70d6',
'palegoldenrod': '#eee8aa',
'palegreen': '#98fb98',
'paleturquoise': '#afeeee',
'palevioletred': '#db7093',
'papayawhip': '#ffefd5',
'peachpuff': '#ffdab9',
'peru': '#cd853f',
'pink': '#ffc0cb',
'plum': '#dda0dd',
'powderblue': '#b0e0e6',
'purple': '#800080',
'red': '#ff0000',
'rosybrown': '#bc8f8f',
'royalblue': '#4169e1',
'saddlebrown': '#8b4513',
'salmon': '#fa8072',
'sandybrown': '#f4a460',
'seagreen': '#2e8b57',
'seashell': '#fff5ee',
'sienna': '#a0522d',
'silver': '#c0c0c0',
'skyblue': '#87ceeb',
'slateblue': '#6a5acd',
'slategray': '#708090',
'snow': '#fffafa',
'springgreen': '#00ff7f',
'steelblue': '#4682b4',
'tan': '#d2b48c',
'teal': '#008080',
'thistle': '#d8bfd8',
'tomato': '#ff6347',
'turquoise': '#40e0d0',
'violet': '#ee82ee',
'wheat': '#f5deb3',
'white': '#ffffff',
'whitesmoke': '#f5f5f5',
'yellow': '#ffff00',
'yellowgreen': '#9acd32'
}
SORTING = dict((v, k) for k, v in enumerate((
# Positioning
'position',
'top',
'right',
'bottom',
'left',
'z-index',
# Box behavior and properties
'float',
'clear',
'display',
'visibility',
'overflow',
'overflow-x',
'overflow-y',
'overflow-style',
'zoom',
'clip',
'box-sizing',
'box-shadow',
# Sizing
'margin',
'margin-top',
'margin-right',
'margin-bottom',
'margin-left',
'padding',
'padding-top',
'padding-right',
'padding-bottom',
'padding-left',
'width',
'height',
'max-width',
'max-height',
'min-width',
'min-height',
# Color appearance
'outline',
'outline-offset',
'outline-width',
'outline-style',
'outline-color',
'border',
'border-break',
'border-collapse',
'border-color',
'border-image',
'border-top-image',
'border-right-image',
'border-bottom-image',
'border-left-image',
'border-corner-image',
'border-top-left-image',
'border-top-right-image',
'border-bottom-right-image',
'border-bottom-left-image',
'border-fit',
'border-length',
'border-spacing',
'border-style',
'border-width',
'border-top',
'border-top-width',
'border-top-style',
'border-top-color',
'border-right',
'border-right-width',
'border-right-style',
'border-right-color',
'border-bottom',
'border-bottom-width',
'border-bottom-style',
'border-bottom-color',
'border-left',
'border-left-width',
'border-left-style',
'border-left-color',
'border-radius',
'border-top-right-radius',
'border-top-left-radius',
'border-bottom-right-radius',
'border-bottom-left-radius',
'background',
'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader',
'background-color',
'background-image',
'background-repeat',
'background-attachment',
'background-position',
'background-position-x',
'background-position-y',
'background-break',
'background-clip',
'background-origin',
'background-size',
'color',
# Special content types
'table-layout',
'caption-side',
'empty-cells',
'list-style',
'list-style-position',
'list-style-type',
'list-style-image',
'quotes',
'content',
'counter-increment',
'counter-reset',
# Text
'direction',
'vertical-align',
'text-align',
'text-align-last',
'text-decoration',
'text-emphasis',
'text-height',
'text-indent',
'text-justify',
'text-outline',
'text-replace',
'text-transform',
'text-wrap',
'text-shadow',
'line-height',
'white-space',
'white-space-collapse',
'word-break',
'word-spacing',
'word-wrap',
'letter-spacing',
'font',
'font-weight',
'font-style',
'font-variant',
'font-size',
'font-size-adjust',
'font-family',
'font-effect',
'font-emphasize',
'font-emphasize-position',
'font-emphasize-style',
'font-smooth',
'font-stretch',
'src',
# Visual properties
'opacity',
'filter:progid:DXImageTransform.Microsoft.Alpha',
'-ms-filter:progid:DXImageTransform.Microsoft.Alpha',
'transitions',
'resize',
'cursor',
# Print
'page-break-before',
'page-break-inside',
'page-break-after',
'orphans',
'widows',
# Transfom
'transition',
'transition-delay',
'transition-duration',
'transition-property',
'transition-timing-function',
)))
class ScssException(Exception):
| """ Raise SCSS exception. """
pass | identifier_body |
|
__init__.py | #!/usr/bin/env python
""" Python SCSS parser. """
import operator
from . import compat
VERSION_INFO = (0, 8, 73)
__project__ = "scss"
__version__ = "0.8.73"
__author__ = "Kirill Klenov <[email protected]>"
__license__ = "GNU LGPL"
CONV = {
'size': {
'em': 13.0,
'px': 1.0},
'length': {
'mm': 1.0,
'cm': 10.0,
'in': 25.4,
'pt': 25.4 / 72,
'pc': 25.4 / 6},
'time': {
'ms': 1.0,
's': 1000.0},
'freq': {
'hz': 1.0,
'khz': 1000.0},
'any': {
'%': 1.0 / 100,
'deg': 1.0 / 360,
's': 1.0 / 60}}
CONV_TYPE = {}
CONV_FACTOR = {}
for t, m in CONV.items():
for k, f in m.items():
|
OPRT = {
'^': operator.__pow__,
'+': operator.__add__,
'-': operator.__sub__,
'*': operator.__mul__,
'/': compat.div,
'!': operator.__neg__,
'<': operator.__lt__,
'<=': operator.__le__,
'>': operator.__gt__,
'>=': operator.__ge__,
'==': operator.__eq__,
'=': operator.__eq__,
'!=': operator.__ne__,
'&': operator.__and__,
'|': operator.__or__,
'and': lambda x, y: x and y,
'or': lambda x, y: x or y,
}
ELEMENTS_OF_TYPE = {
'block': (
"address, article, aside, blockquote, center, dd, dialog, dir, div, dl, dt, fieldset, "
"figure, footer, form, frameset, h1, h2, h3, h4, h5, h6, header, hgroup, hr, isindex, "
"menu, nav, noframes, noscript, ol, p, pre, section, ul"),
'inline': (
"a, abbr, acronym, b, basefont, bdo, big, br, cite, code, dfn, em, font, i, img, input, "
"kbd, label, q, s, samp, select, small, span, strike, strong, sub, sup, textarea, tt, u, "
"var"),
'table': 'table', 'list-item': 'li', 'table-row-group': 'tbody',
'table-header-group': 'thead', 'table-footer-group': 'tfoot', 'table-row':
'tr', 'table-cell': 'td, th', }
COLORS = {
'aliceblue': '#f0f8ff',
'antiquewhite': '#faebd7',
'aqua': '#00ffff',
'aquamarine': '#7fffd4',
'azure': '#f0ffff',
'beige': '#f5f5dc',
'bisque': '#ffe4c4',
'black': '#000000',
'blanchedalmond': '#ffebcd',
'blue': '#0000ff',
'blueviolet': '#8a2be2',
'brown': '#a52a2a',
'burlywood': '#deb887',
'cadetblue': '#5f9ea0',
'chartreuse': '#7fff00',
'chocolate': '#d2691e',
'coral': '#ff7f50',
'cornflowerblue': '#6495ed',
'cornsilk': '#fff8dc',
'crimson': '#dc143c',
'cyan': '#00ffff',
'darkblue': '#00008b',
'darkcyan': '#008b8b',
'darkgoldenrod': '#b8860b',
'darkgray': '#a9a9a9',
'darkgreen': '#006400',
'darkkhaki': '#bdb76b',
'darkmagenta': '#8b008b',
'darkolivegreen': '#556b2f',
'darkorange': '#ff8c00',
'darkorchid': '#9932cc',
'darkred': '#8b0000',
'darksalmon': '#e9967a',
'darkseagreen': '#8fbc8f',
'darkslateblue': '#483d8b',
'darkslategray': '#2f4f4f',
'darkturquoise': '#00ced1',
'darkviolet': '#9400d3',
'deeppink': '#ff1493',
'deepskyblue': '#00bfff',
'dimgray': '#696969',
'dodgerblue': '#1e90ff',
'firebrick': '#b22222',
'floralwhite': '#fffaf0',
'forestgreen': '#228b22',
'fuchsia': '#ff00ff',
'gainsboro': '#dcdcdc',
'ghostwhite': '#f8f8ff',
'gold': '#ffd700',
'goldenrod': '#daa520',
'gray': '#808080',
'green': '#008000',
'greenyellow': '#adff2f',
'honeydew': '#f0fff0',
'hotpink': '#ff69b4',
'indianred': '#cd5c5c',
'indigo': '#4b0082',
'ivory': '#fffff0',
'khaki': '#f0e68c',
'lavender': '#e6e6fa',
'lavenderblush': '#fff0f5',
'lawngreen': '#7cfc00',
'lemonchiffon': '#fffacd',
'lightblue': '#add8e6',
'lightcoral': '#f08080',
'lightcyan': '#e0ffff',
'lightgoldenrodyellow': '#fafad2',
'lightgreen': '#90ee90',
'lightgrey': '#d3d3d3',
'lightpink': '#ffb6c1',
'lightsalmon': '#ffa07a',
'lightseagreen': '#20b2aa',
'lightskyblue': '#87cefa',
'lightslategray': '#778899',
'lightsteelblue': '#b0c4de',
'lightyellow': '#ffffe0',
'lime': '#00ff00',
'limegreen': '#32cd32',
'linen': '#faf0e6',
'magenta': '#ff00ff',
'maroon': '#800000',
'mediumaquamarine': '#66cdaa',
'mediumblue': '#0000cd',
'mediumorchid': '#ba55d3',
'mediumpurple': '#9370db',
'mediumseagreen': '#3cb371',
'mediumslateblue': '#7b68ee',
'mediumspringgreen': '#00fa9a',
'mediumturquoise': '#48d1cc',
'mediumvioletred': '#c71585',
'midnightblue': '#191970',
'mintcream': '#f5fffa',
'mistyrose': '#ffe4e1',
'moccasin': '#ffe4b5',
'navajowhite': '#ffdead',
'navy': '#000080',
'oldlace': '#fdf5e6',
'olive': '#808000',
'olivedrab': '#6b8e23',
'orange': '#ffa500',
'orangered': '#ff4500',
'orchid': '#da70d6',
'palegoldenrod': '#eee8aa',
'palegreen': '#98fb98',
'paleturquoise': '#afeeee',
'palevioletred': '#db7093',
'papayawhip': '#ffefd5',
'peachpuff': '#ffdab9',
'peru': '#cd853f',
'pink': '#ffc0cb',
'plum': '#dda0dd',
'powderblue': '#b0e0e6',
'purple': '#800080',
'red': '#ff0000',
'rosybrown': '#bc8f8f',
'royalblue': '#4169e1',
'saddlebrown': '#8b4513',
'salmon': '#fa8072',
'sandybrown': '#f4a460',
'seagreen': '#2e8b57',
'seashell': '#fff5ee',
'sienna': '#a0522d',
'silver': '#c0c0c0',
'skyblue': '#87ceeb',
'slateblue': '#6a5acd',
'slategray': '#708090',
'snow': '#fffafa',
'springgreen': '#00ff7f',
'steelblue': '#4682b4',
'tan': '#d2b48c',
'teal': '#008080',
'thistle': '#d8bfd8',
'tomato': '#ff6347',
'turquoise': '#40e0d0',
'violet': '#ee82ee',
'wheat': '#f5deb3',
'white': '#ffffff',
'whitesmoke': '#f5f5f5',
'yellow': '#ffff00',
'yellowgreen': '#9acd32'
}
SORTING = dict((v, k) for k, v in enumerate((
# Positioning
'position',
'top',
'right',
'bottom',
'left',
'z-index',
# Box behavior and properties
'float',
'clear',
'display',
'visibility',
'overflow',
'overflow-x',
'overflow-y',
'overflow-style',
'zoom',
'clip',
'box-sizing',
'box-shadow',
# Sizing
'margin',
'margin-top',
'margin-right',
'margin-bottom',
'margin-left',
'padding',
'padding-top',
'padding-right',
'padding-bottom',
'padding-left',
'width',
'height',
'max-width',
'max-height',
'min-width',
'min-height',
# Color appearance
'outline',
'outline-offset',
'outline-width',
'outline-style',
'outline-color',
'border',
'border-break',
'border-collapse',
'border-color',
'border-image',
'border-top-image',
'border-right-image',
'border-bottom-image',
'border-left-image',
'border-corner-image',
'border-top-left-image',
'border-top-right-image',
'border-bottom-right-image',
'border-bottom-left-image',
'border-fit',
'border-length',
'border-spacing',
'border-style',
'border-width',
'border-top',
'border-top-width',
'border-top-style',
'border-top-color',
'border-right',
'border-right-width',
'border-right-style',
'border-right-color',
'border-bottom',
'border-bottom-width',
'border-bottom-style',
'border-bottom-color',
'border-left',
'border-left-width',
'border-left-style',
'border-left-color',
'border-radius',
'border-top-right-radius',
'border-top-left-radius',
'border-bottom-right-radius',
'border-bottom-left-radius',
'background',
'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader',
'background-color',
'background-image',
'background-repeat',
'background-attachment',
'background-position',
'background-position-x',
'background-position-y',
'background-break',
'background-clip',
'background-origin',
'background-size',
'color',
# Special content types
'table-layout',
'caption-side',
'empty-cells',
'list-style',
'list-style-position',
'list-style-type',
'list-style-image',
'quotes',
'content',
'counter-increment',
'counter-reset',
# Text
'direction',
'vertical-align',
'text-align',
'text-align-last',
'text-decoration',
'text-emphasis',
'text-height',
'text-indent',
'text-justify',
'text-outline',
'text-replace',
'text-transform',
'text-wrap',
'text-shadow',
'line-height',
'white-space',
'white-space-collapse',
'word-break',
'word-spacing',
'word-wrap',
'letter-spacing',
'font',
'font-weight',
'font-style',
'font-variant',
'font-size',
'font-size-adjust',
'font-family',
'font-effect',
'font-emphasize',
'font-emphasize-position',
'font-emphasize-style',
'font-smooth',
'font-stretch',
'src',
# Visual properties
'opacity',
'filter:progid:DXImageTransform.Microsoft.Alpha',
'-ms-filter:progid:DXImageTransform.Microsoft.Alpha',
'transitions',
'resize',
'cursor',
# Print
'page-break-before',
'page-break-inside',
'page-break-after',
'orphans',
'widows',
# Transfom
'transition',
'transition-delay',
'transition-duration',
'transition-property',
'transition-timing-function',
)))
class ScssException(Exception):
""" Raise SCSS exception. """
pass
| CONV_TYPE[k] = t
CONV_FACTOR[k] = f | conditional_block |
hasteMapSize.test.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. | *
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import os from 'os';
import path from 'path';
import HasteMap from 'jest-haste-map';
import {sync as realpath} from 'realpath-native';
import {cleanup, writeFiles} from '../Utils';
const DIR = path.resolve(realpath(os.tmpdir()), 'haste_map_size');
beforeEach(() => {
cleanup(DIR);
writeFiles(DIR, {
'file.js': '"abc"',
});
});
afterEach(() => cleanup(DIR));
const options = {
extensions: ['js'],
forceNodeFilesystemAPI: true,
ignorePattern: / ^/,
maxWorkers: 2,
mocksPattern: '',
name: 'tmp',
platforms: [],
retainAllFiles: true,
rootDir: DIR,
roots: [DIR],
useWatchman: false,
watch: false,
};
test('reports the correct file size', async () => {
const hasteMap = new HasteMap(options);
const hasteFS = (await hasteMap.build()).hasteFS;
expect(hasteFS.getSize(path.join(DIR, 'file.js'))).toBe(5);
});
test('updates the file size when a file changes', async () => {
const hasteMap = new HasteMap({...options, watch: true});
await hasteMap.build();
writeFiles(DIR, {
'file.js': '"asdf"',
});
const {hasteFS} = await new Promise(resolve =>
hasteMap.once('change', resolve),
);
hasteMap.end();
expect(hasteFS.getSize(path.join(DIR, 'file.js'))).toBe(6);
}); | random_line_split |
|
storageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::StorageEventBinding;
use dom::bindings::codegen::Bindings::StorageEventBinding::{StorageEventMethods};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference};
use dom::bindings::reflector::reflect_dom_object;
use dom::event::{Event, EventBubbles, EventCancelable};
use dom::storage::Storage;
use string_cache::Atom; | use util::str::DOMString;
#[dom_struct]
pub struct StorageEvent {
event: Event,
key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
storageArea: MutNullableHeap<JS<Storage>>
}
impl StorageEvent {
pub fn new_inherited(key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
storageArea: Option<&Storage>) -> StorageEvent {
StorageEvent {
event: Event::new_inherited(),
key: key,
oldValue: oldValue,
newValue: newValue,
url: url,
storageArea: MutNullableHeap::new(storageArea)
}
}
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
storageArea: Option<&Storage>) -> Root<StorageEvent> {
let ev = reflect_dom_object(box StorageEvent::new_inherited(key, oldValue, newValue,
url, storageArea),
global,
StorageEventBinding::Wrap);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles == EventBubbles::Bubbles, cancelable == EventCancelable::Cancelable);
}
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &StorageEventBinding::StorageEventInit) -> Fallible<Root<StorageEvent>> {
let key = init.key.clone();
let oldValue = init.oldValue.clone();
let newValue = init.newValue.clone();
let url = init.url.clone();
let storageArea = init.storageArea.r();
let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble };
let cancelable = if init.parent.cancelable {
EventCancelable::Cancelable
} else {
EventCancelable::NotCancelable
};
let event = StorageEvent::new(global, Atom::from(&*type_),
bubbles, cancelable,
key, oldValue, newValue,
url, storageArea);
Ok(event)
}
}
impl StorageEventMethods for StorageEvent {
// https://html.spec.whatwg.org/multipage/#dom-storageevent-key
fn GetKey(&self) -> Option<DOMString> {
self.key.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-oldvalue
fn GetOldValue(&self) -> Option<DOMString> {
self.oldValue.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-newvalue
fn GetNewValue(&self) -> Option<DOMString> {
self.newValue.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-url
fn Url(&self) -> DOMString {
self.url.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-storagearea
fn GetStorageArea(&self) -> Option<Root<Storage>> {
self.storageArea.get()
}
} | random_line_split |
|
storageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::StorageEventBinding;
use dom::bindings::codegen::Bindings::StorageEventBinding::{StorageEventMethods};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference};
use dom::bindings::reflector::reflect_dom_object;
use dom::event::{Event, EventBubbles, EventCancelable};
use dom::storage::Storage;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct StorageEvent {
event: Event,
key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
storageArea: MutNullableHeap<JS<Storage>>
}
impl StorageEvent {
pub fn new_inherited(key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
storageArea: Option<&Storage>) -> StorageEvent {
StorageEvent {
event: Event::new_inherited(),
key: key,
oldValue: oldValue,
newValue: newValue,
url: url,
storageArea: MutNullableHeap::new(storageArea)
}
}
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
storageArea: Option<&Storage>) -> Root<StorageEvent> {
let ev = reflect_dom_object(box StorageEvent::new_inherited(key, oldValue, newValue,
url, storageArea),
global,
StorageEventBinding::Wrap);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles == EventBubbles::Bubbles, cancelable == EventCancelable::Cancelable);
}
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &StorageEventBinding::StorageEventInit) -> Fallible<Root<StorageEvent>> {
let key = init.key.clone();
let oldValue = init.oldValue.clone();
let newValue = init.newValue.clone();
let url = init.url.clone();
let storageArea = init.storageArea.r();
let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble };
let cancelable = if init.parent.cancelable {
EventCancelable::Cancelable
} else {
EventCancelable::NotCancelable
};
let event = StorageEvent::new(global, Atom::from(&*type_),
bubbles, cancelable,
key, oldValue, newValue,
url, storageArea);
Ok(event)
}
}
impl StorageEventMethods for StorageEvent {
// https://html.spec.whatwg.org/multipage/#dom-storageevent-key
fn GetKey(&self) -> Option<DOMString> {
self.key.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-oldvalue
fn GetOldValue(&self) -> Option<DOMString> {
self.oldValue.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-newvalue
fn | (&self) -> Option<DOMString> {
self.newValue.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-url
fn Url(&self) -> DOMString {
self.url.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-storagearea
fn GetStorageArea(&self) -> Option<Root<Storage>> {
self.storageArea.get()
}
}
| GetNewValue | identifier_name |
storageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::StorageEventBinding;
use dom::bindings::codegen::Bindings::StorageEventBinding::{StorageEventMethods};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference};
use dom::bindings::reflector::reflect_dom_object;
use dom::event::{Event, EventBubbles, EventCancelable};
use dom::storage::Storage;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct StorageEvent {
event: Event,
key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
storageArea: MutNullableHeap<JS<Storage>>
}
impl StorageEvent {
pub fn new_inherited(key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
storageArea: Option<&Storage>) -> StorageEvent {
StorageEvent {
event: Event::new_inherited(),
key: key,
oldValue: oldValue,
newValue: newValue,
url: url,
storageArea: MutNullableHeap::new(storageArea)
}
}
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
storageArea: Option<&Storage>) -> Root<StorageEvent> {
let ev = reflect_dom_object(box StorageEvent::new_inherited(key, oldValue, newValue,
url, storageArea),
global,
StorageEventBinding::Wrap);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles == EventBubbles::Bubbles, cancelable == EventCancelable::Cancelable);
}
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &StorageEventBinding::StorageEventInit) -> Fallible<Root<StorageEvent>> {
let key = init.key.clone();
let oldValue = init.oldValue.clone();
let newValue = init.newValue.clone();
let url = init.url.clone();
let storageArea = init.storageArea.r();
let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else | ;
let cancelable = if init.parent.cancelable {
EventCancelable::Cancelable
} else {
EventCancelable::NotCancelable
};
let event = StorageEvent::new(global, Atom::from(&*type_),
bubbles, cancelable,
key, oldValue, newValue,
url, storageArea);
Ok(event)
}
}
impl StorageEventMethods for StorageEvent {
// https://html.spec.whatwg.org/multipage/#dom-storageevent-key
fn GetKey(&self) -> Option<DOMString> {
self.key.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-oldvalue
fn GetOldValue(&self) -> Option<DOMString> {
self.oldValue.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-newvalue
fn GetNewValue(&self) -> Option<DOMString> {
self.newValue.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-url
fn Url(&self) -> DOMString {
self.url.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-storagearea
fn GetStorageArea(&self) -> Option<Root<Storage>> {
self.storageArea.get()
}
}
| { EventBubbles::DoesNotBubble } | conditional_block |
storageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::StorageEventBinding;
use dom::bindings::codegen::Bindings::StorageEventBinding::{StorageEventMethods};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference};
use dom::bindings::reflector::reflect_dom_object;
use dom::event::{Event, EventBubbles, EventCancelable};
use dom::storage::Storage;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct StorageEvent {
event: Event,
key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
storageArea: MutNullableHeap<JS<Storage>>
}
impl StorageEvent {
pub fn new_inherited(key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
storageArea: Option<&Storage>) -> StorageEvent {
StorageEvent {
event: Event::new_inherited(),
key: key,
oldValue: oldValue,
newValue: newValue,
url: url,
storageArea: MutNullableHeap::new(storageArea)
}
}
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
storageArea: Option<&Storage>) -> Root<StorageEvent> {
let ev = reflect_dom_object(box StorageEvent::new_inherited(key, oldValue, newValue,
url, storageArea),
global,
StorageEventBinding::Wrap);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles == EventBubbles::Bubbles, cancelable == EventCancelable::Cancelable);
}
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &StorageEventBinding::StorageEventInit) -> Fallible<Root<StorageEvent>> {
let key = init.key.clone();
let oldValue = init.oldValue.clone();
let newValue = init.newValue.clone();
let url = init.url.clone();
let storageArea = init.storageArea.r();
let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble };
let cancelable = if init.parent.cancelable {
EventCancelable::Cancelable
} else {
EventCancelable::NotCancelable
};
let event = StorageEvent::new(global, Atom::from(&*type_),
bubbles, cancelable,
key, oldValue, newValue,
url, storageArea);
Ok(event)
}
}
impl StorageEventMethods for StorageEvent {
// https://html.spec.whatwg.org/multipage/#dom-storageevent-key
fn GetKey(&self) -> Option<DOMString> {
self.key.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-oldvalue
fn GetOldValue(&self) -> Option<DOMString> {
self.oldValue.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-newvalue
fn GetNewValue(&self) -> Option<DOMString> {
self.newValue.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-storageevent-url
fn Url(&self) -> DOMString |
// https://html.spec.whatwg.org/multipage/#dom-storageevent-storagearea
fn GetStorageArea(&self) -> Option<Root<Storage>> {
self.storageArea.get()
}
}
| {
self.url.clone()
} | identifier_body |
task-perf-spawnalot.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::os;
use std::task;
use std::uint;
fn f(n: uint) {
let mut i = 0u;
while i < n {
task::try(|| g() );
i += 1u;
}
}
fn | () { }
fn main() {
let args = os::args();
let args = if os::getenv(~"RUST_BENCH").is_some() {
~[~"", ~"400"]
} else if args.len() <= 1u {
~[~"", ~"10"]
} else {
args
};
let n = uint::from_str(args[1]).get();
let mut i = 0u;
while i < n { task::spawn(|| f(n) ); i += 1u; }
}
| g | identifier_name |
task-perf-spawnalot.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::os;
use std::task;
use std::uint;
fn f(n: uint) {
let mut i = 0u;
while i < n {
task::try(|| g() );
i += 1u;
}
}
fn g() { }
fn main() {
let args = os::args();
let args = if os::getenv(~"RUST_BENCH").is_some() | else if args.len() <= 1u {
~[~"", ~"10"]
} else {
args
};
let n = uint::from_str(args[1]).get();
let mut i = 0u;
while i < n { task::spawn(|| f(n) ); i += 1u; }
}
| {
~[~"", ~"400"]
} | conditional_block |
task-perf-spawnalot.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::os;
use std::task;
use std::uint;
fn f(n: uint) {
let mut i = 0u;
while i < n {
task::try(|| g() );
i += 1u;
}
}
fn g() { }
fn main() {
let args = os::args();
let args = if os::getenv(~"RUST_BENCH").is_some() {
~[~"", ~"400"]
} else if args.len() <= 1u {
~[~"", ~"10"]
} else {
args
};
let n = uint::from_str(args[1]).get();
let mut i = 0u;
while i < n { task::spawn(|| f(n) ); i += 1u; }
} | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
task-perf-spawnalot.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::os;
use std::task;
use std::uint;
fn f(n: uint) {
let mut i = 0u;
while i < n {
task::try(|| g() );
i += 1u;
}
}
fn g() |
fn main() {
let args = os::args();
let args = if os::getenv(~"RUST_BENCH").is_some() {
~[~"", ~"400"]
} else if args.len() <= 1u {
~[~"", ~"10"]
} else {
args
};
let n = uint::from_str(args[1]).get();
let mut i = 0u;
while i < n { task::spawn(|| f(n) ); i += 1u; }
}
| { } | identifier_body |
default.py | # -*- coding: cp1254 -*-
# please visit http://www.iptvxtra.net
import xbmc,xbmcgui,xbmcplugin,sys
icondir = xbmc.translatePath("special://home/addons/plugin.audio.radio7ulm/icons/")
plugin_handle = int(sys.argv[1])
def add_video_item(url, infolabels, img=''):
listitem = xbmcgui.ListItem(infolabels['title'], iconImage=img, thumbnailImage=img) | add_video_item('http://srv01.radio7.fmstreams.de/stream1/livestream.mp3',{ 'title': 'Radio 7 - Webradio'},img=icondir + 'radio-7_web.png')
add_video_item('http://srv02.radio7.fmstreams.de/radio7_upa',{ 'title': 'Radio 7 - 80er'},img=icondir + 'radio-7_80er.png')
add_video_item('http://srv02.radio7.fmstreams.de/radio7_downa',{ 'title': 'Radio 7 - Herz'},img=icondir + 'radio-7_herz.png')
add_video_item('http://str0.creacast.com/radio7_acta',{ 'title': 'Radio 7 - OnTour'},img=icondir + 'radio-7_ontour.png')
add_video_item('http://srv01.radio7.fmstreams.de/stream5/livestream.mp3',{ 'title': 'Radio 7 - Live'},img=icondir + 'radio-7_live.png')
xbmcplugin.endOfDirectory(plugin_handle)
xbmc.executebuiltin("Container.SetViewMode(500)") | listitem.setInfo('video', infolabels)
listitem.setProperty('IsPlayable', 'true')
xbmcplugin.addDirectoryItem(plugin_handle, url, listitem, isFolder=False)
| random_line_split |
default.py | # -*- coding: cp1254 -*-
# please visit http://www.iptvxtra.net
import xbmc,xbmcgui,xbmcplugin,sys
icondir = xbmc.translatePath("special://home/addons/plugin.audio.radio7ulm/icons/")
plugin_handle = int(sys.argv[1])
def add_video_item(url, infolabels, img=''):
|
add_video_item('http://srv01.radio7.fmstreams.de/stream1/livestream.mp3',{ 'title': 'Radio 7 - Webradio'},img=icondir + 'radio-7_web.png')
add_video_item('http://srv02.radio7.fmstreams.de/radio7_upa',{ 'title': 'Radio 7 - 80er'},img=icondir + 'radio-7_80er.png')
add_video_item('http://srv02.radio7.fmstreams.de/radio7_downa',{ 'title': 'Radio 7 - Herz'},img=icondir + 'radio-7_herz.png')
add_video_item('http://str0.creacast.com/radio7_acta',{ 'title': 'Radio 7 - OnTour'},img=icondir + 'radio-7_ontour.png')
add_video_item('http://srv01.radio7.fmstreams.de/stream5/livestream.mp3',{ 'title': 'Radio 7 - Live'},img=icondir + 'radio-7_live.png')
xbmcplugin.endOfDirectory(plugin_handle)
xbmc.executebuiltin("Container.SetViewMode(500)") | listitem = xbmcgui.ListItem(infolabels['title'], iconImage=img, thumbnailImage=img)
listitem.setInfo('video', infolabels)
listitem.setProperty('IsPlayable', 'true')
xbmcplugin.addDirectoryItem(plugin_handle, url, listitem, isFolder=False) | identifier_body |
default.py | # -*- coding: cp1254 -*-
# please visit http://www.iptvxtra.net
import xbmc,xbmcgui,xbmcplugin,sys
icondir = xbmc.translatePath("special://home/addons/plugin.audio.radio7ulm/icons/")
plugin_handle = int(sys.argv[1])
def | (url, infolabels, img=''):
listitem = xbmcgui.ListItem(infolabels['title'], iconImage=img, thumbnailImage=img)
listitem.setInfo('video', infolabels)
listitem.setProperty('IsPlayable', 'true')
xbmcplugin.addDirectoryItem(plugin_handle, url, listitem, isFolder=False)
add_video_item('http://srv01.radio7.fmstreams.de/stream1/livestream.mp3',{ 'title': 'Radio 7 - Webradio'},img=icondir + 'radio-7_web.png')
add_video_item('http://srv02.radio7.fmstreams.de/radio7_upa',{ 'title': 'Radio 7 - 80er'},img=icondir + 'radio-7_80er.png')
add_video_item('http://srv02.radio7.fmstreams.de/radio7_downa',{ 'title': 'Radio 7 - Herz'},img=icondir + 'radio-7_herz.png')
add_video_item('http://str0.creacast.com/radio7_acta',{ 'title': 'Radio 7 - OnTour'},img=icondir + 'radio-7_ontour.png')
add_video_item('http://srv01.radio7.fmstreams.de/stream5/livestream.mp3',{ 'title': 'Radio 7 - Live'},img=icondir + 'radio-7_live.png')
xbmcplugin.endOfDirectory(plugin_handle)
xbmc.executebuiltin("Container.SetViewMode(500)") | add_video_item | identifier_name |
module.tsx | import { CloudWatchDatasource } from './datasource';
import { CloudWatchAnnotationsQueryCtrl } from './annotations_query_ctrl';
import { CloudWatchJsonData, CloudWatchQuery } from './types';
import { CloudWatchLogsQueryEditor } from './components/LogsQueryEditor';
import { PanelQueryEditor } from './components/PanelQueryEditor';
import LogsCheatSheet from './components/LogsCheatSheet';
export const plugin = new DataSourcePlugin<CloudWatchDatasource, CloudWatchQuery, CloudWatchJsonData>(
CloudWatchDatasource
)
.setExploreStartPage(LogsCheatSheet)
.setConfigEditor(ConfigEditor)
.setQueryEditor(PanelQueryEditor)
.setExploreMetricsQueryField(PanelQueryEditor)
.setExploreLogsQueryField(CloudWatchLogsQueryEditor)
.setAnnotationQueryCtrl(CloudWatchAnnotationsQueryCtrl); | import './query_parameter_ctrl';
import { DataSourcePlugin } from '@grafana/data';
import { ConfigEditor } from './components/ConfigEditor'; | random_line_split |
|
archive.rs | use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::Debug;
use std::fs::File;
use std::io::{Seek, SeekFrom};
use std::mem;
use std::path::Path;
use std::path::PathBuf;
use std::slice;
use std::vec::Vec;
use std::result::Result as StdResult;
use common::ReadExt;
use meta::WadMetadata;
use types::{WadLump, WadInfo, WadName, WadNameCast};
use util::wad_type_from_info;
use error::{Result, Error, ErrorKind, InFile};
use error::ErrorKind::{BadWadHeader, MissingRequiredLump};
pub struct Archive {
file: RefCell<File>,
index_map: HashMap<WadName, usize>,
lumps: Vec<LumpInfo>,
levels: Vec<usize>,
meta: WadMetadata,
path: PathBuf,
}
impl Archive {
pub fn open<W, M>(wad_path: &W, meta_path: &M) -> Result<Archive>
where W: AsRef<Path> + Debug,
M: AsRef<Path> + Debug {
let wad_path = wad_path.as_ref().to_owned();
info!("Loading wad file '{:?}'...", wad_path);
// Open file, read and check header.
let mut file = try!(File::open(&wad_path).in_file(&wad_path));
let header = try!(file.read_binary::<WadInfo>().in_file(&wad_path));
try!(wad_type_from_info(&header).ok_or_else(|| BadWadHeader.in_file(&wad_path)));
// Read lump info.
let mut lumps = Vec::with_capacity(header.num_lumps as usize);
let mut levels = Vec::with_capacity(64);
let mut index_map = HashMap::new();
try!(file.seek(SeekFrom::Start(header.info_table_offset as u64)).in_file(&wad_path));
for i_lump in 0 .. header.num_lumps {
let mut fileinfo = try!(file.read_binary::<WadLump>().in_file(&wad_path));
fileinfo.name.canonicalise();
index_map.insert(fileinfo.name, lumps.len());
lumps.push(LumpInfo { name: fileinfo.name,
offset: fileinfo.file_pos as u64,
size: fileinfo.size as usize });
// Our heuristic for level lumps is that they are preceeded by the "THINGS" lump.
if fileinfo.name == b"THINGS\0\0".to_wad_name() |
}
// Read metadata.
let meta = try!(WadMetadata::from_file(meta_path));
Ok(Archive {
meta: meta,
file: RefCell::new(file),
lumps: lumps,
index_map: index_map,
levels: levels,
path: wad_path,
})
}
pub fn num_levels(&self) -> usize { self.levels.len() }
pub fn level_lump_index(&self, level_index: usize) -> usize {
self.levels[level_index]
}
pub fn level_name(&self, level_index: usize) -> &WadName {
self.lump_name(self.levels[level_index])
}
pub fn num_lumps(&self) -> usize { self.lumps.len() }
pub fn named_lump_index(&self, name: &WadName) -> Option<usize> {
self.index_map.get(name).map(|x| *x)
}
pub fn required_named_lump_index(&self, name: &WadName) -> Result<usize> {
self.named_lump_index(name).ok_or(MissingRequiredLump(*name)).in_archive(self)
}
pub fn lump_name(&self, lump_index: usize) -> &WadName {
&self.lumps[lump_index].name
}
pub fn is_virtual_lump(&self, lump_index: usize) -> bool {
self.lumps[lump_index].size == 0
}
pub fn read_required_named_lump<T: Copy>(&self, name: &WadName) -> Result<Vec<T>> {
self.read_named_lump(name)
.unwrap_or_else(|| Err(MissingRequiredLump(*name).in_archive(self)))
}
pub fn read_named_lump<T: Copy>(&self, name: &WadName) -> Option<Result<Vec<T>>> {
self.named_lump_index(name).map(|index| self.read_lump(index))
}
pub fn read_lump<T: Copy>(&self, index: usize) -> Result<Vec<T>> {
let mut file = self.file.borrow_mut();
let info = self.lumps[index];
assert!(info.size > 0);
assert!(info.size % mem::size_of::<T>() == 0);
let num_elems = info.size / mem::size_of::<T>();
let mut buf = Vec::with_capacity(num_elems);
try!(file.seek(SeekFrom::Start(info.offset)).in_archive(self));
unsafe {
buf.set_len(num_elems);
try!(file.read_at_least(slice::from_raw_parts_mut(
(buf.as_mut_ptr() as *mut u8), info.size)).in_archive(self))
}
Ok(buf)
}
pub fn read_lump_single<T: Copy>(&self, index: usize) -> Result<T> {
let mut file = self.file.borrow_mut();
let info = self.lumps[index];
assert!(info.size == mem::size_of::<T>());
try!(file.seek(SeekFrom::Start(info.offset)).in_archive(self));
Ok(try!(file.read_binary().in_archive(self)))
}
pub fn metadata(&self) -> &WadMetadata { &self.meta }
}
pub trait InArchive {
type Output;
fn in_archive(self, archive: &Archive) -> Self::Output;
}
impl InArchive for Error {
type Output = Error;
fn in_archive(self, archive: &Archive) -> Error {
self.in_file(&archive.path)
}
}
impl InArchive for ErrorKind {
type Output = Error;
fn in_archive(self, archive: &Archive) -> Error {
self.in_file(&archive.path)
}
}
impl<S, E: Into<Error>> InArchive for StdResult<S, E> {
type Output = Result<S>;
fn in_archive(self, archive: &Archive) -> Result<S> {
self.map_err(|e| e.into().in_archive(archive))
}
}
#[derive(Copy, Clone)]
struct LumpInfo {
name: WadName,
offset: u64,
size: usize,
}
| {
assert!(i_lump > 0);
levels.push((i_lump - 1) as usize);
} | conditional_block |
archive.rs | use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::Debug;
use std::fs::File;
use std::io::{Seek, SeekFrom};
use std::mem;
use std::path::Path;
use std::path::PathBuf;
use std::slice;
use std::vec::Vec;
use std::result::Result as StdResult;
use common::ReadExt;
use meta::WadMetadata;
use types::{WadLump, WadInfo, WadName, WadNameCast};
use util::wad_type_from_info;
use error::{Result, Error, ErrorKind, InFile};
use error::ErrorKind::{BadWadHeader, MissingRequiredLump};
pub struct Archive {
file: RefCell<File>,
index_map: HashMap<WadName, usize>,
lumps: Vec<LumpInfo>,
levels: Vec<usize>,
meta: WadMetadata,
path: PathBuf,
}
impl Archive {
pub fn open<W, M>(wad_path: &W, meta_path: &M) -> Result<Archive>
where W: AsRef<Path> + Debug,
M: AsRef<Path> + Debug {
let wad_path = wad_path.as_ref().to_owned();
info!("Loading wad file '{:?}'...", wad_path);
// Open file, read and check header.
let mut file = try!(File::open(&wad_path).in_file(&wad_path));
let header = try!(file.read_binary::<WadInfo>().in_file(&wad_path));
try!(wad_type_from_info(&header).ok_or_else(|| BadWadHeader.in_file(&wad_path)));
// Read lump info.
let mut lumps = Vec::with_capacity(header.num_lumps as usize);
let mut levels = Vec::with_capacity(64);
let mut index_map = HashMap::new();
try!(file.seek(SeekFrom::Start(header.info_table_offset as u64)).in_file(&wad_path));
for i_lump in 0 .. header.num_lumps {
let mut fileinfo = try!(file.read_binary::<WadLump>().in_file(&wad_path));
fileinfo.name.canonicalise();
index_map.insert(fileinfo.name, lumps.len());
lumps.push(LumpInfo { name: fileinfo.name,
offset: fileinfo.file_pos as u64,
size: fileinfo.size as usize });
// Our heuristic for level lumps is that they are preceeded by the "THINGS" lump.
if fileinfo.name == b"THINGS\0\0".to_wad_name() {
assert!(i_lump > 0);
levels.push((i_lump - 1) as usize);
}
}
// Read metadata.
let meta = try!(WadMetadata::from_file(meta_path));
Ok(Archive {
meta: meta,
file: RefCell::new(file),
lumps: lumps,
index_map: index_map,
levels: levels,
path: wad_path,
})
}
pub fn num_levels(&self) -> usize { self.levels.len() }
pub fn level_lump_index(&self, level_index: usize) -> usize {
self.levels[level_index]
}
pub fn level_name(&self, level_index: usize) -> &WadName {
self.lump_name(self.levels[level_index])
}
pub fn num_lumps(&self) -> usize { self.lumps.len() }
pub fn named_lump_index(&self, name: &WadName) -> Option<usize> {
self.index_map.get(name).map(|x| *x)
}
pub fn required_named_lump_index(&self, name: &WadName) -> Result<usize> {
self.named_lump_index(name).ok_or(MissingRequiredLump(*name)).in_archive(self)
}
pub fn lump_name(&self, lump_index: usize) -> &WadName {
&self.lumps[lump_index].name
}
pub fn is_virtual_lump(&self, lump_index: usize) -> bool {
self.lumps[lump_index].size == 0
}
pub fn read_required_named_lump<T: Copy>(&self, name: &WadName) -> Result<Vec<T>> |
pub fn read_named_lump<T: Copy>(&self, name: &WadName) -> Option<Result<Vec<T>>> {
self.named_lump_index(name).map(|index| self.read_lump(index))
}
pub fn read_lump<T: Copy>(&self, index: usize) -> Result<Vec<T>> {
let mut file = self.file.borrow_mut();
let info = self.lumps[index];
assert!(info.size > 0);
assert!(info.size % mem::size_of::<T>() == 0);
let num_elems = info.size / mem::size_of::<T>();
let mut buf = Vec::with_capacity(num_elems);
try!(file.seek(SeekFrom::Start(info.offset)).in_archive(self));
unsafe {
buf.set_len(num_elems);
try!(file.read_at_least(slice::from_raw_parts_mut(
(buf.as_mut_ptr() as *mut u8), info.size)).in_archive(self))
}
Ok(buf)
}
pub fn read_lump_single<T: Copy>(&self, index: usize) -> Result<T> {
let mut file = self.file.borrow_mut();
let info = self.lumps[index];
assert!(info.size == mem::size_of::<T>());
try!(file.seek(SeekFrom::Start(info.offset)).in_archive(self));
Ok(try!(file.read_binary().in_archive(self)))
}
pub fn metadata(&self) -> &WadMetadata { &self.meta }
}
pub trait InArchive {
type Output;
fn in_archive(self, archive: &Archive) -> Self::Output;
}
impl InArchive for Error {
type Output = Error;
fn in_archive(self, archive: &Archive) -> Error {
self.in_file(&archive.path)
}
}
impl InArchive for ErrorKind {
type Output = Error;
fn in_archive(self, archive: &Archive) -> Error {
self.in_file(&archive.path)
}
}
impl<S, E: Into<Error>> InArchive for StdResult<S, E> {
type Output = Result<S>;
fn in_archive(self, archive: &Archive) -> Result<S> {
self.map_err(|e| e.into().in_archive(archive))
}
}
#[derive(Copy, Clone)]
struct LumpInfo {
name: WadName,
offset: u64,
size: usize,
}
| {
self.read_named_lump(name)
.unwrap_or_else(|| Err(MissingRequiredLump(*name).in_archive(self)))
} | identifier_body |
archive.rs | use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::Debug;
use std::fs::File;
use std::io::{Seek, SeekFrom};
use std::mem;
use std::path::Path;
use std::path::PathBuf;
use std::slice;
use std::vec::Vec;
use std::result::Result as StdResult;
use common::ReadExt;
use meta::WadMetadata;
use types::{WadLump, WadInfo, WadName, WadNameCast};
use util::wad_type_from_info;
use error::{Result, Error, ErrorKind, InFile};
use error::ErrorKind::{BadWadHeader, MissingRequiredLump};
pub struct Archive {
file: RefCell<File>,
index_map: HashMap<WadName, usize>,
lumps: Vec<LumpInfo>,
levels: Vec<usize>,
meta: WadMetadata,
path: PathBuf,
}
impl Archive {
pub fn open<W, M>(wad_path: &W, meta_path: &M) -> Result<Archive>
where W: AsRef<Path> + Debug,
M: AsRef<Path> + Debug {
let wad_path = wad_path.as_ref().to_owned();
info!("Loading wad file '{:?}'...", wad_path);
// Open file, read and check header.
let mut file = try!(File::open(&wad_path).in_file(&wad_path));
let header = try!(file.read_binary::<WadInfo>().in_file(&wad_path));
try!(wad_type_from_info(&header).ok_or_else(|| BadWadHeader.in_file(&wad_path)));
// Read lump info.
let mut lumps = Vec::with_capacity(header.num_lumps as usize);
let mut levels = Vec::with_capacity(64);
let mut index_map = HashMap::new();
try!(file.seek(SeekFrom::Start(header.info_table_offset as u64)).in_file(&wad_path));
for i_lump in 0 .. header.num_lumps {
let mut fileinfo = try!(file.read_binary::<WadLump>().in_file(&wad_path));
fileinfo.name.canonicalise();
index_map.insert(fileinfo.name, lumps.len());
lumps.push(LumpInfo { name: fileinfo.name,
offset: fileinfo.file_pos as u64,
size: fileinfo.size as usize });
// Our heuristic for level lumps is that they are preceeded by the "THINGS" lump.
if fileinfo.name == b"THINGS\0\0".to_wad_name() {
assert!(i_lump > 0);
levels.push((i_lump - 1) as usize);
}
}
// Read metadata.
let meta = try!(WadMetadata::from_file(meta_path));
Ok(Archive { | levels: levels,
path: wad_path,
})
}
pub fn num_levels(&self) -> usize { self.levels.len() }
pub fn level_lump_index(&self, level_index: usize) -> usize {
self.levels[level_index]
}
pub fn level_name(&self, level_index: usize) -> &WadName {
self.lump_name(self.levels[level_index])
}
pub fn num_lumps(&self) -> usize { self.lumps.len() }
pub fn named_lump_index(&self, name: &WadName) -> Option<usize> {
self.index_map.get(name).map(|x| *x)
}
pub fn required_named_lump_index(&self, name: &WadName) -> Result<usize> {
self.named_lump_index(name).ok_or(MissingRequiredLump(*name)).in_archive(self)
}
pub fn lump_name(&self, lump_index: usize) -> &WadName {
&self.lumps[lump_index].name
}
pub fn is_virtual_lump(&self, lump_index: usize) -> bool {
self.lumps[lump_index].size == 0
}
pub fn read_required_named_lump<T: Copy>(&self, name: &WadName) -> Result<Vec<T>> {
self.read_named_lump(name)
.unwrap_or_else(|| Err(MissingRequiredLump(*name).in_archive(self)))
}
pub fn read_named_lump<T: Copy>(&self, name: &WadName) -> Option<Result<Vec<T>>> {
self.named_lump_index(name).map(|index| self.read_lump(index))
}
pub fn read_lump<T: Copy>(&self, index: usize) -> Result<Vec<T>> {
let mut file = self.file.borrow_mut();
let info = self.lumps[index];
assert!(info.size > 0);
assert!(info.size % mem::size_of::<T>() == 0);
let num_elems = info.size / mem::size_of::<T>();
let mut buf = Vec::with_capacity(num_elems);
try!(file.seek(SeekFrom::Start(info.offset)).in_archive(self));
unsafe {
buf.set_len(num_elems);
try!(file.read_at_least(slice::from_raw_parts_mut(
(buf.as_mut_ptr() as *mut u8), info.size)).in_archive(self))
}
Ok(buf)
}
pub fn read_lump_single<T: Copy>(&self, index: usize) -> Result<T> {
let mut file = self.file.borrow_mut();
let info = self.lumps[index];
assert!(info.size == mem::size_of::<T>());
try!(file.seek(SeekFrom::Start(info.offset)).in_archive(self));
Ok(try!(file.read_binary().in_archive(self)))
}
pub fn metadata(&self) -> &WadMetadata { &self.meta }
}
pub trait InArchive {
type Output;
fn in_archive(self, archive: &Archive) -> Self::Output;
}
impl InArchive for Error {
type Output = Error;
fn in_archive(self, archive: &Archive) -> Error {
self.in_file(&archive.path)
}
}
impl InArchive for ErrorKind {
type Output = Error;
fn in_archive(self, archive: &Archive) -> Error {
self.in_file(&archive.path)
}
}
impl<S, E: Into<Error>> InArchive for StdResult<S, E> {
type Output = Result<S>;
fn in_archive(self, archive: &Archive) -> Result<S> {
self.map_err(|e| e.into().in_archive(archive))
}
}
#[derive(Copy, Clone)]
struct LumpInfo {
name: WadName,
offset: u64,
size: usize,
} | meta: meta,
file: RefCell::new(file),
lumps: lumps,
index_map: index_map, | random_line_split |
archive.rs | use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::Debug;
use std::fs::File;
use std::io::{Seek, SeekFrom};
use std::mem;
use std::path::Path;
use std::path::PathBuf;
use std::slice;
use std::vec::Vec;
use std::result::Result as StdResult;
use common::ReadExt;
use meta::WadMetadata;
use types::{WadLump, WadInfo, WadName, WadNameCast};
use util::wad_type_from_info;
use error::{Result, Error, ErrorKind, InFile};
use error::ErrorKind::{BadWadHeader, MissingRequiredLump};
pub struct Archive {
file: RefCell<File>,
index_map: HashMap<WadName, usize>,
lumps: Vec<LumpInfo>,
levels: Vec<usize>,
meta: WadMetadata,
path: PathBuf,
}
impl Archive {
pub fn open<W, M>(wad_path: &W, meta_path: &M) -> Result<Archive>
where W: AsRef<Path> + Debug,
M: AsRef<Path> + Debug {
let wad_path = wad_path.as_ref().to_owned();
info!("Loading wad file '{:?}'...", wad_path);
// Open file, read and check header.
let mut file = try!(File::open(&wad_path).in_file(&wad_path));
let header = try!(file.read_binary::<WadInfo>().in_file(&wad_path));
try!(wad_type_from_info(&header).ok_or_else(|| BadWadHeader.in_file(&wad_path)));
// Read lump info.
let mut lumps = Vec::with_capacity(header.num_lumps as usize);
let mut levels = Vec::with_capacity(64);
let mut index_map = HashMap::new();
try!(file.seek(SeekFrom::Start(header.info_table_offset as u64)).in_file(&wad_path));
for i_lump in 0 .. header.num_lumps {
let mut fileinfo = try!(file.read_binary::<WadLump>().in_file(&wad_path));
fileinfo.name.canonicalise();
index_map.insert(fileinfo.name, lumps.len());
lumps.push(LumpInfo { name: fileinfo.name,
offset: fileinfo.file_pos as u64,
size: fileinfo.size as usize });
// Our heuristic for level lumps is that they are preceeded by the "THINGS" lump.
if fileinfo.name == b"THINGS\0\0".to_wad_name() {
assert!(i_lump > 0);
levels.push((i_lump - 1) as usize);
}
}
// Read metadata.
let meta = try!(WadMetadata::from_file(meta_path));
Ok(Archive {
meta: meta,
file: RefCell::new(file),
lumps: lumps,
index_map: index_map,
levels: levels,
path: wad_path,
})
}
pub fn num_levels(&self) -> usize { self.levels.len() }
pub fn | (&self, level_index: usize) -> usize {
self.levels[level_index]
}
pub fn level_name(&self, level_index: usize) -> &WadName {
self.lump_name(self.levels[level_index])
}
pub fn num_lumps(&self) -> usize { self.lumps.len() }
pub fn named_lump_index(&self, name: &WadName) -> Option<usize> {
self.index_map.get(name).map(|x| *x)
}
pub fn required_named_lump_index(&self, name: &WadName) -> Result<usize> {
self.named_lump_index(name).ok_or(MissingRequiredLump(*name)).in_archive(self)
}
pub fn lump_name(&self, lump_index: usize) -> &WadName {
&self.lumps[lump_index].name
}
pub fn is_virtual_lump(&self, lump_index: usize) -> bool {
self.lumps[lump_index].size == 0
}
pub fn read_required_named_lump<T: Copy>(&self, name: &WadName) -> Result<Vec<T>> {
self.read_named_lump(name)
.unwrap_or_else(|| Err(MissingRequiredLump(*name).in_archive(self)))
}
pub fn read_named_lump<T: Copy>(&self, name: &WadName) -> Option<Result<Vec<T>>> {
self.named_lump_index(name).map(|index| self.read_lump(index))
}
pub fn read_lump<T: Copy>(&self, index: usize) -> Result<Vec<T>> {
let mut file = self.file.borrow_mut();
let info = self.lumps[index];
assert!(info.size > 0);
assert!(info.size % mem::size_of::<T>() == 0);
let num_elems = info.size / mem::size_of::<T>();
let mut buf = Vec::with_capacity(num_elems);
try!(file.seek(SeekFrom::Start(info.offset)).in_archive(self));
unsafe {
buf.set_len(num_elems);
try!(file.read_at_least(slice::from_raw_parts_mut(
(buf.as_mut_ptr() as *mut u8), info.size)).in_archive(self))
}
Ok(buf)
}
pub fn read_lump_single<T: Copy>(&self, index: usize) -> Result<T> {
let mut file = self.file.borrow_mut();
let info = self.lumps[index];
assert!(info.size == mem::size_of::<T>());
try!(file.seek(SeekFrom::Start(info.offset)).in_archive(self));
Ok(try!(file.read_binary().in_archive(self)))
}
pub fn metadata(&self) -> &WadMetadata { &self.meta }
}
pub trait InArchive {
type Output;
fn in_archive(self, archive: &Archive) -> Self::Output;
}
impl InArchive for Error {
type Output = Error;
fn in_archive(self, archive: &Archive) -> Error {
self.in_file(&archive.path)
}
}
impl InArchive for ErrorKind {
type Output = Error;
fn in_archive(self, archive: &Archive) -> Error {
self.in_file(&archive.path)
}
}
impl<S, E: Into<Error>> InArchive for StdResult<S, E> {
type Output = Result<S>;
fn in_archive(self, archive: &Archive) -> Result<S> {
self.map_err(|e| e.into().in_archive(archive))
}
}
#[derive(Copy, Clone)]
struct LumpInfo {
name: WadName,
offset: u64,
size: usize,
}
| level_lump_index | identifier_name |
adamax_optimizer.d.ts | /**
* @license
* Copyright 2018 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.
* =============================================================================
*/
import { ConfigDict, Serializable, SerializableConstructor } from '../serialization';
import { NamedTensor, NamedVariableMap } from '../tensor_types';
import { Optimizer } from './optimizer';
export declare class | extends Optimizer {
protected learningRate: number;
protected beta1: number;
protected beta2: number;
protected epsilon: number;
protected decay: number;
/** @nocollapse */
static className: string;
private accBeta1;
private iteration;
private accumulatedFirstMoment;
private accumulatedWeightedInfNorm;
constructor(learningRate: number, beta1: number, beta2: number, epsilon?: number, decay?: number);
applyGradients(variableGradients: NamedVariableMap | NamedTensor[]): void;
dispose(): void;
getWeights(): Promise<NamedTensor[]>;
setWeights(weightValues: NamedTensor[]): Promise<void>;
getConfig(): ConfigDict;
/** @nocollapse */
static fromConfig<T extends Serializable>(cls: SerializableConstructor<T>, config: ConfigDict): T;
}
| AdamaxOptimizer | identifier_name |
adamax_optimizer.d.ts | * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
import { ConfigDict, Serializable, SerializableConstructor } from '../serialization';
import { NamedTensor, NamedVariableMap } from '../tensor_types';
import { Optimizer } from './optimizer';
export declare class AdamaxOptimizer extends Optimizer {
protected learningRate: number;
protected beta1: number;
protected beta2: number;
protected epsilon: number;
protected decay: number;
/** @nocollapse */
static className: string;
private accBeta1;
private iteration;
private accumulatedFirstMoment;
private accumulatedWeightedInfNorm;
constructor(learningRate: number, beta1: number, beta2: number, epsilon?: number, decay?: number);
applyGradients(variableGradients: NamedVariableMap | NamedTensor[]): void;
dispose(): void;
getWeights(): Promise<NamedTensor[]>;
setWeights(weightValues: NamedTensor[]): Promise<void>;
getConfig(): ConfigDict;
/** @nocollapse */
static fromConfig<T extends Serializable>(cls: SerializableConstructor<T>, config: ConfigDict): T;
} | /**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); | random_line_split |
|
forum.js | /*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum.js 33082 2013-04-18 11:13:53Z zhengqingpeng $
*/
function saveData(ignoreempty) {
var ignoreempty = isUndefined(ignoreempty) ? 0 : ignoreempty;
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : ($('fastpostform') ? $('fastpostform') : $('postform'));
if(!obj) return;
if(typeof isfirstpost != 'undefined') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
var messageisnull = trim(html2bbcode(editdoc.body.innerHTML)) === '';
} else {
var messageisnull = $('postform').message.value === '';
}
if(isfirstpost && (messageisnull && $('postform').subject.value === '')) {
return;
}
if(!isfirstpost && messageisnull) {
return;
}
}
var data = subject = message = '';
for(var i = 0; i < obj.elements.length; i++) {
var el = obj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden' || el.type == 'select')) && el.name.substr(0, 6) != 'attach') {
var elvalue = el.value;
if(el.name == 'subject') {
subject = trim(elvalue);
} else if(el.name == 'message') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
elvalue = html2bbcode(editdoc.body.innerHTML);
}
message = trim(elvalue);
}
if((el.type == 'checkbox' || el.type == 'radio') && !el.checked) {
continue;
} else if(el.tagName == 'SELECT') {
elvalue = el.value;
} else if(el.type == 'hidden') {
if(el.id) {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
elvalue = elvalue;
if($(el.id + '_url')) {
elvalue += String.fromCharCode(1) + $(el.id + '_url').value;
}
} else {
continue;
}
} else {
continue;
}
}
if(trim(elvalue)) {
data += el.name + String.fromCharCode(9) + el.tagName + String.fromCharCode(9) + el.type + String.fromCharCode(9) + elvalue + String.fromCharCode(9, 9);
}
}
}
if(!subject && !message && !ignoreempty) {
return;
}
saveUserdata('forum_'+discuz_uid, data);
}
function fastUload() {
appendscript(JSPATH + 'forum_post.js?' + VERHASH);
safescript('forum_post_js', function () { uploadWindow(function (aid, url) {updatefastpostattach(aid, url)}, 'file') }, 100, 50);
}
function switchAdvanceMode(url) |
function sidebar_collapse(lang) {
if(lang[0]) {
toggle_collapse('sidebar', null, null, lang);
$('wrap').className = $('wrap').className == 'wrap with_side s_clear' ? 'wrap s_clear' : 'wrap with_side s_clear';
} else {
var collapsed = getcookie('collapse');
collapsed = updatestring(collapsed, 'sidebar', 1);
setcookie('collapse', collapsed, (collapsed ? 2592000 : -2592000));
location.reload();
}
}
function keyPageScroll(e, prev, next, url, page) {
if(loadUserdata('is_blindman')) {
return true;
}
e = e ? e : window.event;
var tagname = BROWSER.ie ? e.srcElement.tagName : e.target.tagName;
if(tagname == 'INPUT' || tagname == 'TEXTAREA') return;
actualCode = e.keyCode ? e.keyCode : e.charCode;
if(next && actualCode == 39) {
window.location = url + '&page=' + (page + 1);
}
if(prev && actualCode == 37) {
window.location = url + '&page=' + (page - 1);
}
}
function announcement() {
var ann = new Object();
ann.anndelay = 3000;ann.annst = 0;ann.annstop = 0;ann.annrowcount = 0;ann.anncount = 0;ann.annlis = $('anc').getElementsByTagName("li");ann.annrows = new Array();
ann.announcementScroll = function () {
if(this.annstop) {this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);return;}
if(!this.annst) {
var lasttop = -1;
for(i = 0;i < this.annlis.length;i++) {
if(lasttop != this.annlis[i].offsetTop) {
if(lasttop == -1) lasttop = 0;
this.annrows[this.annrowcount] = this.annlis[i].offsetTop - lasttop;this.annrowcount++;
}
lasttop = this.annlis[i].offsetTop;
}
if(this.annrows.length == 1) {
$('an').onmouseover = $('an').onmouseout = null;
} else {
this.annrows[this.annrowcount] = this.annrows[1];
$('ancl').innerHTML += $('ancl').innerHTML;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
$('an').onmouseover = function () {ann.annstop = 1;};
$('an').onmouseout = function () {ann.annstop = 0;};
}
this.annrowcount = 1;
return;
}
if(this.annrowcount >= this.annrows.length) {
$('anc').scrollTop = 0;
this.annrowcount = 1;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
} else {
this.anncount = 0;
this.announcementScrollnext(this.annrows[this.annrowcount]);
}
};
ann.announcementScrollnext = function (time) {
$('anc').scrollTop++;
this.anncount++;
if(this.anncount != time) {
this.annst = setTimeout(function () {ann.announcementScrollnext(time);}, 10);
} else {
this.annrowcount++;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
}
};
ann.announcementScroll();
}
function removeindexheats() {
return confirm('You to confirm that this topic should remove it from the hot topic?');
}
function showTypes(id, mod) {
var o = $(id);
if(!o) return false;
var s = o.className;
mod = isUndefined(mod) ? 1 : mod;
var baseh = o.getElementsByTagName('li')[0].offsetHeight * 2;
var tmph = o.offsetHeight;
var lang = ['Expansion', 'Collapse'];
var cls = ['unfold', 'fold'];
if(tmph > baseh) {
var octrl = document.createElement('li');
octrl.className = cls[mod];
octrl.innerHTML = lang[mod];
o.insertBefore(octrl, o.firstChild);
o.className = s + ' cttp';
mod && (o.style.height = 'auto');
octrl.onclick = function () {
if(this.className == cls[0]) {
o.style.height = 'auto';
this.className = cls[1];
this.innerHTML = lang[1];
} else {
o.style.height = '';
this.className = cls[0];
this.innerHTML = lang[0];
}
}
}
}
var postpt = 0;
function fastpostvalidate(theform, noajaxpost) {
if(postpt) {
return false;
}
postpt = 1;
setTimeout(function() {postpt = 0}, 2000);
noajaxpost = !noajaxpost ? 0 : noajaxpost;
s = '';
if(typeof fastpostvalidateextra == 'function') {
var v = fastpostvalidateextra();
if(!v) {
return false;
}
}
if(theform.message.value == '' || theform.subject.value == '') {
s = 'Sorry, you can not enter a title or content';
theform.message.focus();
} else if(mb_strlen(theform.subject.value) > 80) {
s = 'Your title is longer than 80 characters limit';
theform.subject.focus();
}
if(!disablepostctrl && ((postminchars != 0 && mb_strlen(theform.message.value) < postminchars) || (postmaxchars != 0 && mb_strlen(theform.message.value) > postmaxchars))) {
s = 'Not meet the requirements of the length of your posts.\n\nCurrent length: ' + mb_strlen(theform.message.value) + ' ' + 'Byte\nSystem limits: ' + postminchars + ' to ' + postmaxchars + ' Byte';
}
if(s) {
showError(s);
doane();
$('fastpostsubmit').disabled = false;
return false;
}
$('fastpostsubmit').disabled = true;
theform.message.value = theform.message.value.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, '$1[img]$2[/img]');
theform.message.value = parseurl(theform.message.value);
if(!noajaxpost) {
ajaxpost('fastpostform', 'fastpostreturn', 'fastpostreturn', 'onerror', $('fastpostsubmit'));
return false;
} else {
return true;
}
}
function updatefastpostattach(aid, url) {
ajaxget('forum.php?mod=ajax&action=attachlist&posttime=' + $('posttime').value + (!fid ? '' : '&fid=' + fid), 'attachlist');
$('attach_tblheader').style.display = '';
}
function succeedhandle_fastnewpost(locationhref, message, param) {
location.href = locationhref;
}
function errorhandle_fastnewpost() {
$('fastpostsubmit').disabled = false;
}
function atarget(obj) {
obj.target = getcookie('atarget') > 0 ? '_blank' : '';
}
function setatarget(v) {
$('atarget').className = 'y atarget_' + v;
$('atarget').onclick = function() {setatarget(v == 1 ? -1 : 1);};
setcookie('atarget', v, 2592000);
}
function loadData(quiet, formobj) {
var evalevent = function (obj) {
var script = obj.parentNode.innerHTML;
var re = /onclick="(.+?)["|>]/ig;
var matches = re.exec(script);
if(matches != null) {
matches[1] = matches[1].replace(/this\./ig, 'obj.');
eval(matches[1]);
}
};
var data = '';
data = loadUserdata('forum_'+discuz_uid);
var formobj = !formobj ? $('postform') : formobj;
if(in_array((data = trim(data)), ['', 'null', 'false', null, false])) {
if(!quiet) {
showDialog('No data can be restored!', 'info');
}
return;
}
if(!quiet && !confirm('This action will overwrite the current content of the post, You sure you want to recover data?')) {
return;
}
var data = data.split(/\x09\x09/);
for(var i = 0; i < formobj.elements.length; i++) {
var el = formobj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden'))) {
for(var j = 0; j < data.length; j++) {
var ele = data[j].split(/\x09/);
if(ele[0] == el.name) {
elvalue = !isUndefined(ele[3]) ? ele[3] : '';
if(ele[1] == 'INPUT') {
if(ele[2] == 'text') {
el.value = elvalue;
} else if((ele[2] == 'checkbox' || ele[2] == 'radio') && ele[3] == el.value) {
el.checked = true;
evalevent(el);
} else if(ele[2] == 'hidden') {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
var v = elvalue.split(/\x01/);
el.value = v[0];
if(el.value) {
if($(el.id + '_url') && v[1]) {
$(el.id + '_url').value = v[1];
}
eval(el.id + '_upload(\'' + v[0] + '\', \'' + v[1] + '\')');
if($('unused' + v[0])) {
var attachtype = $('unused' + v[0]).parentNode.parentNode.parentNode.parentNode.id.substr(11);
$('unused' + v[0]).parentNode.parentNode.outerHTML = '';
$('unusednum_' + attachtype).innerHTML = parseInt($('unusednum_' + attachtype).innerHTML) - 1;
if($('unusednum_' + attachtype).innerHTML == 0 && $('attachnotice_' + attachtype)) {
$('attachnotice_' + attachtype).style.display = 'none';
}
}
}
}
}
} else if(ele[1] == 'TEXTAREA') {
if(ele[0] == 'message') {
if(!wysiwyg) {
textobj.value = elvalue;
} else {
editdoc.body.innerHTML = bbcode2html(elvalue);
}
} else {
el.value = elvalue;
}
} else if(ele[1] == 'SELECT') {
if($(el.id + '_ctrl_menu')) {
var lis = $(el.id + '_ctrl_menu').getElementsByTagName('li');
for(var k = 0; k < lis.length; k++) {
if(ele[3] == lis[k].k_value) {
lis[k].onclick();
break;
}
}
} else {
for(var k = 0; k < el.options.length; k++) {
if(ele[3] == el.options[k].value) {
el.options[k].selected = true;
break;
}
}
}
}
break;
}
}
}
}
if($('rstnotice')) {
$('rstnotice').style.display = 'none';
}
extraCheckall();
}
var checkForumcount = 0, checkForumtimeout = 30000, checkForumnew_handle;
function checkForumnew(fid, lasttime) {
var timeout = checkForumtimeout;
var x = new Ajax();
x.get('forum.php?mod=ajax&action=forumchecknew&fid=' + fid + '&time=' + lasttime + '&inajax=yes', function(s){
if(s > 0) {
var table = $('separatorline').parentNode;
if(!isUndefined(checkForumnew_handle)) {
clearTimeout(checkForumnew_handle);
}
removetbodyrow(table, 'forumnewshow');
var colspan = table.getElementsByTagName('tbody')[0].rows[0].children.length;
var checknew = {'tid':'', 'thread':{'common':{'className':'', 'val':'<a href="javascript:void(0);" onclick="ajaxget(\'forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=1&inajax=yes\', \'forumnew\');">New topic Reply, Click to view', 'colspan': colspan }}};
addtbodyrow(table, ['tbody'], ['forumnewshow'], 'separatorline', checknew);
} else {
if(checkForumcount < 50) {
if(checkForumcount > 0) {
var multiple = Math.ceil(50 / checkForumcount);
if(multiple < 5) {
timeout = checkForumtimeout * (5 - multiple + 1);
}
}
checkForumnew_handle = setTimeout(function () {checkForumnew(fid, lasttime);}, timeout);
}
}
checkForumcount++;
});
}
function checkForumnew_btn(fid) {
if(isUndefined(fid)) return;
ajaxget('forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=2&inajax=yes', 'forumnew', 'ajaxwaitid');
lasttime = parseInt(Date.parse(new Date()) / 1000);
}
function addtbodyrow (table, insertID, changename, separatorid, jsonval) {
if(isUndefined(table) || isUndefined(insertID[0])) {
return;
}
var insertobj = document.createElement(insertID[0]);
var thread = jsonval.thread;
var tid = !isUndefined(jsonval.tid) ? jsonval.tid : '' ;
if(!isUndefined(changename[1])) {
removetbodyrow(table, changename[1] + tid);
}
insertobj.id = changename[0] + tid;
if(!isUndefined(insertID[1])) {
insertobj.className = insertID[1];
}
if($(separatorid)) {
table.insertBefore(insertobj, $(separatorid).nextSibling);
} else {
table.insertBefore(insertobj, table.firstChild);
}
var newTH = insertobj.insertRow(-1);
for(var value in thread) {
if(value != 0) {
var cell = newTH.insertCell(-1);
if(isUndefined(thread[value]['val'])) {
cell.innerHTML = thread[value];
} else {
cell.innerHTML = thread[value]['val'];
}
if(!isUndefined(thread[value]['className'])) {
cell.className = thread[value]['className'];
}
if(!isUndefined(thread[value]['colspan'])) {
cell.colSpan = thread[value]['colspan'];
}
}
}
if(!isUndefined(insertID[2])) {
_attachEvent(insertobj, insertID[2], function() {insertobj.className = '';});
}
}
function removetbodyrow(from, objid) {
if(!isUndefined(from) && $(objid)) {
from.removeChild($(objid));
}
}
function leftside(id) {
$(id).className = $(id).className == 'a' ? '' : 'a';
if(id == 'lf_fav') {
setcookie('leftsidefav', $(id).className == 'a' ? 0 : 1, 2592000);
}
}
var DTimers = new Array();
var DItemIDs = new Array();
var DTimers_exists = false;
function settimer(timer, itemid) {
if(timer && itemid) {
DTimers.push(timer);
DItemIDs.push(itemid);
}
if(!DTimers_exists) {
setTimeout("showtime()", 1000);
DTimers_exists = true;
}
}
function showtime() {
for(i=0; i<=DTimers.length; i++) {
if(DItemIDs[i]) {
if(DTimers[i] == 0) {
$(DItemIDs[i]).innerHTML = 'Has ended';
DItemIDs[i] = '';
continue;
}
var timestr = '';
var timer_day = Math.floor(DTimers[i] / 86400);
var timer_hour = Math.floor((DTimers[i] % 86400) / 3600);
var timer_minute = Math.floor(((DTimers[i] % 86400) % 3600) / 60);
var timer_second = (((DTimers[i] % 86400) % 3600) % 60);
if(timer_day > 0) {
timestr += timer_day + 'Day';
}
if(timer_hour > 0) {
timestr += timer_hour + 'Hour'
}
if(timer_minute > 0) {
timestr += timer_minute + 'Min.'
}
if(timer_second > 0) {
timestr += timer_second + 'Sec.'
}
DTimers[i] = DTimers[i] - 1;
$(DItemIDs[i]).innerHTML = timestr;
}
}
setTimeout("showtime()", 1000);
}
function fixed_top_nv(eleid, disbind) {
this.nv = eleid && $(eleid) || $('nv');
this.openflag = this.nv && BROWSER.ie != 6;
this.nvdata = {};
this.init = function (disattachevent) {
if(this.openflag) {
if(!disattachevent) {
var obj = this;
_attachEvent(window, 'resize', function(){obj.reset();obj.init(1);obj.run();});
var switchwidth = $('switchwidth');
if(switchwidth) {
_attachEvent(switchwidth, 'click', function(){obj.reset();obj.openflag=false;});
}
}
var next = this.nv;
try {
while((next = next.nextSibling).nodeType != 1 || next.style.display === 'none') {}
this.nvdata.next = next;
this.nvdata.height = parseInt(this.nv.offsetHeight, 10);
this.nvdata.width = parseInt(this.nv.offsetWidth, 10);
this.nvdata.left = this.nv.getBoundingClientRect().left - document.documentElement.clientLeft;
this.nvdata.position = this.nv.style.position;
this.nvdata.opacity = this.nv.style.opacity;
} catch (e) {
this.nvdata.next = null;
}
}
};
this.run = function () {
var fixedheight = 0;
if(this.openflag && this.nvdata.next){
var nvnexttop = document.body.scrollTop || document.documentElement.scrollTop;
var dofixed = nvnexttop !== 0 && document.documentElement.clientHeight >= 15 && this.nvdata.next.getBoundingClientRect().top - this.nvdata.height < 0;
if(dofixed) {
if(this.nv.style.position != 'fixed') {
this.nv.style.borderLeftWidth = '0';
this.nv.style.borderRightWidth = '0';
this.nv.style.height = this.nvdata.height + 'px';
this.nv.style.width = this.nvdata.width + 'px';
this.nv.style.top = '0';
this.nv.style.left = this.nvdata.left + 'px';
this.nv.style.position = 'fixed';
this.nv.style.zIndex = '199';
this.nv.style.opacity = 0.85;
}
} else {
if(this.nv.style.position != this.nvdata.position) {
this.reset();
}
}
if(this.nv.style.position == 'fixed') {
fixedheight = this.nvdata.height;
}
}
return fixedheight;
};
this.reset = function () {
if(this.nv) {
this.nv.style.position = this.nvdata.position;
this.nv.style.borderLeftWidth = '';
this.nv.style.borderRightWidth = '';
this.nv.style.height = '';
this.nv.style.width = '';
this.nv.style.opacity = this.nvdata.opacity;
}
};
if(!disbind && this.openflag) {
this.init();
_attachEvent(window, 'scroll', this.run);
}
}
var previewTbody = null, previewTid = null, previewDiv = null;
function previewThread(tid, tbody) {
if(!$('threadPreviewTR_'+tid)) {
appendscript(JSPATH + 'forum_viewthread.js?' + VERHASH);
newTr = document.createElement('tr');
newTr.id = 'threadPreviewTR_'+tid;
newTr.className = 'threadpre';
$(tbody).appendChild(newTr);
newTd = document.createElement('td');
newTd.colSpan = listcolspan;
newTd.className = 'threadpretd';
newTr.appendChild(newTd);
newTr.style.display = 'none';
previewTbody = tbody;
previewTid = tid;
if(BROWSER.ie) {
previewDiv = document.createElement('div');
previewDiv.id = 'threadPreview_'+tid;
previewDiv.style.id = 'none';
var x = Ajax();
x.get('forum.php?mod=viewthread&tid='+tid+'&inajax=1&from=preview', function(ret) {
var evaled = false;
if(ret.indexOf('ajaxerror') != -1) {
evalscript(ret);
evaled = true;
}
previewDiv.innerHTML = ret;
newTd.appendChild(previewDiv);
if(!evaled) evalscript(ret);
newTr.style.display = '';
});
} else {
newTd.innerHTML += '<div id="threadPreview_'+tid+'"></div>';
ajaxget('forum.php?mod=viewthread&tid='+tid+'&from=preview', 'threadPreview_'+tid, null, null, null, function() {newTr.style.display = '';});
}
} else {
$(tbody).removeChild($('threadPreviewTR_'+tid));
previewTbody = previewTid = null;
}
}
function hideStickThread(tid) {
var pre = 'stickthread_';
var tids = (new Function("return ("+(loadUserdata('sticktids') || '[]')+")"))();
var format = function (data) {
var str = '{';
for (var i in data) {
if(data[i] instanceof Array) {
str += i + ':' + '[';
for (var j = data[i].length - 1; j >= 0; j--) {
str += data[i][j] + ',';
};
str = str.substr(0, str.length -1);
str += '],';
}
}
str = str.substr(0, str.length -1);
str += '}';
return str;
};
if(!tid) {
if(tids.length > 0) {
for (var i = tids.length - 1; i >= 0; i--) {
var ele = $(pre+tids[i]);
if(ele) {
ele.parentNode.removeChild(ele);
}
};
}
} else {
var eletbody = $(pre+tid);
if(eletbody) {
eletbody.parentNode.removeChild(eletbody);
tids.push(tid);
saveUserdata('sticktids', '['+tids.join(',')+']');
}
}
var clearstickthread = $('clearstickthread');
if(clearstickthread) {
if(tids.length > 0) {
$('clearstickthread').style.display = '';
} else {
$('clearstickthread').style.display = 'none';
}
}
var separatorline = $('separatorline');
if(separatorline) {
try {
if(typeof separatorline.previousElementSibling === 'undefined') {
var findele = separatorline.previousSibling;
while(findele && findele.nodeType != 1){
findele = findele.previousSibling;
}
if(findele === null) {
separatorline.parentNode.removeChild(separatorline);
}
} else {
if(separatorline.previousElementSibling === null) {
separatorline.parentNode.removeChild(separatorline);
}
}
} catch(e) {
}
}
}
function viewhot() {
var obj = $('hottime');
window.location.href = "forum.php?mod=forumdisplay&filter=hot&fid="+obj.getAttribute('fid')+"&time="+obj.value;
}
function clearStickThread () {
saveUserdata('sticktids', '[]');
location.reload();
} | {
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : $('fastpostform');
if(obj && obj.message.value != '') {
saveData();
url += (url.indexOf('?') != -1 ? '&' : '?') + 'cedit=yes';
}
location.href = url;
return false;
} | identifier_body |
forum.js | /*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum.js 33082 2013-04-18 11:13:53Z zhengqingpeng $
*/
function saveData(ignoreempty) {
var ignoreempty = isUndefined(ignoreempty) ? 0 : ignoreempty;
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : ($('fastpostform') ? $('fastpostform') : $('postform'));
if(!obj) return;
if(typeof isfirstpost != 'undefined') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
var messageisnull = trim(html2bbcode(editdoc.body.innerHTML)) === '';
} else {
var messageisnull = $('postform').message.value === '';
}
if(isfirstpost && (messageisnull && $('postform').subject.value === '')) {
return;
}
if(!isfirstpost && messageisnull) {
return;
}
}
var data = subject = message = '';
for(var i = 0; i < obj.elements.length; i++) {
var el = obj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden' || el.type == 'select')) && el.name.substr(0, 6) != 'attach') {
var elvalue = el.value;
if(el.name == 'subject') {
subject = trim(elvalue);
} else if(el.name == 'message') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
elvalue = html2bbcode(editdoc.body.innerHTML);
}
message = trim(elvalue);
}
if((el.type == 'checkbox' || el.type == 'radio') && !el.checked) {
continue;
} else if(el.tagName == 'SELECT') {
elvalue = el.value;
} else if(el.type == 'hidden') {
if(el.id) {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
elvalue = elvalue;
if($(el.id + '_url')) {
elvalue += String.fromCharCode(1) + $(el.id + '_url').value;
}
} else {
continue;
}
} else {
continue;
}
}
if(trim(elvalue)) {
data += el.name + String.fromCharCode(9) + el.tagName + String.fromCharCode(9) + el.type + String.fromCharCode(9) + elvalue + String.fromCharCode(9, 9);
}
}
}
if(!subject && !message && !ignoreempty) {
return;
}
saveUserdata('forum_'+discuz_uid, data);
}
function fastUload() {
appendscript(JSPATH + 'forum_post.js?' + VERHASH);
safescript('forum_post_js', function () { uploadWindow(function (aid, url) {updatefastpostattach(aid, url)}, 'file') }, 100, 50);
}
function switchAdvanceMode(url) {
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : $('fastpostform');
if(obj && obj.message.value != '') {
saveData();
url += (url.indexOf('?') != -1 ? '&' : '?') + 'cedit=yes';
}
location.href = url;
return false;
}
function sidebar_collapse(lang) {
if(lang[0]) {
toggle_collapse('sidebar', null, null, lang);
$('wrap').className = $('wrap').className == 'wrap with_side s_clear' ? 'wrap s_clear' : 'wrap with_side s_clear';
} else {
var collapsed = getcookie('collapse');
collapsed = updatestring(collapsed, 'sidebar', 1);
setcookie('collapse', collapsed, (collapsed ? 2592000 : -2592000));
location.reload();
}
}
function keyPageScroll(e, prev, next, url, page) {
if(loadUserdata('is_blindman')) {
return true;
}
e = e ? e : window.event;
var tagname = BROWSER.ie ? e.srcElement.tagName : e.target.tagName;
if(tagname == 'INPUT' || tagname == 'TEXTAREA') return;
actualCode = e.keyCode ? e.keyCode : e.charCode;
if(next && actualCode == 39) {
window.location = url + '&page=' + (page + 1);
}
if(prev && actualCode == 37) {
window.location = url + '&page=' + (page - 1);
}
}
function announcement() {
var ann = new Object();
ann.anndelay = 3000;ann.annst = 0;ann.annstop = 0;ann.annrowcount = 0;ann.anncount = 0;ann.annlis = $('anc').getElementsByTagName("li");ann.annrows = new Array();
ann.announcementScroll = function () {
if(this.annstop) {this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);return;}
if(!this.annst) {
var lasttop = -1;
for(i = 0;i < this.annlis.length;i++) {
if(lasttop != this.annlis[i].offsetTop) {
if(lasttop == -1) lasttop = 0;
this.annrows[this.annrowcount] = this.annlis[i].offsetTop - lasttop;this.annrowcount++;
}
lasttop = this.annlis[i].offsetTop;
}
if(this.annrows.length == 1) {
$('an').onmouseover = $('an').onmouseout = null;
} else {
this.annrows[this.annrowcount] = this.annrows[1];
$('ancl').innerHTML += $('ancl').innerHTML;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
$('an').onmouseover = function () {ann.annstop = 1;};
$('an').onmouseout = function () {ann.annstop = 0;};
}
this.annrowcount = 1;
return;
}
if(this.annrowcount >= this.annrows.length) {
$('anc').scrollTop = 0;
this.annrowcount = 1;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
} else {
this.anncount = 0;
this.announcementScrollnext(this.annrows[this.annrowcount]);
}
};
ann.announcementScrollnext = function (time) {
$('anc').scrollTop++;
this.anncount++;
if(this.anncount != time) {
this.annst = setTimeout(function () {ann.announcementScrollnext(time);}, 10);
} else {
this.annrowcount++;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
}
};
ann.announcementScroll();
}
function removeindexheats() {
return confirm('You to confirm that this topic should remove it from the hot topic?');
}
function showTypes(id, mod) {
var o = $(id);
if(!o) return false;
var s = o.className;
mod = isUndefined(mod) ? 1 : mod;
var baseh = o.getElementsByTagName('li')[0].offsetHeight * 2;
var tmph = o.offsetHeight;
var lang = ['Expansion', 'Collapse'];
var cls = ['unfold', 'fold'];
if(tmph > baseh) {
var octrl = document.createElement('li');
octrl.className = cls[mod];
octrl.innerHTML = lang[mod];
o.insertBefore(octrl, o.firstChild);
o.className = s + ' cttp';
mod && (o.style.height = 'auto');
octrl.onclick = function () {
if(this.className == cls[0]) {
o.style.height = 'auto';
this.className = cls[1];
this.innerHTML = lang[1];
} else {
o.style.height = '';
this.className = cls[0];
this.innerHTML = lang[0];
}
}
}
}
var postpt = 0;
function fastpostvalidate(theform, noajaxpost) {
if(postpt) {
return false;
}
postpt = 1;
setTimeout(function() {postpt = 0}, 2000);
noajaxpost = !noajaxpost ? 0 : noajaxpost;
s = '';
if(typeof fastpostvalidateextra == 'function') {
var v = fastpostvalidateextra();
if(!v) {
return false;
}
}
if(theform.message.value == '' || theform.subject.value == '') {
s = 'Sorry, you can not enter a title or content';
theform.message.focus();
} else if(mb_strlen(theform.subject.value) > 80) {
s = 'Your title is longer than 80 characters limit';
theform.subject.focus();
}
if(!disablepostctrl && ((postminchars != 0 && mb_strlen(theform.message.value) < postminchars) || (postmaxchars != 0 && mb_strlen(theform.message.value) > postmaxchars))) {
s = 'Not meet the requirements of the length of your posts.\n\nCurrent length: ' + mb_strlen(theform.message.value) + ' ' + 'Byte\nSystem limits: ' + postminchars + ' to ' + postmaxchars + ' Byte';
}
if(s) {
showError(s);
doane();
$('fastpostsubmit').disabled = false;
return false;
}
$('fastpostsubmit').disabled = true;
theform.message.value = theform.message.value.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, '$1[img]$2[/img]');
theform.message.value = parseurl(theform.message.value);
if(!noajaxpost) {
ajaxpost('fastpostform', 'fastpostreturn', 'fastpostreturn', 'onerror', $('fastpostsubmit'));
return false;
} else {
return true;
}
}
function updatefastpostattach(aid, url) {
ajaxget('forum.php?mod=ajax&action=attachlist&posttime=' + $('posttime').value + (!fid ? '' : '&fid=' + fid), 'attachlist');
$('attach_tblheader').style.display = '';
}
function succeedhandle_fastnewpost(locationhref, message, param) {
location.href = locationhref;
}
function errorhandle_fastnewpost() {
$('fastpostsubmit').disabled = false;
}
function atarget(obj) {
obj.target = getcookie('atarget') > 0 ? '_blank' : '';
}
function setatarget(v) {
$('atarget').className = 'y atarget_' + v;
$('atarget').onclick = function() {setatarget(v == 1 ? -1 : 1);};
setcookie('atarget', v, 2592000);
}
function loadData(quiet, formobj) {
var evalevent = function (obj) {
var script = obj.parentNode.innerHTML;
var re = /onclick="(.+?)["|>]/ig;
var matches = re.exec(script);
if(matches != null) {
matches[1] = matches[1].replace(/this\./ig, 'obj.');
eval(matches[1]);
}
};
var data = '';
data = loadUserdata('forum_'+discuz_uid);
var formobj = !formobj ? $('postform') : formobj;
if(in_array((data = trim(data)), ['', 'null', 'false', null, false])) {
if(!quiet) {
showDialog('No data can be restored!', 'info');
}
return;
}
if(!quiet && !confirm('This action will overwrite the current content of the post, You sure you want to recover data?')) {
return;
}
var data = data.split(/\x09\x09/);
for(var i = 0; i < formobj.elements.length; i++) {
var el = formobj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden'))) {
for(var j = 0; j < data.length; j++) {
var ele = data[j].split(/\x09/);
if(ele[0] == el.name) {
elvalue = !isUndefined(ele[3]) ? ele[3] : '';
if(ele[1] == 'INPUT') {
if(ele[2] == 'text') {
el.value = elvalue;
} else if((ele[2] == 'checkbox' || ele[2] == 'radio') && ele[3] == el.value) {
el.checked = true;
evalevent(el);
} else if(ele[2] == 'hidden') {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
var v = elvalue.split(/\x01/);
el.value = v[0];
if(el.value) {
if($(el.id + '_url') && v[1]) {
$(el.id + '_url').value = v[1];
}
eval(el.id + '_upload(\'' + v[0] + '\', \'' + v[1] + '\')');
if($('unused' + v[0])) {
var attachtype = $('unused' + v[0]).parentNode.parentNode.parentNode.parentNode.id.substr(11);
$('unused' + v[0]).parentNode.parentNode.outerHTML = '';
$('unusednum_' + attachtype).innerHTML = parseInt($('unusednum_' + attachtype).innerHTML) - 1;
if($('unusednum_' + attachtype).innerHTML == 0 && $('attachnotice_' + attachtype)) {
$('attachnotice_' + attachtype).style.display = 'none';
}
}
}
| if(ele[0] == 'message') {
if(!wysiwyg) {
textobj.value = elvalue;
} else {
editdoc.body.innerHTML = bbcode2html(elvalue);
}
} else {
el.value = elvalue;
}
} else if(ele[1] == 'SELECT') {
if($(el.id + '_ctrl_menu')) {
var lis = $(el.id + '_ctrl_menu').getElementsByTagName('li');
for(var k = 0; k < lis.length; k++) {
if(ele[3] == lis[k].k_value) {
lis[k].onclick();
break;
}
}
} else {
for(var k = 0; k < el.options.length; k++) {
if(ele[3] == el.options[k].value) {
el.options[k].selected = true;
break;
}
}
}
}
break;
}
}
}
}
if($('rstnotice')) {
$('rstnotice').style.display = 'none';
}
extraCheckall();
}
var checkForumcount = 0, checkForumtimeout = 30000, checkForumnew_handle;
function checkForumnew(fid, lasttime) {
var timeout = checkForumtimeout;
var x = new Ajax();
x.get('forum.php?mod=ajax&action=forumchecknew&fid=' + fid + '&time=' + lasttime + '&inajax=yes', function(s){
if(s > 0) {
var table = $('separatorline').parentNode;
if(!isUndefined(checkForumnew_handle)) {
clearTimeout(checkForumnew_handle);
}
removetbodyrow(table, 'forumnewshow');
var colspan = table.getElementsByTagName('tbody')[0].rows[0].children.length;
var checknew = {'tid':'', 'thread':{'common':{'className':'', 'val':'<a href="javascript:void(0);" onclick="ajaxget(\'forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=1&inajax=yes\', \'forumnew\');">New topic Reply, Click to view', 'colspan': colspan }}};
addtbodyrow(table, ['tbody'], ['forumnewshow'], 'separatorline', checknew);
} else {
if(checkForumcount < 50) {
if(checkForumcount > 0) {
var multiple = Math.ceil(50 / checkForumcount);
if(multiple < 5) {
timeout = checkForumtimeout * (5 - multiple + 1);
}
}
checkForumnew_handle = setTimeout(function () {checkForumnew(fid, lasttime);}, timeout);
}
}
checkForumcount++;
});
}
function checkForumnew_btn(fid) {
if(isUndefined(fid)) return;
ajaxget('forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=2&inajax=yes', 'forumnew', 'ajaxwaitid');
lasttime = parseInt(Date.parse(new Date()) / 1000);
}
function addtbodyrow (table, insertID, changename, separatorid, jsonval) {
if(isUndefined(table) || isUndefined(insertID[0])) {
return;
}
var insertobj = document.createElement(insertID[0]);
var thread = jsonval.thread;
var tid = !isUndefined(jsonval.tid) ? jsonval.tid : '' ;
if(!isUndefined(changename[1])) {
removetbodyrow(table, changename[1] + tid);
}
insertobj.id = changename[0] + tid;
if(!isUndefined(insertID[1])) {
insertobj.className = insertID[1];
}
if($(separatorid)) {
table.insertBefore(insertobj, $(separatorid).nextSibling);
} else {
table.insertBefore(insertobj, table.firstChild);
}
var newTH = insertobj.insertRow(-1);
for(var value in thread) {
if(value != 0) {
var cell = newTH.insertCell(-1);
if(isUndefined(thread[value]['val'])) {
cell.innerHTML = thread[value];
} else {
cell.innerHTML = thread[value]['val'];
}
if(!isUndefined(thread[value]['className'])) {
cell.className = thread[value]['className'];
}
if(!isUndefined(thread[value]['colspan'])) {
cell.colSpan = thread[value]['colspan'];
}
}
}
if(!isUndefined(insertID[2])) {
_attachEvent(insertobj, insertID[2], function() {insertobj.className = '';});
}
}
function removetbodyrow(from, objid) {
if(!isUndefined(from) && $(objid)) {
from.removeChild($(objid));
}
}
function leftside(id) {
$(id).className = $(id).className == 'a' ? '' : 'a';
if(id == 'lf_fav') {
setcookie('leftsidefav', $(id).className == 'a' ? 0 : 1, 2592000);
}
}
var DTimers = new Array();
var DItemIDs = new Array();
var DTimers_exists = false;
function settimer(timer, itemid) {
if(timer && itemid) {
DTimers.push(timer);
DItemIDs.push(itemid);
}
if(!DTimers_exists) {
setTimeout("showtime()", 1000);
DTimers_exists = true;
}
}
function showtime() {
for(i=0; i<=DTimers.length; i++) {
if(DItemIDs[i]) {
if(DTimers[i] == 0) {
$(DItemIDs[i]).innerHTML = 'Has ended';
DItemIDs[i] = '';
continue;
}
var timestr = '';
var timer_day = Math.floor(DTimers[i] / 86400);
var timer_hour = Math.floor((DTimers[i] % 86400) / 3600);
var timer_minute = Math.floor(((DTimers[i] % 86400) % 3600) / 60);
var timer_second = (((DTimers[i] % 86400) % 3600) % 60);
if(timer_day > 0) {
timestr += timer_day + 'Day';
}
if(timer_hour > 0) {
timestr += timer_hour + 'Hour'
}
if(timer_minute > 0) {
timestr += timer_minute + 'Min.'
}
if(timer_second > 0) {
timestr += timer_second + 'Sec.'
}
DTimers[i] = DTimers[i] - 1;
$(DItemIDs[i]).innerHTML = timestr;
}
}
setTimeout("showtime()", 1000);
}
function fixed_top_nv(eleid, disbind) {
this.nv = eleid && $(eleid) || $('nv');
this.openflag = this.nv && BROWSER.ie != 6;
this.nvdata = {};
this.init = function (disattachevent) {
if(this.openflag) {
if(!disattachevent) {
var obj = this;
_attachEvent(window, 'resize', function(){obj.reset();obj.init(1);obj.run();});
var switchwidth = $('switchwidth');
if(switchwidth) {
_attachEvent(switchwidth, 'click', function(){obj.reset();obj.openflag=false;});
}
}
var next = this.nv;
try {
while((next = next.nextSibling).nodeType != 1 || next.style.display === 'none') {}
this.nvdata.next = next;
this.nvdata.height = parseInt(this.nv.offsetHeight, 10);
this.nvdata.width = parseInt(this.nv.offsetWidth, 10);
this.nvdata.left = this.nv.getBoundingClientRect().left - document.documentElement.clientLeft;
this.nvdata.position = this.nv.style.position;
this.nvdata.opacity = this.nv.style.opacity;
} catch (e) {
this.nvdata.next = null;
}
}
};
this.run = function () {
var fixedheight = 0;
if(this.openflag && this.nvdata.next){
var nvnexttop = document.body.scrollTop || document.documentElement.scrollTop;
var dofixed = nvnexttop !== 0 && document.documentElement.clientHeight >= 15 && this.nvdata.next.getBoundingClientRect().top - this.nvdata.height < 0;
if(dofixed) {
if(this.nv.style.position != 'fixed') {
this.nv.style.borderLeftWidth = '0';
this.nv.style.borderRightWidth = '0';
this.nv.style.height = this.nvdata.height + 'px';
this.nv.style.width = this.nvdata.width + 'px';
this.nv.style.top = '0';
this.nv.style.left = this.nvdata.left + 'px';
this.nv.style.position = 'fixed';
this.nv.style.zIndex = '199';
this.nv.style.opacity = 0.85;
}
} else {
if(this.nv.style.position != this.nvdata.position) {
this.reset();
}
}
if(this.nv.style.position == 'fixed') {
fixedheight = this.nvdata.height;
}
}
return fixedheight;
};
this.reset = function () {
if(this.nv) {
this.nv.style.position = this.nvdata.position;
this.nv.style.borderLeftWidth = '';
this.nv.style.borderRightWidth = '';
this.nv.style.height = '';
this.nv.style.width = '';
this.nv.style.opacity = this.nvdata.opacity;
}
};
if(!disbind && this.openflag) {
this.init();
_attachEvent(window, 'scroll', this.run);
}
}
var previewTbody = null, previewTid = null, previewDiv = null;
function previewThread(tid, tbody) {
if(!$('threadPreviewTR_'+tid)) {
appendscript(JSPATH + 'forum_viewthread.js?' + VERHASH);
newTr = document.createElement('tr');
newTr.id = 'threadPreviewTR_'+tid;
newTr.className = 'threadpre';
$(tbody).appendChild(newTr);
newTd = document.createElement('td');
newTd.colSpan = listcolspan;
newTd.className = 'threadpretd';
newTr.appendChild(newTd);
newTr.style.display = 'none';
previewTbody = tbody;
previewTid = tid;
if(BROWSER.ie) {
previewDiv = document.createElement('div');
previewDiv.id = 'threadPreview_'+tid;
previewDiv.style.id = 'none';
var x = Ajax();
x.get('forum.php?mod=viewthread&tid='+tid+'&inajax=1&from=preview', function(ret) {
var evaled = false;
if(ret.indexOf('ajaxerror') != -1) {
evalscript(ret);
evaled = true;
}
previewDiv.innerHTML = ret;
newTd.appendChild(previewDiv);
if(!evaled) evalscript(ret);
newTr.style.display = '';
});
} else {
newTd.innerHTML += '<div id="threadPreview_'+tid+'"></div>';
ajaxget('forum.php?mod=viewthread&tid='+tid+'&from=preview', 'threadPreview_'+tid, null, null, null, function() {newTr.style.display = '';});
}
} else {
$(tbody).removeChild($('threadPreviewTR_'+tid));
previewTbody = previewTid = null;
}
}
function hideStickThread(tid) {
var pre = 'stickthread_';
var tids = (new Function("return ("+(loadUserdata('sticktids') || '[]')+")"))();
var format = function (data) {
var str = '{';
for (var i in data) {
if(data[i] instanceof Array) {
str += i + ':' + '[';
for (var j = data[i].length - 1; j >= 0; j--) {
str += data[i][j] + ',';
};
str = str.substr(0, str.length -1);
str += '],';
}
}
str = str.substr(0, str.length -1);
str += '}';
return str;
};
if(!tid) {
if(tids.length > 0) {
for (var i = tids.length - 1; i >= 0; i--) {
var ele = $(pre+tids[i]);
if(ele) {
ele.parentNode.removeChild(ele);
}
};
}
} else {
var eletbody = $(pre+tid);
if(eletbody) {
eletbody.parentNode.removeChild(eletbody);
tids.push(tid);
saveUserdata('sticktids', '['+tids.join(',')+']');
}
}
var clearstickthread = $('clearstickthread');
if(clearstickthread) {
if(tids.length > 0) {
$('clearstickthread').style.display = '';
} else {
$('clearstickthread').style.display = 'none';
}
}
var separatorline = $('separatorline');
if(separatorline) {
try {
if(typeof separatorline.previousElementSibling === 'undefined') {
var findele = separatorline.previousSibling;
while(findele && findele.nodeType != 1){
findele = findele.previousSibling;
}
if(findele === null) {
separatorline.parentNode.removeChild(separatorline);
}
} else {
if(separatorline.previousElementSibling === null) {
separatorline.parentNode.removeChild(separatorline);
}
}
} catch(e) {
}
}
}
function viewhot() {
var obj = $('hottime');
window.location.href = "forum.php?mod=forumdisplay&filter=hot&fid="+obj.getAttribute('fid')+"&time="+obj.value;
}
function clearStickThread () {
saveUserdata('sticktids', '[]');
location.reload();
} | }
}
} else if(ele[1] == 'TEXTAREA') {
| random_line_split |
forum.js | /*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum.js 33082 2013-04-18 11:13:53Z zhengqingpeng $
*/
function saveData(ignoreempty) {
var ignoreempty = isUndefined(ignoreempty) ? 0 : ignoreempty;
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : ($('fastpostform') ? $('fastpostform') : $('postform'));
if(!obj) return;
if(typeof isfirstpost != 'undefined') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
var messageisnull = trim(html2bbcode(editdoc.body.innerHTML)) === '';
} else {
var messageisnull = $('postform').message.value === '';
}
if(isfirstpost && (messageisnull && $('postform').subject.value === '')) {
return;
}
if(!isfirstpost && messageisnull) {
return;
}
}
var data = subject = message = '';
for(var i = 0; i < obj.elements.length; i++) {
var el = obj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden' || el.type == 'select')) && el.name.substr(0, 6) != 'attach') {
var elvalue = el.value;
if(el.name == 'subject') {
subject = trim(elvalue);
} else if(el.name == 'message') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
elvalue = html2bbcode(editdoc.body.innerHTML);
}
message = trim(elvalue);
}
if((el.type == 'checkbox' || el.type == 'radio') && !el.checked) {
continue;
} else if(el.tagName == 'SELECT') {
elvalue = el.value;
} else if(el.type == 'hidden') {
if(el.id) {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
elvalue = elvalue;
if($(el.id + '_url')) {
elvalue += String.fromCharCode(1) + $(el.id + '_url').value;
}
} else {
continue;
}
} else {
continue;
}
}
if(trim(elvalue)) {
data += el.name + String.fromCharCode(9) + el.tagName + String.fromCharCode(9) + el.type + String.fromCharCode(9) + elvalue + String.fromCharCode(9, 9);
}
}
}
if(!subject && !message && !ignoreempty) {
return;
}
saveUserdata('forum_'+discuz_uid, data);
}
function fastUload() {
appendscript(JSPATH + 'forum_post.js?' + VERHASH);
safescript('forum_post_js', function () { uploadWindow(function (aid, url) {updatefastpostattach(aid, url)}, 'file') }, 100, 50);
}
function switchAdvanceMode(url) {
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : $('fastpostform');
if(obj && obj.message.value != '') {
saveData();
url += (url.indexOf('?') != -1 ? '&' : '?') + 'cedit=yes';
}
location.href = url;
return false;
}
function sidebar_collapse(lang) {
if(lang[0]) {
toggle_collapse('sidebar', null, null, lang);
$('wrap').className = $('wrap').className == 'wrap with_side s_clear' ? 'wrap s_clear' : 'wrap with_side s_clear';
} else {
var collapsed = getcookie('collapse');
collapsed = updatestring(collapsed, 'sidebar', 1);
setcookie('collapse', collapsed, (collapsed ? 2592000 : -2592000));
location.reload();
}
}
function keyPageScroll(e, prev, next, url, page) {
if(loadUserdata('is_blindman')) {
return true;
}
e = e ? e : window.event;
var tagname = BROWSER.ie ? e.srcElement.tagName : e.target.tagName;
if(tagname == 'INPUT' || tagname == 'TEXTAREA') return;
actualCode = e.keyCode ? e.keyCode : e.charCode;
if(next && actualCode == 39) {
window.location = url + '&page=' + (page + 1);
}
if(prev && actualCode == 37) {
window.location = url + '&page=' + (page - 1);
}
}
function announcement() {
var ann = new Object();
ann.anndelay = 3000;ann.annst = 0;ann.annstop = 0;ann.annrowcount = 0;ann.anncount = 0;ann.annlis = $('anc').getElementsByTagName("li");ann.annrows = new Array();
ann.announcementScroll = function () {
if(this.annstop) {this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);return;}
if(!this.annst) {
var lasttop = -1;
for(i = 0;i < this.annlis.length;i++) {
if(lasttop != this.annlis[i].offsetTop) {
if(lasttop == -1) lasttop = 0;
this.annrows[this.annrowcount] = this.annlis[i].offsetTop - lasttop;this.annrowcount++;
}
lasttop = this.annlis[i].offsetTop;
}
if(this.annrows.length == 1) {
$('an').onmouseover = $('an').onmouseout = null;
} else {
this.annrows[this.annrowcount] = this.annrows[1];
$('ancl').innerHTML += $('ancl').innerHTML;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
$('an').onmouseover = function () {ann.annstop = 1;};
$('an').onmouseout = function () {ann.annstop = 0;};
}
this.annrowcount = 1;
return;
}
if(this.annrowcount >= this.annrows.length) {
$('anc').scrollTop = 0;
this.annrowcount = 1;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
} else {
this.anncount = 0;
this.announcementScrollnext(this.annrows[this.annrowcount]);
}
};
ann.announcementScrollnext = function (time) {
$('anc').scrollTop++;
this.anncount++;
if(this.anncount != time) {
this.annst = setTimeout(function () {ann.announcementScrollnext(time);}, 10);
} else {
this.annrowcount++;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
}
};
ann.announcementScroll();
}
function removeindexheats() {
return confirm('You to confirm that this topic should remove it from the hot topic?');
}
function showTypes(id, mod) {
var o = $(id);
if(!o) return false;
var s = o.className;
mod = isUndefined(mod) ? 1 : mod;
var baseh = o.getElementsByTagName('li')[0].offsetHeight * 2;
var tmph = o.offsetHeight;
var lang = ['Expansion', 'Collapse'];
var cls = ['unfold', 'fold'];
if(tmph > baseh) {
var octrl = document.createElement('li');
octrl.className = cls[mod];
octrl.innerHTML = lang[mod];
o.insertBefore(octrl, o.firstChild);
o.className = s + ' cttp';
mod && (o.style.height = 'auto');
octrl.onclick = function () {
if(this.className == cls[0]) {
o.style.height = 'auto';
this.className = cls[1];
this.innerHTML = lang[1];
} else {
o.style.height = '';
this.className = cls[0];
this.innerHTML = lang[0];
}
}
}
}
var postpt = 0;
function fastpostvalidate(theform, noajaxpost) {
if(postpt) {
return false;
}
postpt = 1;
setTimeout(function() {postpt = 0}, 2000);
noajaxpost = !noajaxpost ? 0 : noajaxpost;
s = '';
if(typeof fastpostvalidateextra == 'function') {
var v = fastpostvalidateextra();
if(!v) {
return false;
}
}
if(theform.message.value == '' || theform.subject.value == '') {
s = 'Sorry, you can not enter a title or content';
theform.message.focus();
} else if(mb_strlen(theform.subject.value) > 80) {
s = 'Your title is longer than 80 characters limit';
theform.subject.focus();
}
if(!disablepostctrl && ((postminchars != 0 && mb_strlen(theform.message.value) < postminchars) || (postmaxchars != 0 && mb_strlen(theform.message.value) > postmaxchars))) {
s = 'Not meet the requirements of the length of your posts.\n\nCurrent length: ' + mb_strlen(theform.message.value) + ' ' + 'Byte\nSystem limits: ' + postminchars + ' to ' + postmaxchars + ' Byte';
}
if(s) {
showError(s);
doane();
$('fastpostsubmit').disabled = false;
return false;
}
$('fastpostsubmit').disabled = true;
theform.message.value = theform.message.value.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, '$1[img]$2[/img]');
theform.message.value = parseurl(theform.message.value);
if(!noajaxpost) {
ajaxpost('fastpostform', 'fastpostreturn', 'fastpostreturn', 'onerror', $('fastpostsubmit'));
return false;
} else {
return true;
}
}
function updatefastpostattach(aid, url) {
ajaxget('forum.php?mod=ajax&action=attachlist&posttime=' + $('posttime').value + (!fid ? '' : '&fid=' + fid), 'attachlist');
$('attach_tblheader').style.display = '';
}
function succeedhandle_fastnewpost(locationhref, message, param) {
location.href = locationhref;
}
function errorhandle_fastnewpost() {
$('fastpostsubmit').disabled = false;
}
function atarget(obj) {
obj.target = getcookie('atarget') > 0 ? '_blank' : '';
}
function setatarget(v) {
$('atarget').className = 'y atarget_' + v;
$('atarget').onclick = function() {setatarget(v == 1 ? -1 : 1);};
setcookie('atarget', v, 2592000);
}
function loadData(quiet, formobj) {
var evalevent = function (obj) {
var script = obj.parentNode.innerHTML;
var re = /onclick="(.+?)["|>]/ig;
var matches = re.exec(script);
if(matches != null) {
matches[1] = matches[1].replace(/this\./ig, 'obj.');
eval(matches[1]);
}
};
var data = '';
data = loadUserdata('forum_'+discuz_uid);
var formobj = !formobj ? $('postform') : formobj;
if(in_array((data = trim(data)), ['', 'null', 'false', null, false])) {
if(!quiet) {
showDialog('No data can be restored!', 'info');
}
return;
}
if(!quiet && !confirm('This action will overwrite the current content of the post, You sure you want to recover data?')) {
return;
}
var data = data.split(/\x09\x09/);
for(var i = 0; i < formobj.elements.length; i++) {
var el = formobj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden'))) {
for(var j = 0; j < data.length; j++) {
var ele = data[j].split(/\x09/);
if(ele[0] == el.name) {
elvalue = !isUndefined(ele[3]) ? ele[3] : '';
if(ele[1] == 'INPUT') {
if(ele[2] == 'text') {
el.value = elvalue;
} else if((ele[2] == 'checkbox' || ele[2] == 'radio') && ele[3] == el.value) {
el.checked = true;
evalevent(el);
} else if(ele[2] == 'hidden') {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
var v = elvalue.split(/\x01/);
el.value = v[0];
if(el.value) {
if($(el.id + '_url') && v[1]) {
$(el.id + '_url').value = v[1];
}
eval(el.id + '_upload(\'' + v[0] + '\', \'' + v[1] + '\')');
if($('unused' + v[0])) {
var attachtype = $('unused' + v[0]).parentNode.parentNode.parentNode.parentNode.id.substr(11);
$('unused' + v[0]).parentNode.parentNode.outerHTML = '';
$('unusednum_' + attachtype).innerHTML = parseInt($('unusednum_' + attachtype).innerHTML) - 1;
if($('unusednum_' + attachtype).innerHTML == 0 && $('attachnotice_' + attachtype)) {
$('attachnotice_' + attachtype).style.display = 'none';
}
}
}
}
}
} else if(ele[1] == 'TEXTAREA') {
if(ele[0] == 'message') {
if(!wysiwyg) {
textobj.value = elvalue;
} else {
editdoc.body.innerHTML = bbcode2html(elvalue);
}
} else {
el.value = elvalue;
}
} else if(ele[1] == 'SELECT') {
if($(el.id + '_ctrl_menu')) {
var lis = $(el.id + '_ctrl_menu').getElementsByTagName('li');
for(var k = 0; k < lis.length; k++) {
if(ele[3] == lis[k].k_value) {
lis[k].onclick();
break;
}
}
} else {
for(var k = 0; k < el.options.length; k++) {
if(ele[3] == el.options[k].value) {
el.options[k].selected = true;
break;
}
}
}
}
break;
}
}
}
}
if($('rstnotice')) {
$('rstnotice').style.display = 'none';
}
extraCheckall();
}
var checkForumcount = 0, checkForumtimeout = 30000, checkForumnew_handle;
function checkForumnew(fid, lasttime) {
var timeout = checkForumtimeout;
var x = new Ajax();
x.get('forum.php?mod=ajax&action=forumchecknew&fid=' + fid + '&time=' + lasttime + '&inajax=yes', function(s){
if(s > 0) {
var table = $('separatorline').parentNode;
if(!isUndefined(checkForumnew_handle)) {
clearTimeout(checkForumnew_handle);
}
removetbodyrow(table, 'forumnewshow');
var colspan = table.getElementsByTagName('tbody')[0].rows[0].children.length;
var checknew = {'tid':'', 'thread':{'common':{'className':'', 'val':'<a href="javascript:void(0);" onclick="ajaxget(\'forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=1&inajax=yes\', \'forumnew\');">New topic Reply, Click to view', 'colspan': colspan }}};
addtbodyrow(table, ['tbody'], ['forumnewshow'], 'separatorline', checknew);
} else {
if(checkForumcount < 50) {
if(checkForumcount > 0) {
var multiple = Math.ceil(50 / checkForumcount);
if(multiple < 5) {
timeout = checkForumtimeout * (5 - multiple + 1);
}
}
checkForumnew_handle = setTimeout(function () {checkForumnew(fid, lasttime);}, timeout);
}
}
checkForumcount++;
});
}
function checkForumnew_btn(fid) {
if(isUndefined(fid)) return;
ajaxget('forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=2&inajax=yes', 'forumnew', 'ajaxwaitid');
lasttime = parseInt(Date.parse(new Date()) / 1000);
}
function addtbodyrow (table, insertID, changename, separatorid, jsonval) {
if(isUndefined(table) || isUndefined(insertID[0])) {
return;
}
var insertobj = document.createElement(insertID[0]);
var thread = jsonval.thread;
var tid = !isUndefined(jsonval.tid) ? jsonval.tid : '' ;
if(!isUndefined(changename[1])) {
removetbodyrow(table, changename[1] + tid);
}
insertobj.id = changename[0] + tid;
if(!isUndefined(insertID[1])) {
insertobj.className = insertID[1];
}
if($(separatorid)) {
table.insertBefore(insertobj, $(separatorid).nextSibling);
} else {
table.insertBefore(insertobj, table.firstChild);
}
var newTH = insertobj.insertRow(-1);
for(var value in thread) {
if(value != 0) {
var cell = newTH.insertCell(-1);
if(isUndefined(thread[value]['val'])) {
cell.innerHTML = thread[value];
} else {
cell.innerHTML = thread[value]['val'];
}
if(!isUndefined(thread[value]['className'])) {
cell.className = thread[value]['className'];
}
if(!isUndefined(thread[value]['colspan'])) {
cell.colSpan = thread[value]['colspan'];
}
}
}
if(!isUndefined(insertID[2])) {
_attachEvent(insertobj, insertID[2], function() {insertobj.className = '';});
}
}
function removetbodyrow(from, objid) {
if(!isUndefined(from) && $(objid)) {
from.removeChild($(objid));
}
}
function | (id) {
$(id).className = $(id).className == 'a' ? '' : 'a';
if(id == 'lf_fav') {
setcookie('leftsidefav', $(id).className == 'a' ? 0 : 1, 2592000);
}
}
var DTimers = new Array();
var DItemIDs = new Array();
var DTimers_exists = false;
function settimer(timer, itemid) {
if(timer && itemid) {
DTimers.push(timer);
DItemIDs.push(itemid);
}
if(!DTimers_exists) {
setTimeout("showtime()", 1000);
DTimers_exists = true;
}
}
function showtime() {
for(i=0; i<=DTimers.length; i++) {
if(DItemIDs[i]) {
if(DTimers[i] == 0) {
$(DItemIDs[i]).innerHTML = 'Has ended';
DItemIDs[i] = '';
continue;
}
var timestr = '';
var timer_day = Math.floor(DTimers[i] / 86400);
var timer_hour = Math.floor((DTimers[i] % 86400) / 3600);
var timer_minute = Math.floor(((DTimers[i] % 86400) % 3600) / 60);
var timer_second = (((DTimers[i] % 86400) % 3600) % 60);
if(timer_day > 0) {
timestr += timer_day + 'Day';
}
if(timer_hour > 0) {
timestr += timer_hour + 'Hour'
}
if(timer_minute > 0) {
timestr += timer_minute + 'Min.'
}
if(timer_second > 0) {
timestr += timer_second + 'Sec.'
}
DTimers[i] = DTimers[i] - 1;
$(DItemIDs[i]).innerHTML = timestr;
}
}
setTimeout("showtime()", 1000);
}
function fixed_top_nv(eleid, disbind) {
this.nv = eleid && $(eleid) || $('nv');
this.openflag = this.nv && BROWSER.ie != 6;
this.nvdata = {};
this.init = function (disattachevent) {
if(this.openflag) {
if(!disattachevent) {
var obj = this;
_attachEvent(window, 'resize', function(){obj.reset();obj.init(1);obj.run();});
var switchwidth = $('switchwidth');
if(switchwidth) {
_attachEvent(switchwidth, 'click', function(){obj.reset();obj.openflag=false;});
}
}
var next = this.nv;
try {
while((next = next.nextSibling).nodeType != 1 || next.style.display === 'none') {}
this.nvdata.next = next;
this.nvdata.height = parseInt(this.nv.offsetHeight, 10);
this.nvdata.width = parseInt(this.nv.offsetWidth, 10);
this.nvdata.left = this.nv.getBoundingClientRect().left - document.documentElement.clientLeft;
this.nvdata.position = this.nv.style.position;
this.nvdata.opacity = this.nv.style.opacity;
} catch (e) {
this.nvdata.next = null;
}
}
};
this.run = function () {
var fixedheight = 0;
if(this.openflag && this.nvdata.next){
var nvnexttop = document.body.scrollTop || document.documentElement.scrollTop;
var dofixed = nvnexttop !== 0 && document.documentElement.clientHeight >= 15 && this.nvdata.next.getBoundingClientRect().top - this.nvdata.height < 0;
if(dofixed) {
if(this.nv.style.position != 'fixed') {
this.nv.style.borderLeftWidth = '0';
this.nv.style.borderRightWidth = '0';
this.nv.style.height = this.nvdata.height + 'px';
this.nv.style.width = this.nvdata.width + 'px';
this.nv.style.top = '0';
this.nv.style.left = this.nvdata.left + 'px';
this.nv.style.position = 'fixed';
this.nv.style.zIndex = '199';
this.nv.style.opacity = 0.85;
}
} else {
if(this.nv.style.position != this.nvdata.position) {
this.reset();
}
}
if(this.nv.style.position == 'fixed') {
fixedheight = this.nvdata.height;
}
}
return fixedheight;
};
this.reset = function () {
if(this.nv) {
this.nv.style.position = this.nvdata.position;
this.nv.style.borderLeftWidth = '';
this.nv.style.borderRightWidth = '';
this.nv.style.height = '';
this.nv.style.width = '';
this.nv.style.opacity = this.nvdata.opacity;
}
};
if(!disbind && this.openflag) {
this.init();
_attachEvent(window, 'scroll', this.run);
}
}
var previewTbody = null, previewTid = null, previewDiv = null;
function previewThread(tid, tbody) {
if(!$('threadPreviewTR_'+tid)) {
appendscript(JSPATH + 'forum_viewthread.js?' + VERHASH);
newTr = document.createElement('tr');
newTr.id = 'threadPreviewTR_'+tid;
newTr.className = 'threadpre';
$(tbody).appendChild(newTr);
newTd = document.createElement('td');
newTd.colSpan = listcolspan;
newTd.className = 'threadpretd';
newTr.appendChild(newTd);
newTr.style.display = 'none';
previewTbody = tbody;
previewTid = tid;
if(BROWSER.ie) {
previewDiv = document.createElement('div');
previewDiv.id = 'threadPreview_'+tid;
previewDiv.style.id = 'none';
var x = Ajax();
x.get('forum.php?mod=viewthread&tid='+tid+'&inajax=1&from=preview', function(ret) {
var evaled = false;
if(ret.indexOf('ajaxerror') != -1) {
evalscript(ret);
evaled = true;
}
previewDiv.innerHTML = ret;
newTd.appendChild(previewDiv);
if(!evaled) evalscript(ret);
newTr.style.display = '';
});
} else {
newTd.innerHTML += '<div id="threadPreview_'+tid+'"></div>';
ajaxget('forum.php?mod=viewthread&tid='+tid+'&from=preview', 'threadPreview_'+tid, null, null, null, function() {newTr.style.display = '';});
}
} else {
$(tbody).removeChild($('threadPreviewTR_'+tid));
previewTbody = previewTid = null;
}
}
function hideStickThread(tid) {
var pre = 'stickthread_';
var tids = (new Function("return ("+(loadUserdata('sticktids') || '[]')+")"))();
var format = function (data) {
var str = '{';
for (var i in data) {
if(data[i] instanceof Array) {
str += i + ':' + '[';
for (var j = data[i].length - 1; j >= 0; j--) {
str += data[i][j] + ',';
};
str = str.substr(0, str.length -1);
str += '],';
}
}
str = str.substr(0, str.length -1);
str += '}';
return str;
};
if(!tid) {
if(tids.length > 0) {
for (var i = tids.length - 1; i >= 0; i--) {
var ele = $(pre+tids[i]);
if(ele) {
ele.parentNode.removeChild(ele);
}
};
}
} else {
var eletbody = $(pre+tid);
if(eletbody) {
eletbody.parentNode.removeChild(eletbody);
tids.push(tid);
saveUserdata('sticktids', '['+tids.join(',')+']');
}
}
var clearstickthread = $('clearstickthread');
if(clearstickthread) {
if(tids.length > 0) {
$('clearstickthread').style.display = '';
} else {
$('clearstickthread').style.display = 'none';
}
}
var separatorline = $('separatorline');
if(separatorline) {
try {
if(typeof separatorline.previousElementSibling === 'undefined') {
var findele = separatorline.previousSibling;
while(findele && findele.nodeType != 1){
findele = findele.previousSibling;
}
if(findele === null) {
separatorline.parentNode.removeChild(separatorline);
}
} else {
if(separatorline.previousElementSibling === null) {
separatorline.parentNode.removeChild(separatorline);
}
}
} catch(e) {
}
}
}
function viewhot() {
var obj = $('hottime');
window.location.href = "forum.php?mod=forumdisplay&filter=hot&fid="+obj.getAttribute('fid')+"&time="+obj.value;
}
function clearStickThread () {
saveUserdata('sticktids', '[]');
location.reload();
} | leftside | identifier_name |
forum.js | /*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum.js 33082 2013-04-18 11:13:53Z zhengqingpeng $
*/
function saveData(ignoreempty) {
var ignoreempty = isUndefined(ignoreempty) ? 0 : ignoreempty;
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : ($('fastpostform') ? $('fastpostform') : $('postform'));
if(!obj) return;
if(typeof isfirstpost != 'undefined') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
var messageisnull = trim(html2bbcode(editdoc.body.innerHTML)) === '';
} else {
var messageisnull = $('postform').message.value === '';
}
if(isfirstpost && (messageisnull && $('postform').subject.value === '')) {
return;
}
if(!isfirstpost && messageisnull) {
return;
}
}
var data = subject = message = '';
for(var i = 0; i < obj.elements.length; i++) {
var el = obj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden' || el.type == 'select')) && el.name.substr(0, 6) != 'attach') {
var elvalue = el.value;
if(el.name == 'subject') {
subject = trim(elvalue);
} else if(el.name == 'message') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
elvalue = html2bbcode(editdoc.body.innerHTML);
}
message = trim(elvalue);
}
if((el.type == 'checkbox' || el.type == 'radio') && !el.checked) {
continue;
} else if(el.tagName == 'SELECT') {
elvalue = el.value;
} else if(el.type == 'hidden') {
if(el.id) {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
elvalue = elvalue;
if($(el.id + '_url')) {
elvalue += String.fromCharCode(1) + $(el.id + '_url').value;
}
} else {
continue;
}
} else {
continue;
}
}
if(trim(elvalue)) {
data += el.name + String.fromCharCode(9) + el.tagName + String.fromCharCode(9) + el.type + String.fromCharCode(9) + elvalue + String.fromCharCode(9, 9);
}
}
}
if(!subject && !message && !ignoreempty) {
return;
}
saveUserdata('forum_'+discuz_uid, data);
}
function fastUload() {
appendscript(JSPATH + 'forum_post.js?' + VERHASH);
safescript('forum_post_js', function () { uploadWindow(function (aid, url) {updatefastpostattach(aid, url)}, 'file') }, 100, 50);
}
function switchAdvanceMode(url) {
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : $('fastpostform');
if(obj && obj.message.value != '') {
saveData();
url += (url.indexOf('?') != -1 ? '&' : '?') + 'cedit=yes';
}
location.href = url;
return false;
}
function sidebar_collapse(lang) {
if(lang[0]) {
toggle_collapse('sidebar', null, null, lang);
$('wrap').className = $('wrap').className == 'wrap with_side s_clear' ? 'wrap s_clear' : 'wrap with_side s_clear';
} else {
var collapsed = getcookie('collapse');
collapsed = updatestring(collapsed, 'sidebar', 1);
setcookie('collapse', collapsed, (collapsed ? 2592000 : -2592000));
location.reload();
}
}
function keyPageScroll(e, prev, next, url, page) {
if(loadUserdata('is_blindman')) {
return true;
}
e = e ? e : window.event;
var tagname = BROWSER.ie ? e.srcElement.tagName : e.target.tagName;
if(tagname == 'INPUT' || tagname == 'TEXTAREA') return;
actualCode = e.keyCode ? e.keyCode : e.charCode;
if(next && actualCode == 39) {
window.location = url + '&page=' + (page + 1);
}
if(prev && actualCode == 37) {
window.location = url + '&page=' + (page - 1);
}
}
function announcement() {
var ann = new Object();
ann.anndelay = 3000;ann.annst = 0;ann.annstop = 0;ann.annrowcount = 0;ann.anncount = 0;ann.annlis = $('anc').getElementsByTagName("li");ann.annrows = new Array();
ann.announcementScroll = function () {
if(this.annstop) {this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);return;}
if(!this.annst) {
var lasttop = -1;
for(i = 0;i < this.annlis.length;i++) {
if(lasttop != this.annlis[i].offsetTop) {
if(lasttop == -1) lasttop = 0;
this.annrows[this.annrowcount] = this.annlis[i].offsetTop - lasttop;this.annrowcount++;
}
lasttop = this.annlis[i].offsetTop;
}
if(this.annrows.length == 1) {
$('an').onmouseover = $('an').onmouseout = null;
} else {
this.annrows[this.annrowcount] = this.annrows[1];
$('ancl').innerHTML += $('ancl').innerHTML;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
$('an').onmouseover = function () {ann.annstop = 1;};
$('an').onmouseout = function () {ann.annstop = 0;};
}
this.annrowcount = 1;
return;
}
if(this.annrowcount >= this.annrows.length) {
$('anc').scrollTop = 0;
this.annrowcount = 1;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
} else {
this.anncount = 0;
this.announcementScrollnext(this.annrows[this.annrowcount]);
}
};
ann.announcementScrollnext = function (time) {
$('anc').scrollTop++;
this.anncount++;
if(this.anncount != time) {
this.annst = setTimeout(function () {ann.announcementScrollnext(time);}, 10);
} else {
this.annrowcount++;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
}
};
ann.announcementScroll();
}
function removeindexheats() {
return confirm('You to confirm that this topic should remove it from the hot topic?');
}
function showTypes(id, mod) {
var o = $(id);
if(!o) return false;
var s = o.className;
mod = isUndefined(mod) ? 1 : mod;
var baseh = o.getElementsByTagName('li')[0].offsetHeight * 2;
var tmph = o.offsetHeight;
var lang = ['Expansion', 'Collapse'];
var cls = ['unfold', 'fold'];
if(tmph > baseh) {
var octrl = document.createElement('li');
octrl.className = cls[mod];
octrl.innerHTML = lang[mod];
o.insertBefore(octrl, o.firstChild);
o.className = s + ' cttp';
mod && (o.style.height = 'auto');
octrl.onclick = function () {
if(this.className == cls[0]) {
o.style.height = 'auto';
this.className = cls[1];
this.innerHTML = lang[1];
} else {
o.style.height = '';
this.className = cls[0];
this.innerHTML = lang[0];
}
}
}
}
var postpt = 0;
function fastpostvalidate(theform, noajaxpost) {
if(postpt) {
return false;
}
postpt = 1;
setTimeout(function() {postpt = 0}, 2000);
noajaxpost = !noajaxpost ? 0 : noajaxpost;
s = '';
if(typeof fastpostvalidateextra == 'function') {
var v = fastpostvalidateextra();
if(!v) {
return false;
}
}
if(theform.message.value == '' || theform.subject.value == '') {
s = 'Sorry, you can not enter a title or content';
theform.message.focus();
} else if(mb_strlen(theform.subject.value) > 80) {
s = 'Your title is longer than 80 characters limit';
theform.subject.focus();
}
if(!disablepostctrl && ((postminchars != 0 && mb_strlen(theform.message.value) < postminchars) || (postmaxchars != 0 && mb_strlen(theform.message.value) > postmaxchars))) {
s = 'Not meet the requirements of the length of your posts.\n\nCurrent length: ' + mb_strlen(theform.message.value) + ' ' + 'Byte\nSystem limits: ' + postminchars + ' to ' + postmaxchars + ' Byte';
}
if(s) {
showError(s);
doane();
$('fastpostsubmit').disabled = false;
return false;
}
$('fastpostsubmit').disabled = true;
theform.message.value = theform.message.value.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, '$1[img]$2[/img]');
theform.message.value = parseurl(theform.message.value);
if(!noajaxpost) {
ajaxpost('fastpostform', 'fastpostreturn', 'fastpostreturn', 'onerror', $('fastpostsubmit'));
return false;
} else {
return true;
}
}
function updatefastpostattach(aid, url) {
ajaxget('forum.php?mod=ajax&action=attachlist&posttime=' + $('posttime').value + (!fid ? '' : '&fid=' + fid), 'attachlist');
$('attach_tblheader').style.display = '';
}
function succeedhandle_fastnewpost(locationhref, message, param) {
location.href = locationhref;
}
function errorhandle_fastnewpost() {
$('fastpostsubmit').disabled = false;
}
function atarget(obj) {
obj.target = getcookie('atarget') > 0 ? '_blank' : '';
}
function setatarget(v) {
$('atarget').className = 'y atarget_' + v;
$('atarget').onclick = function() {setatarget(v == 1 ? -1 : 1);};
setcookie('atarget', v, 2592000);
}
function loadData(quiet, formobj) {
var evalevent = function (obj) {
var script = obj.parentNode.innerHTML;
var re = /onclick="(.+?)["|>]/ig;
var matches = re.exec(script);
if(matches != null) {
matches[1] = matches[1].replace(/this\./ig, 'obj.');
eval(matches[1]);
}
};
var data = '';
data = loadUserdata('forum_'+discuz_uid);
var formobj = !formobj ? $('postform') : formobj;
if(in_array((data = trim(data)), ['', 'null', 'false', null, false])) {
if(!quiet) {
showDialog('No data can be restored!', 'info');
}
return;
}
if(!quiet && !confirm('This action will overwrite the current content of the post, You sure you want to recover data?')) {
return;
}
var data = data.split(/\x09\x09/);
for(var i = 0; i < formobj.elements.length; i++) {
var el = formobj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden'))) {
for(var j = 0; j < data.length; j++) {
var ele = data[j].split(/\x09/);
if(ele[0] == el.name) {
elvalue = !isUndefined(ele[3]) ? ele[3] : '';
if(ele[1] == 'INPUT') {
if(ele[2] == 'text') {
el.value = elvalue;
} else if((ele[2] == 'checkbox' || ele[2] == 'radio') && ele[3] == el.value) {
el.checked = true;
evalevent(el);
} else if(ele[2] == 'hidden') {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
var v = elvalue.split(/\x01/);
el.value = v[0];
if(el.value) {
if($(el.id + '_url') && v[1]) {
$(el.id + '_url').value = v[1];
}
eval(el.id + '_upload(\'' + v[0] + '\', \'' + v[1] + '\')');
if($('unused' + v[0])) {
var attachtype = $('unused' + v[0]).parentNode.parentNode.parentNode.parentNode.id.substr(11);
$('unused' + v[0]).parentNode.parentNode.outerHTML = '';
$('unusednum_' + attachtype).innerHTML = parseInt($('unusednum_' + attachtype).innerHTML) - 1;
if($('unusednum_' + attachtype).innerHTML == 0 && $('attachnotice_' + attachtype)) {
$('attachnotice_' + attachtype).style.display = 'none';
}
}
}
}
}
} else if(ele[1] == 'TEXTAREA') {
if(ele[0] == 'message') {
if(!wysiwyg) {
textobj.value = elvalue;
} else {
editdoc.body.innerHTML = bbcode2html(elvalue);
}
} else {
el.value = elvalue;
}
} else if(ele[1] == 'SELECT') {
if($(el.id + '_ctrl_menu')) {
var lis = $(el.id + '_ctrl_menu').getElementsByTagName('li');
for(var k = 0; k < lis.length; k++) {
if(ele[3] == lis[k].k_value) {
lis[k].onclick();
break;
}
}
} else {
for(var k = 0; k < el.options.length; k++) {
if(ele[3] == el.options[k].value) {
el.options[k].selected = true;
break;
}
}
}
}
break;
}
}
}
}
if($('rstnotice')) {
$('rstnotice').style.display = 'none';
}
extraCheckall();
}
var checkForumcount = 0, checkForumtimeout = 30000, checkForumnew_handle;
function checkForumnew(fid, lasttime) {
var timeout = checkForumtimeout;
var x = new Ajax();
x.get('forum.php?mod=ajax&action=forumchecknew&fid=' + fid + '&time=' + lasttime + '&inajax=yes', function(s){
if(s > 0) {
var table = $('separatorline').parentNode;
if(!isUndefined(checkForumnew_handle)) {
clearTimeout(checkForumnew_handle);
}
removetbodyrow(table, 'forumnewshow');
var colspan = table.getElementsByTagName('tbody')[0].rows[0].children.length;
var checknew = {'tid':'', 'thread':{'common':{'className':'', 'val':'<a href="javascript:void(0);" onclick="ajaxget(\'forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=1&inajax=yes\', \'forumnew\');">New topic Reply, Click to view', 'colspan': colspan }}};
addtbodyrow(table, ['tbody'], ['forumnewshow'], 'separatorline', checknew);
} else {
if(checkForumcount < 50) {
if(checkForumcount > 0) {
var multiple = Math.ceil(50 / checkForumcount);
if(multiple < 5) {
timeout = checkForumtimeout * (5 - multiple + 1);
}
}
checkForumnew_handle = setTimeout(function () {checkForumnew(fid, lasttime);}, timeout);
}
}
checkForumcount++;
});
}
function checkForumnew_btn(fid) {
if(isUndefined(fid)) return;
ajaxget('forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=2&inajax=yes', 'forumnew', 'ajaxwaitid');
lasttime = parseInt(Date.parse(new Date()) / 1000);
}
function addtbodyrow (table, insertID, changename, separatorid, jsonval) {
if(isUndefined(table) || isUndefined(insertID[0])) {
return;
}
var insertobj = document.createElement(insertID[0]);
var thread = jsonval.thread;
var tid = !isUndefined(jsonval.tid) ? jsonval.tid : '' ;
if(!isUndefined(changename[1])) {
removetbodyrow(table, changename[1] + tid);
}
insertobj.id = changename[0] + tid;
if(!isUndefined(insertID[1])) {
insertobj.className = insertID[1];
}
if($(separatorid)) {
table.insertBefore(insertobj, $(separatorid).nextSibling);
} else {
table.insertBefore(insertobj, table.firstChild);
}
var newTH = insertobj.insertRow(-1);
for(var value in thread) {
if(value != 0) {
var cell = newTH.insertCell(-1);
if(isUndefined(thread[value]['val'])) {
cell.innerHTML = thread[value];
} else {
cell.innerHTML = thread[value]['val'];
}
if(!isUndefined(thread[value]['className'])) {
cell.className = thread[value]['className'];
}
if(!isUndefined(thread[value]['colspan'])) {
cell.colSpan = thread[value]['colspan'];
}
}
}
if(!isUndefined(insertID[2])) |
}
function removetbodyrow(from, objid) {
if(!isUndefined(from) && $(objid)) {
from.removeChild($(objid));
}
}
function leftside(id) {
$(id).className = $(id).className == 'a' ? '' : 'a';
if(id == 'lf_fav') {
setcookie('leftsidefav', $(id).className == 'a' ? 0 : 1, 2592000);
}
}
var DTimers = new Array();
var DItemIDs = new Array();
var DTimers_exists = false;
function settimer(timer, itemid) {
if(timer && itemid) {
DTimers.push(timer);
DItemIDs.push(itemid);
}
if(!DTimers_exists) {
setTimeout("showtime()", 1000);
DTimers_exists = true;
}
}
function showtime() {
for(i=0; i<=DTimers.length; i++) {
if(DItemIDs[i]) {
if(DTimers[i] == 0) {
$(DItemIDs[i]).innerHTML = 'Has ended';
DItemIDs[i] = '';
continue;
}
var timestr = '';
var timer_day = Math.floor(DTimers[i] / 86400);
var timer_hour = Math.floor((DTimers[i] % 86400) / 3600);
var timer_minute = Math.floor(((DTimers[i] % 86400) % 3600) / 60);
var timer_second = (((DTimers[i] % 86400) % 3600) % 60);
if(timer_day > 0) {
timestr += timer_day + 'Day';
}
if(timer_hour > 0) {
timestr += timer_hour + 'Hour'
}
if(timer_minute > 0) {
timestr += timer_minute + 'Min.'
}
if(timer_second > 0) {
timestr += timer_second + 'Sec.'
}
DTimers[i] = DTimers[i] - 1;
$(DItemIDs[i]).innerHTML = timestr;
}
}
setTimeout("showtime()", 1000);
}
function fixed_top_nv(eleid, disbind) {
this.nv = eleid && $(eleid) || $('nv');
this.openflag = this.nv && BROWSER.ie != 6;
this.nvdata = {};
this.init = function (disattachevent) {
if(this.openflag) {
if(!disattachevent) {
var obj = this;
_attachEvent(window, 'resize', function(){obj.reset();obj.init(1);obj.run();});
var switchwidth = $('switchwidth');
if(switchwidth) {
_attachEvent(switchwidth, 'click', function(){obj.reset();obj.openflag=false;});
}
}
var next = this.nv;
try {
while((next = next.nextSibling).nodeType != 1 || next.style.display === 'none') {}
this.nvdata.next = next;
this.nvdata.height = parseInt(this.nv.offsetHeight, 10);
this.nvdata.width = parseInt(this.nv.offsetWidth, 10);
this.nvdata.left = this.nv.getBoundingClientRect().left - document.documentElement.clientLeft;
this.nvdata.position = this.nv.style.position;
this.nvdata.opacity = this.nv.style.opacity;
} catch (e) {
this.nvdata.next = null;
}
}
};
this.run = function () {
var fixedheight = 0;
if(this.openflag && this.nvdata.next){
var nvnexttop = document.body.scrollTop || document.documentElement.scrollTop;
var dofixed = nvnexttop !== 0 && document.documentElement.clientHeight >= 15 && this.nvdata.next.getBoundingClientRect().top - this.nvdata.height < 0;
if(dofixed) {
if(this.nv.style.position != 'fixed') {
this.nv.style.borderLeftWidth = '0';
this.nv.style.borderRightWidth = '0';
this.nv.style.height = this.nvdata.height + 'px';
this.nv.style.width = this.nvdata.width + 'px';
this.nv.style.top = '0';
this.nv.style.left = this.nvdata.left + 'px';
this.nv.style.position = 'fixed';
this.nv.style.zIndex = '199';
this.nv.style.opacity = 0.85;
}
} else {
if(this.nv.style.position != this.nvdata.position) {
this.reset();
}
}
if(this.nv.style.position == 'fixed') {
fixedheight = this.nvdata.height;
}
}
return fixedheight;
};
this.reset = function () {
if(this.nv) {
this.nv.style.position = this.nvdata.position;
this.nv.style.borderLeftWidth = '';
this.nv.style.borderRightWidth = '';
this.nv.style.height = '';
this.nv.style.width = '';
this.nv.style.opacity = this.nvdata.opacity;
}
};
if(!disbind && this.openflag) {
this.init();
_attachEvent(window, 'scroll', this.run);
}
}
var previewTbody = null, previewTid = null, previewDiv = null;
function previewThread(tid, tbody) {
if(!$('threadPreviewTR_'+tid)) {
appendscript(JSPATH + 'forum_viewthread.js?' + VERHASH);
newTr = document.createElement('tr');
newTr.id = 'threadPreviewTR_'+tid;
newTr.className = 'threadpre';
$(tbody).appendChild(newTr);
newTd = document.createElement('td');
newTd.colSpan = listcolspan;
newTd.className = 'threadpretd';
newTr.appendChild(newTd);
newTr.style.display = 'none';
previewTbody = tbody;
previewTid = tid;
if(BROWSER.ie) {
previewDiv = document.createElement('div');
previewDiv.id = 'threadPreview_'+tid;
previewDiv.style.id = 'none';
var x = Ajax();
x.get('forum.php?mod=viewthread&tid='+tid+'&inajax=1&from=preview', function(ret) {
var evaled = false;
if(ret.indexOf('ajaxerror') != -1) {
evalscript(ret);
evaled = true;
}
previewDiv.innerHTML = ret;
newTd.appendChild(previewDiv);
if(!evaled) evalscript(ret);
newTr.style.display = '';
});
} else {
newTd.innerHTML += '<div id="threadPreview_'+tid+'"></div>';
ajaxget('forum.php?mod=viewthread&tid='+tid+'&from=preview', 'threadPreview_'+tid, null, null, null, function() {newTr.style.display = '';});
}
} else {
$(tbody).removeChild($('threadPreviewTR_'+tid));
previewTbody = previewTid = null;
}
}
function hideStickThread(tid) {
var pre = 'stickthread_';
var tids = (new Function("return ("+(loadUserdata('sticktids') || '[]')+")"))();
var format = function (data) {
var str = '{';
for (var i in data) {
if(data[i] instanceof Array) {
str += i + ':' + '[';
for (var j = data[i].length - 1; j >= 0; j--) {
str += data[i][j] + ',';
};
str = str.substr(0, str.length -1);
str += '],';
}
}
str = str.substr(0, str.length -1);
str += '}';
return str;
};
if(!tid) {
if(tids.length > 0) {
for (var i = tids.length - 1; i >= 0; i--) {
var ele = $(pre+tids[i]);
if(ele) {
ele.parentNode.removeChild(ele);
}
};
}
} else {
var eletbody = $(pre+tid);
if(eletbody) {
eletbody.parentNode.removeChild(eletbody);
tids.push(tid);
saveUserdata('sticktids', '['+tids.join(',')+']');
}
}
var clearstickthread = $('clearstickthread');
if(clearstickthread) {
if(tids.length > 0) {
$('clearstickthread').style.display = '';
} else {
$('clearstickthread').style.display = 'none';
}
}
var separatorline = $('separatorline');
if(separatorline) {
try {
if(typeof separatorline.previousElementSibling === 'undefined') {
var findele = separatorline.previousSibling;
while(findele && findele.nodeType != 1){
findele = findele.previousSibling;
}
if(findele === null) {
separatorline.parentNode.removeChild(separatorline);
}
} else {
if(separatorline.previousElementSibling === null) {
separatorline.parentNode.removeChild(separatorline);
}
}
} catch(e) {
}
}
}
function viewhot() {
var obj = $('hottime');
window.location.href = "forum.php?mod=forumdisplay&filter=hot&fid="+obj.getAttribute('fid')+"&time="+obj.value;
}
function clearStickThread () {
saveUserdata('sticktids', '[]');
location.reload();
} | {
_attachEvent(insertobj, insertID[2], function() {insertobj.className = '';});
} | conditional_block |
play-circle-outline.js | 'use strict';
var React = require('react/addons');
var PureRenderMixin = React.addons.PureRenderMixin;
var SvgIcon = require('../../svg-icon');
| render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M10 16.5l6-4.5-6-4.5v9zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z' })
);
}
});
module.exports = AvPlayCircleOutline; | var AvPlayCircleOutline = React.createClass({
displayName: 'AvPlayCircleOutline',
mixins: [PureRenderMixin],
| random_line_split |
issue-19340-1.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unused_variables)] | // pretty-expanded FIXME #23616
extern crate issue_19340_1 as lib;
use lib::Homura;
fn main() {
let homura = Homura::Madoka { name: "Kaname".to_string() };
match homura {
Homura::Madoka { name } => (),
};
} | // aux-build:issue-19340-1.rs
| random_line_split |
issue-19340-1.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unused_variables)]
// aux-build:issue-19340-1.rs
// pretty-expanded FIXME #23616
extern crate issue_19340_1 as lib;
use lib::Homura;
fn main() | {
let homura = Homura::Madoka { name: "Kaname".to_string() };
match homura {
Homura::Madoka { name } => (),
};
} | identifier_body |
|
issue-19340-1.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unused_variables)]
// aux-build:issue-19340-1.rs
// pretty-expanded FIXME #23616
extern crate issue_19340_1 as lib;
use lib::Homura;
fn | () {
let homura = Homura::Madoka { name: "Kaname".to_string() };
match homura {
Homura::Madoka { name } => (),
};
}
| main | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
| dependencies = [
]
operations = [
migrations.CreateModel(
name='BTBeacon',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('label', models.CharField(max_length=255)),
('uuid', models.UUIDField(unique=True, max_length=32)),
('rssi_in', models.IntegerField()),
('rssi_out', models.IntegerField()),
],
),
migrations.CreateModel(
name='Website',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title_fr', models.CharField(max_length=255)),
('title_en', models.CharField(max_length=255)),
('language', models.CharField(max_length=2, choices=[(b'FR', b'French'), (b'EN', b'English')])),
('url', models.URLField()),
],
),
] | identifier_body |
|
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class | (migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='BTBeacon',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('label', models.CharField(max_length=255)),
('uuid', models.UUIDField(unique=True, max_length=32)),
('rssi_in', models.IntegerField()),
('rssi_out', models.IntegerField()),
],
),
migrations.CreateModel(
name='Website',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title_fr', models.CharField(max_length=255)),
('title_en', models.CharField(max_length=255)),
('language', models.CharField(max_length=2, choices=[(b'FR', b'French'), (b'EN', b'English')])),
('url', models.URLField()),
],
),
]
| Migration | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='BTBeacon',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('label', models.CharField(max_length=255)),
('uuid', models.UUIDField(unique=True, max_length=32)),
('rssi_in', models.IntegerField()),
('rssi_out', models.IntegerField()), | ],
),
migrations.CreateModel(
name='Website',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title_fr', models.CharField(max_length=255)),
('title_en', models.CharField(max_length=255)),
('language', models.CharField(max_length=2, choices=[(b'FR', b'French'), (b'EN', b'English')])),
('url', models.URLField()),
],
),
] | random_line_split |
|
contributor_orcid.py | # coding: utf-8
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class ContributorOrcid(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, uri=None, path=None, host=None):
"""
ContributorOrcid - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'uri': 'str',
'path': 'str',
'host': 'str'
}
self.attribute_map = {
'uri': 'uri',
'path': 'path',
'host': 'host'
}
self._uri = uri
self._path = path
self._host = host
@property
def uri(self):
"""
Gets the uri of this ContributorOrcid.
:return: The uri of this ContributorOrcid.
:rtype: str
"""
return self._uri
@uri.setter
def uri(self, uri):
"""
Sets the uri of this ContributorOrcid.
:param uri: The uri of this ContributorOrcid.
:type: str
"""
self._uri = uri
@property
def path(self):
"""
Gets the path of this ContributorOrcid.
:return: The path of this ContributorOrcid.
:rtype: str
"""
return self._path
@path.setter
def path(self, path):
"""
Sets the path of this ContributorOrcid.
:param path: The path of this ContributorOrcid.
:type: str
"""
self._path = path
@property
def host(self):
"""
Gets the host of this ContributorOrcid.
:return: The host of this ContributorOrcid.
:rtype: str
"""
return self._host
@host.setter
def host(self, host):
"""
Sets the host of this ContributorOrcid.
:param host: The host of this ContributorOrcid.
:type: str
"""
self._host = host
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, ContributorOrcid):
|
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| return False | conditional_block |
contributor_orcid.py | # coding: utf-8
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class ContributorOrcid(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, uri=None, path=None, host=None):
"""
ContributorOrcid - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'uri': 'str',
'path': 'str',
'host': 'str'
}
self.attribute_map = {
'uri': 'uri',
'path': 'path',
'host': 'host'
}
self._uri = uri
self._path = path
self._host = host
@property
def uri(self):
"""
Gets the uri of this ContributorOrcid.
:return: The uri of this ContributorOrcid.
:rtype: str
"""
return self._uri
@uri.setter
def uri(self, uri):
"""
Sets the uri of this ContributorOrcid.
:param uri: The uri of this ContributorOrcid.
:type: str
"""
self._uri = uri
@property
def path(self):
"""
Gets the path of this ContributorOrcid.
:return: The path of this ContributorOrcid.
:rtype: str
"""
return self._path
@path.setter
def path(self, path):
"""
Sets the path of this ContributorOrcid.
:param path: The path of this ContributorOrcid.
:type: str
"""
self._path = path
@property
def host(self):
"""
Gets the host of this ContributorOrcid.
:return: The host of this ContributorOrcid.
:rtype: str
"""
return self._host
@host.setter
def host(self, host):
"""
Sets the host of this ContributorOrcid.
:param host: The host of this ContributorOrcid.
:type: str
"""
self._host = host
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, ContributorOrcid):
return False
return self.__dict__ == other.__dict__
def | (self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| __ne__ | identifier_name |
contributor_orcid.py | # coding: utf-8
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class ContributorOrcid(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, uri=None, path=None, host=None):
"""
ContributorOrcid - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'uri': 'str',
'path': 'str',
'host': 'str'
}
self.attribute_map = {
'uri': 'uri',
'path': 'path',
'host': 'host'
}
self._uri = uri
self._path = path
self._host = host
@property
def uri(self):
"""
Gets the uri of this ContributorOrcid.
:return: The uri of this ContributorOrcid.
:rtype: str
"""
return self._uri
@uri.setter
def uri(self, uri):
"""
Sets the uri of this ContributorOrcid.
:param uri: The uri of this ContributorOrcid.
:type: str
"""
self._uri = uri
@property
def path(self):
"""
Gets the path of this ContributorOrcid.
:return: The path of this ContributorOrcid.
:rtype: str
"""
return self._path
@path.setter
def path(self, path):
"""
Sets the path of this ContributorOrcid.
:param path: The path of this ContributorOrcid.
:type: str
"""
self._path = path
@property
def host(self):
"""
Gets the host of this ContributorOrcid.
:return: The host of this ContributorOrcid.
:rtype: str
"""
return self._host
@host.setter
def host(self, host):
|
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, ContributorOrcid):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| """
Sets the host of this ContributorOrcid.
:param host: The host of this ContributorOrcid.
:type: str
"""
self._host = host | identifier_body |
contributor_orcid.py | # coding: utf-8
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class ContributorOrcid(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, uri=None, path=None, host=None):
"""
ContributorOrcid - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'uri': 'str',
'path': 'str',
'host': 'str'
}
self.attribute_map = {
'uri': 'uri',
'path': 'path',
'host': 'host'
}
self._uri = uri
self._path = path
self._host = host
@property
def uri(self):
"""
Gets the uri of this ContributorOrcid.
:return: The uri of this ContributorOrcid.
:rtype: str
"""
return self._uri
@uri.setter
def uri(self, uri):
"""
Sets the uri of this ContributorOrcid.
:param uri: The uri of this ContributorOrcid.
:type: str
"""
self._uri = uri
@property
def path(self):
"""
Gets the path of this ContributorOrcid.
:return: The path of this ContributorOrcid.
:rtype: str
"""
return self._path
@path.setter
def path(self, path):
"""
Sets the path of this ContributorOrcid.
:param path: The path of this ContributorOrcid.
:type: str
"""
self._path = path
@property
def host(self):
"""
Gets the host of this ContributorOrcid.
:return: The host of this ContributorOrcid.
:rtype: str
"""
return self._host | def host(self, host):
"""
Sets the host of this ContributorOrcid.
:param host: The host of this ContributorOrcid.
:type: str
"""
self._host = host
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, ContributorOrcid):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other |
@host.setter | random_line_split |
run_tests.py | #!/usr/bin/env python
# Copyright 2013-present Barefoot Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at | #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
from subprocess import Popen
root_dir = os.path.dirname(os.path.realpath(__file__))
pd_dir = os.path.join(root_dir, 'of-tests/pd_thrift')
oft_path = os.path.join(root_dir, '..', '..', 'submodules', 'oft-infra', 'oft')
if __name__ == "__main__":
args = sys.argv[1:]
args += ["--pd-thrift-path", pd_dir]
args += ["--enable-erspan", "--enable-vxlan", "--enable-geneve", "--enable-nvgre", "--enable-mpls"]
child = Popen([oft_path] + args)
child.wait()
sys.exit(child.returncode) | random_line_split |
|
run_tests.py | #!/usr/bin/env python
# Copyright 2013-present Barefoot Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
from subprocess import Popen
root_dir = os.path.dirname(os.path.realpath(__file__))
pd_dir = os.path.join(root_dir, 'of-tests/pd_thrift')
oft_path = os.path.join(root_dir, '..', '..', 'submodules', 'oft-infra', 'oft')
if __name__ == "__main__":
| args = sys.argv[1:]
args += ["--pd-thrift-path", pd_dir]
args += ["--enable-erspan", "--enable-vxlan", "--enable-geneve", "--enable-nvgre", "--enable-mpls"]
child = Popen([oft_path] + args)
child.wait()
sys.exit(child.returncode) | conditional_block |
|
element_wrapper.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/. */
//! A wrapper over an element and a snapshot, that allows us to selector-match
//! against a past state of the element.
use {Atom, CaseSensitivityExt, LocalName, Namespace, WeakAtom};
use dom::TElement;
use element_state::ElementState;
use selector_parser::{NonTSPseudoClass, PseudoElement, SelectorImpl, Snapshot, SnapshotMap, AttrValue};
use selectors::{Element, OpaqueElement};
use selectors::attr::{AttrSelectorOperation, CaseSensitivity, NamespaceConstraint};
use selectors::matching::{ElementSelectorFlags, MatchingContext};
use std::cell::Cell;
use std::fmt;
/// In order to compute restyle hints, we perform a selector match against a
/// list of partial selectors whose rightmost simple selector may be sensitive
/// to the thing being changed. We do this matching twice, once for the element
/// as it exists now and once for the element as it existed at the time of the
/// last restyle. If the results of the selector match differ, that means that
/// the given partial selector is sensitive to the change, and we compute a
/// restyle hint based on its combinator.
///
/// In order to run selector matching against the old element state, we generate
/// a wrapper for the element which claims to have the old state. This is the
/// ElementWrapper logic below.
///
/// Gecko does this differently for element states, and passes a mask called
/// mStateMask, which indicates the states that need to be ignored during
/// selector matching. This saves an ElementWrapper allocation and an additional
/// selector match call at the expense of additional complexity inside the
/// selector matching logic. This only works for boolean states though, so we
/// still need to take the ElementWrapper approach for attribute-dependent
/// style. So we do it the same both ways for now to reduce complexity, but it's
/// worth measuring the performance impact (if any) of the mStateMask approach.
pub trait ElementSnapshot : Sized {
/// The state of the snapshot, if any.
fn state(&self) -> Option<ElementState>;
/// If this snapshot contains attribute information.
fn has_attrs(&self) -> bool;
/// The ID attribute per this snapshot. Should only be called if
/// `has_attrs()` returns true.
fn id_attr(&self) -> Option<&WeakAtom>;
/// Whether this snapshot contains the class `name`. Should only be called
/// if `has_attrs()` returns true.
fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool;
/// A callback that should be called for each class of the snapshot. Should
/// only be called if `has_attrs()` returns true.
fn each_class<F>(&self, F)
where
F: FnMut(&Atom);
/// The `xml:lang=""` or `lang=""` attribute value per this snapshot.
fn lang_attr(&self) -> Option<AttrValue>;
}
/// A simple wrapper over an element and a snapshot, that allows us to
/// selector-match against a past state of the element.
#[derive(Clone)]
pub struct ElementWrapper<'a, E>
where
E: TElement,
{
element: E,
cached_snapshot: Cell<Option<&'a Snapshot>>,
snapshot_map: &'a SnapshotMap,
}
impl<'a, E> ElementWrapper<'a, E>
where
E: TElement,
{
/// Trivially constructs an `ElementWrapper`.
pub fn new(el: E, snapshot_map: &'a SnapshotMap) -> Self {
ElementWrapper {
element: el,
cached_snapshot: Cell::new(None),
snapshot_map: snapshot_map,
}
}
/// Gets the snapshot associated with this element, if any.
pub fn snapshot(&self) -> Option<&'a Snapshot> {
if !self.element.has_snapshot() {
return None;
}
if let Some(s) = self.cached_snapshot.get() {
return Some(s);
}
let snapshot = self.snapshot_map.get(&self.element);
debug_assert!(snapshot.is_some(), "has_snapshot lied!");
self.cached_snapshot.set(snapshot);
snapshot
}
/// Returns the states that have changed since the element was snapshotted.
pub fn state_changes(&self) -> ElementState {
let snapshot = match self.snapshot() {
Some(s) => s,
None => return ElementState::empty(),
};
match snapshot.state() {
Some(state) => state ^ self.element.state(),
None => ElementState::empty(),
}
}
/// Returns the value of the `xml:lang=""` (or, if appropriate, `lang=""`)
/// attribute from this element's snapshot or the closest ancestor
/// element snapshot with the attribute specified.
fn get_lang(&self) -> Option<AttrValue> {
let mut current = self.clone();
loop {
let lang = match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => snapshot.lang_attr(),
_ => current.element.lang_attr(),
};
if lang.is_some() {
return lang;
}
current = current.parent_element()?;
}
}
}
impl<'a, E> fmt::Debug for ElementWrapper<'a, E>
where
E: TElement,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Ignore other fields for now, can change later if needed.
self.element.fmt(f)
}
}
impl<'a, E> Element for ElementWrapper<'a, E>
where
E: TElement,
{
type Impl = SelectorImpl;
fn match_non_ts_pseudo_class<F>(
&self,
pseudo_class: &NonTSPseudoClass,
context: &mut MatchingContext<Self::Impl>,
_setter: &mut F,
) -> bool
where
F: FnMut(&Self, ElementSelectorFlags),
{
// Some pseudo-classes need special handling to evaluate them against
// the snapshot.
match *pseudo_class {
#[cfg(feature = "gecko")]
NonTSPseudoClass::MozAny(ref selectors) => {
use selectors::matching::matches_complex_selector;
return context.nest(|context| {
selectors.iter().any(|s| {
matches_complex_selector(s.iter(), self, context, _setter)
})
});
}
// :dir is implemented in terms of state flags, but which state flag
// it maps to depends on the argument to :dir. That means we can't
// just add its state flags to the NonTSPseudoClass, because if we
// added all of them there, and tested via intersects() here, we'd
// get incorrect behavior for :not(:dir()) cases.
//
// FIXME(bz): How can I set this up so once Servo adds :dir()
// support we don't forget to update this code?
#[cfg(feature = "gecko")]
NonTSPseudoClass::Dir(ref dir) => {
use invalidation::element::invalidation_map::dir_selector_to_state;
let selector_flag = dir_selector_to_state(dir);
if selector_flag.is_empty() {
// :dir() with some random argument; does not match.
return false;
}
let state = match self.snapshot().and_then(|s| s.state()) {
Some(snapshot_state) => snapshot_state,
None => self.element.state(),
};
return state.contains(selector_flag);
}
// For :link and :visited, we don't actually want to test the
// element state directly.
//
// Instead, we use the `visited_handling` to determine if they
// match.
NonTSPseudoClass::Link => {
return self.is_link() && context.visited_handling().matches_unvisited()
}
NonTSPseudoClass::Visited => {
return self.is_link() && context.visited_handling().matches_visited()
}
#[cfg(feature = "gecko")]
NonTSPseudoClass::MozTableBorderNonzero => {
if let Some(snapshot) = self.snapshot() {
if snapshot.has_other_pseudo_class_state() {
return snapshot.mIsTableBorderNonzero();
}
}
}
#[cfg(feature = "gecko")]
NonTSPseudoClass::MozBrowserFrame => {
if let Some(snapshot) = self.snapshot() {
if snapshot.has_other_pseudo_class_state() {
return snapshot.mIsMozBrowserFrame();
}
}
}
// :lang() needs to match using the closest ancestor xml:lang="" or
// lang="" attribtue from snapshots.
NonTSPseudoClass::Lang(ref lang_arg) => {
return self.element.match_element_lang(Some(self.get_lang()), lang_arg);
}
_ => {}
}
let flag = pseudo_class.state_flag();
if flag.is_empty() {
return self.element.match_non_ts_pseudo_class(
pseudo_class,
context,
&mut |_, _| {},
)
}
match self.snapshot().and_then(|s| s.state()) {
Some(snapshot_state) => snapshot_state.intersects(flag),
None => {
self.element.match_non_ts_pseudo_class(
pseudo_class,
context,
&mut |_, _| {},
)
}
}
}
fn match_pseudo_element(
&self,
pseudo_element: &PseudoElement,
context: &mut MatchingContext<Self::Impl>,
) -> bool {
self.element.match_pseudo_element(pseudo_element, context)
}
fn is_link(&self) -> bool {
self.element.is_link()
}
fn opaque(&self) -> OpaqueElement {
self.element.opaque()
}
fn parent_element(&self) -> Option<Self> {
self.element.parent_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn first_child_element(&self) -> Option<Self> {
self.element.first_child_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn last_child_element(&self) -> Option<Self> {
self.element.last_child_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn prev_sibling_element(&self) -> Option<Self> |
fn next_sibling_element(&self) -> Option<Self> {
self.element.next_sibling_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
#[inline]
fn is_html_element_in_html_document(&self) -> bool {
self.element.is_html_element_in_html_document()
}
#[inline]
fn is_html_slot_element(&self) -> bool {
self.element.is_html_slot_element()
}
#[inline]
fn local_name(&self) -> &<Self::Impl as ::selectors::SelectorImpl>::BorrowedLocalName {
self.element.local_name()
}
#[inline]
fn namespace(&self) -> &<Self::Impl as ::selectors::SelectorImpl>::BorrowedNamespaceUrl {
self.element.namespace()
}
fn attr_matches(
&self,
ns: &NamespaceConstraint<&Namespace>,
local_name: &LocalName,
operation: &AttrSelectorOperation<&AttrValue>,
) -> bool {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => {
snapshot.attr_matches(ns, local_name, operation)
}
_ => self.element.attr_matches(ns, local_name, operation)
}
}
fn has_id(&self, id: &Atom, case_sensitivity: CaseSensitivity) -> bool {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => {
snapshot.id_attr().map_or(false, |atom| case_sensitivity.eq_atom(&atom, id))
}
_ => self.element.has_id(id, case_sensitivity)
}
}
fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => {
snapshot.has_class(name, case_sensitivity)
}
_ => self.element.has_class(name, case_sensitivity)
}
}
fn is_empty(&self) -> bool {
self.element.is_empty()
}
fn is_root(&self) -> bool {
self.element.is_root()
}
fn pseudo_element_originating_element(&self) -> Option<Self> {
self.element.pseudo_element_originating_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn assigned_slot(&self) -> Option<Self> {
self.element.assigned_slot()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn blocks_ancestor_combinators(&self) -> bool {
self.element.blocks_ancestor_combinators()
}
}
| {
self.element.prev_sibling_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
} | identifier_body |
element_wrapper.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/. */
//! A wrapper over an element and a snapshot, that allows us to selector-match
//! against a past state of the element.
use {Atom, CaseSensitivityExt, LocalName, Namespace, WeakAtom};
use dom::TElement;
use element_state::ElementState;
use selector_parser::{NonTSPseudoClass, PseudoElement, SelectorImpl, Snapshot, SnapshotMap, AttrValue};
use selectors::{Element, OpaqueElement};
use selectors::attr::{AttrSelectorOperation, CaseSensitivity, NamespaceConstraint};
use selectors::matching::{ElementSelectorFlags, MatchingContext};
use std::cell::Cell;
use std::fmt;
/// In order to compute restyle hints, we perform a selector match against a
/// list of partial selectors whose rightmost simple selector may be sensitive
/// to the thing being changed. We do this matching twice, once for the element
/// as it exists now and once for the element as it existed at the time of the
/// last restyle. If the results of the selector match differ, that means that
/// the given partial selector is sensitive to the change, and we compute a
/// restyle hint based on its combinator.
///
/// In order to run selector matching against the old element state, we generate
/// a wrapper for the element which claims to have the old state. This is the
/// ElementWrapper logic below.
///
/// Gecko does this differently for element states, and passes a mask called
/// mStateMask, which indicates the states that need to be ignored during
/// selector matching. This saves an ElementWrapper allocation and an additional
/// selector match call at the expense of additional complexity inside the
/// selector matching logic. This only works for boolean states though, so we
/// still need to take the ElementWrapper approach for attribute-dependent
/// style. So we do it the same both ways for now to reduce complexity, but it's
/// worth measuring the performance impact (if any) of the mStateMask approach.
pub trait ElementSnapshot : Sized {
/// The state of the snapshot, if any.
fn state(&self) -> Option<ElementState>;
/// If this snapshot contains attribute information.
fn has_attrs(&self) -> bool;
/// The ID attribute per this snapshot. Should only be called if
/// `has_attrs()` returns true.
fn id_attr(&self) -> Option<&WeakAtom>;
/// Whether this snapshot contains the class `name`. Should only be called
/// if `has_attrs()` returns true.
fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool;
/// A callback that should be called for each class of the snapshot. Should
/// only be called if `has_attrs()` returns true.
fn each_class<F>(&self, F)
where
F: FnMut(&Atom);
/// The `xml:lang=""` or `lang=""` attribute value per this snapshot.
fn lang_attr(&self) -> Option<AttrValue>;
}
/// A simple wrapper over an element and a snapshot, that allows us to
/// selector-match against a past state of the element.
#[derive(Clone)]
pub struct ElementWrapper<'a, E>
where
E: TElement,
{
element: E,
cached_snapshot: Cell<Option<&'a Snapshot>>,
snapshot_map: &'a SnapshotMap,
}
impl<'a, E> ElementWrapper<'a, E>
where
E: TElement,
{
/// Trivially constructs an `ElementWrapper`.
pub fn new(el: E, snapshot_map: &'a SnapshotMap) -> Self {
ElementWrapper {
element: el,
cached_snapshot: Cell::new(None),
snapshot_map: snapshot_map,
}
}
/// Gets the snapshot associated with this element, if any.
pub fn snapshot(&self) -> Option<&'a Snapshot> {
if !self.element.has_snapshot() {
return None;
}
if let Some(s) = self.cached_snapshot.get() {
return Some(s);
}
let snapshot = self.snapshot_map.get(&self.element);
debug_assert!(snapshot.is_some(), "has_snapshot lied!");
self.cached_snapshot.set(snapshot);
snapshot
}
/// Returns the states that have changed since the element was snapshotted.
pub fn state_changes(&self) -> ElementState {
let snapshot = match self.snapshot() {
Some(s) => s,
None => return ElementState::empty(),
};
match snapshot.state() {
Some(state) => state ^ self.element.state(),
None => ElementState::empty(),
}
}
/// Returns the value of the `xml:lang=""` (or, if appropriate, `lang=""`)
/// attribute from this element's snapshot or the closest ancestor
/// element snapshot with the attribute specified.
fn get_lang(&self) -> Option<AttrValue> {
let mut current = self.clone();
loop {
let lang = match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => snapshot.lang_attr(),
_ => current.element.lang_attr(),
};
if lang.is_some() {
return lang;
}
current = current.parent_element()?;
}
}
}
impl<'a, E> fmt::Debug for ElementWrapper<'a, E>
where
E: TElement,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Ignore other fields for now, can change later if needed.
self.element.fmt(f)
}
}
impl<'a, E> Element for ElementWrapper<'a, E>
where
E: TElement,
{
type Impl = SelectorImpl;
fn match_non_ts_pseudo_class<F>(
&self,
pseudo_class: &NonTSPseudoClass,
context: &mut MatchingContext<Self::Impl>,
_setter: &mut F,
) -> bool
where
F: FnMut(&Self, ElementSelectorFlags),
{
// Some pseudo-classes need special handling to evaluate them against
// the snapshot.
match *pseudo_class {
#[cfg(feature = "gecko")]
NonTSPseudoClass::MozAny(ref selectors) => {
use selectors::matching::matches_complex_selector;
return context.nest(|context| {
selectors.iter().any(|s| {
matches_complex_selector(s.iter(), self, context, _setter)
})
});
}
// :dir is implemented in terms of state flags, but which state flag
// it maps to depends on the argument to :dir. That means we can't
// just add its state flags to the NonTSPseudoClass, because if we
// added all of them there, and tested via intersects() here, we'd
// get incorrect behavior for :not(:dir()) cases.
//
// FIXME(bz): How can I set this up so once Servo adds :dir()
// support we don't forget to update this code?
#[cfg(feature = "gecko")]
NonTSPseudoClass::Dir(ref dir) => {
use invalidation::element::invalidation_map::dir_selector_to_state;
let selector_flag = dir_selector_to_state(dir);
if selector_flag.is_empty() {
// :dir() with some random argument; does not match.
return false;
}
let state = match self.snapshot().and_then(|s| s.state()) {
Some(snapshot_state) => snapshot_state,
None => self.element.state(),
};
return state.contains(selector_flag);
}
// For :link and :visited, we don't actually want to test the
// element state directly.
//
// Instead, we use the `visited_handling` to determine if they
// match.
NonTSPseudoClass::Link => {
return self.is_link() && context.visited_handling().matches_unvisited()
}
NonTSPseudoClass::Visited => {
return self.is_link() && context.visited_handling().matches_visited()
}
#[cfg(feature = "gecko")]
NonTSPseudoClass::MozTableBorderNonzero => {
if let Some(snapshot) = self.snapshot() {
if snapshot.has_other_pseudo_class_state() {
return snapshot.mIsTableBorderNonzero();
}
}
}
#[cfg(feature = "gecko")]
NonTSPseudoClass::MozBrowserFrame => {
if let Some(snapshot) = self.snapshot() {
if snapshot.has_other_pseudo_class_state() {
return snapshot.mIsMozBrowserFrame();
}
}
}
// :lang() needs to match using the closest ancestor xml:lang="" or
// lang="" attribtue from snapshots.
NonTSPseudoClass::Lang(ref lang_arg) => {
return self.element.match_element_lang(Some(self.get_lang()), lang_arg);
}
_ => {}
}
let flag = pseudo_class.state_flag();
if flag.is_empty() {
return self.element.match_non_ts_pseudo_class(
pseudo_class,
context,
&mut |_, _| {},
)
}
match self.snapshot().and_then(|s| s.state()) {
Some(snapshot_state) => snapshot_state.intersects(flag),
None => {
self.element.match_non_ts_pseudo_class(
pseudo_class,
context,
&mut |_, _| {},
)
}
}
}
fn match_pseudo_element(
&self,
pseudo_element: &PseudoElement,
context: &mut MatchingContext<Self::Impl>,
) -> bool {
self.element.match_pseudo_element(pseudo_element, context)
}
fn is_link(&self) -> bool {
self.element.is_link()
}
fn opaque(&self) -> OpaqueElement {
self.element.opaque()
}
fn parent_element(&self) -> Option<Self> {
self.element.parent_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn first_child_element(&self) -> Option<Self> {
self.element.first_child_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn | (&self) -> Option<Self> {
self.element.last_child_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn prev_sibling_element(&self) -> Option<Self> {
self.element.prev_sibling_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn next_sibling_element(&self) -> Option<Self> {
self.element.next_sibling_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
#[inline]
fn is_html_element_in_html_document(&self) -> bool {
self.element.is_html_element_in_html_document()
}
#[inline]
fn is_html_slot_element(&self) -> bool {
self.element.is_html_slot_element()
}
#[inline]
fn local_name(&self) -> &<Self::Impl as ::selectors::SelectorImpl>::BorrowedLocalName {
self.element.local_name()
}
#[inline]
fn namespace(&self) -> &<Self::Impl as ::selectors::SelectorImpl>::BorrowedNamespaceUrl {
self.element.namespace()
}
fn attr_matches(
&self,
ns: &NamespaceConstraint<&Namespace>,
local_name: &LocalName,
operation: &AttrSelectorOperation<&AttrValue>,
) -> bool {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => {
snapshot.attr_matches(ns, local_name, operation)
}
_ => self.element.attr_matches(ns, local_name, operation)
}
}
fn has_id(&self, id: &Atom, case_sensitivity: CaseSensitivity) -> bool {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => {
snapshot.id_attr().map_or(false, |atom| case_sensitivity.eq_atom(&atom, id))
}
_ => self.element.has_id(id, case_sensitivity)
}
}
fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => {
snapshot.has_class(name, case_sensitivity)
}
_ => self.element.has_class(name, case_sensitivity)
}
}
fn is_empty(&self) -> bool {
self.element.is_empty()
}
fn is_root(&self) -> bool {
self.element.is_root()
}
fn pseudo_element_originating_element(&self) -> Option<Self> {
self.element.pseudo_element_originating_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn assigned_slot(&self) -> Option<Self> {
self.element.assigned_slot()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn blocks_ancestor_combinators(&self) -> bool {
self.element.blocks_ancestor_combinators()
}
}
| last_child_element | identifier_name |
element_wrapper.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/. */
//! A wrapper over an element and a snapshot, that allows us to selector-match
//! against a past state of the element.
use {Atom, CaseSensitivityExt, LocalName, Namespace, WeakAtom};
use dom::TElement;
use element_state::ElementState;
use selector_parser::{NonTSPseudoClass, PseudoElement, SelectorImpl, Snapshot, SnapshotMap, AttrValue};
use selectors::{Element, OpaqueElement};
use selectors::attr::{AttrSelectorOperation, CaseSensitivity, NamespaceConstraint};
use selectors::matching::{ElementSelectorFlags, MatchingContext};
use std::cell::Cell;
use std::fmt;
/// In order to compute restyle hints, we perform a selector match against a
/// list of partial selectors whose rightmost simple selector may be sensitive
/// to the thing being changed. We do this matching twice, once for the element
/// as it exists now and once for the element as it existed at the time of the
/// last restyle. If the results of the selector match differ, that means that
/// the given partial selector is sensitive to the change, and we compute a
/// restyle hint based on its combinator.
///
/// In order to run selector matching against the old element state, we generate
/// a wrapper for the element which claims to have the old state. This is the
/// ElementWrapper logic below.
///
/// Gecko does this differently for element states, and passes a mask called
/// mStateMask, which indicates the states that need to be ignored during
/// selector matching. This saves an ElementWrapper allocation and an additional
/// selector match call at the expense of additional complexity inside the
/// selector matching logic. This only works for boolean states though, so we
/// still need to take the ElementWrapper approach for attribute-dependent
/// style. So we do it the same both ways for now to reduce complexity, but it's
/// worth measuring the performance impact (if any) of the mStateMask approach.
pub trait ElementSnapshot : Sized {
/// The state of the snapshot, if any.
fn state(&self) -> Option<ElementState>;
/// If this snapshot contains attribute information.
fn has_attrs(&self) -> bool;
/// The ID attribute per this snapshot. Should only be called if
/// `has_attrs()` returns true.
fn id_attr(&self) -> Option<&WeakAtom>;
/// Whether this snapshot contains the class `name`. Should only be called
/// if `has_attrs()` returns true.
fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool;
/// A callback that should be called for each class of the snapshot. Should
/// only be called if `has_attrs()` returns true.
fn each_class<F>(&self, F)
where
F: FnMut(&Atom);
/// The `xml:lang=""` or `lang=""` attribute value per this snapshot.
fn lang_attr(&self) -> Option<AttrValue>;
}
/// A simple wrapper over an element and a snapshot, that allows us to
/// selector-match against a past state of the element.
#[derive(Clone)]
pub struct ElementWrapper<'a, E>
where
E: TElement,
{
element: E,
cached_snapshot: Cell<Option<&'a Snapshot>>,
snapshot_map: &'a SnapshotMap,
}
impl<'a, E> ElementWrapper<'a, E>
where
E: TElement,
{
/// Trivially constructs an `ElementWrapper`.
pub fn new(el: E, snapshot_map: &'a SnapshotMap) -> Self {
ElementWrapper {
element: el,
cached_snapshot: Cell::new(None),
snapshot_map: snapshot_map,
}
}
/// Gets the snapshot associated with this element, if any.
pub fn snapshot(&self) -> Option<&'a Snapshot> {
if !self.element.has_snapshot() {
return None;
}
| return Some(s);
}
let snapshot = self.snapshot_map.get(&self.element);
debug_assert!(snapshot.is_some(), "has_snapshot lied!");
self.cached_snapshot.set(snapshot);
snapshot
}
/// Returns the states that have changed since the element was snapshotted.
pub fn state_changes(&self) -> ElementState {
let snapshot = match self.snapshot() {
Some(s) => s,
None => return ElementState::empty(),
};
match snapshot.state() {
Some(state) => state ^ self.element.state(),
None => ElementState::empty(),
}
}
/// Returns the value of the `xml:lang=""` (or, if appropriate, `lang=""`)
/// attribute from this element's snapshot or the closest ancestor
/// element snapshot with the attribute specified.
fn get_lang(&self) -> Option<AttrValue> {
let mut current = self.clone();
loop {
let lang = match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => snapshot.lang_attr(),
_ => current.element.lang_attr(),
};
if lang.is_some() {
return lang;
}
current = current.parent_element()?;
}
}
}
impl<'a, E> fmt::Debug for ElementWrapper<'a, E>
where
E: TElement,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Ignore other fields for now, can change later if needed.
self.element.fmt(f)
}
}
impl<'a, E> Element for ElementWrapper<'a, E>
where
E: TElement,
{
type Impl = SelectorImpl;
fn match_non_ts_pseudo_class<F>(
&self,
pseudo_class: &NonTSPseudoClass,
context: &mut MatchingContext<Self::Impl>,
_setter: &mut F,
) -> bool
where
F: FnMut(&Self, ElementSelectorFlags),
{
// Some pseudo-classes need special handling to evaluate them against
// the snapshot.
match *pseudo_class {
#[cfg(feature = "gecko")]
NonTSPseudoClass::MozAny(ref selectors) => {
use selectors::matching::matches_complex_selector;
return context.nest(|context| {
selectors.iter().any(|s| {
matches_complex_selector(s.iter(), self, context, _setter)
})
});
}
// :dir is implemented in terms of state flags, but which state flag
// it maps to depends on the argument to :dir. That means we can't
// just add its state flags to the NonTSPseudoClass, because if we
// added all of them there, and tested via intersects() here, we'd
// get incorrect behavior for :not(:dir()) cases.
//
// FIXME(bz): How can I set this up so once Servo adds :dir()
// support we don't forget to update this code?
#[cfg(feature = "gecko")]
NonTSPseudoClass::Dir(ref dir) => {
use invalidation::element::invalidation_map::dir_selector_to_state;
let selector_flag = dir_selector_to_state(dir);
if selector_flag.is_empty() {
// :dir() with some random argument; does not match.
return false;
}
let state = match self.snapshot().and_then(|s| s.state()) {
Some(snapshot_state) => snapshot_state,
None => self.element.state(),
};
return state.contains(selector_flag);
}
// For :link and :visited, we don't actually want to test the
// element state directly.
//
// Instead, we use the `visited_handling` to determine if they
// match.
NonTSPseudoClass::Link => {
return self.is_link() && context.visited_handling().matches_unvisited()
}
NonTSPseudoClass::Visited => {
return self.is_link() && context.visited_handling().matches_visited()
}
#[cfg(feature = "gecko")]
NonTSPseudoClass::MozTableBorderNonzero => {
if let Some(snapshot) = self.snapshot() {
if snapshot.has_other_pseudo_class_state() {
return snapshot.mIsTableBorderNonzero();
}
}
}
#[cfg(feature = "gecko")]
NonTSPseudoClass::MozBrowserFrame => {
if let Some(snapshot) = self.snapshot() {
if snapshot.has_other_pseudo_class_state() {
return snapshot.mIsMozBrowserFrame();
}
}
}
// :lang() needs to match using the closest ancestor xml:lang="" or
// lang="" attribtue from snapshots.
NonTSPseudoClass::Lang(ref lang_arg) => {
return self.element.match_element_lang(Some(self.get_lang()), lang_arg);
}
_ => {}
}
let flag = pseudo_class.state_flag();
if flag.is_empty() {
return self.element.match_non_ts_pseudo_class(
pseudo_class,
context,
&mut |_, _| {},
)
}
match self.snapshot().and_then(|s| s.state()) {
Some(snapshot_state) => snapshot_state.intersects(flag),
None => {
self.element.match_non_ts_pseudo_class(
pseudo_class,
context,
&mut |_, _| {},
)
}
}
}
fn match_pseudo_element(
&self,
pseudo_element: &PseudoElement,
context: &mut MatchingContext<Self::Impl>,
) -> bool {
self.element.match_pseudo_element(pseudo_element, context)
}
fn is_link(&self) -> bool {
self.element.is_link()
}
fn opaque(&self) -> OpaqueElement {
self.element.opaque()
}
fn parent_element(&self) -> Option<Self> {
self.element.parent_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn first_child_element(&self) -> Option<Self> {
self.element.first_child_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn last_child_element(&self) -> Option<Self> {
self.element.last_child_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn prev_sibling_element(&self) -> Option<Self> {
self.element.prev_sibling_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn next_sibling_element(&self) -> Option<Self> {
self.element.next_sibling_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
#[inline]
fn is_html_element_in_html_document(&self) -> bool {
self.element.is_html_element_in_html_document()
}
#[inline]
fn is_html_slot_element(&self) -> bool {
self.element.is_html_slot_element()
}
#[inline]
fn local_name(&self) -> &<Self::Impl as ::selectors::SelectorImpl>::BorrowedLocalName {
self.element.local_name()
}
#[inline]
fn namespace(&self) -> &<Self::Impl as ::selectors::SelectorImpl>::BorrowedNamespaceUrl {
self.element.namespace()
}
fn attr_matches(
&self,
ns: &NamespaceConstraint<&Namespace>,
local_name: &LocalName,
operation: &AttrSelectorOperation<&AttrValue>,
) -> bool {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => {
snapshot.attr_matches(ns, local_name, operation)
}
_ => self.element.attr_matches(ns, local_name, operation)
}
}
fn has_id(&self, id: &Atom, case_sensitivity: CaseSensitivity) -> bool {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => {
snapshot.id_attr().map_or(false, |atom| case_sensitivity.eq_atom(&atom, id))
}
_ => self.element.has_id(id, case_sensitivity)
}
}
fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => {
snapshot.has_class(name, case_sensitivity)
}
_ => self.element.has_class(name, case_sensitivity)
}
}
fn is_empty(&self) -> bool {
self.element.is_empty()
}
fn is_root(&self) -> bool {
self.element.is_root()
}
fn pseudo_element_originating_element(&self) -> Option<Self> {
self.element.pseudo_element_originating_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn assigned_slot(&self) -> Option<Self> {
self.element.assigned_slot()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn blocks_ancestor_combinators(&self) -> bool {
self.element.blocks_ancestor_combinators()
}
} | if let Some(s) = self.cached_snapshot.get() { | random_line_split |
public.py | from configurations import values
from . import common, databases, email
from .. import __version__
class Raven(object):
|
class Sentry404(Raven):
"""Log 404 events to the Sentry server."""
MIDDLEWARE_CLASSES = (
'raven.contrib.django.raven_compat.middleware.Sentry404CatchMiddleware',
) + common.Common.MIDDLEWARE_CLASSES
class Public(email.Email, databases.Databases, common.Common):
"""General settings for public projects."""
SECRET_KEY = values.SecretValue()
CSRF_COOKIE_HTTPONLY = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = 'DENY'
SILENCED_SYSTEM_CHECKS = values.ListValue([])
class Stage(Public):
"""Settings for staging server."""
pass
class SSL(object):
"""Settings for SSL."""
SECURE_SSL_HOST = values.Value('www.example.com')
SECURE_SSL_REDIRECT = True
class Prod(Public, SSL):
"""Settings for production server."""
pass
| """Report uncaught exceptions to the Sentry server."""
INSTALLED_APPS = common.Common.INSTALLED_APPS + ('raven.contrib.django.raven_compat',)
RAVEN_CONFIG = {
'dsn': values.URLValue(environ_name='RAVEN_CONFIG_DSN'),
'release': __version__,
} | identifier_body |
public.py | from configurations import values
from . import common, databases, email
from .. import __version__
class Raven(object):
"""Report uncaught exceptions to the Sentry server."""
INSTALLED_APPS = common.Common.INSTALLED_APPS + ('raven.contrib.django.raven_compat',)
RAVEN_CONFIG = {
'dsn': values.URLValue(environ_name='RAVEN_CONFIG_DSN'),
'release': __version__,
}
class Sentry404(Raven):
"""Log 404 events to the Sentry server."""
MIDDLEWARE_CLASSES = (
'raven.contrib.django.raven_compat.middleware.Sentry404CatchMiddleware',
) + common.Common.MIDDLEWARE_CLASSES
class Public(email.Email, databases.Databases, common.Common):
"""General settings for public projects."""
SECRET_KEY = values.SecretValue()
CSRF_COOKIE_HTTPONLY = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = 'DENY'
SILENCED_SYSTEM_CHECKS = values.ListValue([])
class Stage(Public):
"""Settings for staging server."""
pass
class SSL(object): | SECURE_SSL_REDIRECT = True
class Prod(Public, SSL):
"""Settings for production server."""
pass | """Settings for SSL."""
SECURE_SSL_HOST = values.Value('www.example.com')
| random_line_split |
public.py | from configurations import values
from . import common, databases, email
from .. import __version__
class Raven(object):
"""Report uncaught exceptions to the Sentry server."""
INSTALLED_APPS = common.Common.INSTALLED_APPS + ('raven.contrib.django.raven_compat',)
RAVEN_CONFIG = {
'dsn': values.URLValue(environ_name='RAVEN_CONFIG_DSN'),
'release': __version__,
}
class Sentry404(Raven):
"""Log 404 events to the Sentry server."""
MIDDLEWARE_CLASSES = (
'raven.contrib.django.raven_compat.middleware.Sentry404CatchMiddleware',
) + common.Common.MIDDLEWARE_CLASSES
class | (email.Email, databases.Databases, common.Common):
"""General settings for public projects."""
SECRET_KEY = values.SecretValue()
CSRF_COOKIE_HTTPONLY = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = 'DENY'
SILENCED_SYSTEM_CHECKS = values.ListValue([])
class Stage(Public):
"""Settings for staging server."""
pass
class SSL(object):
"""Settings for SSL."""
SECURE_SSL_HOST = values.Value('www.example.com')
SECURE_SSL_REDIRECT = True
class Prod(Public, SSL):
"""Settings for production server."""
pass
| Public | identifier_name |
karma.conf.js | module.exports = function(config) {
config.set({
basePath: './',
frameworks: ['systemjs', 'jasmine'],
systemjs: {
configFile: 'config.js',
config: {
paths: {
"*": null,
"src/*": "src/*",
"typescript": "node_modules/typescript/lib/typescript.js",
"systemjs": "node_modules/systemjs/dist/system.js",
'system-polyfills': 'node_modules/systemjs/dist/system-polyfills.js',
'es6-module-loader': 'node_modules/es6-module-loader/dist/es6-module-loader.js'
},
packages: {
'test/unit': {
defaultExtension: 'ts'
},
| }
},
transpiler: 'typescript'
},
serveFiles: [
'src/**/*.ts',
'jspm_packages/**/*.js'
]
},
files: [
'test/unit/*.spec.ts'
],
exclude: [],
preprocessors: { },
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
}; | 'src': {
defaultExtension: 'ts'
| random_line_split |
startup.py | # Copyright (c) 2016 Tigera, 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.
import os
import sys
import socket
import netaddr
from netaddr import AddrFormatError, IPAddress
from pycalico.datastore_datatypes import IPPool
from pycalico.ipam import IPAMClient
from pycalico.util import get_host_ips, validate_asn
DEFAULT_IPV4_POOL = IPPool("192.168.0.0/16")
DEFAULT_IPV6_POOL = IPPool("fd80:24e2:f998:72d6::/64")
def _find_pool(ip_addr, ipv4_pools):
"""
Find the pool containing the given IP.
:param ip_addr: IP address to find.
:param ipv4_pools: iterable containing IPPools.
:return: The pool, or None if not found
"""
for pool in ipv4_pools:
if ip_addr in pool.cidr:
return pool
else:
return None
def _ensure_host_tunnel_addr(ipv4_pools, ipip_pools):
"""
Ensure the host has a valid IP address for its IPIP tunnel device.
This must be an IP address claimed from one of the IPIP pools.
Handles re-allocating the address if it finds an existing address
that is not from an IPIP pool.
:param ipv4_pools: List of all IPv4 pools.
:param ipip_pools: List of IPIP-enabled pools.
"""
ip_addr = _get_host_tunnel_ip()
if ip_addr:
# Host already has a tunnel IP assigned, verify that it's still valid.
pool = _find_pool(ip_addr, ipv4_pools)
if pool and not pool.ipip:
# No longer an IPIP pool. Release the IP, it's no good to us.
client.release_ips({ip_addr})
ip_addr = None
elif not pool:
# Not in any IPIP pool. IP must be stale. Since it's not in any
# pool, we can't release it.
ip_addr = None
if not ip_addr:
# Either there was no IP or the IP needs to be replaced. Try to
# get an IP from one of the IPIP-enabled pools.
_assign_host_tunnel_addr(ipip_pools)
def _assign_host_tunnel_addr(ipip_pools):
"""
Claims an IPIP-enabled IP address from the first pool with some
space.
Stores the result in the host's config as its tunnel address.
Exits on failure.
:param ipip_pools: List of IPPools to search for an address.
"""
for ipip_pool in ipip_pools:
v4_addrs, _ = client.auto_assign_ips(
num_v4=1, num_v6=0,
handle_id=None,
attributes={},
pool=(ipip_pool, None),
host=hostname
)
if v4_addrs:
# Successfully allocated an address. Unpack the list.
[ip_addr] = v4_addrs
break
else:
# Failed to allocate an address, the pools must be full.
print "Failed to allocate an IP address from an IPIP-enabled pool " \
"for the host's IPIP tunnel device. Pools are likely " \
"exhausted."
sys.exit(1)
# If we get here, we've allocated a new IPIP-enabled address,
# Store it in etcd so that Felix will pick it up.
client.set_per_host_config(hostname, "IpInIpTunnelAddr",
str(ip_addr))
def _remove_host_tunnel_addr():
"""
Remove any existing IP address for this host's IPIP tunnel device.
Idempotent; does nothing if there is no IP assigned. Releases the
IP from IPAM.
"""
ip_addr = _get_host_tunnel_ip()
if ip_addr:
|
client.remove_per_host_config(hostname, "IpInIpTunnelAddr")
def _get_host_tunnel_ip():
"""
:return: The IPAddress of the host's IPIP tunnel or None if not
present/invalid.
"""
raw_addr = client.get_per_host_config(hostname, "IpInIpTunnelAddr")
try:
ip_addr = IPAddress(raw_addr)
except (AddrFormatError, ValueError, TypeError):
# Either there's no address or the data is bad. Treat as missing.
ip_addr = None
return ip_addr
def error_if_bgp_ip_conflict(ip, ip6):
"""
Prints an error message and exits if either of the IPv4 or IPv6 addresses
is already in use by another calico BGP host.
:param ip: User-provided IPv4 address to start this node with.
:param ip6: User-provided IPv6 address to start this node with.
:return: Nothing
"""
ip_list = []
if ip:
ip_list.append(ip)
if ip6:
ip_list.append(ip6)
try:
# Get hostname of host that already uses the given IP, if it exists
ip_conflicts = client.get_hostnames_from_ips(ip_list)
except KeyError:
# No hosts have been configured in etcd, so there cannot be a conflict
return
if ip_conflicts.keys():
ip_error = "ERROR: IP address %s is already in use by host %s. " \
"Calico requires each compute host to have a unique IP. " \
"If this is your first time running the Calico node on " \
"this host, ensure that another host is not already using " \
"the same IP address."
try:
if ip_conflicts[ip] != hostname:
ip_error = ip_error % (ip, str(ip_conflicts[ip]))
print ip_error
sys.exit(1)
except KeyError:
# IP address was not found in ip-host dictionary
pass
try:
if ip6 and ip_conflicts[ip6] != hostname:
ip_error = ip_error % (ip6, str(ip_conflicts[ip6]))
print ip_error
sys.exit(1)
except KeyError:
# IP address was not found in ip-host dictionary
pass
def warn_if_unknown_ip(ip, ip6):
"""
Prints a warning message if the IP addresses are not assigned to interfaces
on the current host.
:param ip: IPv4 address which should be present on the host.
:param ip6: IPv6 address which should be present on the host.
:return: None
"""
if ip and IPAddress(ip) not in get_host_ips(version=4, exclude=["docker0"]):
print "WARNING: Could not confirm that the provided IPv4 address is" \
" assigned to this host."
if ip6 and IPAddress(ip6) not in get_host_ips(version=6,
exclude=["docker0"]):
print "WARNING: Could not confirm that the provided IPv6 address is" \
" assigned to this host."
def warn_if_hostname_conflict(ip):
"""
Prints a warning message if it seems like an existing host is already running
calico using this hostname.
:param ip: User-provided or detected IP address to start this node with.
:return: Nothing
"""
try:
current_ipv4, _ = client.get_host_bgp_ips(hostname)
except KeyError:
# No other machine has registered configuration under this hostname.
# This must be a new host with a unique hostname, which is the
# expected behavior.
pass
else:
if current_ipv4 != "" and current_ipv4 != ip:
hostname_warning = "WARNING: Hostname '%s' is already in use " \
"with IP address %s. Calico requires each " \
"compute host to have a unique hostname. " \
"If this is your first time running " \
"the Calico node on this host, ensure " \
"that another host is not already using the " \
"same hostname." % (hostname, current_ipv4)
print hostname_warning
def main():
ip = os.getenv("IP")
ip = ip or None
if ip and not netaddr.valid_ipv4(ip):
print "IP environment (%s) is not a valid IPv4 address." % ip
sys.exit(1)
ip6 = os.getenv("IP6")
ip6 = ip6 or None
if ip6 and not netaddr.valid_ipv6(ip6):
print "IP6 environment (%s) is not a valid IPv6 address." % ip6
sys.exit(1)
as_num = os.getenv("AS")
as_num = as_num or None
if as_num and not validate_asn(as_num):
print "AS environment (%s) is not a AS number." % as_num
sys.exit(1)
# Get IP address of host, if none was specified
if not ip:
ips = get_host_ips(exclude=["^docker.*", "^cbr.*",
"virbr.*", "lxcbr.*", "veth.*",
"cali.*", "tunl.*", "flannel.*"])
try:
ip = str(ips.pop())
except IndexError:
print "Couldn't autodetect a management IP address. Please " \
"provide an IP address by rerunning the container with the" \
" IP environment variable set."
sys.exit(1)
else:
print "No IP provided. Using detected IP: %s" % ip
# Write a startup environment file containing the IP address that may have
# just been detected.
# This is required because the confd templates expect to be able to fill in
# some templates by fetching them from the environment.
with open('startup.env', 'w') as f:
f.write("IP=%s\n" % ip)
f.write("HOSTNAME=%s\n" % hostname)
warn_if_hostname_conflict(ip)
# Verify that IPs are not already in use by another host.
error_if_bgp_ip_conflict(ip, ip6)
# Verify that the chosen IP exists on the current host
warn_if_unknown_ip(ip, ip6)
if os.getenv("NO_DEFAULT_POOLS", "").lower() != "true":
# Set up etcd
ipv4_pools = client.get_ip_pools(4)
ipv6_pools = client.get_ip_pools(6)
# Create default pools if required
if not ipv4_pools:
client.add_ip_pool(4, DEFAULT_IPV4_POOL)
# If the OS has not been built with IPv6 then the /proc config for IPv6
# will not be present.
if not ipv6_pools and os.path.exists('/proc/sys/net/ipv6'):
client.add_ip_pool(6, DEFAULT_IPV6_POOL)
client.ensure_global_config()
client.create_host(hostname, ip, ip6, as_num)
# If IPIP is enabled, the host requires an IP address for its tunnel
# device, which is in an IPIP pool. Without this, a host can't originate
# traffic to a pool address because the response traffic would not be
# routed via the tunnel (likely being dropped by RPF checks in the fabric).
ipv4_pools = client.get_ip_pools(4)
ipip_pools = [p for p in ipv4_pools if p.ipip]
if ipip_pools:
# IPIP is enabled, make sure the host has an address for its tunnel.
_ensure_host_tunnel_addr(ipv4_pools, ipip_pools)
else:
# No IPIP pools, clean up any old address.
_remove_host_tunnel_addr()
# Try the HOSTNAME environment variable, but default to
# the socket.gethostname() value if unset.
hostname = os.getenv("HOSTNAME")
if not hostname:
hostname = socket.gethostname()
client = IPAMClient()
if __name__ == "__main__":
main()
| client.release_ips({ip_addr}) | conditional_block |
startup.py | # Copyright (c) 2016 Tigera, 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.
import os
import sys
import socket
import netaddr
from netaddr import AddrFormatError, IPAddress
from pycalico.datastore_datatypes import IPPool
from pycalico.ipam import IPAMClient
from pycalico.util import get_host_ips, validate_asn
DEFAULT_IPV4_POOL = IPPool("192.168.0.0/16")
DEFAULT_IPV6_POOL = IPPool("fd80:24e2:f998:72d6::/64")
def _find_pool(ip_addr, ipv4_pools):
"""
Find the pool containing the given IP.
:param ip_addr: IP address to find.
:param ipv4_pools: iterable containing IPPools.
:return: The pool, or None if not found
"""
for pool in ipv4_pools:
if ip_addr in pool.cidr:
return pool
else:
return None
def _ensure_host_tunnel_addr(ipv4_pools, ipip_pools):
"""
Ensure the host has a valid IP address for its IPIP tunnel device.
This must be an IP address claimed from one of the IPIP pools.
Handles re-allocating the address if it finds an existing address
that is not from an IPIP pool.
:param ipv4_pools: List of all IPv4 pools.
:param ipip_pools: List of IPIP-enabled pools.
"""
ip_addr = _get_host_tunnel_ip()
if ip_addr:
# Host already has a tunnel IP assigned, verify that it's still valid.
pool = _find_pool(ip_addr, ipv4_pools)
if pool and not pool.ipip:
# No longer an IPIP pool. Release the IP, it's no good to us.
client.release_ips({ip_addr})
ip_addr = None
elif not pool:
# Not in any IPIP pool. IP must be stale. Since it's not in any
# pool, we can't release it.
ip_addr = None
if not ip_addr:
# Either there was no IP or the IP needs to be replaced. Try to
# get an IP from one of the IPIP-enabled pools.
_assign_host_tunnel_addr(ipip_pools)
def | (ipip_pools):
"""
Claims an IPIP-enabled IP address from the first pool with some
space.
Stores the result in the host's config as its tunnel address.
Exits on failure.
:param ipip_pools: List of IPPools to search for an address.
"""
for ipip_pool in ipip_pools:
v4_addrs, _ = client.auto_assign_ips(
num_v4=1, num_v6=0,
handle_id=None,
attributes={},
pool=(ipip_pool, None),
host=hostname
)
if v4_addrs:
# Successfully allocated an address. Unpack the list.
[ip_addr] = v4_addrs
break
else:
# Failed to allocate an address, the pools must be full.
print "Failed to allocate an IP address from an IPIP-enabled pool " \
"for the host's IPIP tunnel device. Pools are likely " \
"exhausted."
sys.exit(1)
# If we get here, we've allocated a new IPIP-enabled address,
# Store it in etcd so that Felix will pick it up.
client.set_per_host_config(hostname, "IpInIpTunnelAddr",
str(ip_addr))
def _remove_host_tunnel_addr():
"""
Remove any existing IP address for this host's IPIP tunnel device.
Idempotent; does nothing if there is no IP assigned. Releases the
IP from IPAM.
"""
ip_addr = _get_host_tunnel_ip()
if ip_addr:
client.release_ips({ip_addr})
client.remove_per_host_config(hostname, "IpInIpTunnelAddr")
def _get_host_tunnel_ip():
"""
:return: The IPAddress of the host's IPIP tunnel or None if not
present/invalid.
"""
raw_addr = client.get_per_host_config(hostname, "IpInIpTunnelAddr")
try:
ip_addr = IPAddress(raw_addr)
except (AddrFormatError, ValueError, TypeError):
# Either there's no address or the data is bad. Treat as missing.
ip_addr = None
return ip_addr
def error_if_bgp_ip_conflict(ip, ip6):
"""
Prints an error message and exits if either of the IPv4 or IPv6 addresses
is already in use by another calico BGP host.
:param ip: User-provided IPv4 address to start this node with.
:param ip6: User-provided IPv6 address to start this node with.
:return: Nothing
"""
ip_list = []
if ip:
ip_list.append(ip)
if ip6:
ip_list.append(ip6)
try:
# Get hostname of host that already uses the given IP, if it exists
ip_conflicts = client.get_hostnames_from_ips(ip_list)
except KeyError:
# No hosts have been configured in etcd, so there cannot be a conflict
return
if ip_conflicts.keys():
ip_error = "ERROR: IP address %s is already in use by host %s. " \
"Calico requires each compute host to have a unique IP. " \
"If this is your first time running the Calico node on " \
"this host, ensure that another host is not already using " \
"the same IP address."
try:
if ip_conflicts[ip] != hostname:
ip_error = ip_error % (ip, str(ip_conflicts[ip]))
print ip_error
sys.exit(1)
except KeyError:
# IP address was not found in ip-host dictionary
pass
try:
if ip6 and ip_conflicts[ip6] != hostname:
ip_error = ip_error % (ip6, str(ip_conflicts[ip6]))
print ip_error
sys.exit(1)
except KeyError:
# IP address was not found in ip-host dictionary
pass
def warn_if_unknown_ip(ip, ip6):
"""
Prints a warning message if the IP addresses are not assigned to interfaces
on the current host.
:param ip: IPv4 address which should be present on the host.
:param ip6: IPv6 address which should be present on the host.
:return: None
"""
if ip and IPAddress(ip) not in get_host_ips(version=4, exclude=["docker0"]):
print "WARNING: Could not confirm that the provided IPv4 address is" \
" assigned to this host."
if ip6 and IPAddress(ip6) not in get_host_ips(version=6,
exclude=["docker0"]):
print "WARNING: Could not confirm that the provided IPv6 address is" \
" assigned to this host."
def warn_if_hostname_conflict(ip):
"""
Prints a warning message if it seems like an existing host is already running
calico using this hostname.
:param ip: User-provided or detected IP address to start this node with.
:return: Nothing
"""
try:
current_ipv4, _ = client.get_host_bgp_ips(hostname)
except KeyError:
# No other machine has registered configuration under this hostname.
# This must be a new host with a unique hostname, which is the
# expected behavior.
pass
else:
if current_ipv4 != "" and current_ipv4 != ip:
hostname_warning = "WARNING: Hostname '%s' is already in use " \
"with IP address %s. Calico requires each " \
"compute host to have a unique hostname. " \
"If this is your first time running " \
"the Calico node on this host, ensure " \
"that another host is not already using the " \
"same hostname." % (hostname, current_ipv4)
print hostname_warning
def main():
ip = os.getenv("IP")
ip = ip or None
if ip and not netaddr.valid_ipv4(ip):
print "IP environment (%s) is not a valid IPv4 address." % ip
sys.exit(1)
ip6 = os.getenv("IP6")
ip6 = ip6 or None
if ip6 and not netaddr.valid_ipv6(ip6):
print "IP6 environment (%s) is not a valid IPv6 address." % ip6
sys.exit(1)
as_num = os.getenv("AS")
as_num = as_num or None
if as_num and not validate_asn(as_num):
print "AS environment (%s) is not a AS number." % as_num
sys.exit(1)
# Get IP address of host, if none was specified
if not ip:
ips = get_host_ips(exclude=["^docker.*", "^cbr.*",
"virbr.*", "lxcbr.*", "veth.*",
"cali.*", "tunl.*", "flannel.*"])
try:
ip = str(ips.pop())
except IndexError:
print "Couldn't autodetect a management IP address. Please " \
"provide an IP address by rerunning the container with the" \
" IP environment variable set."
sys.exit(1)
else:
print "No IP provided. Using detected IP: %s" % ip
# Write a startup environment file containing the IP address that may have
# just been detected.
# This is required because the confd templates expect to be able to fill in
# some templates by fetching them from the environment.
with open('startup.env', 'w') as f:
f.write("IP=%s\n" % ip)
f.write("HOSTNAME=%s\n" % hostname)
warn_if_hostname_conflict(ip)
# Verify that IPs are not already in use by another host.
error_if_bgp_ip_conflict(ip, ip6)
# Verify that the chosen IP exists on the current host
warn_if_unknown_ip(ip, ip6)
if os.getenv("NO_DEFAULT_POOLS", "").lower() != "true":
# Set up etcd
ipv4_pools = client.get_ip_pools(4)
ipv6_pools = client.get_ip_pools(6)
# Create default pools if required
if not ipv4_pools:
client.add_ip_pool(4, DEFAULT_IPV4_POOL)
# If the OS has not been built with IPv6 then the /proc config for IPv6
# will not be present.
if not ipv6_pools and os.path.exists('/proc/sys/net/ipv6'):
client.add_ip_pool(6, DEFAULT_IPV6_POOL)
client.ensure_global_config()
client.create_host(hostname, ip, ip6, as_num)
# If IPIP is enabled, the host requires an IP address for its tunnel
# device, which is in an IPIP pool. Without this, a host can't originate
# traffic to a pool address because the response traffic would not be
# routed via the tunnel (likely being dropped by RPF checks in the fabric).
ipv4_pools = client.get_ip_pools(4)
ipip_pools = [p for p in ipv4_pools if p.ipip]
if ipip_pools:
# IPIP is enabled, make sure the host has an address for its tunnel.
_ensure_host_tunnel_addr(ipv4_pools, ipip_pools)
else:
# No IPIP pools, clean up any old address.
_remove_host_tunnel_addr()
# Try the HOSTNAME environment variable, but default to
# the socket.gethostname() value if unset.
hostname = os.getenv("HOSTNAME")
if not hostname:
hostname = socket.gethostname()
client = IPAMClient()
if __name__ == "__main__":
main()
| _assign_host_tunnel_addr | identifier_name |
startup.py | # Copyright (c) 2016 Tigera, 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.
import os
import sys
import socket
import netaddr
from netaddr import AddrFormatError, IPAddress
from pycalico.datastore_datatypes import IPPool
from pycalico.ipam import IPAMClient
from pycalico.util import get_host_ips, validate_asn
DEFAULT_IPV4_POOL = IPPool("192.168.0.0/16")
DEFAULT_IPV6_POOL = IPPool("fd80:24e2:f998:72d6::/64")
def _find_pool(ip_addr, ipv4_pools):
"""
Find the pool containing the given IP.
:param ip_addr: IP address to find.
:param ipv4_pools: iterable containing IPPools.
:return: The pool, or None if not found
"""
for pool in ipv4_pools:
if ip_addr in pool.cidr:
return pool
else:
return None
def _ensure_host_tunnel_addr(ipv4_pools, ipip_pools):
"""
Ensure the host has a valid IP address for its IPIP tunnel device.
This must be an IP address claimed from one of the IPIP pools.
Handles re-allocating the address if it finds an existing address
that is not from an IPIP pool.
:param ipv4_pools: List of all IPv4 pools.
:param ipip_pools: List of IPIP-enabled pools.
"""
ip_addr = _get_host_tunnel_ip()
if ip_addr:
# Host already has a tunnel IP assigned, verify that it's still valid.
pool = _find_pool(ip_addr, ipv4_pools)
if pool and not pool.ipip:
# No longer an IPIP pool. Release the IP, it's no good to us.
client.release_ips({ip_addr})
ip_addr = None
elif not pool:
# Not in any IPIP pool. IP must be stale. Since it's not in any
# pool, we can't release it.
ip_addr = None
if not ip_addr:
# Either there was no IP or the IP needs to be replaced. Try to
# get an IP from one of the IPIP-enabled pools.
_assign_host_tunnel_addr(ipip_pools)
def _assign_host_tunnel_addr(ipip_pools):
"""
Claims an IPIP-enabled IP address from the first pool with some
space.
Stores the result in the host's config as its tunnel address.
Exits on failure.
:param ipip_pools: List of IPPools to search for an address.
"""
for ipip_pool in ipip_pools:
v4_addrs, _ = client.auto_assign_ips(
num_v4=1, num_v6=0,
handle_id=None,
attributes={},
pool=(ipip_pool, None),
host=hostname
)
if v4_addrs:
# Successfully allocated an address. Unpack the list.
[ip_addr] = v4_addrs
break
else:
# Failed to allocate an address, the pools must be full.
print "Failed to allocate an IP address from an IPIP-enabled pool " \
"for the host's IPIP tunnel device. Pools are likely " \
"exhausted."
sys.exit(1)
# If we get here, we've allocated a new IPIP-enabled address,
# Store it in etcd so that Felix will pick it up.
client.set_per_host_config(hostname, "IpInIpTunnelAddr",
str(ip_addr))
def _remove_host_tunnel_addr():
"""
Remove any existing IP address for this host's IPIP tunnel device.
Idempotent; does nothing if there is no IP assigned. Releases the
IP from IPAM.
"""
ip_addr = _get_host_tunnel_ip()
if ip_addr:
client.release_ips({ip_addr})
client.remove_per_host_config(hostname, "IpInIpTunnelAddr")
def _get_host_tunnel_ip():
"""
:return: The IPAddress of the host's IPIP tunnel or None if not
present/invalid.
"""
raw_addr = client.get_per_host_config(hostname, "IpInIpTunnelAddr")
try:
ip_addr = IPAddress(raw_addr)
except (AddrFormatError, ValueError, TypeError):
# Either there's no address or the data is bad. Treat as missing.
ip_addr = None
return ip_addr
def error_if_bgp_ip_conflict(ip, ip6):
|
def warn_if_unknown_ip(ip, ip6):
"""
Prints a warning message if the IP addresses are not assigned to interfaces
on the current host.
:param ip: IPv4 address which should be present on the host.
:param ip6: IPv6 address which should be present on the host.
:return: None
"""
if ip and IPAddress(ip) not in get_host_ips(version=4, exclude=["docker0"]):
print "WARNING: Could not confirm that the provided IPv4 address is" \
" assigned to this host."
if ip6 and IPAddress(ip6) not in get_host_ips(version=6,
exclude=["docker0"]):
print "WARNING: Could not confirm that the provided IPv6 address is" \
" assigned to this host."
def warn_if_hostname_conflict(ip):
"""
Prints a warning message if it seems like an existing host is already running
calico using this hostname.
:param ip: User-provided or detected IP address to start this node with.
:return: Nothing
"""
try:
current_ipv4, _ = client.get_host_bgp_ips(hostname)
except KeyError:
# No other machine has registered configuration under this hostname.
# This must be a new host with a unique hostname, which is the
# expected behavior.
pass
else:
if current_ipv4 != "" and current_ipv4 != ip:
hostname_warning = "WARNING: Hostname '%s' is already in use " \
"with IP address %s. Calico requires each " \
"compute host to have a unique hostname. " \
"If this is your first time running " \
"the Calico node on this host, ensure " \
"that another host is not already using the " \
"same hostname." % (hostname, current_ipv4)
print hostname_warning
def main():
ip = os.getenv("IP")
ip = ip or None
if ip and not netaddr.valid_ipv4(ip):
print "IP environment (%s) is not a valid IPv4 address." % ip
sys.exit(1)
ip6 = os.getenv("IP6")
ip6 = ip6 or None
if ip6 and not netaddr.valid_ipv6(ip6):
print "IP6 environment (%s) is not a valid IPv6 address." % ip6
sys.exit(1)
as_num = os.getenv("AS")
as_num = as_num or None
if as_num and not validate_asn(as_num):
print "AS environment (%s) is not a AS number." % as_num
sys.exit(1)
# Get IP address of host, if none was specified
if not ip:
ips = get_host_ips(exclude=["^docker.*", "^cbr.*",
"virbr.*", "lxcbr.*", "veth.*",
"cali.*", "tunl.*", "flannel.*"])
try:
ip = str(ips.pop())
except IndexError:
print "Couldn't autodetect a management IP address. Please " \
"provide an IP address by rerunning the container with the" \
" IP environment variable set."
sys.exit(1)
else:
print "No IP provided. Using detected IP: %s" % ip
# Write a startup environment file containing the IP address that may have
# just been detected.
# This is required because the confd templates expect to be able to fill in
# some templates by fetching them from the environment.
with open('startup.env', 'w') as f:
f.write("IP=%s\n" % ip)
f.write("HOSTNAME=%s\n" % hostname)
warn_if_hostname_conflict(ip)
# Verify that IPs are not already in use by another host.
error_if_bgp_ip_conflict(ip, ip6)
# Verify that the chosen IP exists on the current host
warn_if_unknown_ip(ip, ip6)
if os.getenv("NO_DEFAULT_POOLS", "").lower() != "true":
# Set up etcd
ipv4_pools = client.get_ip_pools(4)
ipv6_pools = client.get_ip_pools(6)
# Create default pools if required
if not ipv4_pools:
client.add_ip_pool(4, DEFAULT_IPV4_POOL)
# If the OS has not been built with IPv6 then the /proc config for IPv6
# will not be present.
if not ipv6_pools and os.path.exists('/proc/sys/net/ipv6'):
client.add_ip_pool(6, DEFAULT_IPV6_POOL)
client.ensure_global_config()
client.create_host(hostname, ip, ip6, as_num)
# If IPIP is enabled, the host requires an IP address for its tunnel
# device, which is in an IPIP pool. Without this, a host can't originate
# traffic to a pool address because the response traffic would not be
# routed via the tunnel (likely being dropped by RPF checks in the fabric).
ipv4_pools = client.get_ip_pools(4)
ipip_pools = [p for p in ipv4_pools if p.ipip]
if ipip_pools:
# IPIP is enabled, make sure the host has an address for its tunnel.
_ensure_host_tunnel_addr(ipv4_pools, ipip_pools)
else:
# No IPIP pools, clean up any old address.
_remove_host_tunnel_addr()
# Try the HOSTNAME environment variable, but default to
# the socket.gethostname() value if unset.
hostname = os.getenv("HOSTNAME")
if not hostname:
hostname = socket.gethostname()
client = IPAMClient()
if __name__ == "__main__":
main()
| """
Prints an error message and exits if either of the IPv4 or IPv6 addresses
is already in use by another calico BGP host.
:param ip: User-provided IPv4 address to start this node with.
:param ip6: User-provided IPv6 address to start this node with.
:return: Nothing
"""
ip_list = []
if ip:
ip_list.append(ip)
if ip6:
ip_list.append(ip6)
try:
# Get hostname of host that already uses the given IP, if it exists
ip_conflicts = client.get_hostnames_from_ips(ip_list)
except KeyError:
# No hosts have been configured in etcd, so there cannot be a conflict
return
if ip_conflicts.keys():
ip_error = "ERROR: IP address %s is already in use by host %s. " \
"Calico requires each compute host to have a unique IP. " \
"If this is your first time running the Calico node on " \
"this host, ensure that another host is not already using " \
"the same IP address."
try:
if ip_conflicts[ip] != hostname:
ip_error = ip_error % (ip, str(ip_conflicts[ip]))
print ip_error
sys.exit(1)
except KeyError:
# IP address was not found in ip-host dictionary
pass
try:
if ip6 and ip_conflicts[ip6] != hostname:
ip_error = ip_error % (ip6, str(ip_conflicts[ip6]))
print ip_error
sys.exit(1)
except KeyError:
# IP address was not found in ip-host dictionary
pass | identifier_body |
startup.py | # Copyright (c) 2016 Tigera, 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.
import os
import sys
import socket
import netaddr
from netaddr import AddrFormatError, IPAddress
from pycalico.datastore_datatypes import IPPool
from pycalico.ipam import IPAMClient
from pycalico.util import get_host_ips, validate_asn
DEFAULT_IPV4_POOL = IPPool("192.168.0.0/16")
DEFAULT_IPV6_POOL = IPPool("fd80:24e2:f998:72d6::/64")
def _find_pool(ip_addr, ipv4_pools):
"""
Find the pool containing the given IP.
:param ip_addr: IP address to find.
:param ipv4_pools: iterable containing IPPools.
:return: The pool, or None if not found
"""
for pool in ipv4_pools:
if ip_addr in pool.cidr:
return pool
else:
return None
def _ensure_host_tunnel_addr(ipv4_pools, ipip_pools):
"""
Ensure the host has a valid IP address for its IPIP tunnel device.
This must be an IP address claimed from one of the IPIP pools.
Handles re-allocating the address if it finds an existing address
that is not from an IPIP pool.
:param ipv4_pools: List of all IPv4 pools.
:param ipip_pools: List of IPIP-enabled pools.
"""
ip_addr = _get_host_tunnel_ip()
if ip_addr:
# Host already has a tunnel IP assigned, verify that it's still valid.
pool = _find_pool(ip_addr, ipv4_pools)
if pool and not pool.ipip:
# No longer an IPIP pool. Release the IP, it's no good to us.
client.release_ips({ip_addr})
ip_addr = None
elif not pool:
# Not in any IPIP pool. IP must be stale. Since it's not in any
# pool, we can't release it.
ip_addr = None
if not ip_addr:
# Either there was no IP or the IP needs to be replaced. Try to
# get an IP from one of the IPIP-enabled pools.
_assign_host_tunnel_addr(ipip_pools)
def _assign_host_tunnel_addr(ipip_pools):
"""
Claims an IPIP-enabled IP address from the first pool with some
space.
Stores the result in the host's config as its tunnel address.
Exits on failure.
:param ipip_pools: List of IPPools to search for an address.
"""
for ipip_pool in ipip_pools:
v4_addrs, _ = client.auto_assign_ips(
num_v4=1, num_v6=0,
handle_id=None,
attributes={},
pool=(ipip_pool, None),
host=hostname
)
if v4_addrs:
# Successfully allocated an address. Unpack the list.
[ip_addr] = v4_addrs
break
else:
# Failed to allocate an address, the pools must be full.
print "Failed to allocate an IP address from an IPIP-enabled pool " \
"for the host's IPIP tunnel device. Pools are likely " \
"exhausted."
sys.exit(1)
# If we get here, we've allocated a new IPIP-enabled address,
# Store it in etcd so that Felix will pick it up.
client.set_per_host_config(hostname, "IpInIpTunnelAddr",
str(ip_addr))
def _remove_host_tunnel_addr():
"""
Remove any existing IP address for this host's IPIP tunnel device.
Idempotent; does nothing if there is no IP assigned. Releases the
IP from IPAM.
"""
ip_addr = _get_host_tunnel_ip()
if ip_addr:
client.release_ips({ip_addr})
client.remove_per_host_config(hostname, "IpInIpTunnelAddr")
def _get_host_tunnel_ip():
"""
:return: The IPAddress of the host's IPIP tunnel or None if not
present/invalid.
"""
raw_addr = client.get_per_host_config(hostname, "IpInIpTunnelAddr")
try:
ip_addr = IPAddress(raw_addr)
except (AddrFormatError, ValueError, TypeError):
# Either there's no address or the data is bad. Treat as missing.
ip_addr = None
return ip_addr
def error_if_bgp_ip_conflict(ip, ip6):
"""
Prints an error message and exits if either of the IPv4 or IPv6 addresses
is already in use by another calico BGP host.
:param ip: User-provided IPv4 address to start this node with.
:param ip6: User-provided IPv6 address to start this node with.
:return: Nothing
"""
ip_list = []
if ip:
ip_list.append(ip)
if ip6:
ip_list.append(ip6)
try:
# Get hostname of host that already uses the given IP, if it exists | if ip_conflicts.keys():
ip_error = "ERROR: IP address %s is already in use by host %s. " \
"Calico requires each compute host to have a unique IP. " \
"If this is your first time running the Calico node on " \
"this host, ensure that another host is not already using " \
"the same IP address."
try:
if ip_conflicts[ip] != hostname:
ip_error = ip_error % (ip, str(ip_conflicts[ip]))
print ip_error
sys.exit(1)
except KeyError:
# IP address was not found in ip-host dictionary
pass
try:
if ip6 and ip_conflicts[ip6] != hostname:
ip_error = ip_error % (ip6, str(ip_conflicts[ip6]))
print ip_error
sys.exit(1)
except KeyError:
# IP address was not found in ip-host dictionary
pass
def warn_if_unknown_ip(ip, ip6):
"""
Prints a warning message if the IP addresses are not assigned to interfaces
on the current host.
:param ip: IPv4 address which should be present on the host.
:param ip6: IPv6 address which should be present on the host.
:return: None
"""
if ip and IPAddress(ip) not in get_host_ips(version=4, exclude=["docker0"]):
print "WARNING: Could not confirm that the provided IPv4 address is" \
" assigned to this host."
if ip6 and IPAddress(ip6) not in get_host_ips(version=6,
exclude=["docker0"]):
print "WARNING: Could not confirm that the provided IPv6 address is" \
" assigned to this host."
def warn_if_hostname_conflict(ip):
"""
Prints a warning message if it seems like an existing host is already running
calico using this hostname.
:param ip: User-provided or detected IP address to start this node with.
:return: Nothing
"""
try:
current_ipv4, _ = client.get_host_bgp_ips(hostname)
except KeyError:
# No other machine has registered configuration under this hostname.
# This must be a new host with a unique hostname, which is the
# expected behavior.
pass
else:
if current_ipv4 != "" and current_ipv4 != ip:
hostname_warning = "WARNING: Hostname '%s' is already in use " \
"with IP address %s. Calico requires each " \
"compute host to have a unique hostname. " \
"If this is your first time running " \
"the Calico node on this host, ensure " \
"that another host is not already using the " \
"same hostname." % (hostname, current_ipv4)
print hostname_warning
def main():
ip = os.getenv("IP")
ip = ip or None
if ip and not netaddr.valid_ipv4(ip):
print "IP environment (%s) is not a valid IPv4 address." % ip
sys.exit(1)
ip6 = os.getenv("IP6")
ip6 = ip6 or None
if ip6 and not netaddr.valid_ipv6(ip6):
print "IP6 environment (%s) is not a valid IPv6 address." % ip6
sys.exit(1)
as_num = os.getenv("AS")
as_num = as_num or None
if as_num and not validate_asn(as_num):
print "AS environment (%s) is not a AS number." % as_num
sys.exit(1)
# Get IP address of host, if none was specified
if not ip:
ips = get_host_ips(exclude=["^docker.*", "^cbr.*",
"virbr.*", "lxcbr.*", "veth.*",
"cali.*", "tunl.*", "flannel.*"])
try:
ip = str(ips.pop())
except IndexError:
print "Couldn't autodetect a management IP address. Please " \
"provide an IP address by rerunning the container with the" \
" IP environment variable set."
sys.exit(1)
else:
print "No IP provided. Using detected IP: %s" % ip
# Write a startup environment file containing the IP address that may have
# just been detected.
# This is required because the confd templates expect to be able to fill in
# some templates by fetching them from the environment.
with open('startup.env', 'w') as f:
f.write("IP=%s\n" % ip)
f.write("HOSTNAME=%s\n" % hostname)
warn_if_hostname_conflict(ip)
# Verify that IPs are not already in use by another host.
error_if_bgp_ip_conflict(ip, ip6)
# Verify that the chosen IP exists on the current host
warn_if_unknown_ip(ip, ip6)
if os.getenv("NO_DEFAULT_POOLS", "").lower() != "true":
# Set up etcd
ipv4_pools = client.get_ip_pools(4)
ipv6_pools = client.get_ip_pools(6)
# Create default pools if required
if not ipv4_pools:
client.add_ip_pool(4, DEFAULT_IPV4_POOL)
# If the OS has not been built with IPv6 then the /proc config for IPv6
# will not be present.
if not ipv6_pools and os.path.exists('/proc/sys/net/ipv6'):
client.add_ip_pool(6, DEFAULT_IPV6_POOL)
client.ensure_global_config()
client.create_host(hostname, ip, ip6, as_num)
# If IPIP is enabled, the host requires an IP address for its tunnel
# device, which is in an IPIP pool. Without this, a host can't originate
# traffic to a pool address because the response traffic would not be
# routed via the tunnel (likely being dropped by RPF checks in the fabric).
ipv4_pools = client.get_ip_pools(4)
ipip_pools = [p for p in ipv4_pools if p.ipip]
if ipip_pools:
# IPIP is enabled, make sure the host has an address for its tunnel.
_ensure_host_tunnel_addr(ipv4_pools, ipip_pools)
else:
# No IPIP pools, clean up any old address.
_remove_host_tunnel_addr()
# Try the HOSTNAME environment variable, but default to
# the socket.gethostname() value if unset.
hostname = os.getenv("HOSTNAME")
if not hostname:
hostname = socket.gethostname()
client = IPAMClient()
if __name__ == "__main__":
main() | ip_conflicts = client.get_hostnames_from_ips(ip_list)
except KeyError:
# No hosts have been configured in etcd, so there cannot be a conflict
return
| random_line_split |
lib.rs | #![deny(missing_debug_implementations)]
use janus_plugin_sys as ffi;
use bitflags::bitflags;
pub use debug::LogLevel;
pub use debug::log;
pub use jansson::{JanssonDecodingFlags, JanssonEncodingFlags, JanssonValue, RawJanssonValue};
pub use session::SessionWrapper;
pub use ffi::events::janus_eventhandler as EventHandler;
pub use ffi::plugin::janus_callbacks as PluginCallbacks;
pub use ffi::plugin::janus_plugin as Plugin;
pub use ffi::plugin::janus_plugin_result as RawPluginResult;
pub use ffi::plugin::janus_plugin_session as PluginSession;
pub use ffi::plugin::janus_plugin_rtp as PluginRtpPacket;
pub use ffi::plugin::janus_plugin_rtcp as PluginRtcpPacket;
pub use ffi::plugin::janus_plugin_data as PluginDataPacket;
pub use ffi::plugin::janus_plugin_rtp_extensions as PluginRtpExtensions;
use ffi::plugin::janus_plugin_result_type as PluginResultType;
use std::error::Error;
use std::fmt;
use std::ffi::CStr;
use std::mem;
use std::ops::Deref;
use std::os::raw::{c_char, c_int};
use std::ptr;
pub mod debug;
pub mod rtcp;
pub mod sdp;
pub mod session;
pub mod jansson;
pub mod utils;
pub mod refcount;
bitflags! {
/// Flags that control which events an event handler receives.
pub struct JanusEventType: u32 {
const JANUS_EVENT_TYPE_SESSION = 1 << 0;
const JANUS_EVENT_TYPE_HANDLE = 1 << 1;
const JANUS_EVENT_TYPE_JSEP = 1 << 3; // yes, really
const JANUS_EVENT_TYPE_WEBRTC = 1 << 4;
const JANUS_EVENT_TYPE_MEDIA = 1 << 5;
const JANUS_EVENT_TYPE_PLUGIN = 1 << 6;
const JANUS_EVENT_TYPE_TRANSPORT = 1 << 7;
const JANUS_EVENT_TYPE_CORE = 1 << 8;
}
}
/// An error emitted by the Janus core in response to a plugin pushing an event.
#[derive(Debug, Clone, Copy)]
pub struct JanusError {
pub code: i32
}
/// A result from pushing an event to Janus core.
pub type JanusResult = Result<(), JanusError>;
impl JanusError {
/// Returns Janus's description text for this error.
pub fn to_cstr(self) -> &'static CStr {
unsafe { CStr::from_ptr(ffi::janus_get_api_error(self.code)) }
}
/// Converts a Janus result code to either success or a potential error.
pub fn | (val: i32) -> JanusResult {
match val {
0 => Ok(()),
e => Err(JanusError { code: e })
}
}
}
impl Error for JanusError {}
impl fmt::Display for JanusError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} (code: {})", self.to_cstr().to_str().unwrap()
, self.code)
}
}
/// A Janus plugin result; what a plugin returns to the gateway as a direct response to a signalling message.
#[derive(Debug)]
pub struct PluginResult {
ptr: *mut RawPluginResult,
}
impl PluginResult {
/// Creates a new plugin result.
pub unsafe fn new(type_: PluginResultType, text: *const c_char, content: *mut RawJanssonValue) -> Self {
Self { ptr: ffi::plugin::janus_plugin_result_new(type_, text, content) }
}
/// Creates a plugin result indicating a synchronously successful request. The provided response
/// JSON will be passed back to the client.
pub fn ok(response: JanssonValue) -> Self {
unsafe { Self::new(PluginResultType::JANUS_PLUGIN_OK, ptr::null(), response.into_raw()) }
}
/// Creates a plugin result indicating an asynchronous request in progress. If provided, the hint text
/// will be synchronously passed back to the client in the acknowledgement.
pub fn ok_wait(hint: Option<&'static CStr>) -> Self {
let hint_ptr = hint.map(|x| x.as_ptr()).unwrap_or_else(ptr::null);
unsafe { Self::new(PluginResultType::JANUS_PLUGIN_OK_WAIT, hint_ptr, ptr::null_mut()) }
}
/// Creates a plugin result indicating an error. The provided error text will be synchronously passed
/// back to the client.
pub fn error(msg: &'static CStr) -> Self {
unsafe { Self::new(PluginResultType::JANUS_PLUGIN_ERROR, msg.as_ptr(), ptr::null_mut()) }
}
/// Transfers ownership of this result to the wrapped raw pointer. The consumer is responsible for calling
/// `janus_plugin_result_destroy` on the pointer when finished.
pub fn into_raw(self) -> *mut RawPluginResult {
let ptr = self.ptr;
mem::forget(self);
ptr
}
}
impl Deref for PluginResult {
type Target = RawPluginResult;
fn deref(&self) -> &RawPluginResult {
unsafe { &*self.ptr }
}
}
impl Drop for PluginResult {
fn drop(&mut self) {
unsafe { ffi::plugin::janus_plugin_result_destroy(self.ptr) }
}
}
unsafe impl Send for PluginResult {}
#[derive(Debug)]
/// Represents metadata about this library which Janus can query at runtime.
pub struct LibraryMetadata<'a> {
pub api_version: c_int,
pub version: c_int,
pub version_str: &'a CStr,
pub description: &'a CStr,
pub name: &'a CStr,
pub author: &'a CStr,
pub package: &'a CStr,
}
/// Helper macro to produce a Janus plugin instance. Should be called with
/// a `LibraryMetadata` instance and a series of exported plugin callbacks.
#[macro_export]
macro_rules! build_plugin {
($md:expr, $($cb:ident),*) => {{
extern "C" fn get_api_compatibility() -> c_int { $md.api_version }
extern "C" fn get_version() -> c_int { $md.version }
extern "C" fn get_version_string() -> *const c_char { $md.version_str.as_ptr() }
extern "C" fn get_description() -> *const c_char { $md.description.as_ptr() }
extern "C" fn get_name() -> *const c_char { $md.name.as_ptr() }
extern "C" fn get_author() -> *const c_char { $md.author.as_ptr() }
extern "C" fn get_package() -> *const c_char { $md.package.as_ptr() }
$crate::Plugin {
get_api_compatibility,
get_version,
get_version_string,
get_description,
get_name,
get_author,
get_package,
$($cb,)*
}
}}
}
/// Macro to export a Janus plugin instance from this module.
#[macro_export]
macro_rules! export_plugin {
($pl:expr) => {
/// Called by Janus to create an instance of this plugin, using the provided callbacks to dispatch events.
#[no_mangle]
pub extern "C" fn create() -> *const $crate::Plugin { $pl }
}
}
/// Helper macro to produce a Janus event handler instance. Should be called with
/// a `LibraryMetadata` instance and a series of exported event handler callbacks.
#[macro_export]
macro_rules! build_eventhandler {
($md:expr, $mask:expr, $($cb:ident),*) => {{
extern "C" fn get_api_compatibility() -> c_int { $md.api_version }
extern "C" fn get_version() -> c_int { $md.version }
extern "C" fn get_version_string() -> *const c_char { $md.version_str.as_ptr() }
extern "C" fn get_description() -> *const c_char { $md.description.as_ptr() }
extern "C" fn get_name() -> *const c_char { $md.name.as_ptr() }
extern "C" fn get_author() -> *const c_char { $md.author.as_ptr() }
extern "C" fn get_package() -> *const c_char { $md.package.as_ptr() }
$crate::EventHandler {
events_mask: $mask,
get_api_compatibility,
get_version,
get_version_string,
get_description,
get_name,
get_author,
get_package,
$($cb,)*
}
}}
}
/// Macro to export a Janus event handler instance from this module.
#[macro_export]
macro_rules! export_eventhandler {
($evh:expr) => {
/// Called by Janus to create an instance of this event handler, using the provided callbacks to dispatch events.
#[no_mangle]
pub extern "C" fn create() -> *const $crate::EventHandler { $evh }
}
}
| from | identifier_name |
lib.rs | #![deny(missing_debug_implementations)]
use janus_plugin_sys as ffi;
use bitflags::bitflags;
pub use debug::LogLevel;
pub use debug::log;
pub use jansson::{JanssonDecodingFlags, JanssonEncodingFlags, JanssonValue, RawJanssonValue};
pub use session::SessionWrapper;
pub use ffi::events::janus_eventhandler as EventHandler;
pub use ffi::plugin::janus_callbacks as PluginCallbacks;
pub use ffi::plugin::janus_plugin as Plugin;
pub use ffi::plugin::janus_plugin_result as RawPluginResult;
pub use ffi::plugin::janus_plugin_session as PluginSession;
pub use ffi::plugin::janus_plugin_rtp as PluginRtpPacket;
pub use ffi::plugin::janus_plugin_rtcp as PluginRtcpPacket;
pub use ffi::plugin::janus_plugin_data as PluginDataPacket;
pub use ffi::plugin::janus_plugin_rtp_extensions as PluginRtpExtensions;
use ffi::plugin::janus_plugin_result_type as PluginResultType;
use std::error::Error;
use std::fmt;
use std::ffi::CStr;
use std::mem;
use std::ops::Deref;
use std::os::raw::{c_char, c_int};
use std::ptr;
pub mod debug;
pub mod rtcp;
pub mod sdp;
pub mod session;
pub mod jansson;
pub mod utils;
pub mod refcount;
bitflags! {
/// Flags that control which events an event handler receives.
pub struct JanusEventType: u32 {
const JANUS_EVENT_TYPE_SESSION = 1 << 0;
const JANUS_EVENT_TYPE_HANDLE = 1 << 1;
const JANUS_EVENT_TYPE_JSEP = 1 << 3; // yes, really
const JANUS_EVENT_TYPE_WEBRTC = 1 << 4;
const JANUS_EVENT_TYPE_MEDIA = 1 << 5;
const JANUS_EVENT_TYPE_PLUGIN = 1 << 6;
const JANUS_EVENT_TYPE_TRANSPORT = 1 << 7;
const JANUS_EVENT_TYPE_CORE = 1 << 8;
}
}
/// An error emitted by the Janus core in response to a plugin pushing an event.
#[derive(Debug, Clone, Copy)]
pub struct JanusError {
pub code: i32
}
/// A result from pushing an event to Janus core.
pub type JanusResult = Result<(), JanusError>;
impl JanusError {
/// Returns Janus's description text for this error.
pub fn to_cstr(self) -> &'static CStr {
unsafe { CStr::from_ptr(ffi::janus_get_api_error(self.code)) }
}
/// Converts a Janus result code to either success or a potential error.
pub fn from(val: i32) -> JanusResult {
match val {
0 => Ok(()),
e => Err(JanusError { code: e })
}
}
}
impl Error for JanusError {}
impl fmt::Display for JanusError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} (code: {})", self.to_cstr().to_str().unwrap()
, self.code)
}
}
/// A Janus plugin result; what a plugin returns to the gateway as a direct response to a signalling message.
#[derive(Debug)]
pub struct PluginResult {
ptr: *mut RawPluginResult,
}
impl PluginResult {
/// Creates a new plugin result.
pub unsafe fn new(type_: PluginResultType, text: *const c_char, content: *mut RawJanssonValue) -> Self {
Self { ptr: ffi::plugin::janus_plugin_result_new(type_, text, content) }
}
/// Creates a plugin result indicating a synchronously successful request. The provided response
/// JSON will be passed back to the client.
pub fn ok(response: JanssonValue) -> Self {
unsafe { Self::new(PluginResultType::JANUS_PLUGIN_OK, ptr::null(), response.into_raw()) }
}
/// Creates a plugin result indicating an asynchronous request in progress. If provided, the hint text
/// will be synchronously passed back to the client in the acknowledgement.
pub fn ok_wait(hint: Option<&'static CStr>) -> Self {
let hint_ptr = hint.map(|x| x.as_ptr()).unwrap_or_else(ptr::null);
unsafe { Self::new(PluginResultType::JANUS_PLUGIN_OK_WAIT, hint_ptr, ptr::null_mut()) }
}
/// Creates a plugin result indicating an error. The provided error text will be synchronously passed
/// back to the client.
pub fn error(msg: &'static CStr) -> Self {
unsafe { Self::new(PluginResultType::JANUS_PLUGIN_ERROR, msg.as_ptr(), ptr::null_mut()) }
}
/// Transfers ownership of this result to the wrapped raw pointer. The consumer is responsible for calling
/// `janus_plugin_result_destroy` on the pointer when finished.
pub fn into_raw(self) -> *mut RawPluginResult |
}
impl Deref for PluginResult {
type Target = RawPluginResult;
fn deref(&self) -> &RawPluginResult {
unsafe { &*self.ptr }
}
}
impl Drop for PluginResult {
fn drop(&mut self) {
unsafe { ffi::plugin::janus_plugin_result_destroy(self.ptr) }
}
}
unsafe impl Send for PluginResult {}
#[derive(Debug)]
/// Represents metadata about this library which Janus can query at runtime.
pub struct LibraryMetadata<'a> {
pub api_version: c_int,
pub version: c_int,
pub version_str: &'a CStr,
pub description: &'a CStr,
pub name: &'a CStr,
pub author: &'a CStr,
pub package: &'a CStr,
}
/// Helper macro to produce a Janus plugin instance. Should be called with
/// a `LibraryMetadata` instance and a series of exported plugin callbacks.
#[macro_export]
macro_rules! build_plugin {
($md:expr, $($cb:ident),*) => {{
extern "C" fn get_api_compatibility() -> c_int { $md.api_version }
extern "C" fn get_version() -> c_int { $md.version }
extern "C" fn get_version_string() -> *const c_char { $md.version_str.as_ptr() }
extern "C" fn get_description() -> *const c_char { $md.description.as_ptr() }
extern "C" fn get_name() -> *const c_char { $md.name.as_ptr() }
extern "C" fn get_author() -> *const c_char { $md.author.as_ptr() }
extern "C" fn get_package() -> *const c_char { $md.package.as_ptr() }
$crate::Plugin {
get_api_compatibility,
get_version,
get_version_string,
get_description,
get_name,
get_author,
get_package,
$($cb,)*
}
}}
}
/// Macro to export a Janus plugin instance from this module.
#[macro_export]
macro_rules! export_plugin {
($pl:expr) => {
/// Called by Janus to create an instance of this plugin, using the provided callbacks to dispatch events.
#[no_mangle]
pub extern "C" fn create() -> *const $crate::Plugin { $pl }
}
}
/// Helper macro to produce a Janus event handler instance. Should be called with
/// a `LibraryMetadata` instance and a series of exported event handler callbacks.
#[macro_export]
macro_rules! build_eventhandler {
($md:expr, $mask:expr, $($cb:ident),*) => {{
extern "C" fn get_api_compatibility() -> c_int { $md.api_version }
extern "C" fn get_version() -> c_int { $md.version }
extern "C" fn get_version_string() -> *const c_char { $md.version_str.as_ptr() }
extern "C" fn get_description() -> *const c_char { $md.description.as_ptr() }
extern "C" fn get_name() -> *const c_char { $md.name.as_ptr() }
extern "C" fn get_author() -> *const c_char { $md.author.as_ptr() }
extern "C" fn get_package() -> *const c_char { $md.package.as_ptr() }
$crate::EventHandler {
events_mask: $mask,
get_api_compatibility,
get_version,
get_version_string,
get_description,
get_name,
get_author,
get_package,
$($cb,)*
}
}}
}
/// Macro to export a Janus event handler instance from this module.
#[macro_export]
macro_rules! export_eventhandler {
($evh:expr) => {
/// Called by Janus to create an instance of this event handler, using the provided callbacks to dispatch events.
#[no_mangle]
pub extern "C" fn create() -> *const $crate::EventHandler { $evh }
}
}
| {
let ptr = self.ptr;
mem::forget(self);
ptr
} | identifier_body |
lib.rs | #![deny(missing_debug_implementations)]
use janus_plugin_sys as ffi;
use bitflags::bitflags;
pub use debug::LogLevel;
pub use debug::log;
pub use jansson::{JanssonDecodingFlags, JanssonEncodingFlags, JanssonValue, RawJanssonValue};
pub use session::SessionWrapper;
pub use ffi::events::janus_eventhandler as EventHandler;
pub use ffi::plugin::janus_callbacks as PluginCallbacks;
pub use ffi::plugin::janus_plugin as Plugin;
pub use ffi::plugin::janus_plugin_result as RawPluginResult;
pub use ffi::plugin::janus_plugin_session as PluginSession;
pub use ffi::plugin::janus_plugin_rtp as PluginRtpPacket;
pub use ffi::plugin::janus_plugin_rtcp as PluginRtcpPacket;
pub use ffi::plugin::janus_plugin_data as PluginDataPacket;
pub use ffi::plugin::janus_plugin_rtp_extensions as PluginRtpExtensions;
use ffi::plugin::janus_plugin_result_type as PluginResultType;
use std::error::Error;
use std::fmt;
use std::ffi::CStr;
use std::mem;
use std::ops::Deref;
use std::os::raw::{c_char, c_int};
use std::ptr;
pub mod debug;
pub mod rtcp;
pub mod sdp;
pub mod session;
pub mod jansson;
pub mod utils;
pub mod refcount;
bitflags! {
/// Flags that control which events an event handler receives.
pub struct JanusEventType: u32 {
const JANUS_EVENT_TYPE_SESSION = 1 << 0;
const JANUS_EVENT_TYPE_HANDLE = 1 << 1;
const JANUS_EVENT_TYPE_JSEP = 1 << 3; // yes, really
const JANUS_EVENT_TYPE_WEBRTC = 1 << 4;
const JANUS_EVENT_TYPE_MEDIA = 1 << 5;
const JANUS_EVENT_TYPE_PLUGIN = 1 << 6;
const JANUS_EVENT_TYPE_TRANSPORT = 1 << 7;
const JANUS_EVENT_TYPE_CORE = 1 << 8;
}
}
/// An error emitted by the Janus core in response to a plugin pushing an event.
#[derive(Debug, Clone, Copy)]
pub struct JanusError {
pub code: i32
}
/// A result from pushing an event to Janus core.
pub type JanusResult = Result<(), JanusError>;
impl JanusError {
/// Returns Janus's description text for this error.
pub fn to_cstr(self) -> &'static CStr {
unsafe { CStr::from_ptr(ffi::janus_get_api_error(self.code)) }
}
/// Converts a Janus result code to either success or a potential error.
pub fn from(val: i32) -> JanusResult {
match val {
0 => Ok(()),
e => Err(JanusError { code: e })
}
}
}
impl Error for JanusError {}
impl fmt::Display for JanusError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} (code: {})", self.to_cstr().to_str().unwrap()
, self.code)
}
}
/// A Janus plugin result; what a plugin returns to the gateway as a direct response to a signalling message.
#[derive(Debug)]
pub struct PluginResult {
ptr: *mut RawPluginResult,
}
impl PluginResult {
/// Creates a new plugin result.
pub unsafe fn new(type_: PluginResultType, text: *const c_char, content: *mut RawJanssonValue) -> Self {
Self { ptr: ffi::plugin::janus_plugin_result_new(type_, text, content) }
}
/// Creates a plugin result indicating a synchronously successful request. The provided response
/// JSON will be passed back to the client.
pub fn ok(response: JanssonValue) -> Self {
unsafe { Self::new(PluginResultType::JANUS_PLUGIN_OK, ptr::null(), response.into_raw()) }
}
/// Creates a plugin result indicating an asynchronous request in progress. If provided, the hint text
/// will be synchronously passed back to the client in the acknowledgement.
pub fn ok_wait(hint: Option<&'static CStr>) -> Self {
let hint_ptr = hint.map(|x| x.as_ptr()).unwrap_or_else(ptr::null);
unsafe { Self::new(PluginResultType::JANUS_PLUGIN_OK_WAIT, hint_ptr, ptr::null_mut()) }
}
/// Creates a plugin result indicating an error. The provided error text will be synchronously passed
/// back to the client.
pub fn error(msg: &'static CStr) -> Self {
unsafe { Self::new(PluginResultType::JANUS_PLUGIN_ERROR, msg.as_ptr(), ptr::null_mut()) }
}
/// Transfers ownership of this result to the wrapped raw pointer. The consumer is responsible for calling
/// `janus_plugin_result_destroy` on the pointer when finished.
pub fn into_raw(self) -> *mut RawPluginResult {
let ptr = self.ptr;
mem::forget(self);
ptr
}
}
impl Deref for PluginResult {
type Target = RawPluginResult;
fn deref(&self) -> &RawPluginResult {
unsafe { &*self.ptr }
}
}
impl Drop for PluginResult {
fn drop(&mut self) {
unsafe { ffi::plugin::janus_plugin_result_destroy(self.ptr) }
}
}
unsafe impl Send for PluginResult {}
#[derive(Debug)]
/// Represents metadata about this library which Janus can query at runtime.
pub struct LibraryMetadata<'a> {
pub api_version: c_int,
pub version: c_int,
pub version_str: &'a CStr,
pub description: &'a CStr,
pub name: &'a CStr,
pub author: &'a CStr,
pub package: &'a CStr,
}
/// Helper macro to produce a Janus plugin instance. Should be called with
/// a `LibraryMetadata` instance and a series of exported plugin callbacks.
#[macro_export]
macro_rules! build_plugin {
($md:expr, $($cb:ident),*) => {{
extern "C" fn get_api_compatibility() -> c_int { $md.api_version }
extern "C" fn get_version() -> c_int { $md.version } | $crate::Plugin {
get_api_compatibility,
get_version,
get_version_string,
get_description,
get_name,
get_author,
get_package,
$($cb,)*
}
}}
}
/// Macro to export a Janus plugin instance from this module.
#[macro_export]
macro_rules! export_plugin {
($pl:expr) => {
/// Called by Janus to create an instance of this plugin, using the provided callbacks to dispatch events.
#[no_mangle]
pub extern "C" fn create() -> *const $crate::Plugin { $pl }
}
}
/// Helper macro to produce a Janus event handler instance. Should be called with
/// a `LibraryMetadata` instance and a series of exported event handler callbacks.
#[macro_export]
macro_rules! build_eventhandler {
($md:expr, $mask:expr, $($cb:ident),*) => {{
extern "C" fn get_api_compatibility() -> c_int { $md.api_version }
extern "C" fn get_version() -> c_int { $md.version }
extern "C" fn get_version_string() -> *const c_char { $md.version_str.as_ptr() }
extern "C" fn get_description() -> *const c_char { $md.description.as_ptr() }
extern "C" fn get_name() -> *const c_char { $md.name.as_ptr() }
extern "C" fn get_author() -> *const c_char { $md.author.as_ptr() }
extern "C" fn get_package() -> *const c_char { $md.package.as_ptr() }
$crate::EventHandler {
events_mask: $mask,
get_api_compatibility,
get_version,
get_version_string,
get_description,
get_name,
get_author,
get_package,
$($cb,)*
}
}}
}
/// Macro to export a Janus event handler instance from this module.
#[macro_export]
macro_rules! export_eventhandler {
($evh:expr) => {
/// Called by Janus to create an instance of this event handler, using the provided callbacks to dispatch events.
#[no_mangle]
pub extern "C" fn create() -> *const $crate::EventHandler { $evh }
}
} | extern "C" fn get_version_string() -> *const c_char { $md.version_str.as_ptr() }
extern "C" fn get_description() -> *const c_char { $md.description.as_ptr() }
extern "C" fn get_name() -> *const c_char { $md.name.as_ptr() }
extern "C" fn get_author() -> *const c_char { $md.author.as_ptr() }
extern "C" fn get_package() -> *const c_char { $md.package.as_ptr() } | random_line_split |
form.py | """Form classes."""
from .errors import ValidationError
from .meta import FormBuilder
from .types import FormType, ListType, SetType, DictType
from .utils import Struct
class Form(object):
"""A form."""
__metaclass__ = FormBuilder
@classmethod
def from_obj(cls, obj):
"""
Return a form object containing the values extracted from attributes on the provided
object. No decoding or validation is performed. This has the same effect as passing the
values as kwargs to `__init__`. Missing attributes are skipped.
"""
def obj_to_dict(form, obj):
values = {}
for name, field in form._meta.fields.iteritems():
if hasattr(obj, name):
value = getattr(obj, name)
if value is not None:
if isinstance(field.typ, FormType):
value = obj_to_dict(field.typ.form, value)
if (isinstance(field.typ, (ListType, SetType)) and
isinstance(field.typ.typ, FormType)):
value = [obj_to_dict(field.typ.typ.form, v) for v in value]
if (isinstance(field.typ, DictType) and
isinstance(field.typ.typ, FormType)):
value = {k: obj_to_dict(field.typ.typ.form, v)
for k, v in value.iteritems()}
values[name] = value
return values
values = obj_to_dict(cls, obj)
return cls(**values)
@classmethod
def decode(cls, raw, extra=None, require=True, validate=True):
"""
Return a form object containing the raw form data. By default fields present in raw that
are not defined on the form will cause a ValidationError. If extra is True then all extra
fields are ignored. If extra is a list then extra fields in that list will be ignored.
Fields not in the list will still cause a ValidationError. By default values missing in raw
whose field has require=True will raise a ValidationError. If the require parameter is set
to False then these values will be replaced with their defaults. Values in raw set to None
are considered to be missing. If the validate parameter is False then field validation will
be skipped.
"""
raw = raw.copy()
attrs = {}
for name, field in cls._meta.fields.iteritems():
value = raw.pop(name, None)
if value is None and require and field.require:
msg = "{} data is missing required fields: {}".format(cls.__name__, name)
raise ValidationError(msg)
if value is not None:
attrs[name] = field.decode(cls, name, value)
if len(raw) > 0 and extra is not True:
invalid = set(raw.keys()) - (extra and set(extra) or set())
if invalid:
invalid = ', '.join(sorted(invalid))
msg = "{} data has extra fields: {}".format(cls.__name__, invalid)
raise ValidationError(msg)
form = cls()
form._attrs.update(attrs)
if validate:
form.validate()
return form
def __init__(self, *args, **kwargs):
"""Initialize a form object."""
for name, value in kwargs.iteritems():
setattr(self, name, value)
def encode(self, missing=False):
"""
Return the form data encoded as a dictionary ready for serialization. Data is not validated
during this method. If missing is True then fields set to `None` will be included.
"""
encoded = {}
for name, field in self._meta.fields.iteritems():
value = self._attrs.get(name)
if value is not None:
value = field.encode(self.__class__, name, value)
if value is not None or missing:
encoded[name] = value
return encoded
def validate(self):
"""Validate the decoded form data. Raise ValidationError on failure."""
for name, field in self._meta.fields.iteritems():
value = self._attrs.get(name)
if value is None and field.require is True:
msg = "{} data is missing required fields: {}"
raise ValidationError(msg.format(self.__class__.__name__, name))
if value is not None:
field.validate(self.__class__, name, value)
def to_dict(self):
"""Return the decoded form data as a dictionary."""
def copy(value):
if isinstance(value, dict):
value = {k: copy(v) for k, v in value.iteritems()}
return value
return copy(self._attrs)
def to_obj(self, obj=None):
"""
Return the decoded form data as an object. If the obj parameter is provided then it will be
loaded with the data. Otherwise a new object is created to return.
"""
if obj is None:
obj = Struct()
for name, field in self._meta.fields.iteritems():
|
return obj
| value = self._attrs.get(name)
if isinstance(field.typ, FormType):
obj_attr = getattr(obj, name, None)
subform = field.typ.form(**value)
value = subform.to_obj(obj_attr)
setattr(obj, name, value) | conditional_block |
form.py | """Form classes."""
from .errors import ValidationError
from .meta import FormBuilder
from .types import FormType, ListType, SetType, DictType
from .utils import Struct
class Form(object):
"""A form."""
__metaclass__ = FormBuilder
@classmethod
def from_obj(cls, obj):
"""
Return a form object containing the values extracted from attributes on the provided
object. No decoding or validation is performed. This has the same effect as passing the
values as kwargs to `__init__`. Missing attributes are skipped.
"""
def obj_to_dict(form, obj):
values = {}
for name, field in form._meta.fields.iteritems():
if hasattr(obj, name):
value = getattr(obj, name)
if value is not None:
if isinstance(field.typ, FormType):
value = obj_to_dict(field.typ.form, value)
if (isinstance(field.typ, (ListType, SetType)) and
isinstance(field.typ.typ, FormType)):
value = [obj_to_dict(field.typ.typ.form, v) for v in value]
if (isinstance(field.typ, DictType) and
isinstance(field.typ.typ, FormType)):
value = {k: obj_to_dict(field.typ.typ.form, v)
for k, v in value.iteritems()}
values[name] = value
return values
values = obj_to_dict(cls, obj)
return cls(**values)
@classmethod
def decode(cls, raw, extra=None, require=True, validate=True):
"""
Return a form object containing the raw form data. By default fields present in raw that
are not defined on the form will cause a ValidationError. If extra is True then all extra
fields are ignored. If extra is a list then extra fields in that list will be ignored.
Fields not in the list will still cause a ValidationError. By default values missing in raw
whose field has require=True will raise a ValidationError. If the require parameter is set
to False then these values will be replaced with their defaults. Values in raw set to None
are considered to be missing. If the validate parameter is False then field validation will
be skipped.
"""
raw = raw.copy()
attrs = {}
for name, field in cls._meta.fields.iteritems():
value = raw.pop(name, None)
if value is None and require and field.require:
msg = "{} data is missing required fields: {}".format(cls.__name__, name)
raise ValidationError(msg)
if value is not None:
attrs[name] = field.decode(cls, name, value)
if len(raw) > 0 and extra is not True:
invalid = set(raw.keys()) - (extra and set(extra) or set())
if invalid:
invalid = ', '.join(sorted(invalid))
msg = "{} data has extra fields: {}".format(cls.__name__, invalid)
raise ValidationError(msg)
form = cls()
form._attrs.update(attrs)
if validate:
form.validate()
return form
def __init__(self, *args, **kwargs):
"""Initialize a form object."""
for name, value in kwargs.iteritems():
setattr(self, name, value)
def encode(self, missing=False):
"""
Return the form data encoded as a dictionary ready for serialization. Data is not validated
during this method. If missing is True then fields set to `None` will be included.
"""
encoded = {}
for name, field in self._meta.fields.iteritems():
value = self._attrs.get(name)
if value is not None:
value = field.encode(self.__class__, name, value)
if value is not None or missing:
encoded[name] = value
return encoded
def | (self):
"""Validate the decoded form data. Raise ValidationError on failure."""
for name, field in self._meta.fields.iteritems():
value = self._attrs.get(name)
if value is None and field.require is True:
msg = "{} data is missing required fields: {}"
raise ValidationError(msg.format(self.__class__.__name__, name))
if value is not None:
field.validate(self.__class__, name, value)
def to_dict(self):
"""Return the decoded form data as a dictionary."""
def copy(value):
if isinstance(value, dict):
value = {k: copy(v) for k, v in value.iteritems()}
return value
return copy(self._attrs)
def to_obj(self, obj=None):
"""
Return the decoded form data as an object. If the obj parameter is provided then it will be
loaded with the data. Otherwise a new object is created to return.
"""
if obj is None:
obj = Struct()
for name, field in self._meta.fields.iteritems():
value = self._attrs.get(name)
if isinstance(field.typ, FormType):
obj_attr = getattr(obj, name, None)
subform = field.typ.form(**value)
value = subform.to_obj(obj_attr)
setattr(obj, name, value)
return obj
| validate | identifier_name |
form.py | """Form classes."""
from .errors import ValidationError
from .meta import FormBuilder
from .types import FormType, ListType, SetType, DictType
from .utils import Struct
class Form(object):
"""A form."""
__metaclass__ = FormBuilder
@classmethod
def from_obj(cls, obj):
"""
Return a form object containing the values extracted from attributes on the provided
object. No decoding or validation is performed. This has the same effect as passing the
values as kwargs to `__init__`. Missing attributes are skipped.
"""
def obj_to_dict(form, obj):
values = {}
for name, field in form._meta.fields.iteritems():
if hasattr(obj, name):
value = getattr(obj, name)
if value is not None:
if isinstance(field.typ, FormType):
value = obj_to_dict(field.typ.form, value)
if (isinstance(field.typ, (ListType, SetType)) and
isinstance(field.typ.typ, FormType)):
value = [obj_to_dict(field.typ.typ.form, v) for v in value]
if (isinstance(field.typ, DictType) and
isinstance(field.typ.typ, FormType)):
value = {k: obj_to_dict(field.typ.typ.form, v)
for k, v in value.iteritems()}
values[name] = value
return values
values = obj_to_dict(cls, obj)
return cls(**values)
@classmethod
def decode(cls, raw, extra=None, require=True, validate=True):
"""
Return a form object containing the raw form data. By default fields present in raw that
are not defined on the form will cause a ValidationError. If extra is True then all extra
fields are ignored. If extra is a list then extra fields in that list will be ignored.
Fields not in the list will still cause a ValidationError. By default values missing in raw
whose field has require=True will raise a ValidationError. If the require parameter is set
to False then these values will be replaced with their defaults. Values in raw set to None
are considered to be missing. If the validate parameter is False then field validation will
be skipped.
"""
raw = raw.copy()
attrs = {}
for name, field in cls._meta.fields.iteritems():
value = raw.pop(name, None)
if value is None and require and field.require:
msg = "{} data is missing required fields: {}".format(cls.__name__, name)
raise ValidationError(msg)
if value is not None:
attrs[name] = field.decode(cls, name, value)
if len(raw) > 0 and extra is not True:
invalid = set(raw.keys()) - (extra and set(extra) or set())
if invalid:
invalid = ', '.join(sorted(invalid))
msg = "{} data has extra fields: {}".format(cls.__name__, invalid)
raise ValidationError(msg)
form = cls()
form._attrs.update(attrs)
if validate:
form.validate()
return form
def __init__(self, *args, **kwargs):
"""Initialize a form object."""
for name, value in kwargs.iteritems():
setattr(self, name, value)
def encode(self, missing=False):
"""
Return the form data encoded as a dictionary ready for serialization. Data is not validated
during this method. If missing is True then fields set to `None` will be included.
"""
encoded = {}
for name, field in self._meta.fields.iteritems():
value = self._attrs.get(name)
if value is not None:
value = field.encode(self.__class__, name, value)
if value is not None or missing:
encoded[name] = value
return encoded
def validate(self):
"""Validate the decoded form data. Raise ValidationError on failure."""
for name, field in self._meta.fields.iteritems():
value = self._attrs.get(name)
if value is None and field.require is True:
msg = "{} data is missing required fields: {}" | raise ValidationError(msg.format(self.__class__.__name__, name))
if value is not None:
field.validate(self.__class__, name, value)
def to_dict(self):
"""Return the decoded form data as a dictionary."""
def copy(value):
if isinstance(value, dict):
value = {k: copy(v) for k, v in value.iteritems()}
return value
return copy(self._attrs)
def to_obj(self, obj=None):
"""
Return the decoded form data as an object. If the obj parameter is provided then it will be
loaded with the data. Otherwise a new object is created to return.
"""
if obj is None:
obj = Struct()
for name, field in self._meta.fields.iteritems():
value = self._attrs.get(name)
if isinstance(field.typ, FormType):
obj_attr = getattr(obj, name, None)
subform = field.typ.form(**value)
value = subform.to_obj(obj_attr)
setattr(obj, name, value)
return obj | random_line_split |
|
form.py | """Form classes."""
from .errors import ValidationError
from .meta import FormBuilder
from .types import FormType, ListType, SetType, DictType
from .utils import Struct
class Form(object):
"""A form."""
__metaclass__ = FormBuilder
@classmethod
def from_obj(cls, obj):
"""
Return a form object containing the values extracted from attributes on the provided
object. No decoding or validation is performed. This has the same effect as passing the
values as kwargs to `__init__`. Missing attributes are skipped.
"""
def obj_to_dict(form, obj):
values = {}
for name, field in form._meta.fields.iteritems():
if hasattr(obj, name):
value = getattr(obj, name)
if value is not None:
if isinstance(field.typ, FormType):
value = obj_to_dict(field.typ.form, value)
if (isinstance(field.typ, (ListType, SetType)) and
isinstance(field.typ.typ, FormType)):
value = [obj_to_dict(field.typ.typ.form, v) for v in value]
if (isinstance(field.typ, DictType) and
isinstance(field.typ.typ, FormType)):
value = {k: obj_to_dict(field.typ.typ.form, v)
for k, v in value.iteritems()}
values[name] = value
return values
values = obj_to_dict(cls, obj)
return cls(**values)
@classmethod
def decode(cls, raw, extra=None, require=True, validate=True):
"""
Return a form object containing the raw form data. By default fields present in raw that
are not defined on the form will cause a ValidationError. If extra is True then all extra
fields are ignored. If extra is a list then extra fields in that list will be ignored.
Fields not in the list will still cause a ValidationError. By default values missing in raw
whose field has require=True will raise a ValidationError. If the require parameter is set
to False then these values will be replaced with their defaults. Values in raw set to None
are considered to be missing. If the validate parameter is False then field validation will
be skipped.
"""
raw = raw.copy()
attrs = {}
for name, field in cls._meta.fields.iteritems():
value = raw.pop(name, None)
if value is None and require and field.require:
msg = "{} data is missing required fields: {}".format(cls.__name__, name)
raise ValidationError(msg)
if value is not None:
attrs[name] = field.decode(cls, name, value)
if len(raw) > 0 and extra is not True:
invalid = set(raw.keys()) - (extra and set(extra) or set())
if invalid:
invalid = ', '.join(sorted(invalid))
msg = "{} data has extra fields: {}".format(cls.__name__, invalid)
raise ValidationError(msg)
form = cls()
form._attrs.update(attrs)
if validate:
form.validate()
return form
def __init__(self, *args, **kwargs):
"""Initialize a form object."""
for name, value in kwargs.iteritems():
setattr(self, name, value)
def encode(self, missing=False):
"""
Return the form data encoded as a dictionary ready for serialization. Data is not validated
during this method. If missing is True then fields set to `None` will be included.
"""
encoded = {}
for name, field in self._meta.fields.iteritems():
value = self._attrs.get(name)
if value is not None:
value = field.encode(self.__class__, name, value)
if value is not None or missing:
encoded[name] = value
return encoded
def validate(self):
"""Validate the decoded form data. Raise ValidationError on failure."""
for name, field in self._meta.fields.iteritems():
value = self._attrs.get(name)
if value is None and field.require is True:
msg = "{} data is missing required fields: {}"
raise ValidationError(msg.format(self.__class__.__name__, name))
if value is not None:
field.validate(self.__class__, name, value)
def to_dict(self):
"""Return the decoded form data as a dictionary."""
def copy(value):
if isinstance(value, dict):
value = {k: copy(v) for k, v in value.iteritems()}
return value
return copy(self._attrs)
def to_obj(self, obj=None):
| """
Return the decoded form data as an object. If the obj parameter is provided then it will be
loaded with the data. Otherwise a new object is created to return.
"""
if obj is None:
obj = Struct()
for name, field in self._meta.fields.iteritems():
value = self._attrs.get(name)
if isinstance(field.typ, FormType):
obj_attr = getattr(obj, name, None)
subform = field.typ.form(**value)
value = subform.to_obj(obj_attr)
setattr(obj, name, value)
return obj | identifier_body |
|
urls.py | from __future__ import absolute_import
| from django.conf.urls import url
from . import views as test_views
urlpatterns = [
url(r'^no-logging$', test_views.MockNoLoggingView.as_view()),
url(r'^logging$', test_views.MockLoggingView.as_view()),
url(r'^slow-logging$', test_views.MockSlowLoggingView.as_view()),
url(r'^explicit-logging$', test_views.MockExplicitLoggingView.as_view()),
url(r'^unsafe-methods-logging$', test_views.MockUnsafeMethodsLoggingView.as_view()),
url(r'^no-response-save-logging$', test_views.MockNotSaveResponseLoggingView.as_view()),
url(r'^session-auth-logging$', test_views.MockSessionAuthLoggingView.as_view()),
url(r'^token-auth-logging$', test_views.MockTokenAuthLoggingView.as_view()),
url(r'^json-logging$', test_views.MockJSONLoggingView.as_view()),
url(r'^validation-error-logging$', test_views.MockValidationErrorLoggingView.as_view()),
url(r'^404-error-logging$', test_views.Mock404ErrorLoggingView.as_view()),
url(r'^500-error-logging$', test_views.Mock500ErrorLoggingView.as_view()),
url(r'^415-error-logging$', test_views.Mock415ErrorLoggingView.as_view()),
url(r'^only-error-logging$', test_views.MockOnlyErrorLoggingView.as_view()),
url(r'^no-view-log$', test_views.MockNameAPIView.as_view()),
url(r'^view-log$', test_views.MockNameViewSet.as_view({'get': 'list'})),
url(r'^400-body-parse-error-logging$', test_views.Mock400BodyParseErrorLoggingView.as_view()),
] | random_line_split |
|
example.js | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var lastModuleError = '';
var crashed = false;
function domContentLoaded(name, tc, config, width, height) {
common.attachDefaultListeners();
common.createNaClModule(name, tc, config, width, height);
updateStatus('Page Loaded');
}
// Indicate success when the NaCl module has loaded.
function moduleDidLoad() {
updateStatus('LOADED');
setTimeout(boom, 2000);
}
function findAddress(addr, map) {
if (map.length < 1) {
return 'MAP Unavailable';
}
if (addr < map[0].offs) {
return 'Invalid Address';
}
for (var i = 1; i < map.length; i++) {
if (addr < map[i].offs) {
var offs = addr - map[i - 1].offs;
var filename = map[i - 1].file;
// Force filename to 50 chars
if (filename) {
if (filename.length > 50) {
filename = '...' + filename.substr(filename.length - 47);
}
} else {
filename = 'Unknown';
} | }
return filename + ' ' + map[i - 1].name + ' + 0x' + offs.toString(16);
}
}
var last = map.length - 1;
return filename + ' ' + map[last].name + ' + 0x' + offs.toString(16);
}
function buildTextMap(map) {
// The expected format of the map file is this:
// ...
// .text 0x00000000000201e0 0x10e0 newlib/Debug/debugging_x86_64.o
// 0x0000000000020280 layer5
// 0x00000000000202e0 layer4
// 0x0000000000020320 layer3
// 0x0000000000020380 layer2
// 0x00000000000203e0 layer1
// 0x0000000000020460 NexeMain
// ...
var lines = map.split('\n');
var orderedMap = [];
var inTextSection = false;
var fileName = '';
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (inTextSection) {
// <hex address> <symbol name>
var vals = line.trim().split(/\s+/);
if (vals.length != 2) {
inTextSection = false;
continue;
}
var obj = {
offs: parseInt(vals[0], 16),
name: vals[1],
file: fileName
};
orderedMap.push(obj);
} else {
// If line starts with .text:
if (line.lastIndexOf(' .text', 0) === 0) {
inTextSection = true;
// .text <hex address> <size> <filename>
var vals = line.trim().split(/\s+/);
fileName = vals[3];
}
}
}
orderedMap.sort(function(a, b) { return a.offs - b.offs; });
return orderedMap;
}
function updateStack(traceinfo, map) {
map = buildTextMap(map);
var text = 'Stack Trace\n';
for (var i = 0; i < traceinfo.frames.length; i++) {
var frame = traceinfo.frames[i];
var addr = findAddress(frame.prog_ctr, map);
text += '[' + i.toString(10) + '] ' + addr + '\n';
}
document.getElementById('trace').value = text;
}
function fetchMap(url, traceinfo) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', url, true);
xmlhttp.onload = function() {
updateStack(traceinfo, this.responseText);
};
xmlhttp.traceinfo = traceinfo;
xmlhttp.send();
}
// Handle a message coming from the NaCl module.
function handleMessage(message_event) {
msg_type = message_event.data.substring(0, 4);
msg_data = message_event.data.substring(5, message_event.data.length);
if (msg_type == 'LOG:') {
document.getElementById('log').value += msg_data + '\n';
return;
}
if (msg_type == 'TRC:') {
crashed = true;
document.getElementById('json').value = msg_data;
crash_info = JSON.parse(msg_data);
updateStatus('Crash Reported');
src = common.naclModule.getAttribute('path');
fetchMap(src + '/debugging_' + crash_info['arch'] + '.map', crash_info);
return;
}
}
function updateStatus(message) {
common.updateStatus(message);
if (message)
document.getElementById('log').value += message + '\n';
}
function boom() {
if (!crashed) {
updateStatus('Send BOOM');
common.naclModule.postMessage('BOOM');
}
} | while (filename.length < 50) {
filename = ' ' + filename; | random_line_split |
example.js | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var lastModuleError = '';
var crashed = false;
function | (name, tc, config, width, height) {
common.attachDefaultListeners();
common.createNaClModule(name, tc, config, width, height);
updateStatus('Page Loaded');
}
// Indicate success when the NaCl module has loaded.
function moduleDidLoad() {
updateStatus('LOADED');
setTimeout(boom, 2000);
}
function findAddress(addr, map) {
if (map.length < 1) {
return 'MAP Unavailable';
}
if (addr < map[0].offs) {
return 'Invalid Address';
}
for (var i = 1; i < map.length; i++) {
if (addr < map[i].offs) {
var offs = addr - map[i - 1].offs;
var filename = map[i - 1].file;
// Force filename to 50 chars
if (filename) {
if (filename.length > 50) {
filename = '...' + filename.substr(filename.length - 47);
}
} else {
filename = 'Unknown';
}
while (filename.length < 50) {
filename = ' ' + filename;
}
return filename + ' ' + map[i - 1].name + ' + 0x' + offs.toString(16);
}
}
var last = map.length - 1;
return filename + ' ' + map[last].name + ' + 0x' + offs.toString(16);
}
function buildTextMap(map) {
// The expected format of the map file is this:
// ...
// .text 0x00000000000201e0 0x10e0 newlib/Debug/debugging_x86_64.o
// 0x0000000000020280 layer5
// 0x00000000000202e0 layer4
// 0x0000000000020320 layer3
// 0x0000000000020380 layer2
// 0x00000000000203e0 layer1
// 0x0000000000020460 NexeMain
// ...
var lines = map.split('\n');
var orderedMap = [];
var inTextSection = false;
var fileName = '';
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (inTextSection) {
// <hex address> <symbol name>
var vals = line.trim().split(/\s+/);
if (vals.length != 2) {
inTextSection = false;
continue;
}
var obj = {
offs: parseInt(vals[0], 16),
name: vals[1],
file: fileName
};
orderedMap.push(obj);
} else {
// If line starts with .text:
if (line.lastIndexOf(' .text', 0) === 0) {
inTextSection = true;
// .text <hex address> <size> <filename>
var vals = line.trim().split(/\s+/);
fileName = vals[3];
}
}
}
orderedMap.sort(function(a, b) { return a.offs - b.offs; });
return orderedMap;
}
function updateStack(traceinfo, map) {
map = buildTextMap(map);
var text = 'Stack Trace\n';
for (var i = 0; i < traceinfo.frames.length; i++) {
var frame = traceinfo.frames[i];
var addr = findAddress(frame.prog_ctr, map);
text += '[' + i.toString(10) + '] ' + addr + '\n';
}
document.getElementById('trace').value = text;
}
function fetchMap(url, traceinfo) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', url, true);
xmlhttp.onload = function() {
updateStack(traceinfo, this.responseText);
};
xmlhttp.traceinfo = traceinfo;
xmlhttp.send();
}
// Handle a message coming from the NaCl module.
function handleMessage(message_event) {
msg_type = message_event.data.substring(0, 4);
msg_data = message_event.data.substring(5, message_event.data.length);
if (msg_type == 'LOG:') {
document.getElementById('log').value += msg_data + '\n';
return;
}
if (msg_type == 'TRC:') {
crashed = true;
document.getElementById('json').value = msg_data;
crash_info = JSON.parse(msg_data);
updateStatus('Crash Reported');
src = common.naclModule.getAttribute('path');
fetchMap(src + '/debugging_' + crash_info['arch'] + '.map', crash_info);
return;
}
}
function updateStatus(message) {
common.updateStatus(message);
if (message)
document.getElementById('log').value += message + '\n';
}
function boom() {
if (!crashed) {
updateStatus('Send BOOM');
common.naclModule.postMessage('BOOM');
}
}
| domContentLoaded | identifier_name |
example.js | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var lastModuleError = '';
var crashed = false;
function domContentLoaded(name, tc, config, width, height) {
common.attachDefaultListeners();
common.createNaClModule(name, tc, config, width, height);
updateStatus('Page Loaded');
}
// Indicate success when the NaCl module has loaded.
function moduleDidLoad() |
function findAddress(addr, map) {
if (map.length < 1) {
return 'MAP Unavailable';
}
if (addr < map[0].offs) {
return 'Invalid Address';
}
for (var i = 1; i < map.length; i++) {
if (addr < map[i].offs) {
var offs = addr - map[i - 1].offs;
var filename = map[i - 1].file;
// Force filename to 50 chars
if (filename) {
if (filename.length > 50) {
filename = '...' + filename.substr(filename.length - 47);
}
} else {
filename = 'Unknown';
}
while (filename.length < 50) {
filename = ' ' + filename;
}
return filename + ' ' + map[i - 1].name + ' + 0x' + offs.toString(16);
}
}
var last = map.length - 1;
return filename + ' ' + map[last].name + ' + 0x' + offs.toString(16);
}
function buildTextMap(map) {
// The expected format of the map file is this:
// ...
// .text 0x00000000000201e0 0x10e0 newlib/Debug/debugging_x86_64.o
// 0x0000000000020280 layer5
// 0x00000000000202e0 layer4
// 0x0000000000020320 layer3
// 0x0000000000020380 layer2
// 0x00000000000203e0 layer1
// 0x0000000000020460 NexeMain
// ...
var lines = map.split('\n');
var orderedMap = [];
var inTextSection = false;
var fileName = '';
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (inTextSection) {
// <hex address> <symbol name>
var vals = line.trim().split(/\s+/);
if (vals.length != 2) {
inTextSection = false;
continue;
}
var obj = {
offs: parseInt(vals[0], 16),
name: vals[1],
file: fileName
};
orderedMap.push(obj);
} else {
// If line starts with .text:
if (line.lastIndexOf(' .text', 0) === 0) {
inTextSection = true;
// .text <hex address> <size> <filename>
var vals = line.trim().split(/\s+/);
fileName = vals[3];
}
}
}
orderedMap.sort(function(a, b) { return a.offs - b.offs; });
return orderedMap;
}
function updateStack(traceinfo, map) {
map = buildTextMap(map);
var text = 'Stack Trace\n';
for (var i = 0; i < traceinfo.frames.length; i++) {
var frame = traceinfo.frames[i];
var addr = findAddress(frame.prog_ctr, map);
text += '[' + i.toString(10) + '] ' + addr + '\n';
}
document.getElementById('trace').value = text;
}
function fetchMap(url, traceinfo) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', url, true);
xmlhttp.onload = function() {
updateStack(traceinfo, this.responseText);
};
xmlhttp.traceinfo = traceinfo;
xmlhttp.send();
}
// Handle a message coming from the NaCl module.
function handleMessage(message_event) {
msg_type = message_event.data.substring(0, 4);
msg_data = message_event.data.substring(5, message_event.data.length);
if (msg_type == 'LOG:') {
document.getElementById('log').value += msg_data + '\n';
return;
}
if (msg_type == 'TRC:') {
crashed = true;
document.getElementById('json').value = msg_data;
crash_info = JSON.parse(msg_data);
updateStatus('Crash Reported');
src = common.naclModule.getAttribute('path');
fetchMap(src + '/debugging_' + crash_info['arch'] + '.map', crash_info);
return;
}
}
function updateStatus(message) {
common.updateStatus(message);
if (message)
document.getElementById('log').value += message + '\n';
}
function boom() {
if (!crashed) {
updateStatus('Send BOOM');
common.naclModule.postMessage('BOOM');
}
}
| {
updateStatus('LOADED');
setTimeout(boom, 2000);
} | identifier_body |
example.js | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var lastModuleError = '';
var crashed = false;
function domContentLoaded(name, tc, config, width, height) {
common.attachDefaultListeners();
common.createNaClModule(name, tc, config, width, height);
updateStatus('Page Loaded');
}
// Indicate success when the NaCl module has loaded.
function moduleDidLoad() {
updateStatus('LOADED');
setTimeout(boom, 2000);
}
function findAddress(addr, map) {
if (map.length < 1) {
return 'MAP Unavailable';
}
if (addr < map[0].offs) {
return 'Invalid Address';
}
for (var i = 1; i < map.length; i++) {
if (addr < map[i].offs) {
var offs = addr - map[i - 1].offs;
var filename = map[i - 1].file;
// Force filename to 50 chars
if (filename) {
if (filename.length > 50) {
filename = '...' + filename.substr(filename.length - 47);
}
} else {
filename = 'Unknown';
}
while (filename.length < 50) |
return filename + ' ' + map[i - 1].name + ' + 0x' + offs.toString(16);
}
}
var last = map.length - 1;
return filename + ' ' + map[last].name + ' + 0x' + offs.toString(16);
}
function buildTextMap(map) {
// The expected format of the map file is this:
// ...
// .text 0x00000000000201e0 0x10e0 newlib/Debug/debugging_x86_64.o
// 0x0000000000020280 layer5
// 0x00000000000202e0 layer4
// 0x0000000000020320 layer3
// 0x0000000000020380 layer2
// 0x00000000000203e0 layer1
// 0x0000000000020460 NexeMain
// ...
var lines = map.split('\n');
var orderedMap = [];
var inTextSection = false;
var fileName = '';
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (inTextSection) {
// <hex address> <symbol name>
var vals = line.trim().split(/\s+/);
if (vals.length != 2) {
inTextSection = false;
continue;
}
var obj = {
offs: parseInt(vals[0], 16),
name: vals[1],
file: fileName
};
orderedMap.push(obj);
} else {
// If line starts with .text:
if (line.lastIndexOf(' .text', 0) === 0) {
inTextSection = true;
// .text <hex address> <size> <filename>
var vals = line.trim().split(/\s+/);
fileName = vals[3];
}
}
}
orderedMap.sort(function(a, b) { return a.offs - b.offs; });
return orderedMap;
}
function updateStack(traceinfo, map) {
map = buildTextMap(map);
var text = 'Stack Trace\n';
for (var i = 0; i < traceinfo.frames.length; i++) {
var frame = traceinfo.frames[i];
var addr = findAddress(frame.prog_ctr, map);
text += '[' + i.toString(10) + '] ' + addr + '\n';
}
document.getElementById('trace').value = text;
}
function fetchMap(url, traceinfo) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', url, true);
xmlhttp.onload = function() {
updateStack(traceinfo, this.responseText);
};
xmlhttp.traceinfo = traceinfo;
xmlhttp.send();
}
// Handle a message coming from the NaCl module.
function handleMessage(message_event) {
msg_type = message_event.data.substring(0, 4);
msg_data = message_event.data.substring(5, message_event.data.length);
if (msg_type == 'LOG:') {
document.getElementById('log').value += msg_data + '\n';
return;
}
if (msg_type == 'TRC:') {
crashed = true;
document.getElementById('json').value = msg_data;
crash_info = JSON.parse(msg_data);
updateStatus('Crash Reported');
src = common.naclModule.getAttribute('path');
fetchMap(src + '/debugging_' + crash_info['arch'] + '.map', crash_info);
return;
}
}
function updateStatus(message) {
common.updateStatus(message);
if (message)
document.getElementById('log').value += message + '\n';
}
function boom() {
if (!crashed) {
updateStatus('Send BOOM');
common.naclModule.postMessage('BOOM');
}
}
| {
filename = ' ' + filename;
} | conditional_block |
Gruntfile.js | var module = module;
//this keeps the module file from doing anything inside the jasmine tests.
//We could avoid this by making all the source be in a specific directory, but that would break backwards compatibility.
if (module) | {
module.exports = function (grunt) {
'use strict';
var config, debug, environment, spec;
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.registerTask('default', ['jasmine']);
spec = grunt.option('spec') || '*';
config = grunt.file.readJSON('config.json');
return grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jasmine: {
dev: {
src: "./*.js",
options: {
vendor:["https://rally1.rallydev.com/apps/"+config.sdk+"/sdk-debug.js"],
template: 'test/specs.tmpl',
specs: "test/**/" + spec + "Spec.js",
helpers: []
}
}
},
rallydeploy: {
options: {
server: config.server,
projectOid: 0,
deployFile: "deploy.json",
credentialsFile: "credentials.json",
timeboxFilter: "none"
},
prod: {
options: {
tab: "myhome",
pageName: config.name,
shared: false
}
}
}
});
};
} | conditional_block |
|
Gruntfile.js | var module = module;
//this keeps the module file from doing anything inside the jasmine tests.
//We could avoid this by making all the source be in a specific directory, but that would break backwards compatibility.
if (module) {
module.exports = function (grunt) {
'use strict';
var config, debug, environment, spec;
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.registerTask('default', ['jasmine']);
spec = grunt.option('spec') || '*';
config = grunt.file.readJSON('config.json');
return grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jasmine: {
dev: {
src: "./*.js",
options: {
vendor:["https://rally1.rallydev.com/apps/"+config.sdk+"/sdk-debug.js"],
template: 'test/specs.tmpl',
specs: "test/**/" + spec + "Spec.js",
helpers: []
}
} |
rallydeploy: {
options: {
server: config.server,
projectOid: 0,
deployFile: "deploy.json",
credentialsFile: "credentials.json",
timeboxFilter: "none"
},
prod: {
options: {
tab: "myhome",
pageName: config.name,
shared: false
}
}
}
});
};
} | }, | random_line_split |
tab-native.esm.js | /*!
* Native JavaScript for Bootstrap Tab v4.0.3 (https://thednp.github.io/bootstrap.native/)
* Copyright 2015-2021 © dnp_theme
* Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE)
*/
const supportTransition = 'webkitTransition' in document.head.style || 'transition' in document.head.style;
const transitionEndEvent = 'webkitTransition' in document.head.style ? 'webkitTransitionEnd' : 'transitionend';
const transitionDuration = 'webkitTransition' in document.head.style ? 'webkitTransitionDuration' : 'transitionDuration';
const transitionProperty = 'webkitTransition' in document.head.style ? 'webkitTransitionProperty' : 'transitionProperty';
function getElementTransitionDuration(element) {
const computedStyle = getComputedStyle(element);
const propertyValue = computedStyle[transitionProperty];
const durationValue = computedStyle[transitionDuration];
const durationScale = durationValue.includes('ms') ? 1 : 1000;
const duration = supportTransition && propertyValue && propertyValue !== 'none'
? parseFloat(durationValue) * durationScale : 0;
return !Number.isNaN(duration) ? duration : 0;
}
function emulateTransitionEnd(element, handler) {
let called = 0;
const endEvent = new Event(transitionEndEvent);
const duration = getElementTransitionDuration(element);
if (duration) {
element.addEventListener(transitionEndEvent, function transitionEndWrapper(e) {
if (e.target === element) {
handler.apply(element, [e]);
element.removeEventListener(transitionEndEvent, transitionEndWrapper);
called = 1;
}
});
setTimeout(() => {
if (!called) element.dispatchEvent(endEvent);
}, duration + 17);
} else {
handler.apply(element, [endEvent]);
}
}
function reflow(element) {
return element.offsetHeight;
}
function queryElement(selector, parent) {
const lookUp = parent && parent instanceof Element ? parent : document;
return selector instanceof Element ? selector : lookUp.querySelector(selector);
}
function addClass(element, classNAME) {
element.classList.add(classNAME);
}
function hasClass(element, classNAME) {
return element.classList.contains(classNAME);
}
function r | element, classNAME) {
element.classList.remove(classNAME);
}
const addEventListener = 'addEventListener';
const removeEventListener = 'removeEventListener';
const ariaSelected = 'aria-selected';
// collapse / tab
const collapsingClass = 'collapsing';
const activeClass = 'active';
const fadeClass = 'fade';
const showClass = 'show';
const dropdownMenuClasses = ['dropdown', 'dropup', 'dropstart', 'dropend'];
const dropdownMenuClass = 'dropdown-menu';
const dataBsToggle = 'data-bs-toggle';
function bootstrapCustomEvent(namespacedEventType, eventProperties) {
const OriginalCustomEvent = new CustomEvent(namespacedEventType, { cancelable: true });
if (eventProperties instanceof Object) {
Object.keys(eventProperties).forEach((key) => {
Object.defineProperty(OriginalCustomEvent, key, {
value: eventProperties[key],
});
});
}
return OriginalCustomEvent;
}
function normalizeValue(value) {
if (value === 'true') {
return true;
}
if (value === 'false') {
return false;
}
if (!Number.isNaN(+value)) {
return +value;
}
if (value === '' || value === 'null') {
return null;
}
// string / function / Element / Object
return value;
}
function normalizeOptions(element, defaultOps, inputOps, ns) {
const normalOps = {};
const dataOps = {};
const data = { ...element.dataset };
Object.keys(data)
.forEach((k) => {
const key = k.includes(ns)
? k.replace(ns, '').replace(/[A-Z]/, (match) => match.toLowerCase())
: k;
dataOps[key] = normalizeValue(data[k]);
});
Object.keys(inputOps)
.forEach((k) => {
inputOps[k] = normalizeValue(inputOps[k]);
});
Object.keys(defaultOps)
.forEach((k) => {
if (k in inputOps) {
normalOps[k] = inputOps[k];
} else if (k in dataOps) {
normalOps[k] = dataOps[k];
} else {
normalOps[k] = defaultOps[k];
}
});
return normalOps;
}
/* Native JavaScript for Bootstrap 5 | Base Component
----------------------------------------------------- */
class BaseComponent {
constructor(name, target, defaults, config) {
const self = this;
const element = queryElement(target);
if (element[name]) element[name].dispose();
self.element = element;
if (defaults && Object.keys(defaults).length) {
self.options = normalizeOptions(element, defaults, (config || {}), 'bs');
}
element[name] = self;
}
dispose(name) {
const self = this;
self.element[name] = null;
Object.keys(self).forEach((prop) => { self[prop] = null; });
}
}
/* Native JavaScript for Bootstrap 5 | Tab
------------------------------------------ */
// TAB PRIVATE GC
// ================
const tabString = 'tab';
const tabComponent = 'Tab';
const tabSelector = `[${dataBsToggle}="${tabString}"]`;
// TAB CUSTOM EVENTS
// =================
const showTabEvent = bootstrapCustomEvent(`show.bs.${tabString}`);
const shownTabEvent = bootstrapCustomEvent(`shown.bs.${tabString}`);
const hideTabEvent = bootstrapCustomEvent(`hide.bs.${tabString}`);
const hiddenTabEvent = bootstrapCustomEvent(`hidden.bs.${tabString}`);
let nextTab;
let nextTabContent;
let nextTabHeight;
let activeTab;
let activeTabContent;
let tabContainerHeight;
let tabEqualContents;
// TAB PRIVATE METHODS
// ===================
function triggerTabEnd(self) {
const { tabContent, nav } = self;
tabContent.style.height = '';
removeClass(tabContent, collapsingClass);
nav.isAnimating = false;
}
function triggerTabShow(self) {
const { tabContent, nav } = self;
if (tabContent) { // height animation
if (tabEqualContents) {
triggerTabEnd(self);
} else {
setTimeout(() => { // enables height animation
tabContent.style.height = `${nextTabHeight}px`; // height animation
reflow(tabContent);
emulateTransitionEnd(tabContent, () => triggerTabEnd(self));
}, 50);
}
} else {
nav.isAnimating = false;
}
shownTabEvent.relatedTarget = activeTab;
nextTab.dispatchEvent(shownTabEvent);
}
function triggerTabHide(self) {
const { tabContent } = self;
if (tabContent) {
activeTabContent.style.float = 'left';
nextTabContent.style.float = 'left';
tabContainerHeight = activeTabContent.scrollHeight;
}
// update relatedTarget and dispatch event
showTabEvent.relatedTarget = activeTab;
hiddenTabEvent.relatedTarget = nextTab;
nextTab.dispatchEvent(showTabEvent);
if (showTabEvent.defaultPrevented) return;
addClass(nextTabContent, activeClass);
removeClass(activeTabContent, activeClass);
if (tabContent) {
nextTabHeight = nextTabContent.scrollHeight;
tabEqualContents = nextTabHeight === tabContainerHeight;
addClass(tabContent, collapsingClass);
tabContent.style.height = `${tabContainerHeight}px`; // height animation
reflow(tabContent);
activeTabContent.style.float = '';
nextTabContent.style.float = '';
}
if (hasClass(nextTabContent, fadeClass)) {
setTimeout(() => {
addClass(nextTabContent, showClass);
emulateTransitionEnd(nextTabContent, () => {
triggerTabShow(self);
});
}, 20);
} else { triggerTabShow(self); }
activeTab.dispatchEvent(hiddenTabEvent);
}
function getActiveTab({ nav }) {
const activeTabs = nav.getElementsByClassName(activeClass);
if (activeTabs.length === 1
&& !dropdownMenuClasses.some((c) => hasClass(activeTabs[0].parentNode, c))) {
[activeTab] = activeTabs;
} else if (activeTabs.length > 1) {
activeTab = activeTabs[activeTabs.length - 1];
}
return activeTab;
}
function getActiveTabContent(self) {
return queryElement(getActiveTab(self).getAttribute('href'));
}
function toggleTabHandler(self, add) {
const action = add ? addEventListener : removeEventListener;
self.element[action]('click', tabClickHandler);
}
// TAB EVENT HANDLER
// =================
function tabClickHandler(e) {
const self = this[tabComponent];
e.preventDefault();
if (!self.nav.isAnimating) self.show();
}
// TAB DEFINITION
// ==============
class Tab extends BaseComponent {
constructor(target) {
super(tabComponent, target);
// bind
const self = this;
// initialization element
const { element } = self;
// event targets
self.nav = element.closest('.nav');
const { nav } = self;
self.dropdown = nav && queryElement(`.${dropdownMenuClasses[0]}-toggle`, nav);
activeTabContent = getActiveTabContent(self);
self.tabContent = supportTransition && activeTabContent.closest('.tab-content');
tabContainerHeight = activeTabContent.scrollHeight;
// set default animation state
nav.isAnimating = false;
// add event listener
toggleTabHandler(self, 1);
}
// TAB PUBLIC METHODS
// ==================
show() { // the tab we clicked is now the nextTab tab
const self = this;
const { element, nav, dropdown } = self;
nextTab = element;
if (!hasClass(nextTab, activeClass)) {
// this is the actual object, the nextTab tab content to activate
nextTabContent = queryElement(nextTab.getAttribute('href'));
activeTab = getActiveTab({ nav });
activeTabContent = getActiveTabContent({ nav });
// update relatedTarget and dispatch
hideTabEvent.relatedTarget = nextTab;
activeTab.dispatchEvent(hideTabEvent);
if (hideTabEvent.defaultPrevented) return;
nav.isAnimating = true;
removeClass(activeTab, activeClass);
activeTab.setAttribute(ariaSelected, 'false');
addClass(nextTab, activeClass);
nextTab.setAttribute(ariaSelected, 'true');
if (dropdown) {
if (!hasClass(element.parentNode, dropdownMenuClass)) {
if (hasClass(dropdown, activeClass)) removeClass(dropdown, activeClass);
} else if (!hasClass(dropdown, activeClass)) addClass(dropdown, activeClass);
}
if (hasClass(activeTabContent, fadeClass)) {
removeClass(activeTabContent, showClass);
emulateTransitionEnd(activeTabContent, () => triggerTabHide(self));
} else {
triggerTabHide(self);
}
}
}
dispose() {
toggleTabHandler(this);
super.dispose(tabComponent);
}
}
Tab.init = {
component: tabComponent,
selector: tabSelector,
constructor: Tab,
};
export default Tab;
| emoveClass( | identifier_name |
tab-native.esm.js | /*!
* Native JavaScript for Bootstrap Tab v4.0.3 (https://thednp.github.io/bootstrap.native/)
* Copyright 2015-2021 © dnp_theme
* Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE)
*/
const supportTransition = 'webkitTransition' in document.head.style || 'transition' in document.head.style;
const transitionEndEvent = 'webkitTransition' in document.head.style ? 'webkitTransitionEnd' : 'transitionend';
const transitionDuration = 'webkitTransition' in document.head.style ? 'webkitTransitionDuration' : 'transitionDuration';
const transitionProperty = 'webkitTransition' in document.head.style ? 'webkitTransitionProperty' : 'transitionProperty';
function getElementTransitionDuration(element) {
const computedStyle = getComputedStyle(element);
const propertyValue = computedStyle[transitionProperty];
const durationValue = computedStyle[transitionDuration];
const durationScale = durationValue.includes('ms') ? 1 : 1000;
const duration = supportTransition && propertyValue && propertyValue !== 'none'
? parseFloat(durationValue) * durationScale : 0;
return !Number.isNaN(duration) ? duration : 0;
}
function emulateTransitionEnd(element, handler) {
let called = 0;
const endEvent = new Event(transitionEndEvent);
const duration = getElementTransitionDuration(element);
if (duration) {
element.addEventListener(transitionEndEvent, function transitionEndWrapper(e) {
if (e.target === element) {
handler.apply(element, [e]);
element.removeEventListener(transitionEndEvent, transitionEndWrapper);
called = 1;
}
}); | } else {
handler.apply(element, [endEvent]);
}
}
function reflow(element) {
return element.offsetHeight;
}
function queryElement(selector, parent) {
const lookUp = parent && parent instanceof Element ? parent : document;
return selector instanceof Element ? selector : lookUp.querySelector(selector);
}
function addClass(element, classNAME) {
element.classList.add(classNAME);
}
function hasClass(element, classNAME) {
return element.classList.contains(classNAME);
}
function removeClass(element, classNAME) {
element.classList.remove(classNAME);
}
const addEventListener = 'addEventListener';
const removeEventListener = 'removeEventListener';
const ariaSelected = 'aria-selected';
// collapse / tab
const collapsingClass = 'collapsing';
const activeClass = 'active';
const fadeClass = 'fade';
const showClass = 'show';
const dropdownMenuClasses = ['dropdown', 'dropup', 'dropstart', 'dropend'];
const dropdownMenuClass = 'dropdown-menu';
const dataBsToggle = 'data-bs-toggle';
function bootstrapCustomEvent(namespacedEventType, eventProperties) {
const OriginalCustomEvent = new CustomEvent(namespacedEventType, { cancelable: true });
if (eventProperties instanceof Object) {
Object.keys(eventProperties).forEach((key) => {
Object.defineProperty(OriginalCustomEvent, key, {
value: eventProperties[key],
});
});
}
return OriginalCustomEvent;
}
function normalizeValue(value) {
if (value === 'true') {
return true;
}
if (value === 'false') {
return false;
}
if (!Number.isNaN(+value)) {
return +value;
}
if (value === '' || value === 'null') {
return null;
}
// string / function / Element / Object
return value;
}
function normalizeOptions(element, defaultOps, inputOps, ns) {
const normalOps = {};
const dataOps = {};
const data = { ...element.dataset };
Object.keys(data)
.forEach((k) => {
const key = k.includes(ns)
? k.replace(ns, '').replace(/[A-Z]/, (match) => match.toLowerCase())
: k;
dataOps[key] = normalizeValue(data[k]);
});
Object.keys(inputOps)
.forEach((k) => {
inputOps[k] = normalizeValue(inputOps[k]);
});
Object.keys(defaultOps)
.forEach((k) => {
if (k in inputOps) {
normalOps[k] = inputOps[k];
} else if (k in dataOps) {
normalOps[k] = dataOps[k];
} else {
normalOps[k] = defaultOps[k];
}
});
return normalOps;
}
/* Native JavaScript for Bootstrap 5 | Base Component
----------------------------------------------------- */
class BaseComponent {
constructor(name, target, defaults, config) {
const self = this;
const element = queryElement(target);
if (element[name]) element[name].dispose();
self.element = element;
if (defaults && Object.keys(defaults).length) {
self.options = normalizeOptions(element, defaults, (config || {}), 'bs');
}
element[name] = self;
}
dispose(name) {
const self = this;
self.element[name] = null;
Object.keys(self).forEach((prop) => { self[prop] = null; });
}
}
/* Native JavaScript for Bootstrap 5 | Tab
------------------------------------------ */
// TAB PRIVATE GC
// ================
const tabString = 'tab';
const tabComponent = 'Tab';
const tabSelector = `[${dataBsToggle}="${tabString}"]`;
// TAB CUSTOM EVENTS
// =================
const showTabEvent = bootstrapCustomEvent(`show.bs.${tabString}`);
const shownTabEvent = bootstrapCustomEvent(`shown.bs.${tabString}`);
const hideTabEvent = bootstrapCustomEvent(`hide.bs.${tabString}`);
const hiddenTabEvent = bootstrapCustomEvent(`hidden.bs.${tabString}`);
let nextTab;
let nextTabContent;
let nextTabHeight;
let activeTab;
let activeTabContent;
let tabContainerHeight;
let tabEqualContents;
// TAB PRIVATE METHODS
// ===================
function triggerTabEnd(self) {
const { tabContent, nav } = self;
tabContent.style.height = '';
removeClass(tabContent, collapsingClass);
nav.isAnimating = false;
}
function triggerTabShow(self) {
const { tabContent, nav } = self;
if (tabContent) { // height animation
if (tabEqualContents) {
triggerTabEnd(self);
} else {
setTimeout(() => { // enables height animation
tabContent.style.height = `${nextTabHeight}px`; // height animation
reflow(tabContent);
emulateTransitionEnd(tabContent, () => triggerTabEnd(self));
}, 50);
}
} else {
nav.isAnimating = false;
}
shownTabEvent.relatedTarget = activeTab;
nextTab.dispatchEvent(shownTabEvent);
}
function triggerTabHide(self) {
const { tabContent } = self;
if (tabContent) {
activeTabContent.style.float = 'left';
nextTabContent.style.float = 'left';
tabContainerHeight = activeTabContent.scrollHeight;
}
// update relatedTarget and dispatch event
showTabEvent.relatedTarget = activeTab;
hiddenTabEvent.relatedTarget = nextTab;
nextTab.dispatchEvent(showTabEvent);
if (showTabEvent.defaultPrevented) return;
addClass(nextTabContent, activeClass);
removeClass(activeTabContent, activeClass);
if (tabContent) {
nextTabHeight = nextTabContent.scrollHeight;
tabEqualContents = nextTabHeight === tabContainerHeight;
addClass(tabContent, collapsingClass);
tabContent.style.height = `${tabContainerHeight}px`; // height animation
reflow(tabContent);
activeTabContent.style.float = '';
nextTabContent.style.float = '';
}
if (hasClass(nextTabContent, fadeClass)) {
setTimeout(() => {
addClass(nextTabContent, showClass);
emulateTransitionEnd(nextTabContent, () => {
triggerTabShow(self);
});
}, 20);
} else { triggerTabShow(self); }
activeTab.dispatchEvent(hiddenTabEvent);
}
function getActiveTab({ nav }) {
const activeTabs = nav.getElementsByClassName(activeClass);
if (activeTabs.length === 1
&& !dropdownMenuClasses.some((c) => hasClass(activeTabs[0].parentNode, c))) {
[activeTab] = activeTabs;
} else if (activeTabs.length > 1) {
activeTab = activeTabs[activeTabs.length - 1];
}
return activeTab;
}
function getActiveTabContent(self) {
return queryElement(getActiveTab(self).getAttribute('href'));
}
function toggleTabHandler(self, add) {
const action = add ? addEventListener : removeEventListener;
self.element[action]('click', tabClickHandler);
}
// TAB EVENT HANDLER
// =================
function tabClickHandler(e) {
const self = this[tabComponent];
e.preventDefault();
if (!self.nav.isAnimating) self.show();
}
// TAB DEFINITION
// ==============
class Tab extends BaseComponent {
constructor(target) {
super(tabComponent, target);
// bind
const self = this;
// initialization element
const { element } = self;
// event targets
self.nav = element.closest('.nav');
const { nav } = self;
self.dropdown = nav && queryElement(`.${dropdownMenuClasses[0]}-toggle`, nav);
activeTabContent = getActiveTabContent(self);
self.tabContent = supportTransition && activeTabContent.closest('.tab-content');
tabContainerHeight = activeTabContent.scrollHeight;
// set default animation state
nav.isAnimating = false;
// add event listener
toggleTabHandler(self, 1);
}
// TAB PUBLIC METHODS
// ==================
show() { // the tab we clicked is now the nextTab tab
const self = this;
const { element, nav, dropdown } = self;
nextTab = element;
if (!hasClass(nextTab, activeClass)) {
// this is the actual object, the nextTab tab content to activate
nextTabContent = queryElement(nextTab.getAttribute('href'));
activeTab = getActiveTab({ nav });
activeTabContent = getActiveTabContent({ nav });
// update relatedTarget and dispatch
hideTabEvent.relatedTarget = nextTab;
activeTab.dispatchEvent(hideTabEvent);
if (hideTabEvent.defaultPrevented) return;
nav.isAnimating = true;
removeClass(activeTab, activeClass);
activeTab.setAttribute(ariaSelected, 'false');
addClass(nextTab, activeClass);
nextTab.setAttribute(ariaSelected, 'true');
if (dropdown) {
if (!hasClass(element.parentNode, dropdownMenuClass)) {
if (hasClass(dropdown, activeClass)) removeClass(dropdown, activeClass);
} else if (!hasClass(dropdown, activeClass)) addClass(dropdown, activeClass);
}
if (hasClass(activeTabContent, fadeClass)) {
removeClass(activeTabContent, showClass);
emulateTransitionEnd(activeTabContent, () => triggerTabHide(self));
} else {
triggerTabHide(self);
}
}
}
dispose() {
toggleTabHandler(this);
super.dispose(tabComponent);
}
}
Tab.init = {
component: tabComponent,
selector: tabSelector,
constructor: Tab,
};
export default Tab; | setTimeout(() => {
if (!called) element.dispatchEvent(endEvent);
}, duration + 17); | random_line_split |
tab-native.esm.js | /*!
* Native JavaScript for Bootstrap Tab v4.0.3 (https://thednp.github.io/bootstrap.native/)
* Copyright 2015-2021 © dnp_theme
* Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE)
*/
const supportTransition = 'webkitTransition' in document.head.style || 'transition' in document.head.style;
const transitionEndEvent = 'webkitTransition' in document.head.style ? 'webkitTransitionEnd' : 'transitionend';
const transitionDuration = 'webkitTransition' in document.head.style ? 'webkitTransitionDuration' : 'transitionDuration';
const transitionProperty = 'webkitTransition' in document.head.style ? 'webkitTransitionProperty' : 'transitionProperty';
function getElementTransitionDuration(element) {
const computedStyle = getComputedStyle(element);
const propertyValue = computedStyle[transitionProperty];
const durationValue = computedStyle[transitionDuration];
const durationScale = durationValue.includes('ms') ? 1 : 1000;
const duration = supportTransition && propertyValue && propertyValue !== 'none'
? parseFloat(durationValue) * durationScale : 0;
return !Number.isNaN(duration) ? duration : 0;
}
function emulateTransitionEnd(element, handler) { |
function reflow(element) {
return element.offsetHeight;
}
function queryElement(selector, parent) {
const lookUp = parent && parent instanceof Element ? parent : document;
return selector instanceof Element ? selector : lookUp.querySelector(selector);
}
function addClass(element, classNAME) {
element.classList.add(classNAME);
}
function hasClass(element, classNAME) {
return element.classList.contains(classNAME);
}
function removeClass(element, classNAME) {
element.classList.remove(classNAME);
}
const addEventListener = 'addEventListener';
const removeEventListener = 'removeEventListener';
const ariaSelected = 'aria-selected';
// collapse / tab
const collapsingClass = 'collapsing';
const activeClass = 'active';
const fadeClass = 'fade';
const showClass = 'show';
const dropdownMenuClasses = ['dropdown', 'dropup', 'dropstart', 'dropend'];
const dropdownMenuClass = 'dropdown-menu';
const dataBsToggle = 'data-bs-toggle';
function bootstrapCustomEvent(namespacedEventType, eventProperties) {
const OriginalCustomEvent = new CustomEvent(namespacedEventType, { cancelable: true });
if (eventProperties instanceof Object) {
Object.keys(eventProperties).forEach((key) => {
Object.defineProperty(OriginalCustomEvent, key, {
value: eventProperties[key],
});
});
}
return OriginalCustomEvent;
}
function normalizeValue(value) {
if (value === 'true') {
return true;
}
if (value === 'false') {
return false;
}
if (!Number.isNaN(+value)) {
return +value;
}
if (value === '' || value === 'null') {
return null;
}
// string / function / Element / Object
return value;
}
function normalizeOptions(element, defaultOps, inputOps, ns) {
const normalOps = {};
const dataOps = {};
const data = { ...element.dataset };
Object.keys(data)
.forEach((k) => {
const key = k.includes(ns)
? k.replace(ns, '').replace(/[A-Z]/, (match) => match.toLowerCase())
: k;
dataOps[key] = normalizeValue(data[k]);
});
Object.keys(inputOps)
.forEach((k) => {
inputOps[k] = normalizeValue(inputOps[k]);
});
Object.keys(defaultOps)
.forEach((k) => {
if (k in inputOps) {
normalOps[k] = inputOps[k];
} else if (k in dataOps) {
normalOps[k] = dataOps[k];
} else {
normalOps[k] = defaultOps[k];
}
});
return normalOps;
}
/* Native JavaScript for Bootstrap 5 | Base Component
----------------------------------------------------- */
class BaseComponent {
constructor(name, target, defaults, config) {
const self = this;
const element = queryElement(target);
if (element[name]) element[name].dispose();
self.element = element;
if (defaults && Object.keys(defaults).length) {
self.options = normalizeOptions(element, defaults, (config || {}), 'bs');
}
element[name] = self;
}
dispose(name) {
const self = this;
self.element[name] = null;
Object.keys(self).forEach((prop) => { self[prop] = null; });
}
}
/* Native JavaScript for Bootstrap 5 | Tab
------------------------------------------ */
// TAB PRIVATE GC
// ================
const tabString = 'tab';
const tabComponent = 'Tab';
const tabSelector = `[${dataBsToggle}="${tabString}"]`;
// TAB CUSTOM EVENTS
// =================
const showTabEvent = bootstrapCustomEvent(`show.bs.${tabString}`);
const shownTabEvent = bootstrapCustomEvent(`shown.bs.${tabString}`);
const hideTabEvent = bootstrapCustomEvent(`hide.bs.${tabString}`);
const hiddenTabEvent = bootstrapCustomEvent(`hidden.bs.${tabString}`);
let nextTab;
let nextTabContent;
let nextTabHeight;
let activeTab;
let activeTabContent;
let tabContainerHeight;
let tabEqualContents;
// TAB PRIVATE METHODS
// ===================
function triggerTabEnd(self) {
const { tabContent, nav } = self;
tabContent.style.height = '';
removeClass(tabContent, collapsingClass);
nav.isAnimating = false;
}
function triggerTabShow(self) {
const { tabContent, nav } = self;
if (tabContent) { // height animation
if (tabEqualContents) {
triggerTabEnd(self);
} else {
setTimeout(() => { // enables height animation
tabContent.style.height = `${nextTabHeight}px`; // height animation
reflow(tabContent);
emulateTransitionEnd(tabContent, () => triggerTabEnd(self));
}, 50);
}
} else {
nav.isAnimating = false;
}
shownTabEvent.relatedTarget = activeTab;
nextTab.dispatchEvent(shownTabEvent);
}
function triggerTabHide(self) {
const { tabContent } = self;
if (tabContent) {
activeTabContent.style.float = 'left';
nextTabContent.style.float = 'left';
tabContainerHeight = activeTabContent.scrollHeight;
}
// update relatedTarget and dispatch event
showTabEvent.relatedTarget = activeTab;
hiddenTabEvent.relatedTarget = nextTab;
nextTab.dispatchEvent(showTabEvent);
if (showTabEvent.defaultPrevented) return;
addClass(nextTabContent, activeClass);
removeClass(activeTabContent, activeClass);
if (tabContent) {
nextTabHeight = nextTabContent.scrollHeight;
tabEqualContents = nextTabHeight === tabContainerHeight;
addClass(tabContent, collapsingClass);
tabContent.style.height = `${tabContainerHeight}px`; // height animation
reflow(tabContent);
activeTabContent.style.float = '';
nextTabContent.style.float = '';
}
if (hasClass(nextTabContent, fadeClass)) {
setTimeout(() => {
addClass(nextTabContent, showClass);
emulateTransitionEnd(nextTabContent, () => {
triggerTabShow(self);
});
}, 20);
} else { triggerTabShow(self); }
activeTab.dispatchEvent(hiddenTabEvent);
}
function getActiveTab({ nav }) {
const activeTabs = nav.getElementsByClassName(activeClass);
if (activeTabs.length === 1
&& !dropdownMenuClasses.some((c) => hasClass(activeTabs[0].parentNode, c))) {
[activeTab] = activeTabs;
} else if (activeTabs.length > 1) {
activeTab = activeTabs[activeTabs.length - 1];
}
return activeTab;
}
function getActiveTabContent(self) {
return queryElement(getActiveTab(self).getAttribute('href'));
}
function toggleTabHandler(self, add) {
const action = add ? addEventListener : removeEventListener;
self.element[action]('click', tabClickHandler);
}
// TAB EVENT HANDLER
// =================
function tabClickHandler(e) {
const self = this[tabComponent];
e.preventDefault();
if (!self.nav.isAnimating) self.show();
}
// TAB DEFINITION
// ==============
class Tab extends BaseComponent {
constructor(target) {
super(tabComponent, target);
// bind
const self = this;
// initialization element
const { element } = self;
// event targets
self.nav = element.closest('.nav');
const { nav } = self;
self.dropdown = nav && queryElement(`.${dropdownMenuClasses[0]}-toggle`, nav);
activeTabContent = getActiveTabContent(self);
self.tabContent = supportTransition && activeTabContent.closest('.tab-content');
tabContainerHeight = activeTabContent.scrollHeight;
// set default animation state
nav.isAnimating = false;
// add event listener
toggleTabHandler(self, 1);
}
// TAB PUBLIC METHODS
// ==================
show() { // the tab we clicked is now the nextTab tab
const self = this;
const { element, nav, dropdown } = self;
nextTab = element;
if (!hasClass(nextTab, activeClass)) {
// this is the actual object, the nextTab tab content to activate
nextTabContent = queryElement(nextTab.getAttribute('href'));
activeTab = getActiveTab({ nav });
activeTabContent = getActiveTabContent({ nav });
// update relatedTarget and dispatch
hideTabEvent.relatedTarget = nextTab;
activeTab.dispatchEvent(hideTabEvent);
if (hideTabEvent.defaultPrevented) return;
nav.isAnimating = true;
removeClass(activeTab, activeClass);
activeTab.setAttribute(ariaSelected, 'false');
addClass(nextTab, activeClass);
nextTab.setAttribute(ariaSelected, 'true');
if (dropdown) {
if (!hasClass(element.parentNode, dropdownMenuClass)) {
if (hasClass(dropdown, activeClass)) removeClass(dropdown, activeClass);
} else if (!hasClass(dropdown, activeClass)) addClass(dropdown, activeClass);
}
if (hasClass(activeTabContent, fadeClass)) {
removeClass(activeTabContent, showClass);
emulateTransitionEnd(activeTabContent, () => triggerTabHide(self));
} else {
triggerTabHide(self);
}
}
}
dispose() {
toggleTabHandler(this);
super.dispose(tabComponent);
}
}
Tab.init = {
component: tabComponent,
selector: tabSelector,
constructor: Tab,
};
export default Tab;
|
let called = 0;
const endEvent = new Event(transitionEndEvent);
const duration = getElementTransitionDuration(element);
if (duration) {
element.addEventListener(transitionEndEvent, function transitionEndWrapper(e) {
if (e.target === element) {
handler.apply(element, [e]);
element.removeEventListener(transitionEndEvent, transitionEndWrapper);
called = 1;
}
});
setTimeout(() => {
if (!called) element.dispatchEvent(endEvent);
}, duration + 17);
} else {
handler.apply(element, [endEvent]);
}
}
| identifier_body |
jquery.countto.js | (function ($) {
$.fn.countTo = function (options) {
options = options || {};
return $(this).each(function () {
// set options for current element
var settings = $.extend({}, $.fn.countTo.defaults, {
from: $(this).data('from'),
to: $(this).data('to'),
speed: $(this).data('speed'),
refreshInterval: $(this).data('refresh-interval'),
decimals: $(this).data('decimals')
}, options);
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(settings.speed / settings.refreshInterval),
increment = (settings.to - settings.from) / loops;
// references & variables that will change with each update
var self = this,
$self = $(this),
loopCount = 0,
value = settings.from,
data = $self.data('countTo') || {};
$self.data('countTo', data);
// if an existing interval can be found, clear it first
if (data.interval) {
clearInterval(data.interval);
}
data.interval = setInterval(updateTimer, settings.refreshInterval);
// initialize the element with the starting value
render(value);
function updateTimer() {
value += increment;
loopCount++;
render(value);
if (typeof(settings.onUpdate) == 'function') {
settings.onUpdate.call(self, value);
}
if (loopCount >= loops) |
}
function render(value) {
var formattedValue = settings.formatter.call(self, value, settings);
$self.html(formattedValue);
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 0, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
formatter: formatter, // handler for formatting the value before rendering
onUpdate: null, // callback method for every time the element is updated
onComplete: null // callback method for when the element finishes updating
};
function formatter(value, settings) {
return value.toFixed(settings.decimals);
}
}(jQuery)); | {
// remove the interval
$self.removeData('countTo');
clearInterval(data.interval);
value = settings.to;
if (typeof(settings.onComplete) == 'function') {
settings.onComplete.call(self, value);
}
} | conditional_block |
jquery.countto.js | (function ($) {
$.fn.countTo = function (options) {
options = options || {};
return $(this).each(function () {
// set options for current element
var settings = $.extend({}, $.fn.countTo.defaults, {
from: $(this).data('from'),
to: $(this).data('to'),
speed: $(this).data('speed'),
refreshInterval: $(this).data('refresh-interval'),
decimals: $(this).data('decimals')
}, options);
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(settings.speed / settings.refreshInterval),
increment = (settings.to - settings.from) / loops;
// references & variables that will change with each update
var self = this,
$self = $(this),
loopCount = 0,
value = settings.from, | $self.data('countTo', data);
// if an existing interval can be found, clear it first
if (data.interval) {
clearInterval(data.interval);
}
data.interval = setInterval(updateTimer, settings.refreshInterval);
// initialize the element with the starting value
render(value);
function updateTimer() {
value += increment;
loopCount++;
render(value);
if (typeof(settings.onUpdate) == 'function') {
settings.onUpdate.call(self, value);
}
if (loopCount >= loops) {
// remove the interval
$self.removeData('countTo');
clearInterval(data.interval);
value = settings.to;
if (typeof(settings.onComplete) == 'function') {
settings.onComplete.call(self, value);
}
}
}
function render(value) {
var formattedValue = settings.formatter.call(self, value, settings);
$self.html(formattedValue);
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 0, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
formatter: formatter, // handler for formatting the value before rendering
onUpdate: null, // callback method for every time the element is updated
onComplete: null // callback method for when the element finishes updating
};
function formatter(value, settings) {
return value.toFixed(settings.decimals);
}
}(jQuery)); | data = $self.data('countTo') || {};
| random_line_split |
jquery.countto.js | (function ($) {
$.fn.countTo = function (options) {
options = options || {};
return $(this).each(function () {
// set options for current element
var settings = $.extend({}, $.fn.countTo.defaults, {
from: $(this).data('from'),
to: $(this).data('to'),
speed: $(this).data('speed'),
refreshInterval: $(this).data('refresh-interval'),
decimals: $(this).data('decimals')
}, options);
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(settings.speed / settings.refreshInterval),
increment = (settings.to - settings.from) / loops;
// references & variables that will change with each update
var self = this,
$self = $(this),
loopCount = 0,
value = settings.from,
data = $self.data('countTo') || {};
$self.data('countTo', data);
// if an existing interval can be found, clear it first
if (data.interval) {
clearInterval(data.interval);
}
data.interval = setInterval(updateTimer, settings.refreshInterval);
// initialize the element with the starting value
render(value);
function updateTimer() {
value += increment;
loopCount++;
render(value);
if (typeof(settings.onUpdate) == 'function') {
settings.onUpdate.call(self, value);
}
if (loopCount >= loops) {
// remove the interval
$self.removeData('countTo');
clearInterval(data.interval);
value = settings.to;
if (typeof(settings.onComplete) == 'function') {
settings.onComplete.call(self, value);
}
}
}
function render(value) |
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 0, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
formatter: formatter, // handler for formatting the value before rendering
onUpdate: null, // callback method for every time the element is updated
onComplete: null // callback method for when the element finishes updating
};
function formatter(value, settings) {
return value.toFixed(settings.decimals);
}
}(jQuery)); | {
var formattedValue = settings.formatter.call(self, value, settings);
$self.html(formattedValue);
} | identifier_body |
jquery.countto.js | (function ($) {
$.fn.countTo = function (options) {
options = options || {};
return $(this).each(function () {
// set options for current element
var settings = $.extend({}, $.fn.countTo.defaults, {
from: $(this).data('from'),
to: $(this).data('to'),
speed: $(this).data('speed'),
refreshInterval: $(this).data('refresh-interval'),
decimals: $(this).data('decimals')
}, options);
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(settings.speed / settings.refreshInterval),
increment = (settings.to - settings.from) / loops;
// references & variables that will change with each update
var self = this,
$self = $(this),
loopCount = 0,
value = settings.from,
data = $self.data('countTo') || {};
$self.data('countTo', data);
// if an existing interval can be found, clear it first
if (data.interval) {
clearInterval(data.interval);
}
data.interval = setInterval(updateTimer, settings.refreshInterval);
// initialize the element with the starting value
render(value);
function updateTimer() {
value += increment;
loopCount++;
render(value);
if (typeof(settings.onUpdate) == 'function') {
settings.onUpdate.call(self, value);
}
if (loopCount >= loops) {
// remove the interval
$self.removeData('countTo');
clearInterval(data.interval);
value = settings.to;
if (typeof(settings.onComplete) == 'function') {
settings.onComplete.call(self, value);
}
}
}
function render(value) {
var formattedValue = settings.formatter.call(self, value, settings);
$self.html(formattedValue);
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 0, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
formatter: formatter, // handler for formatting the value before rendering
onUpdate: null, // callback method for every time the element is updated
onComplete: null // callback method for when the element finishes updating
};
function | (value, settings) {
return value.toFixed(settings.decimals);
}
}(jQuery)); | formatter | identifier_name |
core.js | define(["jquery", "underscore", "backbone"], function ($,_,Backbone) {
/* *****************************************************************************************************************
Prototype Inheritance
**************************************************************************************************************** */
$.curCSS = $.css; // back-port jquery 1.8+
/* *****************************************************************************************************************
**************************************************************************************************************** */
return {
DEBUG: false,
idAttribute: "id", labelAttribute: "label", typeAttribute: "type", commentAttribute: "comment",
fact: {
},
ux: {
i18n: {},
types: {},
mixin: {},
view: { field: {} }
},
iq: {
},
NS: {
"owl": "http://www.w3.org/2002/07/owl#",
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"xsd": "http://www.w3.org/2001/XMLSchema#",
"ux": "meta4:ux:",
"iq": "meta4:iq:",
"fact": "meta4:fact:",
"asq": "meta4:asq:",
},
/**
curried fn()
when invoked returns a fn() that in turns calls a named fn() on a context object
e.g: dispatch(source, "doSomething")(a,b,c) -> source.doSomething(a,b,c)
**/
dispatch: function(self, event) {
return function() {
return self[event] && self[event].apply(self, arguments)
}
},
resolve: function(options, modelled) {
if (!options) throw "meta4:ux:oops:missing-options"
var _DEBUG = options.debug || this.ux.DEBUG
modelled = modelled || _.extend({},options);
// Resolve Backbone Model - last resort, use 'options'
if (_.isString(options.model)) {
modelled.model = this.fact.models.get(options.model);
//_DEBUG &&
console.warn("Model$ (%s) %o %o -> %o", options.model, this.fact.models, options, modelled);
} else if ( options.model instanceof Backbone.Model ) {
modelled.model = options.model;
} else if (_.isFunction(options.model)) {
modelled.model = options.model(options);
} else if (_.isObject(options.model)) {
modelled.model = new this.fact.Model( options.model );
} else if ( options.model === false ) {
// modelled.model = new Backbone.Model()
_DEBUG && console.debug("No Model: %o %o", options, modelled)
} else if ( options.model === true || options.model == undefined) {
var _options = { label: options.label, comment: (options.comment || ""), icon: (options.icon || "") };
_options.idAttribute = options[this.ux.idAttribute]
modelled.model = new this.fact.Model({})
modelled.model.set(_options)
_DEBUG && console.debug("View Model (%s): %o %o", modelled.id, _options, modelled.model)
} else throw "meta4:ux:oops:invalid-model#"+options.model
// Resolve Backbone Collection
if (_.isString(options.collection)) {
// recursively re-model ... check if a sub-model first
var _collection = false
// nested-collection
if (options.collection.indexOf(".")==0) {
var cid = options.collection.substring(1)
_collection = modelled.model.get(cid)
if (!_collection) {
_collection = new Backbone.Collection()
_DEBUG && console.log("New Local Collection (%s): %o %o %o", cid, options, modelled, _collection)
modelled.model.set(cid, _collection)
} else {
_DEBUG && console.log("Existing Local Collection (%s): %o %o %o", cid, options, modelled, _collection)
}
} else if (options.collection.indexOf("!")==0) | else {
var cid = options.collection
_collection = modelled.model.get(cid) || this.fact.models.get(cid)
_DEBUG && console.log("Local/Global Collection (%s): %o %o %o", cid, options, modelled, _collection)
}
if (!_collection) {
_collection = this.fact.factory.Local({ id: options.collection, fetch: false })
_DEBUG && console.log("Local Collection: %o %o %o %o", options.collection, options, modelled, _collection)
}
// resolve any string models
this.ux.model( { model: modelled.model, collection: _collection }, modelled);
_DEBUG && console.log("String Modelled: %o", modelled)
} else if (_.isArray(options.collection)) {
_DEBUG && console.log("Array Collection", options.collection, this.fact)
modelled.collection = this.fact.Collection(options.collection);
} else if (_.isObject(options.collection) && options.collection instanceof Backbone.Collection ) {
_DEBUG && console.log("Existing Collection: %o", options.collection)
modelled.collection = options.collection;
} else if (_.isObject(options.collection) && _.isString(options.collection.id) ) {
//_DEBUG &&
console.log("Register Collection: %s -> %o / %o", options.collection.id, options.collection, this.fact)
modelled.collection = this.fact.models.get(options.collection.id) || this.fact.register(options.collection)
} else if (_.isFunction(options.collection)) {
_DEBUG && console.log("Function Collection", options.collection, this.fact)
modelled.collection = options.collection(options);
}
// cloned originally options - with resolved Model, optionally a Collection
return modelled;
},
/**
Uses a curried fn() to replace key/values in options{}
if a matching option key exists within mix_ins{}
if the mixin is fn() then execute & bind the returned value
**/
curry: function(options, mix_ins, _options) {
if (!options || !mix_ins) return options;
_options = _options || {} // cloned object
_.each(options, function(option,key) {
var mixin = mix_ins[key]
_options[key] = _.isFunction(mixin)?mixin(option):option
})
return _options;
},
/**
Rename/Replace the keys in an key/value Object using a re-mapping object
@param: options - Object of key/values
@param: remap - Object of key1/key2
**/
remap: function(options, remap) {
if (!options || !remap) return options;
var map = {}
_.each(remap, function(v,k) {
var n = options[k]
if (_.isFunction(v)) map[v] = v(n, k, map)
else if ( !_.isUndefined(n) && !_.isUndefined(v) ) map[v] = n
})
return map;
},
/**
De-reference string-based 'values' to a mix-in fn()
Replaces string values in options with corresponding fn() from mixin
**/
mixin: function(options, mix_ins, _options) {
if (!options || !mix_ins) return options;
_options = _options || options // default original
_.each(options, function(value,key) {
if (_.isString(value)) {
var mixin = mix_ins[value]
if (mixin && _.isFunction(mixin)) {
options[key] = _.isFunction(mixin)?mixin:value
}
}
})
return _options;
},
isDefaultTrue: function(options, key) {
if (_.isUndefined(options)) return true;
return options[key]?true:false
},
/**
Utilities to deal with Strings (including special cases for 'id' strings)
**/
/**
Generate a reasonably unique UUID
**/
uuid: function() {
function _id() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); };
return (_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id());
},
/**
Generate a scoped UUID by pre-pending a prefix
**/
urn: function(prefix) {
return (prefix || core[idAttribute])+"#"+this.uuid();
},
/**
Turn camel-cased strings into a capitalised, space-separated string
**/
humanize: function(s) {
return s.replace(/\W+|_|-/g, " ").toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g, function($1) { return $1.toUpperCase() });
},
toQueryString(obj, prefix) {
serialize = function(obj, prefix) {
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push(typeof v == "object" ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
return serialize(obj, prefix)
}
}
}); | {
// global-collection
var cid = options.collection.substring(1)
_collection = fact.models.get(cid)
_DEBUG && console.log("Global Collection (%s): %o %o %o", cid, options, modelled, _collection)
} | conditional_block |
core.js | define(["jquery", "underscore", "backbone"], function ($,_,Backbone) {
/* *****************************************************************************************************************
Prototype Inheritance
**************************************************************************************************************** */
$.curCSS = $.css; // back-port jquery 1.8+
/* *****************************************************************************************************************
**************************************************************************************************************** */
return {
DEBUG: false,
idAttribute: "id", labelAttribute: "label", typeAttribute: "type", commentAttribute: "comment",
fact: {
},
ux: {
i18n: {},
types: {},
mixin: {},
view: { field: {} }
},
iq: {
},
NS: {
"owl": "http://www.w3.org/2002/07/owl#",
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"xsd": "http://www.w3.org/2001/XMLSchema#",
"ux": "meta4:ux:",
"iq": "meta4:iq:",
"fact": "meta4:fact:",
"asq": "meta4:asq:",
},
/**
curried fn()
when invoked returns a fn() that in turns calls a named fn() on a context object
e.g: dispatch(source, "doSomething")(a,b,c) -> source.doSomething(a,b,c)
**/
dispatch: function(self, event) {
return function() {
return self[event] && self[event].apply(self, arguments)
}
},
resolve: function(options, modelled) {
if (!options) throw "meta4:ux:oops:missing-options"
var _DEBUG = options.debug || this.ux.DEBUG
modelled = modelled || _.extend({},options);
// Resolve Backbone Model - last resort, use 'options'
if (_.isString(options.model)) {
modelled.model = this.fact.models.get(options.model);
//_DEBUG &&
console.warn("Model$ (%s) %o %o -> %o", options.model, this.fact.models, options, modelled);
} else if ( options.model instanceof Backbone.Model ) {
modelled.model = options.model;
} else if (_.isFunction(options.model)) {
modelled.model = options.model(options);
} else if (_.isObject(options.model)) {
modelled.model = new this.fact.Model( options.model );
} else if ( options.model === false ) {
// modelled.model = new Backbone.Model()
_DEBUG && console.debug("No Model: %o %o", options, modelled)
} else if ( options.model === true || options.model == undefined) {
var _options = { label: options.label, comment: (options.comment || ""), icon: (options.icon || "") };
_options.idAttribute = options[this.ux.idAttribute]
modelled.model = new this.fact.Model({})
modelled.model.set(_options)
_DEBUG && console.debug("View Model (%s): %o %o", modelled.id, _options, modelled.model)
} else throw "meta4:ux:oops:invalid-model#"+options.model
// Resolve Backbone Collection
if (_.isString(options.collection)) {
// recursively re-model ... check if a sub-model first
var _collection = false
// nested-collection
if (options.collection.indexOf(".")==0) {
var cid = options.collection.substring(1)
_collection = modelled.model.get(cid)
if (!_collection) {
_collection = new Backbone.Collection()
_DEBUG && console.log("New Local Collection (%s): %o %o %o", cid, options, modelled, _collection)
modelled.model.set(cid, _collection)
} else {
_DEBUG && console.log("Existing Local Collection (%s): %o %o %o", cid, options, modelled, _collection)
}
} else if (options.collection.indexOf("!")==0) {
// global-collection
var cid = options.collection.substring(1)
_collection = fact.models.get(cid)
_DEBUG && console.log("Global Collection (%s): %o %o %o", cid, options, modelled, _collection)
} else {
var cid = options.collection
_collection = modelled.model.get(cid) || this.fact.models.get(cid)
_DEBUG && console.log("Local/Global Collection (%s): %o %o %o", cid, options, modelled, _collection) | }
if (!_collection) {
_collection = this.fact.factory.Local({ id: options.collection, fetch: false })
_DEBUG && console.log("Local Collection: %o %o %o %o", options.collection, options, modelled, _collection)
}
// resolve any string models
this.ux.model( { model: modelled.model, collection: _collection }, modelled);
_DEBUG && console.log("String Modelled: %o", modelled)
} else if (_.isArray(options.collection)) {
_DEBUG && console.log("Array Collection", options.collection, this.fact)
modelled.collection = this.fact.Collection(options.collection);
} else if (_.isObject(options.collection) && options.collection instanceof Backbone.Collection ) {
_DEBUG && console.log("Existing Collection: %o", options.collection)
modelled.collection = options.collection;
} else if (_.isObject(options.collection) && _.isString(options.collection.id) ) {
//_DEBUG &&
console.log("Register Collection: %s -> %o / %o", options.collection.id, options.collection, this.fact)
modelled.collection = this.fact.models.get(options.collection.id) || this.fact.register(options.collection)
} else if (_.isFunction(options.collection)) {
_DEBUG && console.log("Function Collection", options.collection, this.fact)
modelled.collection = options.collection(options);
}
// cloned originally options - with resolved Model, optionally a Collection
return modelled;
},
/**
Uses a curried fn() to replace key/values in options{}
if a matching option key exists within mix_ins{}
if the mixin is fn() then execute & bind the returned value
**/
curry: function(options, mix_ins, _options) {
if (!options || !mix_ins) return options;
_options = _options || {} // cloned object
_.each(options, function(option,key) {
var mixin = mix_ins[key]
_options[key] = _.isFunction(mixin)?mixin(option):option
})
return _options;
},
/**
Rename/Replace the keys in an key/value Object using a re-mapping object
@param: options - Object of key/values
@param: remap - Object of key1/key2
**/
remap: function(options, remap) {
if (!options || !remap) return options;
var map = {}
_.each(remap, function(v,k) {
var n = options[k]
if (_.isFunction(v)) map[v] = v(n, k, map)
else if ( !_.isUndefined(n) && !_.isUndefined(v) ) map[v] = n
})
return map;
},
/**
De-reference string-based 'values' to a mix-in fn()
Replaces string values in options with corresponding fn() from mixin
**/
mixin: function(options, mix_ins, _options) {
if (!options || !mix_ins) return options;
_options = _options || options // default original
_.each(options, function(value,key) {
if (_.isString(value)) {
var mixin = mix_ins[value]
if (mixin && _.isFunction(mixin)) {
options[key] = _.isFunction(mixin)?mixin:value
}
}
})
return _options;
},
isDefaultTrue: function(options, key) {
if (_.isUndefined(options)) return true;
return options[key]?true:false
},
/**
Utilities to deal with Strings (including special cases for 'id' strings)
**/
/**
Generate a reasonably unique UUID
**/
uuid: function() {
function _id() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); };
return (_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id());
},
/**
Generate a scoped UUID by pre-pending a prefix
**/
urn: function(prefix) {
return (prefix || core[idAttribute])+"#"+this.uuid();
},
/**
Turn camel-cased strings into a capitalised, space-separated string
**/
humanize: function(s) {
return s.replace(/\W+|_|-/g, " ").toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g, function($1) { return $1.toUpperCase() });
},
toQueryString(obj, prefix) {
serialize = function(obj, prefix) {
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push(typeof v == "object" ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
return serialize(obj, prefix)
}
}
}); | random_line_split |
|
core.js | define(["jquery", "underscore", "backbone"], function ($,_,Backbone) {
/* *****************************************************************************************************************
Prototype Inheritance
**************************************************************************************************************** */
$.curCSS = $.css; // back-port jquery 1.8+
/* *****************************************************************************************************************
**************************************************************************************************************** */
return {
DEBUG: false,
idAttribute: "id", labelAttribute: "label", typeAttribute: "type", commentAttribute: "comment",
fact: {
},
ux: {
i18n: {},
types: {},
mixin: {},
view: { field: {} }
},
iq: {
},
NS: {
"owl": "http://www.w3.org/2002/07/owl#",
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"xsd": "http://www.w3.org/2001/XMLSchema#",
"ux": "meta4:ux:",
"iq": "meta4:iq:",
"fact": "meta4:fact:",
"asq": "meta4:asq:",
},
/**
curried fn()
when invoked returns a fn() that in turns calls a named fn() on a context object
e.g: dispatch(source, "doSomething")(a,b,c) -> source.doSomething(a,b,c)
**/
dispatch: function(self, event) {
return function() {
return self[event] && self[event].apply(self, arguments)
}
},
resolve: function(options, modelled) {
if (!options) throw "meta4:ux:oops:missing-options"
var _DEBUG = options.debug || this.ux.DEBUG
modelled = modelled || _.extend({},options);
// Resolve Backbone Model - last resort, use 'options'
if (_.isString(options.model)) {
modelled.model = this.fact.models.get(options.model);
//_DEBUG &&
console.warn("Model$ (%s) %o %o -> %o", options.model, this.fact.models, options, modelled);
} else if ( options.model instanceof Backbone.Model ) {
modelled.model = options.model;
} else if (_.isFunction(options.model)) {
modelled.model = options.model(options);
} else if (_.isObject(options.model)) {
modelled.model = new this.fact.Model( options.model );
} else if ( options.model === false ) {
// modelled.model = new Backbone.Model()
_DEBUG && console.debug("No Model: %o %o", options, modelled)
} else if ( options.model === true || options.model == undefined) {
var _options = { label: options.label, comment: (options.comment || ""), icon: (options.icon || "") };
_options.idAttribute = options[this.ux.idAttribute]
modelled.model = new this.fact.Model({})
modelled.model.set(_options)
_DEBUG && console.debug("View Model (%s): %o %o", modelled.id, _options, modelled.model)
} else throw "meta4:ux:oops:invalid-model#"+options.model
// Resolve Backbone Collection
if (_.isString(options.collection)) {
// recursively re-model ... check if a sub-model first
var _collection = false
// nested-collection
if (options.collection.indexOf(".")==0) {
var cid = options.collection.substring(1)
_collection = modelled.model.get(cid)
if (!_collection) {
_collection = new Backbone.Collection()
_DEBUG && console.log("New Local Collection (%s): %o %o %o", cid, options, modelled, _collection)
modelled.model.set(cid, _collection)
} else {
_DEBUG && console.log("Existing Local Collection (%s): %o %o %o", cid, options, modelled, _collection)
}
} else if (options.collection.indexOf("!")==0) {
// global-collection
var cid = options.collection.substring(1)
_collection = fact.models.get(cid)
_DEBUG && console.log("Global Collection (%s): %o %o %o", cid, options, modelled, _collection)
} else {
var cid = options.collection
_collection = modelled.model.get(cid) || this.fact.models.get(cid)
_DEBUG && console.log("Local/Global Collection (%s): %o %o %o", cid, options, modelled, _collection)
}
if (!_collection) {
_collection = this.fact.factory.Local({ id: options.collection, fetch: false })
_DEBUG && console.log("Local Collection: %o %o %o %o", options.collection, options, modelled, _collection)
}
// resolve any string models
this.ux.model( { model: modelled.model, collection: _collection }, modelled);
_DEBUG && console.log("String Modelled: %o", modelled)
} else if (_.isArray(options.collection)) {
_DEBUG && console.log("Array Collection", options.collection, this.fact)
modelled.collection = this.fact.Collection(options.collection);
} else if (_.isObject(options.collection) && options.collection instanceof Backbone.Collection ) {
_DEBUG && console.log("Existing Collection: %o", options.collection)
modelled.collection = options.collection;
} else if (_.isObject(options.collection) && _.isString(options.collection.id) ) {
//_DEBUG &&
console.log("Register Collection: %s -> %o / %o", options.collection.id, options.collection, this.fact)
modelled.collection = this.fact.models.get(options.collection.id) || this.fact.register(options.collection)
} else if (_.isFunction(options.collection)) {
_DEBUG && console.log("Function Collection", options.collection, this.fact)
modelled.collection = options.collection(options);
}
// cloned originally options - with resolved Model, optionally a Collection
return modelled;
},
/**
Uses a curried fn() to replace key/values in options{}
if a matching option key exists within mix_ins{}
if the mixin is fn() then execute & bind the returned value
**/
curry: function(options, mix_ins, _options) {
if (!options || !mix_ins) return options;
_options = _options || {} // cloned object
_.each(options, function(option,key) {
var mixin = mix_ins[key]
_options[key] = _.isFunction(mixin)?mixin(option):option
})
return _options;
},
/**
Rename/Replace the keys in an key/value Object using a re-mapping object
@param: options - Object of key/values
@param: remap - Object of key1/key2
**/
remap: function(options, remap) {
if (!options || !remap) return options;
var map = {}
_.each(remap, function(v,k) {
var n = options[k]
if (_.isFunction(v)) map[v] = v(n, k, map)
else if ( !_.isUndefined(n) && !_.isUndefined(v) ) map[v] = n
})
return map;
},
/**
De-reference string-based 'values' to a mix-in fn()
Replaces string values in options with corresponding fn() from mixin
**/
mixin: function(options, mix_ins, _options) {
if (!options || !mix_ins) return options;
_options = _options || options // default original
_.each(options, function(value,key) {
if (_.isString(value)) {
var mixin = mix_ins[value]
if (mixin && _.isFunction(mixin)) {
options[key] = _.isFunction(mixin)?mixin:value
}
}
})
return _options;
},
isDefaultTrue: function(options, key) {
if (_.isUndefined(options)) return true;
return options[key]?true:false
},
/**
Utilities to deal with Strings (including special cases for 'id' strings)
**/
/**
Generate a reasonably unique UUID
**/
uuid: function() {
function _id() | ;
return (_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id());
},
/**
Generate a scoped UUID by pre-pending a prefix
**/
urn: function(prefix) {
return (prefix || core[idAttribute])+"#"+this.uuid();
},
/**
Turn camel-cased strings into a capitalised, space-separated string
**/
humanize: function(s) {
return s.replace(/\W+|_|-/g, " ").toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g, function($1) { return $1.toUpperCase() });
},
toQueryString(obj, prefix) {
serialize = function(obj, prefix) {
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push(typeof v == "object" ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
return serialize(obj, prefix)
}
}
}); | { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); } | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.