prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>###
# Copyright (c) 2012, Valentin Lorentz
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
"""
Add a description of the plugin (to be presented to the user inside the wizard)
here. This should describe *what* the plugin does.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
__version__ = ""
# XXX Replace this with an appropriate author or supybot.Author instance.
__author__ = supybot.authors.unknown
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
# This is a url where the most recent plugin package can be downloaded.
__url__ = '' # 'http://supybot.com/Members/yourname/TwitterStream/download'
from . import config
from . import plugin
from imp import reload
reload(plugin) # In case we're being reloaded.
# Add more reloads here if you add third-party modules and want them to be
# reloaded when this plugin is reloaded. Don't forget to import them as well!
if world.testing:
from . import test
<|fim▁hole|>Class = plugin.Class
configure = config.configure
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:<|fim▁end|> | |
<|file_name|>imports.rs<|end_file_name|><|fim▁begin|>//! A bunch of methods and structures more or less related to resolving imports.
use crate::diagnostics::Suggestion;
use crate::Determinacy::{self, *};
use crate::Namespace::{self, MacroNS, TypeNS};
use crate::{module_to_string, names_to_string};
use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
use crate::{BindingKey, ModuleKind, ResolutionError, Resolver, Segment};
use crate::{CrateLint, Module, ModuleOrUniformRoot, ParentScope, PerNS, ScopeSet, Weak};
use crate::{NameBinding, NameBindingKind, PathResult, PrivacyError, ToNameBinding};
use rustc_ast::unwrap_or;
use rustc_ast::NodeId;
use rustc_ast_lowering::ResolverAstLowering;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::ptr_key::PtrKey;
use rustc_errors::{pluralize, struct_span_err, Applicability};
use rustc_hir::def::{self, PartialRes};
use rustc_hir::def_id::DefId;
use rustc_middle::hir::exports::Export;
use rustc_middle::span_bug;
use rustc_middle::ty;
use rustc_session::lint::builtin::{PUB_USE_OF_PRIVATE_EXTERN_CRATE, UNUSED_IMPORTS};
use rustc_session::lint::BuiltinLintDiagnostics;
use rustc_span::hygiene::LocalExpnId;
use rustc_span::lev_distance::find_best_match_for_name;
use rustc_span::symbol::{kw, Ident, Symbol};
use rustc_span::{MultiSpan, Span};
use tracing::*;
use std::cell::Cell;
use std::{mem, ptr};
type Res = def::Res<NodeId>;
/// Contains data for specific kinds of imports.
#[derive(Clone, Debug)]
pub enum ImportKind<'a> {
Single {
/// `source` in `use prefix::source as target`.
source: Ident,
/// `target` in `use prefix::source as target`.
target: Ident,
/// Bindings to which `source` refers to.
source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
/// Bindings introduced by `target`.
target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
/// `true` for `...::{self [as target]}` imports, `false` otherwise.
type_ns_only: bool,
/// Did this import result from a nested import? ie. `use foo::{bar, baz};`
nested: bool,
},
Glob {
is_prelude: bool,
max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
// n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
},
ExternCrate {
source: Option<Symbol>,
target: Ident,
},
MacroUse,
}
/// One import.
#[derive(Debug, Clone)]
crate struct Import<'a> {
pub kind: ImportKind<'a>,
/// The ID of the `extern crate`, `UseTree` etc that imported this `Import`.
///
/// In the case where the `Import` was expanded from a "nested" use tree,
/// this id is the ID of the leaf tree. For example:
///
/// ```ignore (pacify the mercilous tidy)
/// use foo::bar::{a, b}
/// ```
///
/// If this is the import for `foo::bar::a`, we would have the ID of the `UseTree`
/// for `a` in this field.
pub id: NodeId,
/// The `id` of the "root" use-kind -- this is always the same as
/// `id` except in the case of "nested" use trees, in which case
/// it will be the `id` of the root use tree. e.g., in the example
/// from `id`, this would be the ID of the `use foo::bar`
/// `UseTree` node.
pub root_id: NodeId,
/// Span of the entire use statement.
pub use_span: Span,
/// Span of the entire use statement with attributes.
pub use_span_with_attributes: Span,
/// Did the use statement have any attributes?
pub has_attributes: bool,
/// Span of this use tree.
pub span: Span,
/// Span of the *root* use tree (see `root_id`).
pub root_span: Span,
pub parent_scope: ParentScope<'a>,
pub module_path: Vec<Segment>,
/// The resolution of `module_path`.
pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
pub vis: Cell<ty::Visibility>,
pub used: Cell<bool>,
}
impl<'a> Import<'a> {
pub fn is_glob(&self) -> bool {
matches!(self.kind, ImportKind::Glob { .. })
}
pub fn is_nested(&self) -> bool {
match self.kind {
ImportKind::Single { nested, .. } => nested,
_ => false,
}
}
crate fn crate_lint(&self) -> CrateLint {
CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
}
}
#[derive(Clone, Default, Debug)]
/// Records information about the resolution of a name in a namespace of a module.
pub struct NameResolution<'a> {
/// Single imports that may define the name in the namespace.
/// Imports are arena-allocated, so it's ok to use pointers as keys.
single_imports: FxHashSet<PtrKey<'a, Import<'a>>>,
/// The least shadowable known binding for this name, or None if there are no known bindings.
pub binding: Option<&'a NameBinding<'a>>,
shadowed_glob: Option<&'a NameBinding<'a>>,
}
impl<'a> NameResolution<'a> {
// Returns the binding for the name if it is known or None if it not known.
pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> {
self.binding.and_then(|binding| {
if !binding.is_glob_import() || self.single_imports.is_empty() {
Some(binding)
} else {
None
}
})
}
crate fn add_single_import(&mut self, import: &'a Import<'a>) {
self.single_imports.insert(PtrKey(import));
}
}
// Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;`
// are permitted for backward-compatibility under a deprecation lint.
fn pub_use_of_private_extern_crate_hack(import: &Import<'_>, binding: &NameBinding<'_>) -> bool {
match (&import.kind, &binding.kind) {
(
ImportKind::Single { .. },
NameBindingKind::Import {
import: Import { kind: ImportKind::ExternCrate { .. }, .. },
..
},
) => import.vis.get() == ty::Visibility::Public,
_ => false,
}
}
impl<'a> Resolver<'a> {
crate fn resolve_ident_in_module_unadjusted(
&mut self,
module: ModuleOrUniformRoot<'a>,
ident: Ident,
ns: Namespace,
parent_scope: &ParentScope<'a>,
record_used: bool,
path_span: Span,
) -> Result<&'a NameBinding<'a>, Determinacy> {
self.resolve_ident_in_module_unadjusted_ext(
module,
ident,
ns,
parent_scope,
false,
record_used,
path_span,
)
.map_err(|(determinacy, _)| determinacy)
}
/// Attempts to resolve `ident` in namespaces `ns` of `module`.
/// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
crate fn resolve_ident_in_module_unadjusted_ext(
&mut self,
module: ModuleOrUniformRoot<'a>,
ident: Ident,
ns: Namespace,
parent_scope: &ParentScope<'a>,
restricted_shadowing: bool,
record_used: bool,
path_span: Span,
) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
let module = match module {
ModuleOrUniformRoot::Module(module) => module,
ModuleOrUniformRoot::CrateRootAndExternPrelude => {
assert!(!restricted_shadowing);
let binding = self.early_resolve_ident_in_lexical_scope(
ident,
ScopeSet::AbsolutePath(ns),
parent_scope,
record_used,
record_used,
path_span,
);
return binding.map_err(|determinacy| (determinacy, Weak::No));
}
ModuleOrUniformRoot::ExternPrelude => {
assert!(!restricted_shadowing);
return if ns != TypeNS {
Err((Determined, Weak::No))
} else if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
Ok(binding)
} else if !self.graph_root.unexpanded_invocations.borrow().is_empty() {
// Macro-expanded `extern crate` items can add names to extern prelude.
Err((Undetermined, Weak::No))
} else {
Err((Determined, Weak::No))
};
}
ModuleOrUniformRoot::CurrentScope => {
assert!(!restricted_shadowing);
if ns == TypeNS {
if ident.name == kw::Crate || ident.name == kw::DollarCrate {
let module = self.resolve_crate_root(ident);
let binding =
(module, ty::Visibility::Public, module.span, LocalExpnId::ROOT)
.to_name_binding(self.arenas);
return Ok(binding);
} else if ident.name == kw::Super || ident.name == kw::SelfLower {
// FIXME: Implement these with renaming requirements so that e.g.
// `use super;` doesn't work, but `use super as name;` does.
// Fall through here to get an error from `early_resolve_...`.
}
}
let scopes = ScopeSet::All(ns, true);
let binding = self.early_resolve_ident_in_lexical_scope(
ident,
scopes,
parent_scope,
record_used,
record_used,
path_span,
);
return binding.map_err(|determinacy| (determinacy, Weak::No));
}
};
let key = self.new_key(ident, ns);
let resolution =
self.resolution(module, key).try_borrow_mut().map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
if let Some(binding) = resolution.binding {
if !restricted_shadowing && binding.expansion != LocalExpnId::ROOT {
if let NameBindingKind::Res(_, true) = binding.kind {
self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
}
}
}
let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
if let Some(unusable_binding) = this.unusable_binding {
if ptr::eq(binding, unusable_binding) {
return Err((Determined, Weak::No));
}
}
let usable = this.is_accessible_from(binding.vis, parent_scope.module);
if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
};
if record_used {
return resolution
.binding
.and_then(|binding| {
// If the primary binding is unusable, search further and return the shadowed glob
// binding if it exists. What we really want here is having two separate scopes in
// a module - one for non-globs and one for globs, but until that's done use this
// hack to avoid inconsistent resolution ICEs during import validation.
if let Some(unusable_binding) = self.unusable_binding {
if ptr::eq(binding, unusable_binding) {
return resolution.shadowed_glob;
}
}
Some(binding)
})
.ok_or((Determined, Weak::No))
.and_then(|binding| {
if self.last_import_segment && check_usable(self, binding).is_err() {
Err((Determined, Weak::No))
} else {
self.record_use(ident, binding, restricted_shadowing);
if let Some(shadowed_glob) = resolution.shadowed_glob {
// Forbid expanded shadowing to avoid time travel.
if restricted_shadowing
&& binding.expansion != LocalExpnId::ROOT
&& binding.res() != shadowed_glob.res()
{
self.ambiguity_errors.push(AmbiguityError {
kind: AmbiguityKind::GlobVsExpanded,
ident,
b1: binding,
b2: shadowed_glob,
misc1: AmbiguityErrorMisc::None,
misc2: AmbiguityErrorMisc::None,
});
}
}
if !self.is_accessible_from(binding.vis, parent_scope.module) {
self.privacy_errors.push(PrivacyError {
ident,
binding,
dedup_span: path_span,
});
}
Ok(binding)
}
});
}
// Items and single imports are not shadowable, if we have one, then it's determined.
if let Some(binding) = resolution.binding {
if !binding.is_glob_import() {
return check_usable(self, binding);
}
}
// --- From now on we either have a glob resolution or no resolution. ---
// Check if one of single imports can still define the name,
// if it can then our result is not determined and can be invalidated.
for single_import in &resolution.single_imports {
if !self.is_accessible_from(single_import.vis.get(), parent_scope.module) {
continue;
}
let module = unwrap_or!(
single_import.imported_module.get(),
return Err((Undetermined, Weak::No))
);
let ident = match single_import.kind {
ImportKind::Single { source, .. } => source,
_ => unreachable!(),
};
match self.resolve_ident_in_module(
module,
ident,
ns,
&single_import.parent_scope,
false,
path_span,
) {
Err(Determined) => continue,
Ok(binding)
if !self.is_accessible_from(binding.vis, single_import.parent_scope.module) =>
{
continue;
}
Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
}
}
// So we have a resolution that's from a glob import. This resolution is determined
// if it cannot be shadowed by some new item/import expanded from a macro.
// This happens either if there are no unexpanded macros, or expanded names cannot
// shadow globs (that happens in macro namespace or with restricted shadowing).
//
// Additionally, any macro in any module can plant names in the root module if it creates
// `macro_export` macros, so the root module effectively has unresolved invocations if any
// module has unresolved invocations.
// However, it causes resolution/expansion to stuck too often (#53144), so, to make
// progress, we have to ignore those potential unresolved invocations from other modules
// and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
// shadowing is enabled, see `macro_expanded_macro_export_errors`).
let unexpanded_macros = !module.unexpanded_invocations.borrow().is_empty();
if let Some(binding) = resolution.binding {
if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
return check_usable(self, binding);
} else {
return Err((Undetermined, Weak::No));
}
}
// --- From now on we have no resolution. ---
// Now we are in situation when new item/import can appear only from a glob or a macro
// expansion. With restricted shadowing names from globs and macro expansions cannot
// shadow names from outer scopes, so we can freely fallback from module search to search
// in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
// scopes we return `Undetermined` with `Weak::Yes`.
// Check if one of unexpanded macros can still define the name,
// if it can then our "no resolution" result is not determined and can be invalidated.
if unexpanded_macros {
return Err((Undetermined, Weak::Yes));
}
// Check if one of glob imports can still define the name,
// if it can then our "no resolution" result is not determined and can be invalidated.
for glob_import in module.globs.borrow().iter() {
if !self.is_accessible_from(glob_import.vis.get(), parent_scope.module) {
continue;
}
let module = match glob_import.imported_module.get() {
Some(ModuleOrUniformRoot::Module(module)) => module,
Some(_) => continue,
None => return Err((Undetermined, Weak::Yes)),
};
let tmp_parent_scope;
let (mut adjusted_parent_scope, mut ident) =
(parent_scope, ident.normalize_to_macros_2_0());
match ident.span.glob_adjust(module.expansion, glob_import.span) {
Some(Some(def)) => {
tmp_parent_scope =
ParentScope { module: self.macro_def_scope(def), ..*parent_scope };
adjusted_parent_scope = &tmp_parent_scope;
}
Some(None) => {}
None => continue,
};
let result = self.resolve_ident_in_module_unadjusted(
ModuleOrUniformRoot::Module(module),
ident,
ns,
adjusted_parent_scope,
false,
path_span,
);
match result {
Err(Determined) => continue,
Ok(binding)
if !self.is_accessible_from(binding.vis, glob_import.parent_scope.module) =>
{
continue;
}
Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
}
}
// No resolution and no one else can define the name - determinate error.
Err((Determined, Weak::No))
}
// Given a binding and an import that resolves to it,
// return the corresponding binding defined by the import.
crate fn import(
&self,
binding: &'a NameBinding<'a>,
import: &'a Import<'a>,
) -> &'a NameBinding<'a> {
let vis = if binding.vis.is_at_least(import.vis.get(), self)
|| pub_use_of_private_extern_crate_hack(import, binding)
{
import.vis.get()
} else {
binding.vis
};
if let ImportKind::Glob { ref max_vis, .. } = import.kind {
if vis == import.vis.get() || vis.is_at_least(max_vis.get(), self) {
max_vis.set(vis)
}
}
self.arenas.alloc_name_binding(NameBinding {
kind: NameBindingKind::Import { binding, import, used: Cell::new(false) },
ambiguity: None,
span: import.span,
vis,
expansion: import.parent_scope.expansion,
})
}
// Define the name or return the existing binding if there is a collision.
crate fn try_define(
&mut self,
module: Module<'a>,
key: BindingKey,
binding: &'a NameBinding<'a>,
) -> Result<(), &'a NameBinding<'a>> {
let res = binding.res();
self.check_reserved_macro_name(key.ident, res);
self.set_binding_parent_module(binding, module);
self.update_resolution(module, key, |this, resolution| {
if let Some(old_binding) = resolution.binding {
if res == Res::Err {
// Do not override real bindings with `Res::Err`s from error recovery.
return Ok(());
}
match (old_binding.is_glob_import(), binding.is_glob_import()) {
(true, true) => {
if res != old_binding.res() {
resolution.binding = Some(this.ambiguity(
AmbiguityKind::GlobVsGlob,
old_binding,
binding,
));
} else if !old_binding.vis.is_at_least(binding.vis, &*this) {
// We are glob-importing the same item but with greater visibility.
resolution.binding = Some(binding);
}
}
(old_glob @ true, false) | (old_glob @ false, true) => {
let (glob_binding, nonglob_binding) =
if old_glob { (old_binding, binding) } else { (binding, old_binding) };
if glob_binding.res() != nonglob_binding.res()
&& key.ns == MacroNS
&& nonglob_binding.expansion != LocalExpnId::ROOT
{
resolution.binding = Some(this.ambiguity(
AmbiguityKind::GlobVsExpanded,
nonglob_binding,
glob_binding,
));
} else {
resolution.binding = Some(nonglob_binding);
}
resolution.shadowed_glob = Some(glob_binding);
}
(false, false) => {
return Err(old_binding);
}
}
} else {
resolution.binding = Some(binding);
}
Ok(())
})
}
fn ambiguity(
&self,
kind: AmbiguityKind,
primary_binding: &'a NameBinding<'a>,
secondary_binding: &'a NameBinding<'a>,
) -> &'a NameBinding<'a> {
self.arenas.alloc_name_binding(NameBinding {
ambiguity: Some((secondary_binding, kind)),
..primary_binding.clone()
})
}
// Use `f` to mutate the resolution of the name in the module.
// If the resolution becomes a success, define it in the module's glob importers.
fn update_resolution<T, F>(&mut self, module: Module<'a>, key: BindingKey, f: F) -> T
where
F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T,
{
// Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
// during which the resolution might end up getting re-defined via a glob cycle.
let (binding, t) = {
let resolution = &mut *self.resolution(module, key).borrow_mut();
let old_binding = resolution.binding();
let t = f(self, resolution);
match resolution.binding() {
_ if old_binding.is_some() => return t,
None => return t,
Some(binding) => match old_binding {
Some(old_binding) if ptr::eq(old_binding, binding) => return t,
_ => (binding, t),
},
}
};
// Define `binding` in `module`s glob importers.
for import in module.glob_importers.borrow_mut().iter() {
let mut ident = key.ident;
let scope = match ident.span.reverse_glob_adjust(module.expansion, import.span) {
Some(Some(def)) => self.macro_def_scope(def),
Some(None) => import.parent_scope.module,
None => continue,
};
if self.is_accessible_from(binding.vis, scope) {
let imported_binding = self.import(binding, import);
let key = BindingKey { ident, ..key };
let _ = self.try_define(import.parent_scope.module, key, imported_binding);
}
}
t
}
// Define a "dummy" resolution containing a Res::Err as a placeholder for a
// failed resolution
fn import_dummy_binding(&mut self, import: &'a Import<'a>) {
if let ImportKind::Single { target, .. } = import.kind {
let dummy_binding = self.dummy_binding;
let dummy_binding = self.import(dummy_binding, import);
self.per_ns(|this, ns| {
let key = this.new_key(target, ns);
let _ = this.try_define(import.parent_scope.module, key, dummy_binding);
});
// Consider erroneous imports used to avoid duplicate diagnostics.
self.record_use(target, dummy_binding, false);
}
}
}
/// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
/// import errors within the same use tree into a single diagnostic.
#[derive(Debug, Clone)]
struct UnresolvedImportError {
span: Span,
label: Option<String>,
note: Vec<String>,
suggestion: Option<Suggestion>,
}
pub struct ImportResolver<'a, 'b> {
pub r: &'a mut Resolver<'b>,
}
impl<'a, 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
fn parent(self, id: DefId) -> Option<DefId> {
self.r.parent(id)
}
}
impl<'a, 'b> ImportResolver<'a, 'b> {
// Import resolution
//
// This is a fixed-point algorithm. We resolve imports until our efforts
// are stymied by an unresolved import; then we bail out of the current
// module and continue. We terminate successfully once no more imports
// remain or unsuccessfully when no forward progress in resolving imports
// is made.
/// Resolves all imports for the crate. This method performs the fixed-
/// point iteration.
pub fn resolve_imports(&mut self) {
let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1;
while self.r.indeterminate_imports.len() < prev_num_indeterminates {<|fim▁hole|> prev_num_indeterminates = self.r.indeterminate_imports.len();
for import in mem::take(&mut self.r.indeterminate_imports) {
match self.resolve_import(&import) {
true => self.r.determined_imports.push(import),
false => self.r.indeterminate_imports.push(import),
}
}
}
}
pub fn finalize_imports(&mut self) {
for module in self.r.arenas.local_modules().iter() {
self.finalize_resolutions_in(module);
}
let mut seen_spans = FxHashSet::default();
let mut errors = vec![];
let mut prev_root_id: NodeId = NodeId::from_u32(0);
let determined_imports = mem::take(&mut self.r.determined_imports);
let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports);
for (is_indeterminate, import) in determined_imports
.into_iter()
.map(|i| (false, i))
.chain(indeterminate_imports.into_iter().map(|i| (true, i)))
{
if let Some(err) = self.finalize_import(import) {
if let ImportKind::Single { source, ref source_bindings, .. } = import.kind {
if source.name == kw::SelfLower {
// Silence `unresolved import` error if E0429 is already emitted
if let Err(Determined) = source_bindings.value_ns.get() {
continue;
}
}
}
// If the error is a single failed import then create a "fake" import
// resolution for it so that later resolve stages won't complain.
self.r.import_dummy_binding(import);
if prev_root_id.as_u32() != 0
&& prev_root_id.as_u32() != import.root_id.as_u32()
&& !errors.is_empty()
{
// In the case of a new import line, throw a diagnostic message
// for the previous line.
self.throw_unresolved_import_error(errors, None);
errors = vec![];
}
if seen_spans.insert(err.span) {
let path = import_path_to_string(
&import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
&import.kind,
err.span,
);
errors.push((path, err));
prev_root_id = import.root_id;
}
} else if is_indeterminate {
// Consider erroneous imports used to avoid duplicate diagnostics.
self.r.used_imports.insert(import.id);
let path = import_path_to_string(
&import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
&import.kind,
import.span,
);
let err = UnresolvedImportError {
span: import.span,
label: None,
note: Vec::new(),
suggestion: None,
};
errors.push((path, err));
}
}
if !errors.is_empty() {
self.throw_unresolved_import_error(errors, None);
}
}
fn throw_unresolved_import_error(
&self,
errors: Vec<(String, UnresolvedImportError)>,
span: Option<MultiSpan>,
) {
/// Upper limit on the number of `span_label` messages.
const MAX_LABEL_COUNT: usize = 10;
let (span, msg) = if errors.is_empty() {
(span.unwrap(), "unresolved import".to_string())
} else {
let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
let paths = errors.iter().map(|(path, _)| format!("`{}`", path)).collect::<Vec<_>>();
let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
(span, msg)
};
let mut diag = struct_span_err!(self.r.session, span, E0432, "{}", &msg);
if let Some((_, UnresolvedImportError { note, .. })) = errors.iter().last() {
for message in note {
diag.note(&message);
}
}
for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
if let Some(label) = err.label {
diag.span_label(err.span, label);
}
if let Some((suggestions, msg, applicability)) = err.suggestion {
diag.multipart_suggestion(&msg, suggestions, applicability);
}
}
diag.emit();
}
/// Attempts to resolve the given import, returning true if its resolution is determined.
/// If successful, the resolved bindings are written into the module.
fn resolve_import(&mut self, import: &'b Import<'b>) -> bool {
debug!(
"(resolving import for module) resolving import `{}::...` in `{}`",
Segment::names_to_string(&import.module_path),
module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
);
let module = if let Some(module) = import.imported_module.get() {
module
} else {
// For better failure detection, pretend that the import will
// not define any names while resolving its module path.
let orig_vis = import.vis.replace(ty::Visibility::Invisible);
let path_res = self.r.resolve_path(
&import.module_path,
None,
&import.parent_scope,
false,
import.span,
import.crate_lint(),
);
import.vis.set(orig_vis);
match path_res {
PathResult::Module(module) => module,
PathResult::Indeterminate => return false,
PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
}
};
import.imported_module.set(Some(module));
let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
ImportKind::Single {
source,
target,
ref source_bindings,
ref target_bindings,
type_ns_only,
..
} => (source, target, source_bindings, target_bindings, type_ns_only),
ImportKind::Glob { .. } => {
self.resolve_glob_import(import);
return true;
}
_ => unreachable!(),
};
let mut indeterminate = false;
self.r.per_ns(|this, ns| {
if !type_ns_only || ns == TypeNS {
if let Err(Undetermined) = source_bindings[ns].get() {
// For better failure detection, pretend that the import will
// not define any names while resolving its module path.
let orig_vis = import.vis.replace(ty::Visibility::Invisible);
let binding = this.resolve_ident_in_module(
module,
source,
ns,
&import.parent_scope,
false,
import.span,
);
import.vis.set(orig_vis);
source_bindings[ns].set(binding);
} else {
return;
};
let parent = import.parent_scope.module;
match source_bindings[ns].get() {
Err(Undetermined) => indeterminate = true,
// Don't update the resolution, because it was never added.
Err(Determined) if target.name == kw::Underscore => {}
Err(Determined) => {
let key = this.new_key(target, ns);
this.update_resolution(parent, key, |_, resolution| {
resolution.single_imports.remove(&PtrKey(import));
});
}
Ok(binding) if !binding.is_importable() => {
let msg = format!("`{}` is not directly importable", target);
struct_span_err!(this.session, import.span, E0253, "{}", &msg)
.span_label(import.span, "cannot be imported directly")
.emit();
// Do not import this illegal binding. Import a dummy binding and pretend
// everything is fine
this.import_dummy_binding(import);
}
Ok(binding) => {
let imported_binding = this.import(binding, import);
target_bindings[ns].set(Some(imported_binding));
this.define(parent, target, ns, imported_binding);
}
}
}
});
!indeterminate
}
/// Performs final import resolution, consistency checks and error reporting.
///
/// Optionally returns an unresolved import error. This error is buffered and used to
/// consolidate multiple unresolved import errors into a single diagnostic.
fn finalize_import(&mut self, import: &'b Import<'b>) -> Option<UnresolvedImportError> {
let orig_vis = import.vis.replace(ty::Visibility::Invisible);
let orig_unusable_binding = match &import.kind {
ImportKind::Single { target_bindings, .. } => {
Some(mem::replace(&mut self.r.unusable_binding, target_bindings[TypeNS].get()))
}
_ => None,
};
let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
let path_res = self.r.resolve_path(
&import.module_path,
None,
&import.parent_scope,
true,
import.span,
import.crate_lint(),
);
let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
if let Some(orig_unusable_binding) = orig_unusable_binding {
self.r.unusable_binding = orig_unusable_binding;
}
import.vis.set(orig_vis);
if let PathResult::Failed { .. } | PathResult::NonModule(..) = path_res {
// Consider erroneous imports used to avoid duplicate diagnostics.
self.r.used_imports.insert(import.id);
}
let module = match path_res {
PathResult::Module(module) => {
// Consistency checks, analogous to `finalize_macro_resolutions`.
if let Some(initial_module) = import.imported_module.get() {
if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
span_bug!(import.span, "inconsistent resolution for an import");
}
} else if self.r.privacy_errors.is_empty() {
let msg = "cannot determine resolution for the import";
let msg_note = "import resolution is stuck, try simplifying other imports";
self.r.session.struct_span_err(import.span, msg).note(msg_note).emit();
}
module
}
PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
if no_ambiguity {
assert!(import.imported_module.get().is_none());
self.r
.report_error(span, ResolutionError::FailedToResolve { label, suggestion });
}
return None;
}
PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
if no_ambiguity {
assert!(import.imported_module.get().is_none());
let err = match self.make_path_suggestion(
span,
import.module_path.clone(),
&import.parent_scope,
) {
Some((suggestion, note)) => UnresolvedImportError {
span,
label: None,
note,
suggestion: Some((
vec![(span, Segment::names_to_string(&suggestion))],
String::from("a similar path exists"),
Applicability::MaybeIncorrect,
)),
},
None => UnresolvedImportError {
span,
label: Some(label),
note: Vec::new(),
suggestion,
},
};
return Some(err);
}
return None;
}
PathResult::NonModule(_) => {
if no_ambiguity {
assert!(import.imported_module.get().is_none());
}
// The error was already reported earlier.
return None;
}
PathResult::Indeterminate => unreachable!(),
};
let (ident, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
ImportKind::Single {
source,
target,
ref source_bindings,
ref target_bindings,
type_ns_only,
..
} => (source, target, source_bindings, target_bindings, type_ns_only),
ImportKind::Glob { is_prelude, ref max_vis } => {
if import.module_path.len() <= 1 {
// HACK(eddyb) `lint_if_path_starts_with_module` needs at least
// 2 segments, so the `resolve_path` above won't trigger it.
let mut full_path = import.module_path.clone();
full_path.push(Segment::from_ident(Ident::invalid()));
self.r.lint_if_path_starts_with_module(
import.crate_lint(),
&full_path,
import.span,
None,
);
}
if let ModuleOrUniformRoot::Module(module) = module {
if module.def_id() == import.parent_scope.module.def_id() {
// Importing a module into itself is not allowed.
return Some(UnresolvedImportError {
span: import.span,
label: Some(String::from("cannot glob-import a module into itself")),
note: Vec::new(),
suggestion: None,
});
}
}
if !is_prelude &&
max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
!max_vis.get().is_at_least(import.vis.get(), &*self)
{
let msg = "glob import doesn't reexport anything because no candidate is public enough";
self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg);
}
return None;
}
_ => unreachable!(),
};
let mut all_ns_err = true;
self.r.per_ns(|this, ns| {
if !type_ns_only || ns == TypeNS {
let orig_vis = import.vis.replace(ty::Visibility::Invisible);
let orig_unusable_binding =
mem::replace(&mut this.unusable_binding, target_bindings[ns].get());
let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
let binding = this.resolve_ident_in_module(
module,
ident,
ns,
&import.parent_scope,
true,
import.span,
);
this.last_import_segment = orig_last_import_segment;
this.unusable_binding = orig_unusable_binding;
import.vis.set(orig_vis);
match binding {
Ok(binding) => {
// Consistency checks, analogous to `finalize_macro_resolutions`.
let initial_res = source_bindings[ns].get().map(|initial_binding| {
all_ns_err = false;
if let Some(target_binding) = target_bindings[ns].get() {
if target.name == kw::Underscore
&& initial_binding.is_extern_crate()
&& !initial_binding.is_import()
{
this.record_use(
ident,
target_binding,
import.module_path.is_empty(),
);
}
}
initial_binding.res()
});
let res = binding.res();
if let Ok(initial_res) = initial_res {
if res != initial_res && this.ambiguity_errors.is_empty() {
span_bug!(import.span, "inconsistent resolution for an import");
}
} else if res != Res::Err
&& this.ambiguity_errors.is_empty()
&& this.privacy_errors.is_empty()
{
let msg = "cannot determine resolution for the import";
let msg_note =
"import resolution is stuck, try simplifying other imports";
this.session.struct_span_err(import.span, msg).note(msg_note).emit();
}
}
Err(..) => {
// FIXME: This assert may fire if public glob is later shadowed by a private
// single import (see test `issue-55884-2.rs`). In theory single imports should
// always block globs, even if they are not yet resolved, so that this kind of
// self-inconsistent resolution never happens.
// Re-enable the assert when the issue is fixed.
// assert!(result[ns].get().is_err());
}
}
}
});
if all_ns_err {
let mut all_ns_failed = true;
self.r.per_ns(|this, ns| {
if !type_ns_only || ns == TypeNS {
let binding = this.resolve_ident_in_module(
module,
ident,
ns,
&import.parent_scope,
true,
import.span,
);
if binding.is_ok() {
all_ns_failed = false;
}
}
});
return if all_ns_failed {
let resolutions = match module {
ModuleOrUniformRoot::Module(module) => {
Some(self.r.resolutions(module).borrow())
}
_ => None,
};
let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
let names = resolutions
.filter_map(|(BindingKey { ident: i, .. }, resolution)| {
if *i == ident {
return None;
} // Never suggest the same name
match *resolution.borrow() {
NameResolution { binding: Some(name_binding), .. } => {
match name_binding.kind {
NameBindingKind::Import { binding, .. } => {
match binding.kind {
// Never suggest the name that has binding error
// i.e., the name that cannot be previously resolved
NameBindingKind::Res(Res::Err, _) => None,
_ => Some(i.name),
}
}
_ => Some(i.name),
}
}
NameResolution { ref single_imports, .. }
if single_imports.is_empty() =>
{
None
}
_ => Some(i.name),
}
})
.collect::<Vec<Symbol>>();
let lev_suggestion =
find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
(
vec![(ident.span, suggestion.to_string())],
String::from("a similar name exists in the module"),
Applicability::MaybeIncorrect,
)
});
let (suggestion, note) =
match self.check_for_module_export_macro(import, module, ident) {
Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
_ => (lev_suggestion, Vec::new()),
};
let label = match module {
ModuleOrUniformRoot::Module(module) => {
let module_str = module_to_string(module);
if let Some(module_str) = module_str {
format!("no `{}` in `{}`", ident, module_str)
} else {
format!("no `{}` in the root", ident)
}
}
_ => {
if !ident.is_path_segment_keyword() {
format!("no external crate `{}`", ident)
} else {
// HACK(eddyb) this shows up for `self` & `super`, which
// should work instead - for now keep the same error message.
format!("no `{}` in the root", ident)
}
}
};
Some(UnresolvedImportError {
span: import.span,
label: Some(label),
note,
suggestion,
})
} else {
// `resolve_ident_in_module` reported a privacy error.
self.r.import_dummy_binding(import);
None
};
}
let mut reexport_error = None;
let mut any_successful_reexport = false;
self.r.per_ns(|this, ns| {
if let Ok(binding) = source_bindings[ns].get() {
let vis = import.vis.get();
if !binding.vis.is_at_least(vis, &*this) {
reexport_error = Some((ns, binding));
} else {
any_successful_reexport = true;
}
}
});
// All namespaces must be re-exported with extra visibility for an error to occur.
if !any_successful_reexport {
let (ns, binding) = reexport_error.unwrap();
if pub_use_of_private_extern_crate_hack(import, binding) {
let msg = format!(
"extern crate `{}` is private, and cannot be \
re-exported (error E0365), consider declaring with \
`pub`",
ident
);
self.r.lint_buffer.buffer_lint(
PUB_USE_OF_PRIVATE_EXTERN_CRATE,
import.id,
import.span,
&msg,
);
} else if ns == TypeNS {
struct_span_err!(
self.r.session,
import.span,
E0365,
"`{}` is private, and cannot be re-exported",
ident
)
.span_label(import.span, format!("re-export of private `{}`", ident))
.note(&format!("consider declaring type or module `{}` with `pub`", ident))
.emit();
} else {
let msg = format!("`{}` is private, and cannot be re-exported", ident);
let note_msg =
format!("consider marking `{}` as `pub` in the imported module", ident,);
struct_span_err!(self.r.session, import.span, E0364, "{}", &msg)
.span_note(import.span, ¬e_msg)
.emit();
}
}
if import.module_path.len() <= 1 {
// HACK(eddyb) `lint_if_path_starts_with_module` needs at least
// 2 segments, so the `resolve_path` above won't trigger it.
let mut full_path = import.module_path.clone();
full_path.push(Segment::from_ident(ident));
self.r.per_ns(|this, ns| {
if let Ok(binding) = source_bindings[ns].get() {
this.lint_if_path_starts_with_module(
import.crate_lint(),
&full_path,
import.span,
Some(binding),
);
}
});
}
// Record what this import resolves to for later uses in documentation,
// this may resolve to either a value or a type, but for documentation
// purposes it's good enough to just favor one over the other.
self.r.per_ns(|this, ns| {
if let Ok(binding) = source_bindings[ns].get() {
this.import_res_map.entry(import.id).or_default()[ns] = Some(binding.res());
}
});
self.check_for_redundant_imports(ident, import, source_bindings, target_bindings, target);
debug!("(resolving single import) successfully resolved import");
None
}
fn check_for_redundant_imports(
&mut self,
ident: Ident,
import: &'b Import<'b>,
source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
target: Ident,
) {
// Skip if the import was produced by a macro.
if import.parent_scope.expansion != LocalExpnId::ROOT {
return;
}
// Skip if we are inside a named module (in contrast to an anonymous
// module defined by a block).
if let ModuleKind::Def(..) = import.parent_scope.module.kind {
return;
}
let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None };
let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
self.r.per_ns(|this, ns| {
if let Ok(binding) = source_bindings[ns].get() {
if binding.res() == Res::Err {
return;
}
let orig_unusable_binding =
mem::replace(&mut this.unusable_binding, target_bindings[ns].get());
match this.early_resolve_ident_in_lexical_scope(
target,
ScopeSet::All(ns, false),
&import.parent_scope,
false,
false,
import.span,
) {
Ok(other_binding) => {
is_redundant[ns] = Some(
binding.res() == other_binding.res() && !other_binding.is_ambiguity(),
);
redundant_span[ns] = Some((other_binding.span, other_binding.is_import()));
}
Err(_) => is_redundant[ns] = Some(false),
}
this.unusable_binding = orig_unusable_binding;
}
});
if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant)
{
let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
redundant_spans.sort();
redundant_spans.dedup();
self.r.lint_buffer.buffer_lint_with_diagnostic(
UNUSED_IMPORTS,
import.id,
import.span,
&format!("the item `{}` is imported redundantly", ident),
BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
);
}
}
fn resolve_glob_import(&mut self, import: &'b Import<'b>) {
let module = match import.imported_module.get().unwrap() {
ModuleOrUniformRoot::Module(module) => module,
_ => {
self.r.session.span_err(import.span, "cannot glob-import all possible crates");
return;
}
};
if module.is_trait() {
self.r.session.span_err(import.span, "items in traits are not importable.");
return;
} else if module.def_id() == import.parent_scope.module.def_id() {
return;
} else if let ImportKind::Glob { is_prelude: true, .. } = import.kind {
self.r.prelude = Some(module);
return;
}
// Add to module's glob_importers
module.glob_importers.borrow_mut().push(import);
// Ensure that `resolutions` isn't borrowed during `try_define`,
// since it might get updated via a glob cycle.
let bindings = self
.r
.resolutions(module)
.borrow()
.iter()
.filter_map(|(key, resolution)| {
resolution.borrow().binding().map(|binding| (*key, binding))
})
.collect::<Vec<_>>();
for (mut key, binding) in bindings {
let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) {
Some(Some(def)) => self.r.macro_def_scope(def),
Some(None) => import.parent_scope.module,
None => continue,
};
if self.r.is_accessible_from(binding.vis, scope) {
let imported_binding = self.r.import(binding, import);
let _ = self.r.try_define(import.parent_scope.module, key, imported_binding);
}
}
// Record the destination of this import
self.r.record_partial_res(import.id, PartialRes::new(module.res().unwrap()));
}
// Miscellaneous post-processing, including recording re-exports,
// reporting conflicts, and reporting unresolved imports.
fn finalize_resolutions_in(&mut self, module: Module<'b>) {
// Since import resolution is finished, globs will not define any more names.
*module.globs.borrow_mut() = Vec::new();
let mut reexports = Vec::new();
module.for_each_child(self.r, |this, ident, _, binding| {
// Filter away ambiguous imports and anything that has def-site hygiene.
// FIXME: Implement actual cross-crate hygiene.
let is_good_import =
binding.is_import() && !binding.is_ambiguity() && !ident.span.from_expansion();
if is_good_import || binding.is_macro_def() {
let res = binding.res().map_id(|id| this.local_def_id(id));
if res != def::Res::Err {
reexports.push(Export { ident, res, span: binding.span, vis: binding.vis });
}
}
});
if !reexports.is_empty() {
if let Some(def_id) = module.def_id() {
// Call to `expect_local` should be fine because current
// code is only called for local modules.
self.r.export_map.insert(def_id.expect_local(), reexports);
}
}
}
}
fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
let global = !names.is_empty() && names[0].name == kw::PathRoot;
if let Some(pos) = pos {
let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
} else {
let names = if global { &names[1..] } else { names };
if names.is_empty() {
import_kind_to_string(import_kind)
} else {
format!(
"{}::{}",
names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
import_kind_to_string(import_kind),
)
}
}
}
fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
match import_kind {
ImportKind::Single { source, .. } => source.to_string(),
ImportKind::Glob { .. } => "*".to_string(),
ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
ImportKind::MacroUse => "#[macro_use]".to_string(),
}
}<|fim▁end|> | |
<|file_name|>event.go<|end_file_name|><|fim▁begin|>package models
import (
"fmt"
"github.com/confur-me/confur-api/db"
"time"
)
type Event struct {
ID uint `gorm:"primary_key" json:"id"`
ConferenceSlug *string `sql:"not null;index" binding:"required" json:"conference_slug"`
Conference *Conference `json:"conference,omitempty" gorm:"foreignkey:conference_slug"`
Scope *string `sql:"not null;index" json:"scope" binding:"required"`
Title string `sql:"type:text" binding:"required" json:"title"`
Description string `sql:"type:text" json:"description"`
Country string `sql:"index:idx_country_state_city_address" json:"country"`
City string `sql:"index:idx_country_state_city_address" json:"city"`
State string `sql:"index:idx_country_state_city_address" json:"state"`
Address string `sql:"type:text;index:idx_country_state_city_address" json:"address"`
Speakers *[]Speaker `gorm:"many2many:events_speakers" json:"speakers,omitempty"`
Videos *[]Video `json:"videos,omitempty"`
VideosCount uint `sql:"not null;default:0" json:"videos_count"`
Thumbnail string `json:"thumbnail"`
IsActive *bool `sql:"not null;index" binding:"required" json:"-"`
StartsAt *time.Time `sql:"index" json:"starts_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at,omitempty"`
}
type eventService struct {
Service
}
func NewEventService(params map[string]interface{}) *eventService {
s := new(eventService)
s.params = params
return s
}
func (this *eventService) Event() (*Event, error) {
var (
resource Event
err error
)
if conn, ok := db.Connection(); ok {
if v, ok := this.params["event"]; ok {
err = conn.Scopes(Active).Where("id = ?", v).Preload("Conference").First(&resource).Error
}
}
return &resource, err
}
func (this *eventService) Events() (*[]Event, error) {
var err error
collection := make([]Event, 0)
if conn, ok := db.Connection(); ok {
query := &conn
limit := 20 // Defaults to 20 items per page
page := 1<|fim▁hole|> query = query.Where("conference_slug = ?", v)
}
if v, ok := this.params["query"]; ok {
// FIXME: CHECK injection possibility
query = query.Where("title ILIKE ?", fmt.Sprintf("%%%v%%", v))
}
if _, ok := this.params["shuffle"]; ok {
query = query.Where("random() < 0.1")
}
if v, ok := this.params["limit"]; ok {
if v.(int) <= 50 {
limit = v.(int)
}
}
if v, ok := this.params["page"]; ok {
page = v.(int)
}
err = query.Scopes(Active, Paginate(limit, page)).Preload("Conference").Find(&collection).Error
}
return &collection, err
}<|fim▁end|> | if v, ok := this.params["conference"]; ok { |
<|file_name|>Solution.py<|end_file_name|><|fim▁begin|>"""
We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).
Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.
Example 1:
Input:
bits = [1, 0, 0]
Output: True
Explanation:
The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.
Example 2:
Input:
bits = [1, 1, 1, 0]
Output: False
Explanation:
The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.
Note:
1 <= len(bits) <= 1000.
bits[i] is always 0 or 1.
"""
class Solution(object):<|fim▁hole|> :rtype: bool
"""
skip_next, curr = False, None
for i in bits:
if skip_next:
skip_next = False
curr = 2
continue
if i == 1:
skip_next = True
curr = 2
else:
skip_next = False
curr = 1
return curr == 1<|fim▁end|> | def isOneBitCharacter(self, bits):
"""
:type bits: List[int] |
<|file_name|>FeaturePropertyType.java<|end_file_name|><|fim▁begin|>/**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.gml;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.w3._1999.xlink.ActuateType;
import org.w3._1999.xlink.ShowType;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Feature Property Type</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* Container for a feature - follow gml:AssociationType pattern.
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link net.opengis.gml.FeaturePropertyType#getFeatureGroup <em>Feature Group</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getFeature <em>Feature</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getActuate <em>Actuate</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getArcrole <em>Arcrole</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getHref <em>Href</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getRemoteSchema <em>Remote Schema</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getRole <em>Role</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getShow <em>Show</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getTitle <em>Title</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getType <em>Type</em>}</li>
* </ul>
* </p>
*
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType()
* @model extendedMetaData="name='FeaturePropertyType' kind='elementOnly'"
* @generated
*/
public interface FeaturePropertyType extends EObject {
/**
* Returns the value of the '<em><b>Feature Group</b></em>' attribute list.
* The list contents are of type {@link org.eclipse.emf.ecore.util.FeatureMap.Entry}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Feature Group</em>' attribute list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Feature Group</em>' attribute list.
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_FeatureGroup()
* @model dataType="org.eclipse.emf.ecore.EFeatureMapEntry" many="false"
* extendedMetaData="kind='group' name='_Feature:group' namespace='##targetNamespace'"
* @generated
*/
FeatureMap getFeatureGroup();
/**
* Returns the value of the '<em><b>Feature</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Feature</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Feature</em>' containment reference.
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Feature()
* @model containment="true" transient="true" changeable="false" volatile="true" derived="true"
* extendedMetaData="kind='element' name='_Feature' namespace='##targetNamespace' group='_Feature:group'"
* @generated
*/
AbstractFeatureType getFeature();
/**
* Returns the value of the '<em><b>Actuate</b></em>' attribute.
* The literals are from the enumeration {@link org.w3._1999.xlink.ActuateType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
*
* The 'actuate' attribute is used to communicate the desired timing
* of traversal from the starting resource to the ending resource;
* it's value should be treated as follows:
* onLoad - traverse to the ending resource immediately on loading
* the starting resource
* onRequest - traverse from the starting resource to the ending
* resource only on a post-loading event triggered for
* this purpose
* other - behavior is unconstrained; examine other markup in link
* for hints
* none - behavior is unconstrained
*
* <!-- end-model-doc -->
* @return the value of the '<em>Actuate</em>' attribute.
* @see org.w3._1999.xlink.ActuateType
* @see #isSetActuate()
* @see #unsetActuate()
* @see #setActuate(ActuateType)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Actuate()
* @model unsettable="true"
* extendedMetaData="kind='attribute' name='actuate' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
ActuateType getActuate();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getActuate <em>Actuate</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Actuate</em>' attribute.
* @see org.w3._1999.xlink.ActuateType
* @see #isSetActuate()
* @see #unsetActuate()
* @see #getActuate()
* @generated
*/
void setActuate(ActuateType value);
/**
* Unsets the value of the '{@link net.opengis.gml.FeaturePropertyType#getActuate <em>Actuate</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetActuate()
* @see #getActuate()
* @see #setActuate(ActuateType)
* @generated
*/
void unsetActuate();
/**
* Returns whether the value of the '{@link net.opengis.gml.FeaturePropertyType#getActuate <em>Actuate</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Actuate</em>' attribute is set.
* @see #unsetActuate()
* @see #getActuate()
* @see #setActuate(ActuateType)
* @generated
*/
boolean isSetActuate();
/**
* Returns the value of the '<em><b>Arcrole</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Arcrole</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Arcrole</em>' attribute.
* @see #setArcrole(String)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Arcrole()
* @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI"
* extendedMetaData="kind='attribute' name='arcrole' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getArcrole();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getArcrole <em>Arcrole</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Arcrole</em>' attribute.
* @see #getArcrole()
* @generated
*/
void setArcrole(String value);
/**
* Returns the value of the '<em><b>Href</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Href</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Href</em>' attribute.
* @see #setHref(String)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Href()
* @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI"
* extendedMetaData="kind='attribute' name='href' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getHref();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getHref <em>Href</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Href</em>' attribute.
* @see #getHref()
* @generated
*/
void setHref(String value);
/**
* Returns the value of the '<em><b>Remote Schema</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Reference to an XML Schema fragment that specifies the content model of the propertys value. This is in conformance with the XML Schema Section 4.14 Referencing Schemas from Elsewhere.
* <!-- end-model-doc -->
* @return the value of the '<em>Remote Schema</em>' attribute.
* @see #setRemoteSchema(String)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_RemoteSchema()
* @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI"
* extendedMetaData="kind='attribute' name='remoteSchema' namespace='##targetNamespace'"
* @generated
*/
String getRemoteSchema();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getRemoteSchema <em>Remote Schema</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Remote Schema</em>' attribute.
* @see #getRemoteSchema()
* @generated
*/
void setRemoteSchema(String value);
/**
* Returns the value of the '<em><b>Role</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Role</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Role</em>' attribute.
* @see #setRole(String)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Role()
* @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI"
* extendedMetaData="kind='attribute' name='role' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getRole();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getRole <em>Role</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Role</em>' attribute.
* @see #getRole()
* @generated
*/
void setRole(String value);
/**
* Returns the value of the '<em><b>Show</b></em>' attribute.
* The literals are from the enumeration {@link org.w3._1999.xlink.ShowType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
*
* The 'show' attribute is used to communicate the desired presentation
* of the ending resource on traversal from the starting resource; it's
* value should be treated as follows:
* new - load ending resource in a new window, frame, pane, or other
* presentation context
* replace - load the resource in the same window, frame, pane, or
* other presentation context
* embed - load ending resource in place of the presentation of the
* starting resource
* other - behavior is unconstrained; examine other markup in the
* link for hints
* none - behavior is unconstrained
*
* <!-- end-model-doc -->
* @return the value of the '<em>Show</em>' attribute.
* @see org.w3._1999.xlink.ShowType
* @see #isSetShow()
* @see #unsetShow()
* @see #setShow(ShowType)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Show()
* @model unsettable="true"
* extendedMetaData="kind='attribute' name='show' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
ShowType getShow();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getShow <em>Show</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Show</em>' attribute.
* @see org.w3._1999.xlink.ShowType
* @see #isSetShow()
* @see #unsetShow()
* @see #getShow()
* @generated<|fim▁hole|> * Unsets the value of the '{@link net.opengis.gml.FeaturePropertyType#getShow <em>Show</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetShow()
* @see #getShow()
* @see #setShow(ShowType)
* @generated
*/
void unsetShow();
/**
* Returns whether the value of the '{@link net.opengis.gml.FeaturePropertyType#getShow <em>Show</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Show</em>' attribute is set.
* @see #unsetShow()
* @see #getShow()
* @see #setShow(ShowType)
* @generated
*/
boolean isSetShow();
/**
* Returns the value of the '<em><b>Title</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Title</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Title</em>' attribute.
* @see #setTitle(String)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Title()
* @model dataType="org.eclipse.emf.ecore.xml.type.String"
* extendedMetaData="kind='attribute' name='title' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getTitle();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getTitle <em>Title</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Title</em>' attribute.
* @see #getTitle()
* @generated
*/
void setTitle(String value);
/**
* Returns the value of the '<em><b>Type</b></em>' attribute.
* The default value is <code>"simple"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Type</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Type</em>' attribute.
* @see #isSetType()
* @see #unsetType()
* @see #setType(String)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Type()
* @model default="simple" unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.String"
* extendedMetaData="kind='attribute' name='type' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getType();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getType <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Type</em>' attribute.
* @see #isSetType()
* @see #unsetType()
* @see #getType()
* @generated
*/
void setType(String value);
/**
* Unsets the value of the '{@link net.opengis.gml.FeaturePropertyType#getType <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetType()
* @see #getType()
* @see #setType(String)
* @generated
*/
void unsetType();
/**
* Returns whether the value of the '{@link net.opengis.gml.FeaturePropertyType#getType <em>Type</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Type</em>' attribute is set.
* @see #unsetType()
* @see #getType()
* @see #setType(String)
* @generated
*/
boolean isSetType();
} // FeaturePropertyType<|fim▁end|> | */
void setShow(ShowType value);
/** |
<|file_name|>call-functions.py<|end_file_name|><|fim▁begin|>print ("I'm not a function")
def my_function():<|fim▁hole|>def brett(val):
for i in range(val):
print("I'm a function with args!")
my_function()
brett(5)<|fim▁end|> | print("Hey I'm a function!")
|
<|file_name|>NodePositionTest.java<|end_file_name|><|fim▁begin|>package net.mosstest.tests;
import net.mosstest.scripting.NodePosition;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.fail;
public class NodePositionTest {
public static final int CHUNK_DIMENSION = 16;
public static final int[] coords = {0, 1, -1, 16, -16, 67, -66, 269, -267,
65601, -65601, Integer.MAX_VALUE, Integer.MIN_VALUE};
@Test
public void testHashCode() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; j < coords.length; j++) {
for (int k = 0; k < coords.length; k++) {
for (byte x = 0; x < CHUNK_DIMENSION; x += 8) {
for (byte y = 0; y < CHUNK_DIMENSION; y += 8) {
for (byte z = 0; z < CHUNK_DIMENSION; z += 8) {
NodePosition pos1 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
NodePosition pos2 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
Assert.assertEquals(
"Mismatched hashCodes for value-identical NodePosition objects",
pos1.hashCode(), pos2.hashCode());
}
}
}
}
}
}
}
@Test
public void testByteArrayReadWrite() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; i < coords.length; i++) {
for (int k = 0; i < coords.length; i++) {
for (byte x = 0; x < CHUNK_DIMENSION; x+=8) {
for (byte y = 0; y < CHUNK_DIMENSION; y+=8) {
for (byte z = 0; z < CHUNK_DIMENSION; z+=4) {
NodePosition pos1 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
byte[] bytes = pos1.toBytes();
NodePosition pos2;
try {
pos2 = new NodePosition(bytes);
Assert.assertTrue(
"NodePosition nmarshaled from byte[] fails equals() check with original NodePosition.",
pos1.equals(pos2));
} catch (IOException e) {
fail("IOException caught in unmarshaling NodePosition from byte[]");
}
}
}
}
}
}
}
}
@Test
public void testEqualsObject() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; j < coords.length; j++) {
for (int k = 0; k < coords.length; k++) {
for (byte x = 0; x < CHUNK_DIMENSION; x+=8) {
for (byte y = 0; y < CHUNK_DIMENSION; y+=8) {
for (byte z = 0; z < CHUNK_DIMENSION; z+=4) {
NodePosition pos1 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
NodePosition pos2 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
Assert.assertTrue(
"Value-equal objects fail equals() check",
pos1.equals(pos2));
Assert.assertTrue(
"Value-equal objects fail equals() check",
pos2.equals(pos1));
NodePosition pos3 = new NodePosition(
0, coords[i] + 1, coords[j], coords[k],
x, y, z);
NodePosition pos4 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for x",
pos3.equals(pos4));
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for x",
pos4.equals(pos3));
NodePosition pos5 = new NodePosition(0, coords[i],
coords[j] + 1, coords[k], x, y, z);
NodePosition pos6 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
Assert.assertFalse(
<|fim▁hole|> "Value-unequal objects erroneously pass equals() check for y",
pos5.equals(pos6));
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for y",
pos6.equals(pos5));
NodePosition pos7 = new NodePosition(0, coords[i],
coords[j], coords[k] + 1, x, y, z);
NodePosition pos8 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for z",
pos7.equals(pos8));
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for z",
pos8.equals(pos7));
}
}
}
}
}
}
}
@Test
public void testToBytes() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; j < coords.length; j++) {
for (int k = 0; k < coords.length; k++) {
for (byte x = 0; x < CHUNK_DIMENSION; x+=4) {
for (byte y = 0; y < CHUNK_DIMENSION; y+=8) {
NodePosition pos1 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, (byte)0);
NodePosition pos2 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, (byte)0);
org.junit.Assert.assertArrayEquals(
pos1.toBytes(), pos2.toBytes());
}
}
}
}
}
}
}<|fim▁end|> | |
<|file_name|>function_base.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from __future__ import division, absolute_import, print_function
__all__ = ['logspace', 'linspace']
from . import numeric as _nx
from .numeric import result_type, NaN
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
"""
Return evenly spaced numbers over a specified interval.
Returns `num` evenly spaced samples, calculated over the
interval [`start`, `stop`].
The endpoint of the interval can optionally be excluded.
Parameters
----------
start : scalar
The starting value of the sequence.
stop : scalar
The end value of the sequence, unless `endpoint` is set to False.
In that case, the sequence consists of all but the last of ``num + 1``
evenly spaced samples, so that `stop` is excluded. Note that the step
size changes when `endpoint` is False.
num : int, optional
Number of samples to generate. Default is 50. Must be non-negative.
endpoint : bool, optional
If True, `stop` is the last sample. Otherwise, it is not included.
Default is True.
retstep : bool, optional
If True, return (`samples`, `step`), where `step` is the spacing
between samples.
dtype : dtype, optional
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
.. versionadded:: 1.9.0
Returns
-------
samples : ndarray
There are `num` equally spaced samples in the closed interval
``[start, stop]`` or the half-open interval ``[start, stop)``
(depending on whether `endpoint` is True or False).
step : float
Only returned if `retstep` is True
Size of spacing between samples.
See Also
--------
arange : Similar to `linspace`, but uses a step size (instead of the
number of samples).
logspace : Samples uniformly distributed in log space.
Examples
--------
>>> np.linspace(2.0, 3.0, num=5)
array([ 2. , 2.25, 2.5 , 2.75, 3. ])
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
array([ 2. , 2.2, 2.4, 2.6, 2.8])
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
(array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
Graphical illustration:
>>> import matplotlib.pyplot as plt
>>> N = 8
>>> y = np.zeros(N)
>>> x1 = np.linspace(0, 10, N, endpoint=True)
>>> x2 = np.linspace(0, 10, N, endpoint=False)
>>> plt.plot(x1, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(x2, y + 0.5, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show()
"""
num = int(num)
if num < 0:
raise ValueError("Number of samples, %s, must be non-negative." % num)
div = (num - 1) if endpoint else num
# Convert float/complex array scalars to float, gh-3504
start = start * 1.
stop = stop * 1.
dt = result_type(start, stop, float(num))
if dtype is None:
dtype = dt
y = _nx.arange(0, num, dtype=dt)
if num > 1:
delta = stop - start
step = delta / div
if step == 0:
# Special handling for denormal numbers, gh-5437
y /= div
y *= delta
else:
y *= step
else:
# 0 and 1 item long sequences have an undefined step
step = NaN
y += start
if endpoint and num > 1:
y[-1] = stop
if retstep:
return y.astype(dtype, copy=False), step
else:
return y.astype(dtype, copy=False)
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None):
"""
Return numbers spaced evenly on a log scale.
In linear space, the sequence starts at ``base ** start``
(`base` to the power of `start`) and ends with ``base ** stop``
(see `endpoint` below).
Parameters
----------
start : float
``base ** start`` is the starting value of the sequence.
stop : float
``base ** stop`` is the final value of the sequence, unless `endpoint`
is False. In that case, ``num + 1`` values are spaced over the
interval in log-space, of which all but the last (a sequence of
length ``num``) are returned.
num : integer, optional
Number of samples to generate. Default is 50.
endpoint : boolean, optional
If true, `stop` is the last sample. Otherwise, it is not included.
Default is True.
base : float, optional
The base of the log space. The step size between the elements in
``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
Default is 10.0.
dtype : dtype
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
Returns
-------
samples : ndarray
`num` samples, equally spaced on a log scale.
See Also
--------
arange : Similar to linspace, with the step size specified instead of the
number of samples. Note that, when used with a float endpoint, the
endpoint may or may not be included.
linspace : Similar to logspace, but with the samples uniformly distributed
in linear space, instead of log space.
Notes
-----
Logspace is equivalent to the code
>>> y = np.linspace(start, stop, num=num, endpoint=endpoint)
... # doctest: +SKIP
>>> power(base, y).astype(dtype)
... # doctest: +SKIP
Examples
--------
>>> np.logspace(2.0, 3.0, num=4)
array([ 100. , 215.443469 , 464.15888336, 1000. ])
>>> np.logspace(2.0, 3.0, num=4, endpoint=False)
array([ 100. , 177.827941 , 316.22776602, 562.34132519])
>>> np.logspace(2.0, 3.0, num=4, base=2.0)
array([ 4. , 5.0396842 , 6.34960421, 8. ])
Graphical illustration:
>>> import matplotlib.pyplot as plt
>>> N = 10
>>> x1 = np.logspace(0.1, 1, N, endpoint=True)
>>> x2 = np.logspace(0.1, 1, N, endpoint=False)
>>> y = np.zeros(N)
>>> plt.plot(x1, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(x2, y + 0.5, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show()
"""
y = linspace(start, stop, num=num, endpoint=endpoint)
if dtype is None:
return _nx.power(base, y)
return _nx.power(base, y).astype(dtype)<|fim▁end|> | |
<|file_name|>problem_962.py<|end_file_name|><|fim▁begin|>"""962. Maximum Width Ramp
https://leetcode.com/problems/maximum-width-ramp/
Given an array A of integers, a ramp is a tuple (i, j) for which
i < j and A[i] <= A[j]. The width of such a ramp is j - i.
Find the maximum width of a ramp in A. If one doesn't exist, return 0.
Example 1:
Input: [6,0,8,2,1,5]
Output: 4
Explanation:
The maximum width ramp is achieved at (i, j) = (1, 5): A[1] = 0 and A[5] = 5.
Example 2:
Input: [9,8,1,0,1,9,4,0,4,1]
Output: 7<|fim▁hole|>Explanation:
The maximum width ramp is achieved at (i, j) = (2, 9): A[2] = 1 and A[9] = 1.
Note:
2 <= A.length <= 50000
0 <= A[i] <= 50000
"""
import bisect
from typing import List
class Solution:
def max_width_ramp(self, a: List[int]) -> int:
ramp, size = 0, len(a)
candidates = [(a[size - 1], size - 1)]
# candidates: i's decreasing, by increasing value of a[i]
for i in range(size - 2, -1, -1):
max_j = bisect.bisect(candidates, (a[i],))
if max_j < len(candidates):
ramp = max(ramp, candidates[max_j][1] - i)
else:
candidates.append((a[i], i))
return ramp<|fim▁end|> | |
<|file_name|>plot_roc.py<|end_file_name|><|fim▁begin|>"""
=======================================
Receiver Operating Characteristic (ROC)
=======================================
Example of Receiver Operating Characteristic (ROC) metric to evaluate
classifier output quality.
ROC curves typically feature true positive rate on the Y axis, and false
positive rate on the X axis. This means that the top left corner of the plot is
the "ideal" point - a false positive rate of zero, and a true positive rate of
one. This is not very realistic, but it does mean that a larger area under the
curve (AUC) is usually better.
The "steepness" of ROC curves is also important, since it is ideal to maximize
the true positive rate while minimizing the false positive rate.
ROC curves are typically used in binary classification to study the output of
a classifier. In order to extend ROC curve and ROC area to multi-class
or multi-label classification, it is necessary to binarize the output. One ROC
curve can be drawn per label, but one can also draw a ROC curve by considering
each element of the label indicator matrix as a binary prediction
(micro-averaging).
.. note::
See also :func:`sklearn.metrics.roc_auc_score`,
:ref:`example_plot_roc_crossval.py`.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
# Import some data to play with
iris = datasets.load_iris()
X = iris.data
y = iris.target
# Binarize the output
y = label_binarize(y, classes=[0, 1, 2])
n_classes = y.shape[1]
# Add noisy features to make the problem harder
random_state = np.random.RandomState(0)
n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]
# shuffle and split training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,
random_state=0)
# Learn to predict each class against the other
classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True,
random_state=random_state))
y_score = classifier.fit(X_train, y_train).decision_function(X_test)
# Compute ROC curve and ROC area for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
# Plot of a ROC curve for a specific class
plt.figure()<|fim▁hole|>plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()
# Plot ROC curve
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
label='micro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["micro"]))
for i in range(n_classes):
plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})'
''.format(i, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc="lower right")
plt.show()<|fim▁end|> | plt.plot(fpr[2], tpr[2], label='ROC curve (area = %0.2f)' % roc_auc[2]) |
<|file_name|>documentalesonline.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# ------------------------------------------------------------
import re
from core import httptools
from core import logger
from core import scrapertools
from core.item import Item
HOST = "http://documentales-online.com/"
def mainlist(item):
logger.info()
itemlist = list()
itemlist.append(Item(channel=item.channel, title="Novedades", action="listado", url=HOST))
itemlist.append(Item(channel=item.channel, title="Destacados", action="seccion", url=HOST, extra="destacados"))
itemlist.append(Item(channel=item.channel, title="Series Destacadas", action="seccion", url=HOST, extra="series"))
# itemlist.append(Item(channel=item.channel, title="Top 100", action="categorias", url=HOST))
# itemlist.append(Item(channel=item.channel, title="Populares", action="categorias", url=HOST))
itemlist.append(Item(channel=item.channel, title="Buscar por:"))
itemlist.append(Item(channel=item.channel, title=" Título", action="search"))
itemlist.append(Item(channel=item.channel, title=" Categorías", action="categorias", url=HOST))
# itemlist.append(Item(channel=item.channel, title=" Series y Temas", action="categorias", url=HOST))
return itemlist
def seccion(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|\s{2}|-\s", "", data)
if item.extra == "destacados":
patron_seccion = '<h4 class="widget-title">Destacados</h4><div class="textwidget"><ul>(.*?)</ul>'
action = "findvideos"
else:
patron_seccion = '<h4 class="widget-title">Series destacadas</h4><div class="textwidget"><ul>(.*?)</ul>'
action = "listado"
data = scrapertools.find_single_match(data, patron_seccion)
matches = re.compile('<a href="([^"]+)">(.*?)</a>', re.DOTALL).findall(data)
aux_action = action
for url, title in matches:
if item.extra != "destacados" and "Cosmos (Carl Sagan)" in title:
action = "findvideos"
else:
action = aux_action
itemlist.append(item.clone(title=title, url=url, action=action, fulltitle=title))
return itemlist
def listado(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data<|fim▁hole|> if not pagination:
pagination = scrapertools.find_single_match(data, '<span class=\'current\'>\d</span>'
'<a class="page larger" href="([^"]+)">')
patron = '<ul class="sp-grid">(.*?)</ul>'
data = scrapertools.find_single_match(data, patron)
matches = re.compile('<a href="([^"]+)">(.*?)</a>', re.DOTALL).findall(data)
for url, title in matches:
itemlist.append(item.clone(title=title, url=url, action="findvideos", fulltitle=title))
if pagination:
itemlist.append(item.clone(title=">> Página siguiente", url=pagination))
return itemlist
def categorias(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|\s{2}|-\s", "", data)
data = scrapertools.find_single_match(data, 'a href="#">Categorías</a><ul class="sub-menu">(.*?)</ul>')
matches = re.compile('<a href="([^"]+)">(.*?)</a>', re.DOTALL).findall(data)
for url, title in matches:
itemlist.append(item.clone(title=title, url=url, action="listado", fulltitle=title))
return itemlist
def search(item, texto):
logger.info()
texto = texto.replace(" ", "+")
try:
item.url = HOST + "?s=%s" % texto
return listado(item)
# Se captura la excepción, para no interrumpir al buscador global si un canal falla
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
def findvideos(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|\s{2}|-\s", "", data)
if item.fulltitle == "Cosmos (Carl Sagan)":
matches = scrapertools.find_multiple_matches(data, '<p><strong>(.*?)</strong><br /><iframe.+?src="(https://www\.youtube\.com/[^?]+)')
for title, url in matches:
new_item = item.clone(title=title, url=url)
from core import servertools
aux_itemlist = servertools.find_video_items(new_item)
for videoitem in aux_itemlist:
videoitem.title = new_item.title
videoitem.fulltitle = new_item.title
videoitem.channel = item.channel
# videoitem.thumbnail = item.thumbnail
itemlist.extend(aux_itemlist)
else:
data = scrapertools.find_multiple_matches(data, '<iframe.+?src="(https://www\.youtube\.com/[^?]+)')
from core import servertools
itemlist.extend(servertools.find_video_items(data=",".join(data)))
for videoitem in itemlist:
videoitem.fulltitle = item.fulltitle
videoitem.channel = item.channel
# videoitem.thumbnail = item.thumbnail
return itemlist<|fim▁end|> | data = re.sub(r"\n|\r|\t|\s{2}|-\s", "", data)
pagination = scrapertools.find_single_match(data, '<div class="older"><a href="([^"]+)"') |
<|file_name|>endian.rs<|end_file_name|><|fim▁begin|>use std::marker::PhantomData;
use std::fmt;
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use byteorder::{ByteOrder, LittleEndian, BigEndian, NativeEndian};
use uninitialized::uninitialized;
use packed::{Unaligned, Aligned, Packed};
use pod::Pod;
/// A type alias for unaligned little endian primitives
pub type Le<T> = EndianPrimitive<LittleEndian, T>;
/// A type alias for unaligned big endian primitives
pub type Be<T> = EndianPrimitive<BigEndian, T>;<|fim▁hole|>
/// A POD container for a primitive that stores a value in the specified endianness
/// in memory, and transforms on `get`/`set`
#[repr(C)]
pub struct EndianPrimitive<B, T: EndianConvert> {
value: T::Unaligned,
_phantom: PhantomData<*const B>,
}
impl<B: ByteOrder, T: EndianConvert> EndianPrimitive<B, T> {
/// Creates a new value
#[inline]
pub fn new(v: T) -> Self {
EndianPrimitive {
value: EndianConvert::to::<B>(v),
_phantom: PhantomData,
}
}
/// Transforms to the native value
#[inline]
pub fn get(&self) -> T {
EndianConvert::from::<B>(&self.value)
}
/// Transforms from a native value
#[inline]
pub fn set(&mut self, v: T) {
self.value = EndianConvert::to::<B>(v)
}
/// Gets the inner untransformed value
#[inline]
pub fn raw(&self) -> &T::Unaligned {
&self.value
}
/// A mutable reference to the inner untransformed value
#[inline]
pub fn raw_mut(&mut self) -> &mut T::Unaligned {
&mut self.value
}
}
unsafe impl<B, T: EndianConvert> Pod for EndianPrimitive<B, T> { }
unsafe impl<B, T: EndianConvert> Unaligned for EndianPrimitive<B, T> { }
unsafe impl<B, T: EndianConvert> Packed for EndianPrimitive<B, T> { }
impl<B: ByteOrder, T: Default + EndianConvert> Default for EndianPrimitive<B, T> {
#[inline]
fn default() -> Self {
Self::new(Default::default())
}
}
impl<B: ByteOrder, T: EndianConvert> From<T> for EndianPrimitive<B, T> {
#[inline]
fn from(v: T) -> Self {
Self::new(v)
}
}
impl<B: ByteOrder, T: fmt::Debug + EndianConvert> fmt::Debug for EndianPrimitive<B, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
<T as fmt::Debug>::fmt(&self.get(), f)
}
}
impl<BRHS: ByteOrder, RHS: EndianConvert, B: ByteOrder, T: EndianConvert + PartialEq<RHS>> PartialEq<EndianPrimitive<BRHS, RHS>> for EndianPrimitive<B, T> {
#[inline]
fn eq(&self, other: &EndianPrimitive<BRHS, RHS>) -> bool {
self.get().eq(&other.get())
}
}
impl<B: ByteOrder, T: EndianConvert + Eq> Eq for EndianPrimitive<B, T> { }
impl<BRHS: ByteOrder, RHS: EndianConvert, B: ByteOrder, T: EndianConvert + PartialOrd<RHS>> PartialOrd<EndianPrimitive<BRHS, RHS>> for EndianPrimitive<B, T> {
#[inline]
fn partial_cmp(&self, other: &EndianPrimitive<BRHS, RHS>) -> Option<Ordering> {
self.get().partial_cmp(&other.get())
}
}
impl<B: ByteOrder, T: EndianConvert + Ord> Ord for EndianPrimitive<B, T> {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.get().cmp(&other.get())
}
}
impl<B, T: EndianConvert + Hash> Hash for EndianPrimitive<B, T> where T::Unaligned: Hash {
#[inline]
fn hash<H: Hasher>(&self, h: &mut H) {
self.value.hash(h)
}
}
impl<B, T: EndianConvert> Clone for EndianPrimitive<B, T> {
#[inline]
fn clone(&self) -> Self {
EndianPrimitive {
value: self.value.clone(),
_phantom: PhantomData,
}
}
}
impl<B, T: EndianConvert> Copy for EndianPrimitive<B, T> { }
/// Describes a value that can be converted to and from a specified byte order.
pub trait EndianConvert: Aligned {
/// Converts a value from `B`
fn from<B: ByteOrder>(&Self::Unaligned) -> Self;
/// Converts a value to `B`
fn to<B: ByteOrder>(self) -> Self::Unaligned;
}
macro_rules! endian_impl {
($t:ty: $s:expr => $r:ident, $w:ident) => {
impl EndianConvert for $t {
#[inline]
fn from<B: ByteOrder>(s: &Self::Unaligned) -> Self {
B::$r(s)
}
#[inline]
fn to<B: ByteOrder>(self) -> Self::Unaligned {
let mut s: Self::Unaligned = unsafe { uninitialized() };
B::$w(&mut s, self);
s
}
}
};
}
endian_impl!(u16: 2 => read_u16, write_u16);
endian_impl!(i16: 2 => read_i16, write_i16);
endian_impl!(i32: 4 => read_i32, write_i32);
endian_impl!(u32: 4 => read_u32, write_u32);
endian_impl!(i64: 8 => read_i64, write_i64);
endian_impl!(u64: 8 => read_u64, write_u64);
endian_impl!(f32: 4 => read_f32, write_f32);
endian_impl!(f64: 8 => read_f64, write_f64);
impl EndianConvert for bool {
#[inline]
fn from<B: ByteOrder>(s: &Self::Unaligned) -> Self {
*s as u8 != 0
}
#[inline]
fn to<B: ByteOrder>(self) -> Self::Unaligned {
if self as u8 != 0 { true } else { false }
}
}
#[test]
fn endian_size() {
use std::mem::size_of;
use std::mem::align_of;
type B = NativeEndian;
assert_eq!(size_of::<EndianPrimitive<B, i16>>(), 2);
assert_eq!(size_of::<EndianPrimitive<B, i32>>(), 4);
assert_eq!(size_of::<EndianPrimitive<B, i64>>(), 8);
assert_eq!(size_of::<EndianPrimitive<B, f32>>(), 4);
assert_eq!(size_of::<EndianPrimitive<B, f64>>(), 8);
assert_eq!(align_of::<EndianPrimitive<B, bool>>(), 1);
assert_eq!(align_of::<EndianPrimitive<B, i16>>(), 1);
assert_eq!(align_of::<EndianPrimitive<B, i32>>(), 1);
assert_eq!(align_of::<EndianPrimitive<B, i64>>(), 1);
assert_eq!(align_of::<EndianPrimitive<B, f32>>(), 1);
assert_eq!(align_of::<EndianPrimitive<B, f64>>(), 1);
}<|fim▁end|> |
/// A type alias for unaligned native endian primitives
pub type Native<T> = EndianPrimitive<NativeEndian, T>; |
<|file_name|>011.py<|end_file_name|><|fim▁begin|>import time
def check_vertical(matrix):
max_product = 0
for row in xrange(0, len(matrix)-3):
for col in xrange(0, len(matrix)):
product = matrix[row][col] * matrix[row+1][col] * matrix[row+2][col] * matrix[row+3][col]
max_product = max(product, max_product)
<|fim▁hole|> max_product = 0
for row in xrange(0, len(matrix)):
for col in xrange(0, len(matrix)-3):
product = reduce(lambda x,y: x*y, matrix[row][col:col+3])
max_product = max(product, max_product)
return max_product
def check_left_diagonal(matrix):
max_product = 0
for row in xrange(0, len(matrix)-3):
for col in xrange(0, len(matrix)-3):
product = matrix[row][col] * matrix[row+1][col+1] * matrix[row+2][col+2] * matrix[row+3][col+3]
max_product = max(product, max_product)
return max_product
def check_right_diagonal(matrix):
max_product = 0
for row in xrange(0, len(matrix)-3):
for col in xrange(0, len(matrix)-3):
product = matrix[row+3][col] * matrix[row+2][col+1] * matrix[row+1][col+2] * matrix[row][col+3]
max_product = max(product, max_product)
return max_product
def main():
with open("011.txt", "r") as f:
# Read the matrix from the text file, and store in an integet 2-dimensional array
matrix = []
for line in f.readlines():
matrix.append([int(num) for num in line.split(" ")])
# print matrix
# Check the matrix along the various directions, and find the max product of four adjacent numbers
print("The result is %d." % max(check_vertical(matrix), check_horizontal(matrix), check_left_diagonal(matrix), check_right_diagonal(matrix)))
if __name__ == '__main__':
start = time.time()
main()
done = time.time()
print("The solution took %.4f seconds to compute." % (done - start))<|fim▁end|> | return max_product
def check_horizontal(matrix): |
<|file_name|>reader.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import absolute_import
import csv
from copy import copy
from typing import List, Dict
import typesystem
from .types import PartialActor, ActorIssue, PartialIssue, IssuePosition, IssueDescription, Comment
types = {
PartialActor.starts_with: PartialActor,
ActorIssue.starts_with: ActorIssue,
PartialIssue.starts_with: PartialIssue,
IssuePosition.starts_with: IssuePosition,
IssueDescription.starts_with: IssueDescription,
Comment.starts_with: Comment,
}
class InputDataFile:
def __init__(self):
self.errors = {}
self.rows = {}
self.data = {}
def add_typed_object(self, obj):
klass = obj.__class__
if klass in self.data:
self.data[klass][obj] = obj
else:
self.data[klass] = {obj: obj}
@classmethod
def open(cls, filename: str) -> "InputDataFile":
"""
Transforms a file with comma separated values to a dictionary where the key is the row number
"""
data = cls()
with open(filename, "rt", encoding="utf-8", errors="replace") as csv_file:
# guess the document format
dialect = csv.Sniffer().sniff(csv_file.read(1024))
csv_file.seek(0)
reader = csv.reader(csv_file, dialect=dialect)
InputDataFile.open_reader(reader, data)
return data
@classmethod
def open_reader(cls, reader, data=None):
if not data:
data = cls()
data.parse_rows(reader)
data.update_issues_with_positions()
if data.is_valid:
data.validate_actor_issue_positions()
return data
def parse_rows(self, items):
for index, row in enumerate(items):
# keep the original data
self.rows[index] = row
try:
type_obj = csv_row_to_type(row)
self.add_typed_object(type_obj)
except typesystem.ValidationError as e:
self.errors[index] = e # collect the error for displaying purpose
@property
def is_valid(self):
return len(self.errors) == 0
@property
def actors(self) -> Dict[str, PartialActor]:
return self.data[PartialActor]
@property
def issues(self) -> Dict[str, PartialIssue]:
return self.data[PartialIssue]
@property
def actor_issues(self) -> Dict[str, ActorIssue]:
return self.data[ActorIssue]
@property
def issue_positions(self) -> Dict[str, IssuePosition]:
return self.data[IssuePosition]
def update_issues_with_positions(self):
"""
Once the file is complete, we can update the lower an upper positions of the issue
"""
if IssuePosition in self.data:
for issue_position in self.issue_positions.values():
<|fim▁hole|>
if issue.lower is None:
issue.lower = issue_position.position
elif issue_position.position < issue.lower:
issue.lower = issue_position
if issue.upper is None:
issue.upper = issue_position.position
elif issue_position.position > issue.upper:
issue.upper = issue_position.position
self.set_default_issue_positions()
def set_default_issue_positions(self):
for issue in self.issues.values():
if issue.lower is None:
issue.lower = 0
if issue.upper is None:
issue.upper = 100
def validate_actor_issue_positions(self):
"""
Validate the positions of the actor issues against the lower & upper issue bounds
"""
# find the starting position of the actor issues, so we can show the error at the correct position
row_index_correction = 0
for type_class in types.values():
if type_class in self.data and type_class != ActorIssue:
row_index_correction += len(self.data[type_class])
for index, actor_issue in enumerate(self.actor_issues.values(), row_index_correction + 1):
if actor_issue.actor not in self.actors:
self.errors[index] = typesystem.ValidationError(
key='actor',
text='{} not found in document'.format(actor_issue.actor)
)
if actor_issue.issue in self.issues:
issue = self.issues[actor_issue.issue]
try:
actor_issue.validate_position(issue)
except typesystem.ValidationError as e:
if index in self.errors:
self.errors[index] = e
else:
self.errors[index] = e
else:
self.errors[index] = typesystem.ValidationError(
key='issue',
text='{} not found document'.format(actor_issue.issue)
)
def csv_row_to_type(row: List[str]):
"""
Translate a list of values to the corresponding object
"""
key = row[0] # the first element contains the #id field
row = row[1:] # the rest the row
if key not in types.keys():
raise Exception(f"Add key {key} to Reader.types (row row: {row}")
row_type = types[key]
field_names = row_type.fields.keys()
row = squash(len(row_type.fields), row)
obj = row_type.validate(dict(zip(field_names, row)))
return obj
def squash(fields: int, data: List[str], delimiter=" ") -> List[str]:
"""
Finds out how many fields there are and joins the overhead in to the lasted field
i.e:
The object x, y, z contains 3 field.
The row x,y,z,a,b has 5 values.
The values a & b will be squashed to z with the given delimiter
"""
if fields >= len(data):
return data
output = copy(data)
del output[-1]
output[-1] = delimiter.join(data[fields - 1:])
return output<|fim▁end|> | if issue_position.issue in self.issues:
issue = self.issues[issue_position.issue] |
<|file_name|>MI_example.py<|end_file_name|><|fim▁begin|># Copyright (c) 2006-2007 The Regents of The University of Michigan
# Copyright (c) 2009 Advanced Micro Devices, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Brad Beckmann
import math
import m5
from m5.objects import *
from m5.defines import buildEnv
from Ruby import create_topology
from Ruby import send_evicts
#
# Declare caches used by the protocol
#
class L1Cache(RubyCache): pass
def define_options(parser):
return
def create_system(options, full_system, system, dma_ports, ruby_system):
if buildEnv['PROTOCOL'] != 'MI_example':
panic("This script requires the MI_example protocol to be built.")
cpu_sequencers = []
#
# The ruby network creation expects the list of nodes in the system to be
# consistent with the NetDest list. Therefore the l1 controller nodes must be
# listed before the directory nodes and directory nodes before dma nodes, etc.
#
l1_cntrl_nodes = []
dir_cntrl_nodes = []
dma_cntrl_nodes = []
#
# Must create the individual controllers before the network to ensure the
# controller constructors are called before the network constructor
#
block_size_bits = int(math.log(options.cacheline_size, 2))
for i in xrange(options.num_cpus):
#
# First create the Ruby objects associated with this cpu
# Only one cache exists for this protocol, so by default use the L1D
# config parameters.
#
cache = L1Cache(size = options.l1d_size,
assoc = options.l1d_assoc,
start_index_bit = block_size_bits)
#
# Only one unified L1 cache exists. Can cache instructions and data.
#
l1_cntrl = L1Cache_Controller(version = i,
cacheMemory = cache,
send_evictions = send_evicts(options),
transitions_per_cycle = options.ports,
clk_domain=system.cpu[i].clk_domain,
ruby_system = ruby_system)
cpu_seq = RubySequencer(version = i,
icache = cache,
dcache = cache,
clk_domain=system.cpu[i].clk_domain,
ruby_system = ruby_system)
l1_cntrl.sequencer = cpu_seq
exec("ruby_system.l1_cntrl%d = l1_cntrl" % i)
# Add controllers and sequencers to the appropriate lists
cpu_sequencers.append(cpu_seq)
l1_cntrl_nodes.append(l1_cntrl)
# Connect the L1 controllers and the network
l1_cntrl.mandatoryQueue = MessageBuffer()
l1_cntrl.requestFromCache = MessageBuffer(ordered = True)
l1_cntrl.requestFromCache.master = ruby_system.network.slave
l1_cntrl.responseFromCache = MessageBuffer(ordered = True)
l1_cntrl.responseFromCache.master = ruby_system.network.slave
l1_cntrl.forwardToCache = MessageBuffer(ordered = True)
l1_cntrl.forwardToCache.slave = ruby_system.network.master
l1_cntrl.responseToCache = MessageBuffer(ordered = True)
l1_cntrl.responseToCache.slave = ruby_system.network.master
phys_mem_size = sum(map(lambda r: r.size(), system.mem_ranges))
assert(phys_mem_size % options.num_dirs == 0)
mem_module_size = phys_mem_size / options.num_dirs
# Run each of the ruby memory controllers at a ratio of the frequency of
# the ruby system.
# clk_divider value is a fix to pass regression.
ruby_system.memctrl_clk_domain = DerivedClockDomain(
clk_domain=ruby_system.clk_domain,
clk_divider=3)
for i in xrange(options.num_dirs):
dir_size = MemorySize('0B')
dir_size.value = mem_module_size
dir_cntrl = Directory_Controller(version = i,
directory = RubyDirectoryMemory(
version = i, size = dir_size),
transitions_per_cycle = options.ports,
ruby_system = ruby_system)
exec("ruby_system.dir_cntrl%d = dir_cntrl" % i)
dir_cntrl_nodes.append(dir_cntrl)
# Connect the directory controllers and the network
dir_cntrl.requestToDir = MessageBuffer(ordered = True)
dir_cntrl.requestToDir.slave = ruby_system.network.master
dir_cntrl.dmaRequestToDir = MessageBuffer(ordered = True)
dir_cntrl.dmaRequestToDir.slave = ruby_system.network.master
dir_cntrl.responseFromDir = MessageBuffer()
dir_cntrl.responseFromDir.master = ruby_system.network.slave
dir_cntrl.dmaResponseFromDir = MessageBuffer(ordered = True)
dir_cntrl.dmaResponseFromDir.master = ruby_system.network.slave
dir_cntrl.forwardFromDir = MessageBuffer()
dir_cntrl.forwardFromDir.master = ruby_system.network.slave
dir_cntrl.responseFromMemory = MessageBuffer()
for i, dma_port in enumerate(dma_ports):
#
# Create the Ruby objects associated with the dma controller
#
dma_seq = DMASequencer(version = i,
ruby_system = ruby_system)
dma_cntrl = DMA_Controller(version = i,
dma_sequencer = dma_seq,
transitions_per_cycle = options.ports,
ruby_system = ruby_system)
exec("ruby_system.dma_cntrl%d = dma_cntrl" % i)
exec("ruby_system.dma_cntrl%d.dma_sequencer.slave = dma_port" % i)
dma_cntrl_nodes.append(dma_cntrl)
# Connect the directory controllers and the network
dma_cntrl.mandatoryQueue = MessageBuffer()
dma_cntrl.requestToDir = MessageBuffer()
dma_cntrl.requestToDir.master = ruby_system.network.slave<|fim▁hole|>
all_cntrls = l1_cntrl_nodes + dir_cntrl_nodes + dma_cntrl_nodes
# Create the io controller and the sequencer
if full_system:
io_seq = DMASequencer(version=len(dma_ports), ruby_system=ruby_system)
ruby_system._io_port = io_seq
io_controller = DMA_Controller(version = len(dma_ports),
dma_sequencer = io_seq,
ruby_system = ruby_system)
ruby_system.io_controller = io_controller
# Connect the dma controller to the network
io_controller.mandatoryQueue = MessageBuffer()
io_controller.requestToDir = MessageBuffer()
io_controller.requestToDir.master = ruby_system.network.slave
io_controller.responseFromDir = MessageBuffer(ordered = True)
io_controller.responseFromDir.slave = ruby_system.network.master
all_cntrls = all_cntrls + [io_controller]
topology = create_topology(all_cntrls, options)
return (cpu_sequencers, dir_cntrl_nodes, topology)<|fim▁end|> | dma_cntrl.responseFromDir = MessageBuffer(ordered = True)
dma_cntrl.responseFromDir.slave = ruby_system.network.master |
<|file_name|>registry.py<|end_file_name|><|fim▁begin|>import copy
from threading import Lock
from .metrics_core import Metric
class CollectorRegistry(object):
"""Metric collector registry.
Collectors must have a no-argument method 'collect' that returns a list of
Metric objects. The returned metrics should be consistent with the Prometheus
exposition formats.
"""
def __init__(self, auto_describe=False):
self._collector_to_names = {}
self._names_to_collectors = {}
self._auto_describe = auto_describe
self._lock = Lock()
def register(self, collector):
"""Add a collector to the registry."""
with self._lock:
names = self._get_names(collector)
duplicates = set(self._names_to_collectors).intersection(names)
if duplicates:
raise ValueError(
'Duplicated timeseries in CollectorRegistry: {0}'.format(
duplicates))
for name in names:
self._names_to_collectors[name] = collector
self._collector_to_names[collector] = names
def unregister(self, collector):
"""Remove a collector from the registry."""
with self._lock:
for name in self._collector_to_names[collector]:
del self._names_to_collectors[name]
del self._collector_to_names[collector]
def _get_names(self, collector):
"""Get names of timeseries the collector produces."""
desc_func = None
# If there's a describe function, use it.
try:
desc_func = collector.describe
except AttributeError:
pass
# Otherwise, if auto describe is enabled use the collect function.
if not desc_func and self._auto_describe:
desc_func = collector.collect
if not desc_func:
return []
result = []
type_suffixes = {
'counter': ['_total', '_created'],
'summary': ['', '_sum', '_count', '_created'],
'histogram': ['_bucket', '_sum', '_count', '_created'],
'gaugehistogram': ['_bucket', '_gsum', '_gcount'],
'info': ['_info'],
}
for metric in desc_func():
for suffix in type_suffixes.get(metric.type, ['']):
result.append(metric.name + suffix)
return result
def collect(self):
"""Yields metrics from the collectors in the registry."""
collectors = None
with self._lock:<|fim▁hole|> for metric in collector.collect():
yield metric
def restricted_registry(self, names):
"""Returns object that only collects some metrics.
Returns an object which upon collect() will return
only samples with the given names.
Intended usage is:
generate_latest(REGISTRY.restricted_registry(['a_timeseries']))
Experimental."""
names = set(names)
collectors = set()
with self._lock:
for name in names:
if name in self._names_to_collectors:
collectors.add(self._names_to_collectors[name])
metrics = []
for collector in collectors:
for metric in collector.collect():
samples = [s for s in metric.samples if s[0] in names]
if samples:
m = Metric(metric.name, metric.documentation, metric.type)
m.samples = samples
metrics.append(m)
class RestrictedRegistry(object):
def collect(self):
return metrics
return RestrictedRegistry()
def get_sample_value(self, name, labels=None):
"""Returns the sample value, or None if not found.
This is inefficient, and intended only for use in unittests.
"""
if labels is None:
labels = {}
for metric in self.collect():
for s in metric.samples:
if s.name == name and s.labels == labels:
return s.value
return None
REGISTRY = CollectorRegistry(auto_describe=True)<|fim▁end|> | collectors = copy.copy(self._collector_to_names)
for collector in collectors: |
<|file_name|>AsyncHttpServer.java<|end_file_name|><|fim▁begin|>package com.koushikdutta.async.http.server;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Build;
import android.text.TextUtils;
import com.koushikdutta.async.AsyncSSLSocket;
import com.koushikdutta.async.AsyncSSLSocketWrapper;
import com.koushikdutta.async.AsyncServer;
import com.koushikdutta.async.AsyncServerSocket;
import com.koushikdutta.async.AsyncSocket;
import com.koushikdutta.async.ByteBufferList;
import com.koushikdutta.async.DataEmitter;
import com.koushikdutta.async.Util;
import com.koushikdutta.async.callback.CompletedCallback;
import com.koushikdutta.async.callback.ListenCallback;
import com.koushikdutta.async.http.AsyncHttpGet;
import com.koushikdutta.async.http.AsyncHttpHead;
import com.koushikdutta.async.http.AsyncHttpPost;
import com.koushikdutta.async.http.Headers;
import com.koushikdutta.async.http.HttpUtil;
import com.koushikdutta.async.http.Multimap;
import com.koushikdutta.async.http.Protocol;
import com.koushikdutta.async.http.WebSocket;
import com.koushikdutta.async.http.WebSocketImpl;
import com.koushikdutta.async.http.body.AsyncHttpRequestBody;
import com.koushikdutta.async.util.StreamUtility;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLContext;
@TargetApi(Build.VERSION_CODES.ECLAIR)
public class AsyncHttpServer {
ArrayList<AsyncServerSocket> mListeners = new ArrayList<AsyncServerSocket>();
public void stop() {
if (mListeners != null) {
for (AsyncServerSocket listener: mListeners) {
listener.stop();
}
}
}
protected boolean onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
return false;
}
protected void onRequest(HttpServerRequestCallback callback, AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
if (callback != null)
callback.onRequest(request, response);
}
protected AsyncHttpRequestBody onUnknownBody(Headers headers) {
return new UnknownRequestBody(headers.get("Content-Type"));
}
ListenCallback mListenCallback = new ListenCallback() {
@Override
public void onAccepted(final AsyncSocket socket) {
AsyncHttpServerRequestImpl req = new AsyncHttpServerRequestImpl() {
HttpServerRequestCallback match;
String fullPath;
String path;
boolean responseComplete;
boolean requestComplete;
AsyncHttpServerResponseImpl res;
boolean hasContinued;
@Override
protected AsyncHttpRequestBody onUnknownBody(Headers headers) {
return AsyncHttpServer.this.onUnknownBody(headers);
}
@Override
protected void onHeadersReceived() {
Headers headers = getHeaders();
// should the negotiation of 100 continue be here, or in the request impl?
// probably here, so AsyncResponse can negotiate a 100 continue.
if (!hasContinued && "100-continue".equals(headers.get("Expect"))) {
pause();
// System.out.println("continuing...");
Util.writeAll(mSocket, "HTTP/1.1 100 Continue\r\n\r\n".getBytes(), new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
resume();
if (ex != null) {
report(ex);
return;
}
hasContinued = true;
onHeadersReceived();
}
});
return;
}
// System.out.println(headers.toHeaderString());
String statusLine = getStatusLine();
String[] parts = statusLine.split(" ");
fullPath = parts[1];
path = fullPath.split("\\?")[0];
method = parts[0];
synchronized (mActions) {
ArrayList<Pair> pairs = mActions.get(method);
if (pairs != null) {
for (Pair p: pairs) {
Matcher m = p.regex.matcher(path);
if (m.matches()) {
mMatcher = m;
match = p.callback;
break;
}
}
}
}
res = new AsyncHttpServerResponseImpl(socket, this) {
@Override
protected void report(Exception e) {
super.report(e);
if (e != null) {
socket.setDataCallback(new NullDataCallback());
socket.setEndCallback(new NullCompletedCallback());
socket.close();
}
}
@Override
protected void onEnd() {
super.onEnd();
mSocket.setEndCallback(null);
responseComplete = true;
// reuse the socket for a subsequent request.
handleOnCompleted();
}
};
boolean handled = onRequest(this, res);
if (match == null && !handled) {
res.code(404);
res.end();
return;
}
if (!getBody().readFullyOnRequest()) {
onRequest(match, this, res);
}
else if (requestComplete) {
onRequest(match, this, res);
}
}
@Override
public void onCompleted(Exception e) {
// if the protocol was switched off http, ignore this request/response.
if (res.code() == 101)
return;
requestComplete = true;
super.onCompleted(e);
// no http pipelining, gc trashing if the socket dies
// while the request is being sent and is paused or something
mSocket.setDataCallback(new NullDataCallback() {
@Override
public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
super.onDataAvailable(emitter, bb);
mSocket.close();
}
});
handleOnCompleted();
if (getBody().readFullyOnRequest()) {
onRequest(match, this, res);
}
}
private void handleOnCompleted() {
if (requestComplete && responseComplete) {
if (HttpUtil.isKeepAlive(Protocol.HTTP_1_1, getHeaders())) {
onAccepted(socket);
}
else {
socket.close();
}
}
}
@Override
public String getPath() {
return path;
}
@Override
public Multimap getQuery() {
String[] parts = fullPath.split("\\?", 2);
if (parts.length < 2)
return new Multimap();
return Multimap.parseQuery(parts[1]);
}
};
req.setSocket(socket);
socket.resume();
}
@Override
public void onCompleted(Exception error) {
report(error);
}
@Override
public void onListening(AsyncServerSocket socket) {
mListeners.add(socket);
}
};
public AsyncServerSocket listen(AsyncServer server, int port) {
return server.listen(null, port, mListenCallback);
}
private void report(Exception ex) {
if (mCompletedCallback != null)
mCompletedCallback.onCompleted(ex);
}
public AsyncServerSocket listen(int port) {
return listen(AsyncServer.getDefault(), port);
}
public void listenSecure(final int port, final SSLContext sslContext) {
AsyncServer.getDefault().listen(null, port, new ListenCallback() {
@Override
public void onAccepted(AsyncSocket socket) {
AsyncSSLSocketWrapper.handshake(socket, null, port, sslContext.createSSLEngine(), null, null, false,
new AsyncSSLSocketWrapper.HandshakeCallback() {
@Override
public void onHandshakeCompleted(Exception e, AsyncSSLSocket socket) {
if (socket != null)
mListenCallback.onAccepted(socket);
}
});
}
@Override
public void onListening(AsyncServerSocket socket) {
mListenCallback.onListening(socket);
}
@Override
public void onCompleted(Exception ex) {
mListenCallback.onCompleted(ex);
}
});
}
public ListenCallback getListenCallback() {
return mListenCallback;
}
CompletedCallback mCompletedCallback;
public void setErrorCallback(CompletedCallback callback) {
mCompletedCallback = callback;
}
public CompletedCallback getErrorCallback() {
return mCompletedCallback;
}
private static class Pair {
Pattern regex;
HttpServerRequestCallback callback;
}
final Hashtable<String, ArrayList<Pair>> mActions = new Hashtable<String, ArrayList<Pair>>();
public void removeAction(String action, String regex) {
synchronized (mActions) {
ArrayList<Pair> pairs = mActions.get(action);
if (pairs == null)
return;
for (int i = 0; i < pairs.size(); i++) {
Pair p = pairs.get(i);
if (regex.equals(p.regex.toString())) {
pairs.remove(i);
return;
}
}
}
}
public void addAction(String action, String regex, HttpServerRequestCallback callback) {
Pair p = new Pair();
p.regex = Pattern.compile("^" + regex);
p.callback = callback;
synchronized (mActions) {
ArrayList<Pair> pairs = mActions.get(action);
if (pairs == null) {
pairs = new ArrayList<AsyncHttpServer.Pair>();
mActions.put(action, pairs);
}
pairs.add(p);
}
}
public static interface WebSocketRequestCallback {
public void onConnected(WebSocket webSocket, AsyncHttpServerRequest request);
}
public void websocket(String regex, final WebSocketRequestCallback callback) {
websocket(regex, null, callback);
}
public void websocket(String regex, final String protocol, final WebSocketRequestCallback callback) {
get(regex, new HttpServerRequestCallback() {
@Override
public void onRequest(final AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
boolean hasUpgrade = false;
String connection = request.getHeaders().get("Connection");
if (connection != null) {
String[] connections = connection.split(",");
for (String c: connections) {
if ("Upgrade".equalsIgnoreCase(c.trim())) {
hasUpgrade = true;
break;
}
}
}
if (!"websocket".equalsIgnoreCase(request.getHeaders().get("Upgrade")) || !hasUpgrade) {
response.code(404);
response.end();
return;
}
String peerProtocol = request.getHeaders().get("Sec-WebSocket-Protocol");
if (!TextUtils.equals(protocol, peerProtocol)) {
response.code(404);
response.end();
return;
}
callback.onConnected(new WebSocketImpl(request, response), request);
}
});
}
public void get(String regex, HttpServerRequestCallback callback) {
addAction(AsyncHttpGet.METHOD, regex, callback);
}
public void post(String regex, HttpServerRequestCallback callback) {
addAction(AsyncHttpPost.METHOD, regex, callback);
}
public static android.util.Pair<Integer, InputStream> getAssetStream(final Context context, String asset) {
AssetManager am = context.getAssets();
try {
InputStream is = am.open(asset);
return new android.util.Pair<Integer, InputStream>(is.available(), is);
}
catch (IOException e) {
return null;
}
}
static Hashtable<String, String> mContentTypes = new Hashtable<String, String>();
{
mContentTypes.put("js", "application/javascript");
mContentTypes.put("json", "application/json");
mContentTypes.put("png", "image/png");
mContentTypes.put("jpg", "image/jpeg");
mContentTypes.put("html", "text/html");
mContentTypes.put("css", "text/css");
mContentTypes.put("mp4", "video/mp4");
mContentTypes.put("mov", "video/quicktime");
mContentTypes.put("wmv", "video/x-ms-wmv");
}
public static String getContentType(String path) {
String type = tryGetContentType(path);
if (type != null)
return type;
return "text/plain";
}
public static String tryGetContentType(String path) {
int index = path.lastIndexOf(".");<|fim▁hole|> return ct;
}
return null;
}
public void directory(Context context, String regex, final String assetPath) {
final Context _context = context.getApplicationContext();
addAction(AsyncHttpGet.METHOD, regex, new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
String path = request.getMatcher().replaceAll("");
android.util.Pair<Integer, InputStream> pair = getAssetStream(_context, assetPath + path);
if (pair == null || pair.second == null) {
response.code(404);
response.end();
return;
}
final InputStream is = pair.second;
response.getHeaders().set("Content-Length", String.valueOf(pair.first));
response.code(200);
response.getHeaders().add("Content-Type", getContentType(assetPath + path));
Util.pump(is, response, new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
response.end();
StreamUtility.closeQuietly(is);
}
});
}
});
addAction(AsyncHttpHead.METHOD, regex, new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
String path = request.getMatcher().replaceAll("");
android.util.Pair<Integer, InputStream> pair = getAssetStream(_context, assetPath + path);
if (pair == null || pair.second == null) {
response.code(404);
response.end();
return;
}
final InputStream is = pair.second;
StreamUtility.closeQuietly(is);
response.getHeaders().set("Content-Length", String.valueOf(pair.first));
response.code(200);
response.getHeaders().add("Content-Type", getContentType(assetPath + path));
response.writeHead();
response.end();
}
});
}
public void directory(String regex, final File directory) {
directory(regex, directory, false);
}
public void directory(String regex, final File directory, final boolean list) {
assert directory.isDirectory();
addAction("GET", regex, new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
String path = request.getMatcher().replaceAll("");
File file = new File(directory, path);
if (file.isDirectory() && list) {
ArrayList<File> dirs = new ArrayList<File>();
ArrayList<File> files = new ArrayList<File>();
for (File f: file.listFiles()) {
if (f.isDirectory())
dirs.add(f);
else
files.add(f);
}
Comparator<File> c = new Comparator<File>() {
@Override
public int compare(File lhs, File rhs) {
return lhs.getName().compareTo(rhs.getName());
}
};
Collections.sort(dirs, c);
Collections.sort(files, c);
files.addAll(0, dirs);
return;
}
if (!file.isFile()) {
response.code(404);
response.end();
return;
}
try {
FileInputStream is = new FileInputStream(file);
response.code(200);
Util.pump(is, response, new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
response.end();
}
});
}
catch (FileNotFoundException ex) {
response.code(404);
response.end();
}
}
});
}
private static Hashtable<Integer, String> mCodes = new Hashtable<Integer, String>();
static {
mCodes.put(200, "OK");
mCodes.put(206, "Partial Content");
mCodes.put(101, "Switching Protocols");
mCodes.put(301, "Moved Permanently");
mCodes.put(302, "Found");
mCodes.put(404, "Not Found");
}
public static String getResponseCodeDescription(int code) {
String d = mCodes.get(code);
if (d == null)
return "Unknown";
return d;
}
}<|fim▁end|> | if (index != -1) {
String e = path.substring(index + 1);
String ct = mContentTypes.get(e);
if (ct != null) |
<|file_name|>sgash.rs<|end_file_name|><|fim▁begin|>/* kernel::sgash.rs */
#[allow(unused_imports)];
use core::*;
use core::str::*;
use core::option::{Some, Option, None};
use core::iter::Iterator;
use kernel::*;
use kernel::vec::Vec;
use super::super::platform::*;
use kernel::memory::Allocator;
use kernel::memory::BuddyAlloc;
use kernel::memory::Bitv;
use kernel::memory::BitvStorage;
use kernel::memory::Alloc;
use kernel::memory;
use kernel::fs;
use kernel::fs::FileNode;
use kernel::fs::DirNode;
pub static mut buffer: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 0
};
pub static mut s: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
};
pub static mut numberString: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
};
pub static mut count: uint = 0;
pub static mut root : DirNode = DirNode {
name : cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
},
dchildren : '\0' as *mut Vec<*mut DirNode>,
fchildren : '\0' as *mut Vec<*mut FileNode>,
parent : '\0' as *mut DirNode,
};
pub static mut pwd : *mut DirNode = '\0' as *mut DirNode;
pub fn putchar(key: char) {
unsafe {
/*
* We need to include a blank asm call to prevent rustc
* from optimizing this part out
*/
asm!("");
io::write_char(key, io::UART0);
}
}
pub fn putstr(msg: &str) {
for c in slice::iter(as_bytes(msg)) {
putchar(*c as char);
}
}
pub unsafe fn drawstr(msg: &str) {
let old_fg = super::super::io::FG_COLOR;
let mut x: u32 = 0x6699AAFF;
for c in slice::iter(as_bytes(msg)) {
x = (x << 8) + (x >> 24);
super::super::io::set_fg(x);
drawchar(*c as char);
}
super::super::io::set_fg(old_fg);
}
unsafe fn drawchar(x: char)
{
io::restore();
if x == '\n' {
io::CURSOR_Y += io::CURSOR_HEIGHT;
io::CURSOR_X = 0u32;
}
else {
io::draw_char(x);
io::CURSOR_X += io::CURSOR_WIDTH;
}
io::backup();
io::draw_cursor();
}
unsafe fn backspace()
{
io::restore();
if (io::CURSOR_X >= io::CURSOR_WIDTH) {
io::CURSOR_X -= io::CURSOR_WIDTH;
io::draw_char(' ');
}
io::backup();
io::draw_cursor();
}
pub unsafe fn parsekey(x: char) {
let x = x as u8;
// Set this to false to learn the keycodes of various keys!
// Key codes are printed backwards because life is hard
match x {
13 => {
parse();
putstr(&"\nsgash> ");
drawstr(&"\nsgash> ");
buffer.reset();
}
127 => {
putchar('');
putchar(' ');
putchar('');
backspace();
buffer.delete_char();
}
_ => {
if io::CURSOR_X < io::SCREEN_WIDTH-io::CURSOR_WIDTH && buffer.add_char(x) {
putchar(x as char);
drawchar(x as char);
}
}<|fim▁hole|>unsafe fn parse(){
// cd, rm, mkdir, pwd
match buffer.getarg(' ', 0) {
Some(a) => {
if(a.equals(&"echo")) {
match buffer.getarg(' ', 1) {
Some(z) => {
drawchar('\n');
drawcstr(z);
}
None => {}
}
}
if(a.equals(&"ls")) {
putstr(&"\nfile list");
drawstr(&"\nfile list");
}
if(a.equals(&"cat")) {
putstr(&"\n");
drawstr(&"\n");
match buffer.getarg(' ', 1){
Some(b) =>{
(*pwd).read_file(b);
}
None => {}
};
}
if(a.equals(&"cd")) {
putstr(&"\nchange directory");
drawstr(&"\nhange directory");
}
if(a.equals(&"rm")) {
putstr(&"\nremove");
drawstr(&"\nremove");
}
if(a.equals(&"mkdir")) {
putstr(&"\n");
drawstr(&"\n");
match buffer.getarg(' ', 1){
Some(b) =>{
putcstr(b);
drawcstr(b);
}
None => {}
};
}
if(a.equals(&"pwd")) {
// putcstr((*pwd).name);
// drawcstr((*pwd).name);
putstr(&"\nYou are here");
drawstr(&"\nYou are here");
}
if(a.equals(&"wr")) {
putstr(&"\nwrite file");
drawstr(&"\nwrite file");
}
if(a.equals(&"highlight")) {
match buffer.getarg(' ', 1){
Some(b) =>{
if(b.equals("on")){
io::set_bg(0x33ffff);
}
if(b.equals("off")){
io::set_bg(0x660000);
}
}
None => {}
};
}
if(a.equals(&"clear")){
io::restart();
}
}
None => { }
};
buffer.reset();
}
fn screen() {
putstr(&"\n ");
putstr(&"\n ");
putstr(&"\n 7=..~$=..:7 ");
putstr(&"\n +$: =$$$+$$$?$$$+ ,7? ");
putstr(&"\n $$$$$$$$$$$$$$$$$$Z$$ ");
putstr(&"\n 7$$$$$$$$$$$$. .Z$$$$$Z$$$$$$ ");
putstr(&"\n ~..7$$Z$$$$$7+7$+.?Z7=7$$Z$$Z$$$..: ");
putstr(&"\n ~$$$$$$$$7: :ZZZ, :7ZZZZ$$$$= ");
putstr(&"\n Z$$$$$? .+ZZZZ$$ ");
putstr(&"\n +$ZZ$$$Z7 7ZZZ$Z$$I. ");
putstr(&"\n $$$$ZZZZZZZZZZZZZZZZZZZZZZZZI, ,ZZZ$$Z ");
putstr(&"\n :+$$$$ZZZZZZZZZZZZZZZZZZZZZZZZZZZ= $ZZ$$+~, ");
putstr(&"\n ?$Z$$$$ZZZZZZZZZZZZZZZZZZZZZZZZZZZZI 7ZZZ$ZZI ");
putstr(&"\n =Z$$+7Z$$7ZZZZZZZZ$$$$$$$ZZZZZZZZZZ ~Z$?$ZZ? ");
putstr(&"\n :$Z$Z...$Z $ZZZZZZZ~ ~ZZZZZZZZ,.ZZ...Z$Z$~ ");
putstr(&"\n 7ZZZZZI$ZZ $ZZZZZZZ~ =ZZZZZZZ7..ZZ$?$ZZZZ$ ");
putstr(&"\n ZZZZ$: $ZZZZZZZZZZZZZZZZZZZZZZ= ~$ZZZ$: ");
putstr(&"\n 7Z$ZZ$, $ZZZZZZZZZZZZZZZZZZZZ7 ZZZ$Z$ ");
putstr(&"\n =ZZZZZZ, $ZZZZZZZZZZZZZZZZZZZZZZ, ZZZ$ZZ+ ");
putstr(&"\n ,ZZZZ, $ZZZZZZZ: =ZZZZZZZZZ ZZZZZ$: ");
putstr(&"\n =$ZZZZ+ ZZZZZZZZ~ ZZZZZZZZ~ =ZZZZZZZI ");
putstr(&"\n $ZZ$ZZZ$$Z$$ZZZZZZZZZ$$$$ IZZZZZZZZZ$ZZZZZZZZZ$ ");
putstr(&"\n :ZZZZZZZZZZZZZZZZZZZZZZ ~ZZZZZZZZZZZZZZZZZ~ ");
putstr(&"\n ,Z$$ZZZZZZZZZZZZZZZZZZZZ ZZZZZZZZZZZZZZZZZZ~ ");
putstr(&"\n =$ZZZZZZZZZZZZZZZZZZZZZZ $ZZZZZZZZZZZZZZZ$+ ");
putstr(&"\n IZZZZZ:. . ,ZZZZZ$ ");
putstr(&"\n ~$ZZZZZZZZZZZ ZZZZ$ZZZZZZZ+ ");
putstr(&"\n Z$ZZZ. ,Z~ =Z:.,ZZZ$Z ");
putstr(&"\n ,ZZZZZ..~Z$. .7Z:..ZZZZZ: ");
putstr(&"\n ~7+:$ZZZZZZZZI=:. .,=IZZZZZZZ$Z:=7= ");
putstr(&"\n $$ZZZZZZZZZZZZZZZZZZZZZZ$ZZZZ ");
putstr(&"\n ==..$ZZZ$ZZZZZZZZZZZ$ZZZZ .~+ ");
putstr(&"\n I$?.?ZZZ$ZZZ$ZZZI =$7 ");
putstr(&"\n $7..I$7..I$, ");
putstr(&"\n");
putstr(&"\n _ _ _ _ ");
putstr(&"\n| | (_) | | | | ");
putstr(&"\n| | ____ ___ ____ _____| |_____ ____ ____ _____| | ");
putstr(&"\n| |/ ___) _ \\| _ \\ | _ _) ___ |/ ___) _ \\| ___ | | ");
putstr(&"\n| | | | |_| | | | | | | \\ \\| ____| | | | | | ____| | ");
putstr(&"\n|_|_| \\____/|_| |_| |_| \\_\\_____)_| |_| |_|_____)__)\n\n");
}
pub unsafe fn init() {
buffer = cstr::new(256);
screen();
putstr(&"\nsgash> ");
root = fs::DirNode::new(from_str("Root"), '\0' as *mut DirNode);
pwd = &mut root as *mut DirNode;
(*pwd).name = from_str("Root");
buffer.reset();
}
pub unsafe fn putcstr(s: cstr) {
let mut p = s.p as uint;
while *(p as *char) != '\0'
{
putchar(*(p as *char));
p += 1;
}
}
pub unsafe fn drawcstr(string : cstr) -> bool{
let s = string.p as uint;
let e = string.max;
let mut i = 0;
while i < e {
let theChar : u8 = *((s+i) as *mut u8);
if(theChar as char != '\0') {
drawchar(theChar as char);
i +=1;
}
else {
return true;
}
}
false
}
pub unsafe fn echo() -> bool{
drawstr(&"\n");
putstr(&"\n");
let s = buffer.p as uint;
let e = buffer.max;
let mut i = 0;
while i < e {
let theChar : u8 = *((s+i) as *mut u8);
if(theChar as char != '\0') {
putchar(theChar as char);
drawchar(theChar as char);
i +=1;
}
else {
drawstr(&"\n");
putstr(&"\n");
return true;
}
}
false
}
pub unsafe fn from_str(s: &str) -> cstr {
let mut this = cstr::new(256);
for c in slice::iter(as_bytes(s)) {
this.add_char(*c);
};
this
}
pub struct cstr {
p: *mut u8,
p_cstr_i: uint,
max: uint
}
impl cstr {
pub unsafe fn new(size: uint) -> cstr {
let (x,y) = heap.alloc(size);
let temp = ((x as uint) + 256 * count) as *mut u8;
count = count + 1;
let this = cstr {
p: temp,
p_cstr_i: 0,
max: y
};
*(((this.p as uint)+this.p_cstr_i) as *mut char) = '\0';
this
}
fn len(&self) -> uint {
self.p_cstr_i
}
pub unsafe fn add_char(&mut self, x: u8) -> bool{
if (self.p_cstr_i == self.max) {
putstr("not able to add");
return false;
}
*(((self.p as uint)+self.p_cstr_i) as *mut u8) = x;
self.p_cstr_i += 1;
*(((self.p as uint)+self.p_cstr_i) as *mut char) = '\0';
true
}
unsafe fn delete_char(&mut self) -> bool {
if (self.p_cstr_i == 0) { return false; }
self.p_cstr_i -= 1;
*(((self.p as uint)+self.p_cstr_i) as *mut char) = '\0';
true
}
unsafe fn reset(&mut self) {
self.p_cstr_i = 0;
*(self.p as *mut char) = '\0';
}
unsafe fn charAt(&self, n: u8) -> char {
((*self.p) + n) as char
}
unsafe fn equals(&self, other: &str) -> bool {
// save val of self.p, which is u8, as a unit
let mut selfp: uint = self.p as uint;
// iterate through the str "other"
for c in slice::iter(as_bytes(other)){
// return false if any character does not match
if( *c != *(selfp as *u8) ) {
return false;
}
selfp += 1;
};
true
}
pub unsafe fn equals_cstr(&self, other: cstr) -> bool {
let mut x: uint = 0;
let mut selfp: uint = self.p as uint;
let mut otherp: uint = other.p as uint;
while x < self.len() {
if (*(selfp as *char) != *(otherp as *char)) {
return false;
}
selfp += 1;
otherp += 1;
x += 1;
}
true
}
unsafe fn getarg(&self, delim: char, mut k: uint) -> Option<cstr> {
let mut ind: uint = 0;
let mut found = k == 0;
let mut selfp: uint = self.p as uint;
s.reset();
loop {
if (*(selfp as *char) == '\0') {
// End of string
//return a copy of s (write copy method)
// erased from next call
if (found) { return Some(s); }
else { return None; }
};
if (*(selfp as *u8) == delim as u8) {
if (found) { return Some(s); }
k -= 1;
};
if (found) {
s.add_char(*(selfp as *u8));
};
found = k == 0;
selfp += 1;
ind += 1;
if (ind == self.max) {
putstr(&"\nSomething broke!");
return None;
}
}
}
}<|fim▁end|> | }
}
|
<|file_name|>index.js<|end_file_name|><|fim▁begin|>'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Promise = require('bluebird');
var MongoClient = require('mongodb');
function defaultSerializeFunction(session) {
// Copy each property of the session to a new object
var obj = {};
var prop = void 0;
for (prop in session) {
if (prop === 'cookie') {
// Convert the cookie instance to an object, if possible
// This gets rid of the duplicate object under session.cookie.data property
obj.cookie = session.cookie.toJSON ? session.cookie.toJSON() : session.cookie;
} else {
obj[prop] = session[prop];
}
}
return obj;
}
function computeTransformFunctions(options, defaultStringify) {
if (options.serialize || options.unserialize) {
return {
serialize: options.serialize || defaultSerializeFunction,
unserialize: options.unserialize || function (x) {
return x;
}
};
}
if (options.stringify === false || defaultStringify === false) {
return {
serialize: defaultSerializeFunction,
unserialize: function (x) {
return x;
}
};
}
if (options.stringify === true || defaultStringify === true) {
return {
serialize: JSON.stringify,
unserialize: JSON.parse
};
}
}
module.exports = function connectMongo(connect) {
var Store = connect.Store || connect.session.Store;
var MemoryStore = connect.MemoryStore || connect.session.MemoryStore;
var MongoStore = function (_Store) {
_inherits(MongoStore, _Store);
function MongoStore(options) {
_classCallCheck(this, MongoStore);
options = options || {};
/* Fallback */
if (options.fallbackMemory && MemoryStore) {
var _ret;
return _ret = new MemoryStore(), _possibleConstructorReturn(_this, _ret);
}
/* Options */
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(MongoStore).call(this, options));
_this.ttl = options.ttl || 1209600; // 14 days
_this.collectionName = options.collection || 'sessions';
_this.autoRemove = options.autoRemove || 'native';
_this.autoRemoveInterval = options.autoRemoveInterval || 10;
_this.transformFunctions = computeTransformFunctions(options, true);
_this.options = options;
_this.changeState('init');
var newConnectionCallback = function (err, db) {
if (err) {
_this.connectionFailed(err);
} else {
_this.handleNewConnectionAsync(db);
}
};
if (options.url) {
// New native connection using url + mongoOptions
MongoClient.connect(options.url, options.mongoOptions || {}, newConnectionCallback);
} else if (options.mongooseConnection) {
// Re-use existing or upcoming mongoose connection
if (options.mongooseConnection.readyState === 1) {
_this.handleNewConnectionAsync(options.mongooseConnection.db);
} else {
options.mongooseConnection.once('open', function () {
return _this.handleNewConnectionAsync(options.mongooseConnection.db);
});
}
} else if (options.db && options.db.listCollections) {
// Re-use existing or upcoming native connection
if (options.db.openCalled || options.db.openCalled === undefined) {
// openCalled is undefined in [email protected]
_this.handleNewConnectionAsync(options.db);
} else {
options.db.open(newConnectionCallback);
}
} else if (options.dbPromise) {
options.dbPromise.then(function (db) {
return _this.handleNewConnectionAsync(db);
}).catch(function (err) {
return _this.connectionFailed(err);
});
} else {
throw new Error('Connection strategy not found');
}
_this.changeState('connecting');
return _this;
}
_createClass(MongoStore, [{
key: 'connectionFailed',
value: function connectionFailed(err) {
this.changeState('disconnected');
throw err;
}
}, {
key: 'handleNewConnectionAsync',
value: function handleNewConnectionAsync(db) {
var _this2 = this;
this.db = db;
return this.setCollection(db.collection(this.collectionName)).setAutoRemoveAsync().then(function () {
return _this2.changeState('connected');
});
}
}, {
key: 'setAutoRemoveAsync',
value: function setAutoRemoveAsync() {
var _this3 = this;
switch (this.autoRemove) {
case 'native':
return this.collection.ensureIndexAsync({ expires: 1 }, { expireAfterSeconds: 0 });
case 'interval':
var removeQuery = { expires: { $lt: new Date() } };
this.timer = setInterval(function () {
return _this3.collection.remove(removeQuery, { w: 0 });
}, this.autoRemoveInterval * 1000 * 60);
this.timer.unref();
return Promise.resolve();
default:
return Promise.resolve();
}
}
}, {
key: 'changeState',
value: function changeState(newState) {
if (newState !== this.state) {
this.state = newState;
this.emit(newState);
}
}
}, {
key: 'setCollection',
value: function setCollection(collection) {
if (this.timer) {
clearInterval(this.timer);
}
this.collectionReadyPromise = undefined;
this.collection = collection;
// Promisify used collection methods
['count', 'findOne', 'remove', 'drop', 'update', 'ensureIndex'].forEach(function (method) {
collection[method + 'Async'] = Promise.promisify(collection[method], collection);
});
return this;
}
}, {
key: 'collectionReady',
value: function collectionReady() {
var _this4 = this;
var promise = this.collectionReadyPromise;
if (!promise) {
promise = new Promise(function (resolve, reject) {
switch (_this4.state) {
case 'connected':
resolve(_this4.collection);
break;
case 'connecting':
_this4.once('connected', function () {
return resolve(_this4.collection);
});
break;
case 'disconnected':
reject(new Error('Not connected'));
break;
}
});
this.collectionReadyPromise = promise;
}
return promise;
}
}, {
key: 'computeStorageId',
value: function computeStorageId(sessionId) {
if (this.options.transformId && typeof this.options.transformId === 'function') {
return this.options.transformId(sessionId);
} else {
return sessionId;
}
}
/* Public API */
}, {
key: 'get',
value: function get(sid, callback) {
var _this5 = this;
return this.collectionReady().then(function (collection) {
return collection.findOneAsync({
_id: _this5.computeStorageId(sid),
$or: [{ expires: { $exists: false } }, { expires: { $gt: new Date() } }]
});
}).then(function (session) {
if (session) {
var s = _this5.transformFunctions.unserialize(session.session);
if (_this5.options.touchAfter > 0 && session.lastModified) {
s.lastModified = session.lastModified;
}
_this5.emit('touch', sid);
return s;
}
}).nodeify(callback);
}
}, {
key: 'set',
value: function set(sid, session, callback) {
var _this6 = this;
// removing the lastModified prop from the session object before update
if (this.options.touchAfter > 0 && session && session.lastModified) {
delete session.lastModified;
}
var s;
try {
s = { _id: this.computeStorageId(sid), session: this.transformFunctions.serialize(session) };
} catch (err) {
return callback(err);
}
if (session && session.cookie && session.cookie.expires) {
s.expires = new Date(session.cookie.expires);
} else {
// If there's no expiration date specified, it is
// browser-session cookie or there is no cookie at all,
// as per the connect docs.
//
// So we set the expiration to two-weeks from now
// - as is common practice in the industry (e.g Django) -
// or the default specified in the options.
s.expires = new Date(Date.now() + this.ttl * 1000);
}
if (this.options.touchAfter > 0) {
s.lastModified = new Date();
}
return this.collectionReady().then(function (collection) {
return collection.updateAsync({ _id: _this6.computeStorageId(sid) }, s, { upsert: true });
}).then(function () {
return _this6.emit('set', sid);
}).nodeify(callback);
}
}, {
key: 'touch',
value: function touch(sid, session, callback) {
var _this7 = this;
var updateFields = {},
touchAfter = this.options.touchAfter * 1000,
lastModified = session.lastModified ? session.lastModified.getTime() : 0,
currentDate = new Date();
// if the given options has a touchAfter property, check if the
// current timestamp - lastModified timestamp is bigger than
// the specified, if it's not, don't touch the session
if (touchAfter > 0 && lastModified > 0) {
var timeElapsed = currentDate.getTime() - session.lastModified;
if (timeElapsed < touchAfter) {
return callback();
} else {
updateFields.lastModified = currentDate;
}
}
if (session && session.cookie && session.cookie.expires) {
updateFields.expires = new Date(session.cookie.expires);
} else {
updateFields.expires = new Date(Date.now() + this.ttl * 1000);
}
return this.collectionReady().then(function (collection) {
return collection.updateAsync({ _id: _this7.computeStorageId(sid) }, { $set: updateFields });
}).then(function (result) {
if (result.nModified === 0) {
throw new Error('Unable to find the session to touch');
} else {
_this7.emit('touch', sid);
}
}).nodeify(callback);
}<|fim▁hole|> value: function destroy(sid, callback) {
var _this8 = this;
return this.collectionReady().then(function (collection) {
return collection.removeAsync({ _id: _this8.computeStorageId(sid) });
}).then(function () {
return _this8.emit('destroy', sid);
}).nodeify(callback);
}
}, {
key: 'length',
value: function length(callback) {
return this.collectionReady().then(function (collection) {
return collection.countAsync({});
}).nodeify(callback);
}
}, {
key: 'clear',
value: function clear(callback) {
return this.collectionReady().then(function (collection) {
return collection.dropAsync();
}).nodeify(callback);
}
}, {
key: 'close',
value: function close() {
if (this.db) {
this.db.close();
}
}
}]);
return MongoStore;
}(Store);
return MongoStore;
};<|fim▁end|> | }, {
key: 'destroy', |
<|file_name|>issue-54943-1.rs<|end_file_name|><|fim▁begin|>// This test is a minimal version of an ICE in the dropck-eyepatch tests
// found in the fix for #54943.
<|fim▁hole|>// check-pass
fn foo<T>(_t: T) {
}
fn main() {
struct A<'a, B: 'a>(&'a B);
let (a1, a2): (String, A<_>) = (String::from("auto"), A(&"this"));
foo((a1, a2));
}<|fim▁end|> | |
<|file_name|>bitcoin.cpp<|end_file_name|><|fim▁begin|>/*
* W.J. van der Laan 2011-2012
*/
#include <QApplication>
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "paymentserver.h"
#include "splashscreen.h"
#include <QMessageBox>
#if QT_VERSION < 0x050000
#include <QTextCodec>
#endif
#include <QLocale>
#include <QTimer>
#include <QTranslator>
#include <QLibraryInfo>
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Declare meta types used for QMetaObject::invokeMethod
Q_DECLARE_METATYPE(bool*)
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static SplashScreen *splashref;
static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
bool ret = false;
// In case of modal message, use blocking connection to wait for user to click a button
QMetaObject::invokeMethod(guiref, "message",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(unsigned int, style),
Q_ARG(bool*, &ret));
return ret;
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
return false;
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired)
{
if(!guiref)
return false;
if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55));
qApp->processEvents();
}
printf("init message: %s\n", message.c_str());
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Dogecoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// Command-line options take precedence:
ParseParameters(argc, argv);
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Register meta types used for QMetaObject::invokeMethod
qRegisterMetaType< bool* >();
// Do this early as we don't want to bother initializing if we are just calling IPC
// ... but do it after creating app, so QCoreApplication::arguments is initialized:
if (PaymentServer::ipcSendCommandLine())
exit(0);
PaymentServer* paymentServer = new PaymentServer(&app);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "Dogecoin",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
QApplication::setOrganizationName("Dogecoin");
QApplication::setOrganizationDomain("dogecoin-noexist-domain.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
QApplication::setApplicationName("Dogecoin-Qt-testnet");
else
QApplication::setApplicationName("Dogecoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
#ifdef Q_OS_MAC
// on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange)
if(GetBoolArg("-testnet")) {
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
}
#endif
SplashScreen splash(QPixmap(), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
#if MAC_OSX
// QSplashScreen on Mac seems to always stay on top. Ugh.
splash.setWindowFlags(Qt::FramelessWindowHint);
#endif
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
#ifndef Q_OS_MAC
// Regenerate startup link, to fix links to old versions
// OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs)
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
#endif
boost::thread_group threadGroup;
BitcoinGUI window;
guiref = &window;
QTimer* pollShutdownTimer = new QTimer(guiref);
QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown()));
pollShutdownTimer->start(200);
if(AppInit2(threadGroup))
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel *walletModel = 0;
if(pwalletMain)
walletModel = new WalletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
if(walletModel)
{
window.addWallet("~Default", walletModel);
window.setCurrentWallet("~Default");
}
// If -min option passed, start window minimized.<|fim▁hole|> }
else
{
window.show();
}
// Now that initialization/startup is done, process any command-line
// bitcoin: URIs
QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString)));
QTimer::singleShot(100, paymentServer, SLOT(uiReady()));
app.exec();
window.hide();
window.setClientModel(0);
window.removeAllWallets();
guiref = 0;
delete walletModel;
}
// Shutdown the core and its threads, but don't exit Bitcoin-Qt here
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
}
else
{
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST<|fim▁end|> | if(GetBoolArg("-min"))
{
window.showMinimized(); |
<|file_name|>expression-014.js<|end_file_name|><|fim▁begin|>/**
File Name: expression-014.js
Corresponds To: ecma/Expressions/11.2.2-9-n.js
ECMA Section: 11.2.2. The new operator
Description:
Author: [email protected]
Date: 12 november 1997
*/
var SECTION = "expression-014.js";
var VERSION = "ECMA_1";
var TITLE = "The new operator";
var BUGNUMBER= "327765";
startTest();
writeHeaderToLog( SECTION + " "+ TITLE);
var tc = 0;
var testcases = new Array();
var BOOLEAN = new Boolean();
var result = "Failed";
var exception = "No exception thrown";
var expect = "Passed";
try {
result = new BOOLEAN();
} catch ( e ) {
result = expect;
exception = e.toString();
}
testcases[tc++] = new TestCase(
SECTION,
"BOOLEAN = new Boolean(); result = new BOOLEAN()" +
" (threw " + exception +")",
expect,
result );
<|fim▁hole|><|fim▁end|> | test(); |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import url
from django.contrib.auth import views as auth_views
from app.views import IndexView, RegisterView, UserProfileView<|fim▁hole|> name='index'),
url(r'^register/$',
RegisterView.as_view(),
name='register'),
url(r'^login/$',
auth_views.login,
{'template_name': 'login.djhtml'},
name='login'),
url(r'^logout/$',
auth_views.logout,
{'next_page': '/'},
name='logout'),
url(r'^user/profile/(?P<username>.*)/$',
UserProfileView.as_view(),
name='user-profile'),
]<|fim▁end|> |
urlpatterns = [
url(r'^$',
IndexView.as_view(), |
<|file_name|>synthrepo.py<|end_file_name|><|fim▁begin|># synthrepo.py - repo synthesis
#
# Copyright 2012 Facebook
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''synthesize structurally interesting change history
This extension is useful for creating a repository with properties
that are statistically similar to an existing repository. During
analysis, a simple probability table is constructed from the history
of an existing repository. During synthesis, these properties are
reconstructed.
Properties that are analyzed and synthesized include the following:
- Lines added or removed when an existing file is modified
- Number and sizes of files added
- Number of files removed
- Line lengths
- Topological distance to parent changeset(s)
- Probability of a commit being a merge
- Probability of a newly added file being added to a new directory
- Interarrival time, and time zone, of commits
- Number of files in each directory
A few obvious properties that are not currently handled realistically:
- Merges are treated as regular commits with two parents, which is not
realistic
- Modifications are not treated as operations on hunks of lines, but
as insertions and deletions of randomly chosen single lines
- Committer ID (always random)
- Executability of files
- Symlinks and binary files are ignored
'''
from __future__ import absolute_import
import bisect
import collections
import itertools
import json
import os
import random
import sys
import time
from mercurial.i18n import _
from mercurial.node import (
nullid,
nullrev,
short,
)
from mercurial import (
cmdutil,
context,
error,
hg,
patch,
scmutil,
util,
)
# Note for extension authors: ONLY specify testedwith = 'internal' for
# extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
# be specifying the version(s) of Mercurial they are tested with, or
# leave the attribute unspecified.
testedwith = 'internal'
cmdtable = {}
command = cmdutil.command(cmdtable)
newfile = set(('new fi', 'rename', 'copy f', 'copy t'))
def zerodict():
return collections.defaultdict(lambda: 0)
def roundto(x, k):
if x > k * 2:
return int(round(x / float(k)) * k)
return int(round(x))
def parsegitdiff(lines):
filename, mar, lineadd, lineremove = None, None, zerodict(), 0
binary = False
for line in lines:
start = line[:6]
if start == 'diff -':
if filename:
yield filename, mar, lineadd, lineremove, binary
mar, lineadd, lineremove, binary = 'm', zerodict(), 0, False
filename = patch.gitre.match(line).group(1)
elif start in newfile:
mar = 'a'
elif start == 'GIT bi':
binary = True
elif start == 'delete':
mar = 'r'
elif start:
s = start[0]
if s == '-' and not line.startswith('--- '):
lineremove += 1
elif s == '+' and not line.startswith('+++ '):
lineadd[roundto(len(line) - 1, 5)] += 1
if filename:
yield filename, mar, lineadd, lineremove, binary
@command('analyze',
[('o', 'output', '', _('write output to given file'), _('FILE')),
('r', 'rev', [], _('analyze specified revisions'), _('REV'))],
_('hg analyze'), optionalrepo=True)
def analyze(ui, repo, *revs, **opts):
'''create a simple model of a repository to use for later synthesis
This command examines every changeset in the given range (or all
of history if none are specified) and creates a simple statistical
model of the history of the repository. It also measures the directory
structure of the repository as checked out.
The model is written out to a JSON file, and can be used by
:hg:`synthesize` to create or augment a repository with synthetic
commits that have a structure that is statistically similar to the
analyzed repository.
'''
root = repo.root
if not root.endswith(os.path.sep):
root += os.path.sep
revs = list(revs)
revs.extend(opts['rev'])
if not revs:
revs = [':']
output = opts['output']
if not output:
output = os.path.basename(root) + '.json'
if output == '-':
fp = sys.stdout
else:
fp = open(output, 'w')
# Always obtain file counts of each directory in the given root directory.
def onerror(e):
ui.warn(_('error walking directory structure: %s\n') % e)
dirs = {}
rootprefixlen = len(root)
for dirpath, dirnames, filenames in os.walk(root, onerror=onerror):
dirpathfromroot = dirpath[rootprefixlen:]
dirs[dirpathfromroot] = len(filenames)
if '.hg' in dirnames:
dirnames.remove('.hg')
lineschanged = zerodict()
children = zerodict()
p1distance = zerodict()
p2distance = zerodict()
linesinfilesadded = zerodict()
fileschanged = zerodict()
filesadded = zerodict()
filesremoved = zerodict()
linelengths = zerodict()
interarrival = zerodict()
parents = zerodict()
dirsadded = zerodict()
tzoffset = zerodict()
# If a mercurial repo is available, also model the commit history.
if repo:
revs = scmutil.revrange(repo, revs)
revs.sort()
progress = ui.progress
_analyzing = _('analyzing')
_changesets = _('changesets')
_total = len(revs)
for i, rev in enumerate(revs):
progress(_analyzing, i, unit=_changesets, total=_total)
ctx = repo[rev]
pl = ctx.parents()
pctx = pl[0]
prev = pctx.rev()
children[prev] += 1
p1distance[rev - prev] += 1
parents[len(pl)] += 1
tzoffset[ctx.date()[1]] += 1
if len(pl) > 1:
p2distance[rev - pl[1].rev()] += 1
if prev == rev - 1:
lastctx = pctx
else:
lastctx = repo[rev - 1]
if lastctx.rev() != nullrev:
timedelta = ctx.date()[0] - lastctx.date()[0]
interarrival[roundto(timedelta, 300)] += 1
diff = sum((d.splitlines() for d in ctx.diff(pctx, git=True)), [])
fileadds, diradds, fileremoves, filechanges = 0, 0, 0, 0
for filename, mar, lineadd, lineremove, isbin in parsegitdiff(diff):
if isbin:
continue
added = sum(lineadd.itervalues(), 0)
if mar == 'm':
if added and lineremove:
lineschanged[roundto(added, 5),
roundto(lineremove, 5)] += 1
filechanges += 1
elif mar == 'a':
fileadds += 1
if '/' in filename:
filedir = filename.rsplit('/', 1)[0]
if filedir not in pctx.dirs():
diradds += 1
linesinfilesadded[roundto(added, 5)] += 1
elif mar == 'r':
fileremoves += 1
for length, count in lineadd.iteritems():
linelengths[length] += count
fileschanged[filechanges] += 1
filesadded[fileadds] += 1
dirsadded[diradds] += 1
filesremoved[fileremoves] += 1
invchildren = zerodict()
for rev, count in children.iteritems():
invchildren[count] += 1
if output != '-':
ui.status(_('writing output to %s\n') % output)
def pronk(d):
return sorted(d.iteritems(), key=lambda x: x[1], reverse=True)
json.dump({'revs': len(revs),
'initdirs': pronk(dirs),
'lineschanged': pronk(lineschanged),
'children': pronk(invchildren),
'fileschanged': pronk(fileschanged),
'filesadded': pronk(filesadded),
'linesinfilesadded': pronk(linesinfilesadded),
'dirsadded': pronk(dirsadded),
'filesremoved': pronk(filesremoved),
'linelengths': pronk(linelengths),
'parents': pronk(parents),
'p1distance': pronk(p1distance),
'p2distance': pronk(p2distance),
'interarrival': pronk(interarrival),
'tzoffset': pronk(tzoffset),
},
fp)
fp.close()
@command('synthesize',
[('c', 'count', 0, _('create given number of commits'), _('COUNT')),
('', 'dict', '', _('path to a dictionary of words'), _('FILE')),
('', 'initfiles', 0, _('initial file count to create'), _('COUNT'))],
_('hg synthesize [OPTION].. DESCFILE'))
def synthesize(ui, repo, descpath, **opts):
'''synthesize commits based on a model of an existing repository
The model must have been generated by :hg:`analyze`. Commits will
be generated randomly according to the probabilities described in
the model. If --initfiles is set, the repository will be seeded with
the given number files following the modeled repository's directory
structure.
When synthesizing new content, commit descriptions, and user
names, words will be chosen randomly from a dictionary that is
presumed to contain one word per line. Use --dict to specify the
path to an alternate dictionary to use.
'''
try:
fp = hg.openpath(ui, descpath)
except Exception as err:
raise error.Abort('%s: %s' % (descpath, err[0].strerror))
desc = json.load(fp)
fp.close()
def cdf(l):
if not l:
return [], []
vals, probs = zip(*sorted(l, key=lambda x: x[1], reverse=True))
t = float(sum(probs, 0))
s, cdfs = 0, []
for v in probs:
s += v
cdfs.append(s / t)
return vals, cdfs
lineschanged = cdf(desc['lineschanged'])
fileschanged = cdf(desc['fileschanged'])
filesadded = cdf(desc['filesadded'])
dirsadded = cdf(desc['dirsadded'])
filesremoved = cdf(desc['filesremoved'])
linelengths = cdf(desc['linelengths'])
parents = cdf(desc['parents'])
p1distance = cdf(desc['p1distance'])
p2distance = cdf(desc['p2distance'])
interarrival = cdf(desc['interarrival'])
linesinfilesadded = cdf(desc['linesinfilesadded'])
tzoffset = cdf(desc['tzoffset'])
dictfile = opts.get('dict') or '/usr/share/dict/words'
try:
fp = open(dictfile, 'rU')
except IOError as err:
raise error.Abort('%s: %s' % (dictfile, err.strerror))
words = fp.read().splitlines()
fp.close()
initdirs = {}
if desc['initdirs']:
for k, v in desc['initdirs']:
initdirs[k.encode('utf-8').replace('.hg', '_hg')] = v
initdirs = renamedirs(initdirs, words)
initdirscdf = cdf(initdirs)
def pick(cdf):
return cdf[0][bisect.bisect_left(cdf[1], random.random())]
def pickpath():
return os.path.join(pick(initdirscdf), random.choice(words))
def makeline(minimum=0):
total = max(minimum, pick(linelengths))
c, l = 0, []
while c < total:
w = random.choice(words)
c += len(w) + 1
l.append(w)
return ' '.join(l)
<|fim▁hole|> lock = repo.lock()
nevertouch = set(('.hgsub', '.hgignore', '.hgtags'))
progress = ui.progress
_synthesizing = _('synthesizing')
_files = _('initial files')
_changesets = _('changesets')
# Synthesize a single initial revision adding files to the repo according
# to the modeled directory structure.
initcount = int(opts['initfiles'])
if initcount and initdirs:
pctx = repo[None].parents()[0]
dirs = set(pctx.dirs())
files = {}
def validpath(path):
# Don't pick filenames which are already directory names.
if path in dirs:
return False
# Don't pick directories which were used as file names.
while path:
if path in files:
return False
path = os.path.dirname(path)
return True
for i in xrange(0, initcount):
ui.progress(_synthesizing, i, unit=_files, total=initcount)
path = pickpath()
while not validpath(path):
path = pickpath()
data = '%s contents\n' % path
files[path] = context.memfilectx(repo, path, data)
dir = os.path.dirname(path)
while dir and dir not in dirs:
dirs.add(dir)
dir = os.path.dirname(dir)
def filectxfn(repo, memctx, path):
return files[path]
ui.progress(_synthesizing, None)
message = 'synthesized wide repo with %d files' % (len(files),)
mc = context.memctx(repo, [pctx.node(), nullid], message,
files.iterkeys(), filectxfn, ui.username(),
'%d %d' % util.makedate())
initnode = mc.commit()
if ui.debugflag:
hexfn = hex
else:
hexfn = short
ui.status(_('added commit %s with %d files\n')
% (hexfn(initnode), len(files)))
# Synthesize incremental revisions to the repository, adding repo depth.
count = int(opts['count'])
heads = set(map(repo.changelog.rev, repo.heads()))
for i in xrange(count):
progress(_synthesizing, i, unit=_changesets, total=count)
node = repo.changelog.node
revs = len(repo)
def pickhead(heads, distance):
if heads:
lheads = sorted(heads)
rev = revs - min(pick(distance), revs)
if rev < lheads[-1]:
rev = lheads[bisect.bisect_left(lheads, rev)]
else:
rev = lheads[-1]
return rev, node(rev)
return nullrev, nullid
r1 = revs - min(pick(p1distance), revs)
p1 = node(r1)
# the number of heads will grow without bound if we use a pure
# model, so artificially constrain their proliferation
toomanyheads = len(heads) > random.randint(1, 20)
if p2distance[0] and (pick(parents) == 2 or toomanyheads):
r2, p2 = pickhead(heads.difference([r1]), p2distance)
else:
r2, p2 = nullrev, nullid
pl = [p1, p2]
pctx = repo[r1]
mf = pctx.manifest()
mfk = mf.keys()
changes = {}
if mfk:
for __ in xrange(pick(fileschanged)):
for __ in xrange(10):
fctx = pctx.filectx(random.choice(mfk))
path = fctx.path()
if not (path in nevertouch or fctx.isbinary() or
'l' in fctx.flags()):
break
lines = fctx.data().splitlines()
add, remove = pick(lineschanged)
for __ in xrange(remove):
if not lines:
break
del lines[random.randrange(0, len(lines))]
for __ in xrange(add):
lines.insert(random.randint(0, len(lines)), makeline())
path = fctx.path()
changes[path] = context.memfilectx(repo, path,
'\n'.join(lines) + '\n')
for __ in xrange(pick(filesremoved)):
path = random.choice(mfk)
for __ in xrange(10):
path = random.choice(mfk)
if path not in changes:
changes[path] = None
break
if filesadded:
dirs = list(pctx.dirs())
dirs.insert(0, '')
for __ in xrange(pick(filesadded)):
pathstr = ''
while pathstr in dirs:
path = [random.choice(dirs)]
if pick(dirsadded):
path.append(random.choice(words))
path.append(random.choice(words))
pathstr = '/'.join(filter(None, path))
data = '\n'.join(makeline()
for __ in xrange(pick(linesinfilesadded))) + '\n'
changes[pathstr] = context.memfilectx(repo, pathstr, data)
def filectxfn(repo, memctx, path):
return changes[path]
if not changes:
continue
if revs:
date = repo['tip'].date()[0] + pick(interarrival)
else:
date = time.time() - (86400 * count)
# dates in mercurial must be positive, fit in 32-bit signed integers.
date = min(0x7fffffff, max(0, date))
user = random.choice(words) + '@' + random.choice(words)
mc = context.memctx(repo, pl, makeline(minimum=2),
sorted(changes.iterkeys()),
filectxfn, user, '%d %d' % (date, pick(tzoffset)))
newnode = mc.commit()
heads.add(repo.changelog.rev(newnode))
heads.discard(r1)
heads.discard(r2)
lock.release()
wlock.release()
def renamedirs(dirs, words):
'''Randomly rename the directory names in the per-dir file count dict.'''
wordgen = itertools.cycle(words)
replacements = {'': ''}
def rename(dirpath):
'''Recursively rename the directory and all path prefixes.
The mapping from path to renamed path is stored for all path prefixes
as in dynamic programming, ensuring linear runtime and consistent
renaming regardless of iteration order through the model.
'''
if dirpath in replacements:
return replacements[dirpath]
head, _ = os.path.split(dirpath)
if head:
head = rename(head)
else:
head = ''
renamed = os.path.join(head, next(wordgen))
replacements[dirpath] = renamed
return renamed
result = []
for dirpath, count in dirs.iteritems():
result.append([rename(dirpath.lstrip(os.sep)), count])
return result<|fim▁end|> | wlock = repo.wlock() |
<|file_name|>collections.js<|end_file_name|><|fim▁begin|>Products = new Mongo.Collection('products');
Cart = new Mongo.Collection('cart');
Orders = new Mongo.Collection('orders');<|fim▁hole|>Categories = new Mongo.Collection('categories');<|fim▁end|> | |
<|file_name|>test_call_template.py<|end_file_name|><|fim▁begin|>from Xml.Xslt import test_harness
sheet_str = """<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<root>
<xsl:apply-templates/>
</root>
</xsl:template>
<xsl:template name="do-the-rest">
<xsl:param name="start"/>
<xsl:param name="count"/>
<tr>
<xsl:for-each select="item[position()>=$start and position()<$start+$count]">
<td>
<xsl:value-of select="."/>
</td>
</xsl:for-each>
</tr>
<xsl:if test="$start + $count - 1 < count(child::item)">
<xsl:call-template name="do-the-rest">
<xsl:with-param name="start" select="$start + $count"/>
<xsl:with-param name="count" select="$count"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
<xsl:template match="data">
<xsl:call-template name="do-the-rest">
<xsl:with-param name="start" select="1"/>
<xsl:with-param name="count" select="2"/>
</xsl:call-template>
</xsl:template>
</xsl:stylesheet>
"""
<|fim▁hole|> <item>d</item>
<item>c</item>
</data>
"""
expected = """<?xml version='1.0' encoding='UTF-8'?>
<root><tr><td>b</td><td>a</td></tr><tr><td>d</td><td>c</td></tr></root>"""
def Test(tester):
source = test_harness.FileInfo(string=source_str)
sheet = test_harness.FileInfo(string=sheet_str)
test_harness.XsltTest(tester, source, [sheet], expected,
title='xsl:call-template')
return<|fim▁end|> | source_str = """<?xml version = "1.0"?>
<data>
<item>b</item>
<item>a</item> |
<|file_name|>runner.rs<|end_file_name|><|fim▁begin|>use algebra::Operator;
use common::dataset::DataSet;
use common::err::{Result, Void};
use common::plugin::{Plugin, PluginManager};
use common::session::Session;
pub trait QueryRunner
{
fn default_session(&self) -> Session;
fn add_plugin(&mut self, package: Box<Plugin>) -> Void;<|fim▁hole|>
fn execute(&self, session: &Session, plan: &Operator) -> Result<DataSet>;
fn close(&self) -> Void;
}<|fim▁end|> |
fn plugin_manager(&self) -> &PluginManager; |
<|file_name|>res_users.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import logging
from openerp.osv import osv, fields<|fim▁hole|>class res_users(osv.osv):
_inherit = "res.users"
_columns = {
'xis_user_external_id': fields.integer('XIS external user',
required=True),
}<|fim▁end|> |
_logger = logging.getLogger(__name__)
|
<|file_name|>Error.py<|end_file_name|><|fim▁begin|>import logging
class Error(Exception):
def __init__(self, message, data = {}):
self.message = message
self.data = data
def __str__(self):
return self.message + ": " + repr(self.data)
<|fim▁hole|> @staticmethod
def die(code, error, message = None):
if isinstance(error, Exception):
e = error
error = '{0}.{1}'.format(type(e).__module__, type(e).__name__)
message = str(e)
print 'Error: ' + error
if message:
print message
#logging.exception(message)
exit(code)<|fim▁end|> | |
<|file_name|>alternate_formats_country_code_set.rs<|end_file_name|><|fim▁begin|>// Copyright (C) 2015 Guillaume Gomez
//<|fim▁hole|>// 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.
lazy_static! {
pub static ref countryCodeSet : HashSet<u32> = get_country_code_set();
}
fn get_country_code_set() -> HashSet<u32> {
// The capacity is set to 57 as there are 43 different entries,
// and this offers a load factor of roughly 0.75.
let mut _countryCodeSet = HashSet::with_capacity(57);
_countryCodeSet.insert(7);
_countryCodeSet.insert(27);
_countryCodeSet.insert(30);
_countryCodeSet.insert(31);
_countryCodeSet.insert(34);
_countryCodeSet.insert(36);
_countryCodeSet.insert(43);
_countryCodeSet.insert(44);
_countryCodeSet.insert(49);
_countryCodeSet.insert(54);
_countryCodeSet.insert(55);
_countryCodeSet.insert(58);
_countryCodeSet.insert(61);
_countryCodeSet.insert(62);
_countryCodeSet.insert(63);
_countryCodeSet.insert(66);
_countryCodeSet.insert(81);
_countryCodeSet.insert(84);
_countryCodeSet.insert(90);
_countryCodeSet.insert(91);
_countryCodeSet.insert(94);
_countryCodeSet.insert(95);
_countryCodeSet.insert(255);
_countryCodeSet.insert(350);
_countryCodeSet.insert(351);
_countryCodeSet.insert(352);
_countryCodeSet.insert(358);
_countryCodeSet.insert(359);
_countryCodeSet.insert(372);
_countryCodeSet.insert(373);
_countryCodeSet.insert(380);
_countryCodeSet.insert(381);
_countryCodeSet.insert(385);
_countryCodeSet.insert(505);
_countryCodeSet.insert(506);
_countryCodeSet.insert(595);
_countryCodeSet.insert(675);
_countryCodeSet.insert(676);
_countryCodeSet.insert(679);
_countryCodeSet.insert(855);
_countryCodeSet.insert(971);
_countryCodeSet.insert(972);
_countryCodeSet.insert(995);
_countryCodeSet
}<|fim▁end|> | // Licensed under the Apache License, Version 2.0 (the "License"); |
<|file_name|>container-toggler.module.ts<|end_file_name|><|fim▁begin|>import { CommonModule } from '@angular/common';
import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { ContainerTogglerComponent } from './container-toggler.component';
@NgModule({
imports: [CommonModule],
declarations: [ContainerTogglerComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
exports: [ContainerTogglerComponent],<|fim▁hole|><|fim▁end|> | })
export class ContainerTogglerModule {} |
<|file_name|>client.js<|end_file_name|><|fim▁begin|>var crypto = require('crypto');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var pgPass = require('pgpass');
var TypeOverrides = require('./type-overrides');
var ConnectionParameters = require('./connection-parameters');
var Query = require('./query');
var defaults = require('./defaults');
var Connection = require('./connection');
var Client = function(config) {
EventEmitter.call(this);
this.connectionParameters = new ConnectionParameters(config);
this.user = this.connectionParameters.user;
this.database = this.connectionParameters.database;
this.port = this.connectionParameters.port;
this.host = this.connectionParameters.host;
this.password = this.connectionParameters.password;
var c = config || {};
this._types = new TypeOverrides(c.types);
this.connection = c.connection || new Connection({
stream: c.stream,
ssl: this.connectionParameters.ssl
});
this.queryQueue = [];
this.binary = c.binary || defaults.binary;
this.encoding = 'utf8';
this.processID = null;
this.secretKey = null;
this.ssl = this.connectionParameters.ssl || false;
};
util.inherits(Client, EventEmitter);
Client.prototype.connect = function(callback) {
var self = this;
var con = this.connection;
if(this.host && this.host.indexOf('/') === 0) {
con.connect(this.host + '/.s.PGSQL.' + this.port);
} else {
con.connect(this.port, this.host);
}
//once connection is established send startup message
con.on('connect', function() {
if(self.ssl) {
con.requestSsl();
} else {
con.startup(self.getStartupConf());
}
});
con.on('sslconnect', function() {
con.startup(self.getStartupConf());
});
function checkPgPass(cb) {
return function(msg) {
if (null !== self.password) {
cb(msg);
} else {
pgPass(self.connectionParameters, function(pass){
if (undefined !== pass) {
self.connectionParameters.password = self.password = pass;
}
cb(msg);
});
}
};
}
//password request handling
con.on('authenticationCleartextPassword', checkPgPass(function() {
con.password(self.password);
}));
//password request handling
con.on('authenticationMD5Password', checkPgPass(function(msg) {
var inner = Client.md5(self.password + self.user);
var outer = Client.md5(Buffer.concat([new Buffer(inner), msg.salt]));
var md5password = "md5" + outer;
con.password(md5password);
}));
con.once('backendKeyData', function(msg) {
self.processID = msg.processID;
self.secretKey = msg.secretKey;
});
//hook up query handling events to connection
//after the connection initially becomes ready for queries
con.once('readyForQuery', function() {
//delegate rowDescription to active query
con.on('rowDescription', function(msg) {
self.activeQuery.handleRowDescription(msg);
});
//delegate dataRow to active query
con.on('dataRow', function(msg) {
self.activeQuery.handleDataRow(msg);
});
//delegate portalSuspended to active query
con.on('portalSuspended', function(msg) {<|fim▁hole|> });
//deletagate emptyQuery to active query
con.on('emptyQuery', function(msg) {
self.activeQuery.handleEmptyQuery(con);
});
//delegate commandComplete to active query
con.on('commandComplete', function(msg) {
self.activeQuery.handleCommandComplete(msg, con);
});
//if a prepared statement has a name and properly parses
//we track that its already been executed so we don't parse
//it again on the same client
con.on('parseComplete', function(msg) {
if(self.activeQuery.name) {
con.parsedStatements[self.activeQuery.name] = true;
}
});
con.on('copyInResponse', function(msg) {
self.activeQuery.handleCopyInResponse(self.connection);
});
con.on('copyData', function (msg) {
self.activeQuery.handleCopyData(msg, self.connection);
});
con.on('notification', function(msg) {
self.emit('notification', msg);
});
//process possible callback argument to Client#connect
if (callback) {
callback(null, self);
//remove callback for proper error handling
//after the connect event
callback = null;
}
self.emit('connect');
});
con.on('readyForQuery', function() {
var activeQuery = self.activeQuery;
self.activeQuery = null;
self.readyForQuery = true;
self._pulseQueryQueue();
if(activeQuery) {
activeQuery.handleReadyForQuery();
}
});
con.on('error', function(error) {
if(self.activeQuery) {
var activeQuery = self.activeQuery;
self.activeQuery = null;
return activeQuery.handleError(error, con);
}
if(!callback) {
return self.emit('error', error);
}
callback(error);
callback = null;
});
con.once('end', function() {
if ( callback ) {
// haven't received a connection message yet !
var err = new Error('Connection terminated');
callback(err);
callback = null;
return;
}
if(self.activeQuery) {
var disconnectError = new Error('Connection terminated');
self.activeQuery.handleError(disconnectError, con);
self.activeQuery = null;
}
self.emit('end');
});
con.on('notice', function(msg) {
self.emit('notice', msg);
});
};
Client.prototype.getStartupConf = function() {
var params = this.connectionParameters;
var data = {
user: params.user,
database: params.database
};
var appName = params.application_name || params.fallback_application_name;
if (appName) {
data.application_name = appName;
}
return data;
};
Client.prototype.cancel = function(client, query) {
if(client.activeQuery == query) {
var con = this.connection;
if(this.host && this.host.indexOf('/') === 0) {
con.connect(this.host + '/.s.PGSQL.' + this.port);
} else {
con.connect(this.port, this.host);
}
//once connection is established send cancel message
con.on('connect', function() {
con.cancel(client.processID, client.secretKey);
});
} else if(client.queryQueue.indexOf(query) != -1) {
client.queryQueue.splice(client.queryQueue.indexOf(query), 1);
}
};
Client.prototype.setTypeParser = function(oid, format, parseFn) {
return this._types.setTypeParser(oid, format, parseFn);
};
Client.prototype.getTypeParser = function(oid, format) {
return this._types.getTypeParser(oid, format);
};
// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
Client.prototype.escapeIdentifier = function(str) {
var escaped = '"';
for(var i = 0; i < str.length; i++) {
var c = str[i];
if(c === '"') {
escaped += c + c;
} else {
escaped += c;
}
}
escaped += '"';
return escaped;
};
// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
Client.prototype.escapeLiteral = function(str) {
var hasBackslash = false;
var escaped = '\'';
for(var i = 0; i < str.length; i++) {
var c = str[i];
if(c === '\'') {
escaped += c + c;
} else if (c === '\\') {
escaped += c + c;
hasBackslash = true;
} else {
escaped += c;
}
}
escaped += '\'';
if(hasBackslash === true) {
escaped = ' E' + escaped;
}
return escaped;
};
Client.prototype._pulseQueryQueue = function() {
if(this.readyForQuery===true) {
this.activeQuery = this.queryQueue.shift();
if(this.activeQuery) {
this.readyForQuery = false;
this.hasExecuted = true;
this.activeQuery.submit(this.connection);
} else if(this.hasExecuted) {
this.activeQuery = null;
this.emit('drain');
}
}
};
Client.prototype.copyFrom = function (text) {
throw new Error("For PostgreSQL COPY TO/COPY FROM support npm install pg-copy-streams");
};
Client.prototype.copyTo = function (text) {
throw new Error("For PostgreSQL COPY TO/COPY FROM support npm install pg-copy-streams");
};
Client.prototype.query = function(config, values, callback) {
//can take in strings, config object or query object
var query = (typeof config.submit == 'function') ? config :
new Query(config, values, callback);
if(this.binary && !query.binary) {
query.binary = true;
}
if(query._result) {
query._result._getTypeParser = this._types.getTypeParser.bind(this._types);
}
this.queryQueue.push(query);
this._pulseQueryQueue();
return query;
};
Client.prototype.end = function() {
this.connection.end();
};
Client.md5 = function(string) {
return crypto.createHash('md5').update(string).digest('hex');
};
// expose a Query constructor
Client.Query = Query;
module.exports = Client;<|fim▁end|> | self.activeQuery.handlePortalSuspended(con); |
<|file_name|>s3fs.py<|end_file_name|><|fim▁begin|># Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you 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.
from __future__ import absolute_import
import sys
import errno
import itertools
import logging
import os
import posixpath
from boto.exception import S3ResponseError
from boto.s3.key import Key
from boto.s3.prefix import Prefix
from django.utils.translation import ugettext as _
from aws import s3
from aws.s3 import normpath, s3file, translate_s3_error, S3_ROOT
from aws.s3.s3stat import S3Stat
DEFAULT_READ_SIZE = 1024 * 1024 # 1MB
LOG = logging.getLogger(__name__)
class S3FileSystem(object):
def __init__(self, s3_connection):
self._s3_connection = s3_connection
self._bucket_cache = None
def _init_bucket_cache(self):
if self._bucket_cache is None:
buckets = self._s3_connection.get_all_buckets()
self._bucket_cache = {}
for bucket in buckets:
self._bucket_cache[bucket.name] = bucket
def _get_bucket(self, name):
self._init_bucket_cache()
if name not in self._bucket_cache:
self._bucket_cache[name] = self._s3_connection.get_bucket(name)
return self._bucket_cache[name]
def _get_or_create_bucket(self, name):
try:
bucket = self._get_bucket(name)
except S3ResponseError, e:
if e.status == 404:
bucket = self._s3_connection.create_bucket(name)
self._bucket_cache[name] = bucket
else:
raise e
return bucket
def _get_key(self, path, validate=True):
bucket_name, key_name = s3.parse_uri(path)[:2]
bucket = self._get_bucket(bucket_name)
try:
return bucket.get_key(key_name, validate=validate)
except:
e, exc, tb = sys.exc_info()
raise ValueError(e)
def _stats(self, path):
if s3.is_root(path):
return S3Stat.for_s3_root()
try:
key = self._get_key(path, validate=True)
except S3ResponseError as e:
if e.status == 404:
return None
else:
exc_class, exc, tb = sys.exc_info()
raise exc_class, exc, tb
if key is None:
key = self._get_key(path, validate=False)
return self._stats_key(key)
@staticmethod
def _stats_key(key):
if key.size is not None:
is_directory_name = not key.name or key.name[-1] == '/'
return S3Stat.from_key(key, is_dir=is_directory_name)
else:
key.name = S3FileSystem._append_separator(key.name)
ls = key.bucket.get_all_keys(prefix=key.name, max_keys=1)
if len(ls) > 0:
return S3Stat.from_key(key, is_dir=True)
return None
@staticmethod
def _append_separator(path):
if path and not path.endswith('/'):
path += '/'
return path
@staticmethod
def _cut_separator(path):
return path.endswith('/') and path[:-1] or path
@staticmethod
def isroot(path):
return s3.is_root(path)
@staticmethod
def join(*comp_list):
return s3.join(*comp_list)
@staticmethod
def normpath(path):
return normpath(path)
@staticmethod
def parent_path(path):
parent_dir = S3FileSystem._append_separator(path)
if not s3.is_root(parent_dir):
bucket_name, key_name, basename = s3.parse_uri(path)
if not basename: # bucket is top-level so return root
parent_dir = S3_ROOT
else:
bucket_path = '%s%s' % (S3_ROOT, bucket_name)
key_path = '/'.join(key_name.split('/')[:-1])
parent_dir = s3.abspath(bucket_path, key_path)
return parent_dir
@translate_s3_error
def open(self, path, mode='r'):
key = self._get_key(path, validate=True)
if key is None:
raise IOError(errno.ENOENT, "No such file or directory: '%s'" % path)
return s3file.open(key, mode=mode)
@translate_s3_error
def read(self, path, offset, length):
fh = self.open(path, 'r')
fh.seek(offset, os.SEEK_SET)
return fh.read(length)
@translate_s3_error
def isfile(self, path):
stat = self._stats(path)
if stat is None:
return False
return not stat.isDir
@translate_s3_error
def isdir(self, path):
stat = self._stats(path)
if stat is None:
return False
return stat.isDir
@translate_s3_error
def exists(self, path):
return self._stats(path) is not None
@translate_s3_error
def stats(self, path):
path = normpath(path)
stats = self._stats(path)
if stats:
return stats
raise IOError(errno.ENOENT, "No such file or directory: '%s'" % path)
@translate_s3_error
def listdir_stats(self, path, glob=None):
if glob is not None:
raise NotImplementedError(_("Option `glob` is not implemented"))
if s3.is_root(path):
self._init_bucket_cache()
return [S3Stat.from_bucket(b) for b in self._bucket_cache.values()]
bucket_name, prefix = s3.parse_uri(path)[:2]
bucket = self._get_bucket(bucket_name)
prefix = self._append_separator(prefix)
res = []
for item in bucket.list(prefix=prefix, delimiter='/'):
if isinstance(item, Prefix):
res.append(S3Stat.from_key(Key(item.bucket, item.name), is_dir=True))
else:
if item.name == prefix:
continue
res.append(self._stats_key(item))
return res
def listdir(self, path, glob=None):
return [s3.parse_uri(x.path)[2] for x in self.listdir_stats(path, glob)]
@translate_s3_error
def rmtree(self, path, skipTrash=False):
if not skipTrash:
raise NotImplementedError(_('Moving to trash is not implemented for S3'))
bucket_name, key_name = s3.parse_uri(path)[:2]
if bucket_name and not key_name:
raise NotImplementedError(_('Deleting a bucket is not implemented for S3'))
key = self._get_key(path, validate=False)
if key.exists():
to_delete = iter([key])<|fim▁hole|>
if self.isdir(path):
# add `/` to prevent removing of `s3://b/a_new` trying to remove `s3://b/a`
prefix = self._append_separator(key.name)
keys = key.bucket.list(prefix=prefix)
to_delete = itertools.chain(keys, to_delete)
result = key.bucket.delete_keys(to_delete)
if result.errors:
msg = "%d errors occurred during deleting '%s':\n%s" % (
len(result.errors),
'\n'.join(map(repr, result.errors)))
LOG.error(msg)
raise IOError(msg)
@translate_s3_error
def remove(self, path, skip_trash=False):
if not skip_trash:
raise NotImplementedError(_('Moving to trash is not implemented for S3'))
key = self._get_key(path, validate=False)
key.bucket.delete_key(key.name)
def restore(self, *args, **kwargs):
raise NotImplementedError(_('Moving to trash is not implemented for S3'))
@translate_s3_error
def mkdir(self, path, *args, **kwargs):
"""
Creates a directory and any parent directory if necessary.
Actually it creates an empty object: s3://[bucket]/[path]/
"""
bucket_name, key_name = s3.parse_uri(path)[:2]
self._get_or_create_bucket(bucket_name)
stats = self._stats(path)
if stats:
if stats.isDir:
return None
else:
raise IOError(errno.ENOTDIR, "'%s' already exists and is not a directory" % path)
path = self._append_separator(path) # folder-key should ends by /
self.create(path) # create empty object
@translate_s3_error
def copy(self, src, dst, recursive=False, *args, **kwargs):
self._copy(src, dst, recursive=recursive, use_src_basename=True)
@translate_s3_error
def copyfile(self, src, dst, *args, **kwargs):
if self.isdir(dst):
raise IOError(errno.EINVAL, "Copy dst '%s' is a directory" % dst)
self._copy(src, dst, recursive=False, use_src_basename=False)
@translate_s3_error
def copy_remote_dir(self, src, dst, *args, **kwargs):
self._copy(src, dst, recursive=True, use_src_basename=False)
def _copy(self, src, dst, recursive, use_src_basename):
src_st = self.stats(src)
if src_st.isDir and not recursive:
return # omitting directory
dst = s3.abspath(src, dst)
dst_st = self._stats(dst)
if src_st.isDir and dst_st and not dst_st.isDir:
raise IOError(errno.EEXIST, "Cannot overwrite non-directory '%s' with directory '%s'" % (dst, src))
src_bucket, src_key = s3.parse_uri(src)[:2]
dst_bucket, dst_key = s3.parse_uri(dst)[:2]
keep_src_basename = use_src_basename and dst_st and dst_st.isDir
src_bucket = self._get_bucket(src_bucket)
dst_bucket = self._get_bucket(dst_bucket)
if keep_src_basename:
cut = len(posixpath.dirname(src_key)) # cut of an parent directory name
if cut:
cut += 1
else:
cut = len(src_key)
if not src_key.endswith('/'):
cut += 1
for key in src_bucket.list(prefix=src_key):
if not key.name.startswith(src_key):
raise RuntimeError(_("Invalid key to transform: %s") % key.name)
dst_name = posixpath.normpath(s3.join(dst_key, key.name[cut:]))
key.copy(dst_bucket, dst_name)
@translate_s3_error
def rename(self, old, new):
new = s3.abspath(old, new)
self.copy(old, new, recursive=True)
self.rmtree(old, skipTrash=True)
@translate_s3_error
def rename_star(self, old_dir, new_dir):
if not self.isdir(old_dir):
raise IOError(errno.ENOTDIR, "'%s' is not a directory" % old_dir)
if self.isfile(new_dir):
raise IOError(errno.ENOTDIR, "'%s' is not a directory" % new_dir)
ls = self.listdir(old_dir)
for entry in ls:
self.rename(s3.join(old_dir, entry), s3.join(new_dir, entry))
@translate_s3_error
def create(self, path, overwrite=False, data=None):
key = self._get_key(path, validate=False)
key.set_contents_from_string(data or '', replace=overwrite)
@translate_s3_error
def copyFromLocal(self, local_src, remote_dst, *args, **kwargs):
local_src = self._cut_separator(local_src)
remote_dst = self._cut_separator(remote_dst)
def _copy_file(src, dst):
key = self._get_key(dst, validate=False)
fp = open(src, 'r')
key.set_contents_from_file(fp)
if os.path.isdir(local_src):
for (local_dir, sub_dirs, files) in os.walk(local_src, followlinks=False):
remote_dir = local_dir.replace(local_src, remote_dst)
if not sub_dirs and not files:
self.mkdir(remote_dir)
else:
for file_name in files:
_copy_file(os.path.join(local_dir, file_name), os.path.join(remote_dir, file_name))
else:
file_name = os.path.split(local_src)[1]
if self.isdir(remote_dst):
remote_file = os.path.join(remote_dst, file_name)
else:
remote_file = remote_dst
_copy_file(local_src, remote_file)
def setuser(self, user):
pass # user-concept doesn't have sense for this implementation<|fim▁end|> | else:
to_delete = iter([]) |
<|file_name|>output2csv.py<|end_file_name|><|fim▁begin|>import os, re, csv
# regular expressions for capturing the interesting quantities
noise_pattern = 'noise: \[(.+)\]'
res_pattern = '^([0-9.]+$)'
search_dir = "output"
results_file = '../results.csv'
os.chdir( search_dir )
files = filter( os.path.isfile, os.listdir( '.' ))
#files = [ os.path.join( search_dir, f ) for f in files ] # add path to each file
files.sort( key=lambda x: os.path.getmtime( x ))
results = []
for file in files:
f = open( file )
contents = f.read()
# noise
matches = re.search( noise_pattern, contents, re.DOTALL )
try:
noise = matches.group( 1 )
noise = noise.strip()
noise = noise.split()
except AttributeError:
print "noise error 1: %s" % ( contents )
continue
# rmse
matches = re.search( res_pattern, contents, re.M )
try:
res = matches.group( 1 )
except AttributeError:
print "matches error 2: %s" % ( contents )
continue
<|fim▁hole|>for result in results:
writer.writerow( result )<|fim▁end|> | results.append( [ res ] + noise )
writer = csv.writer( open( results_file, 'wb' )) |
<|file_name|>OuterIterator.java<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this<|fim▁hole|> * the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Sam
*/
package com.caucho.quercus.lib.spl;
import com.caucho.quercus.env.Value;
public interface OuterIterator
extends Iterator
{
public Value getInnerIterator();
}<|fim▁end|> | * notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by |
<|file_name|>note.js<|end_file_name|><|fim▁begin|>OSM.Note = function (map) {
var content = $("#sidebar_content"),
page = {},
halo, currentNote;
var noteIcons = {
"new": L.icon({
iconUrl: OSM.NEW_NOTE_MARKER,
iconSize: [25, 40],
iconAnchor: [12, 40]
}),
"open": L.icon({
iconUrl: OSM.OPEN_NOTE_MARKER,
iconSize: [25, 40],
iconAnchor: [12, 40]
}),
"closed": L.icon({
iconUrl: OSM.CLOSED_NOTE_MARKER,
iconSize: [25, 40],
iconAnchor: [12, 40]
})
};
function updateNote(form, method, url) {
$(form).find("input[type=submit]").prop("disabled", true);
$.ajax({
url: url,
type: method,
oauth: true,
data: { text: $(form.text).val() },
success: function () {
OSM.loadSidebarContent(window.location.pathname, page.load);
}
});
}
<|fim▁hole|> OSM.loadSidebarContent(path, function () {
initialize(function () {
var data = $(".details").data(),
latLng = L.latLng(data.coordinates.split(","));
if (!map.getBounds().contains(latLng)) moveToNote();
});
});
};
page.load = function () {
initialize(moveToNote);
};
function initialize(callback) {
content.find("input[type=submit]").on("click", function (e) {
e.preventDefault();
var data = $(e.target).data();
updateNote(e.target.form, data.method, data.url);
});
content.find("textarea").on("input", function (e) {
var form = e.target.form;
if ($(e.target).val() === "") {
$(form.close).val(I18n.t("javascripts.notes.show.resolve"));
$(form.comment).prop("disabled", true);
} else {
$(form.close).val(I18n.t("javascripts.notes.show.comment_and_resolve"));
$(form.comment).prop("disabled", false);
}
});
content.find("textarea").val("").trigger("input");
var data = $(".details").data(),
latLng = L.latLng(data.coordinates.split(","));
if (!map.hasLayer(halo)) {
halo = L.circleMarker(latLng, {
weight: 2.5,
radius: 20,
fillOpacity: 0.5,
color: "#FF6200"
});
map.addLayer(halo);
}
if (map.hasLayer(currentNote)) map.removeLayer(currentNote);
currentNote = L.marker(latLng, {
icon: noteIcons[data.status],
opacity: 1,
interactive: true
});
map.addLayer(currentNote);
if (callback) callback();
}
function moveToNote() {
var data = $(".details").data(),
latLng = L.latLng(data.coordinates.split(","));
if (!window.location.hash || window.location.hash.match(/^#?c[0-9]+$/)) {
OSM.router.withoutMoveListener(function () {
map.setView(latLng, 15, { reset: true });
});
}
}
page.unload = function () {
if (map.hasLayer(halo)) map.removeLayer(halo);
if (map.hasLayer(currentNote)) map.removeLayer(currentNote);
};
return page;
};<|fim▁end|> | page.pushstate = page.popstate = function (path) { |
<|file_name|>spr2d.cpp<|end_file_name|><|fim▁begin|>/*
Copyright (C) 2000-2001 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csqsqrt.h"
#include "csgeom/box.h"
#include "csgeom/math.h"
#include "csgeom/math3d.h"
#include "csgeom/math2d.h"
#include "csgeom/transfrm.h"
#include "csgfx/renderbuffer.h"
#include "cstool/rbuflock.h"
#include "cstool/rviewclipper.h"
#include "csutil/scfarray.h"
#include "ivaria/reporter.h"
#include "iengine/movable.h"
#include "iengine/rview.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "ivideo/material.h"
#include "ivideo/rendermesh.h"
#include "iengine/material.h"
#include "iengine/camera.h"
#include "igeom/clip2d.h"
#include "iengine/engine.h"
#include "iengine/light.h"
#include "iutil/objreg.h"
#include "spr2d.h"
CS_PLUGIN_NAMESPACE_BEGIN(Spr2D)
{
CS_LEAKGUARD_IMPLEMENT (csSprite2DMeshObject);
CS_LEAKGUARD_IMPLEMENT (csSprite2DMeshObject::RenderBufferAccessor);
CS_LEAKGUARD_IMPLEMENT (csSprite2DMeshObjectFactory);
csSprite2DMeshObject::csSprite2DMeshObject (csSprite2DMeshObjectFactory* factory) :
scfImplementationType (this), uvani (0), vertices_dirty (true),
texels_dirty (true), colors_dirty (true), indicesSize ((size_t)-1),
logparent (0), factory (factory), initialized (false), current_lod (1),
current_features (0)
{
ifactory = scfQueryInterface<iMeshObjectFactory> (factory);
material = factory->GetMaterialWrapper ();
lighting = factory->HasLighting ();
MixMode = factory->GetMixMode ();
}
csSprite2DMeshObject::~csSprite2DMeshObject ()
{
delete uvani;
}
iColoredVertices* csSprite2DMeshObject::GetVertices ()
{
if (!scfVertices.IsValid())
return factory->GetVertices ();
return scfVertices;
}
csColoredVertices* csSprite2DMeshObject::GetCsVertices ()
{
if (!scfVertices.IsValid())
return factory->GetCsVertices ();
return &vertices;
}
void csSprite2DMeshObject::SetupObject ()
{
if (!initialized)
{
initialized = true;
float max_sq_dist = 0;
size_t i;
csColoredVertices* vertices = GetCsVertices ();
bbox_2d.StartBoundingBox((*vertices)[0].pos);
for (i = 0 ; i < vertices->GetSize () ; i++)
{
csSprite2DVertex& v = (*vertices)[i];
bbox_2d.AddBoundingVertexSmart(v.pos);
if (!lighting)
{
// If there is no lighting then we need to copy the color_init
// array to color.
v.color = (*vertices)[i].color_init;
v.color.Clamp (2, 2, 2);
}
float sqdist = v.pos.x*v.pos.x + v.pos.y*v.pos.y;
if (sqdist > max_sq_dist) max_sq_dist = sqdist;
}
radius = csQsqrt (max_sq_dist);
bufferHolder.AttachNew (new csRenderBufferHolder);
csRef<iRenderBufferAccessor> newAccessor;
newAccessor.AttachNew (new RenderBufferAccessor (this));
bufferHolder->SetAccessor (newAccessor, (uint32)CS_BUFFER_ALL_MASK);
svcontext.AttachNew (new csShaderVariableContext);
}
}
static csVector3 cam;
void csSprite2DMeshObject::UpdateLighting (
const csSafeCopyArray<csLightInfluence>& lights,
const csVector3& pos)
{
if (!lighting) return;
csColor color (0, 0, 0);
// @@@ GET AMBIENT
//csSector* sect = movable.GetSector (0);
//if (sect)
//{
//int r, g, b;
//sect->GetAmbientColor (r, g, b);
//color.Set (r / 128.0, g / 128.0, b / 128.0);
//}
int i;
int num_lights = (int)lights.GetSize ();
for (i = 0; i < num_lights; i++)
{
iLight* li = lights[i].light;
if (!li)
continue;
csColor light_color = li->GetColor ()
* (256. / CS_NORMAL_LIGHT_LEVEL);
float sq_light_radius = csSquare (li->GetCutoffDistance ());
// Compute light position.
csVector3 wor_light_pos = li->GetMovable ()->GetFullPosition ();
float wor_sq_dist =
csSquaredDist::PointPoint (wor_light_pos, pos);
if (wor_sq_dist >= sq_light_radius) continue;
float wor_dist = csQsqrt (wor_sq_dist);
float cosinus = 1.0f;
cosinus /= wor_dist;
light_color *= cosinus * li->GetBrightnessAtDistance (wor_dist);
color += light_color;
}
csColoredVertices* vertices = GetCsVertices ();
for (size_t j = 0 ; j < vertices->GetSize () ; j++)
{
(*vertices)[j].color = (*vertices)[j].color_init + color;
(*vertices)[j].color.Clamp (2, 2, 2);
}
colors_dirty = true;
}
void csSprite2DMeshObject::UpdateLighting (
const csSafeCopyArray<csLightInfluence>& lights,
iMovable* movable, csVector3 offset)
{
if (!lighting) return;
csVector3 pos = movable->GetFullPosition ();
UpdateLighting (lights, pos + offset);
}
csRenderMesh** csSprite2DMeshObject::GetRenderMeshes (int &n,
iRenderView* rview,
iMovable* movable,
uint32 frustum_mask,
csVector3 offset)
{
SetupObject ();
if (!material)
{
csReport (factory->object_reg, CS_REPORTER_SEVERITY_ERROR,
"crystalspace.mesh.sprite2d",
"Error! Trying to draw a sprite with no material!");
return 0;
}
iCamera* camera = rview->GetCamera ();
// Camera transformation for the single 'position' vector.
cam = rview->GetCamera ()->GetTransform ().Other2This (
movable->GetFullPosition () + offset);
if (cam.z < SMALL_Z)
{
n = 0;
return 0;
}
if (factory->light_mgr)
{
csSafeCopyArray<csLightInfluence> lightInfluences;
scfArrayWrap<iLightInfluenceArray, csSafeCopyArray<csLightInfluence> >
relevantLights (lightInfluences); //Yes, know, its on the stack...
factory->light_mgr->GetRelevantLights (logparent, &relevantLights, -1);
UpdateLighting (lightInfluences, movable, offset);
}
csReversibleTransform temp = camera->GetTransform ();
if (!movable->IsFullTransformIdentity ())
temp /= movable->GetFullTransform ();
int clip_portal, clip_plane, clip_z_plane;
CS::RenderViewClipper::CalculateClipSettings (rview->GetRenderContext (),
frustum_mask, clip_portal, clip_plane, clip_z_plane);
csReversibleTransform tr_o2c;
tr_o2c.SetO2TTranslation (-temp.Other2This (offset));
bool meshCreated;
csRenderMesh*& rm = rmHolder.GetUnusedMesh (meshCreated,
rview->GetCurrentFrameNumber ());
if (meshCreated)
{
rm->meshtype = CS_MESHTYPE_TRIANGLEFAN;
rm->buffers = bufferHolder;
rm->variablecontext = svcontext;
rm->geometryInstance = this;
}
rm->material = material;//Moved this statement out of the above 'if'
//to make the change of the material possible at any time
//(thru a call to either iSprite2DState::SetMaterialWrapper () or
//csSprite2DMeshObject::SetMaterialWrapper (). Luca
rm->mixmode = MixMode;
rm->clip_portal = clip_portal;
rm->clip_plane = clip_plane;
rm->clip_z_plane = clip_z_plane;
rm->do_mirror = false/* camera->IsMirrored () */;
/*
Force to false as the front-face culling will let the sprite
disappear.
*/
rm->indexstart = 0;
rm->worldspace_origin = movable->GetFullPosition ();
rm->object2world = tr_o2c.GetInverse () * camera->GetTransform ();
rm->bbox = GetObjectBoundingBox();
rm->indexend = (uint)GetCsVertices ()->GetSize ();
n = 1;
return &rm;
}
void csSprite2DMeshObject::PreGetBuffer (csRenderBufferHolder* holder, csRenderBufferName buffer)
{
if (!holder) return;
csColoredVertices* vertices = GetCsVertices ();
if (buffer == CS_BUFFER_INDEX)
{
size_t indexSize = vertices->GetSize ();
if (!index_buffer.IsValid() ||
(indicesSize != indexSize))
{
index_buffer = csRenderBuffer::CreateIndexRenderBuffer (
indexSize, CS_BUF_DYNAMIC,
CS_BUFCOMP_UNSIGNED_INT, 0, vertices->GetSize () - 1);
holder->SetRenderBuffer (CS_BUFFER_INDEX, index_buffer);
csRenderBufferLock<uint> indexLock (index_buffer);
uint* ptr = indexLock;
for (size_t i = 0; i < vertices->GetSize (); i++)
{
*ptr++ = (uint)i;
}
indicesSize = indexSize;
}
}
else if (buffer == CS_BUFFER_TEXCOORD0)
{
if (texels_dirty)
{
int texels_count;
const csVector2 *uvani_uv = 0;
if (!uvani)
texels_count = (int)vertices->GetSize ();
else
uvani_uv = uvani->GetVertices (texels_count);
size_t texelSize = texels_count;
if (!texel_buffer.IsValid() || (texel_buffer->GetSize()
!= texelSize * sizeof(float) * 2))
{
texel_buffer = csRenderBuffer::CreateRenderBuffer (
texelSize, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 2);
holder->SetRenderBuffer (CS_BUFFER_TEXCOORD0, texel_buffer);
}
csRenderBufferLock<csVector2> texelLock (texel_buffer);
for (size_t i = 0; i < (size_t)texels_count; i++)
{
csVector2& v = texelLock[i];
if (!uvani)
{
v.x = (*vertices)[i].u;
v.y = (*vertices)[i].v;
}
else
{
v.x = uvani_uv[i].x;
v.y = uvani_uv[i].y;
}
}
texels_dirty = false;
}
}
else if (buffer == CS_BUFFER_COLOR)
{
if (colors_dirty)
{
size_t color_size = vertices->GetSize ();
if (!color_buffer.IsValid() || (color_buffer->GetSize()
!= color_size * sizeof(float) * 2))
{
color_buffer = csRenderBuffer::CreateRenderBuffer (
color_size, CS_BUF_STATIC,
CS_BUFCOMP_FLOAT, 3);
holder->SetRenderBuffer (CS_BUFFER_COLOR, color_buffer);
}
csRenderBufferLock<csColor> colorLock (color_buffer);
for (size_t i = 0; i < vertices->GetSize (); i++)
{
colorLock[i] = (*vertices)[i].color;
}
colors_dirty = false;
}
}
else if (buffer == CS_BUFFER_POSITION)
{
if (vertices_dirty)
{
size_t vertices_size = vertices->GetSize ();
if (!vertex_buffer.IsValid() || (vertex_buffer->GetSize()
!= vertices_size * sizeof(float) * 3))
{
vertex_buffer = csRenderBuffer::CreateRenderBuffer (
vertices_size, CS_BUF_STATIC,
CS_BUFCOMP_FLOAT, 3);
holder->SetRenderBuffer (CS_BUFFER_POSITION, vertex_buffer);
}
csRenderBufferLock<csVector3> vertexLock (vertex_buffer);
for (size_t i = 0; i < vertices->GetSize (); i++)
{
vertexLock[i].Set ((*vertices)[i].pos.x, (*vertices)[i].pos.y, 0.0f);
}
vertices_dirty = false;
}
}
}
const csBox3& csSprite2DMeshObject::GetObjectBoundingBox ()
{
SetupObject ();
obj_bbox.Set (-radius, radius);
return obj_bbox;
}
void csSprite2DMeshObject::SetObjectBoundingBox (const csBox3&)
{
// @@@ TODO
}
void csSprite2DMeshObject::HardTransform (const csReversibleTransform& t)
{
(void)t;
//@@@ TODO
}
void csSprite2DMeshObject::CreateRegularVertices (int n, bool setuv)
{
double angle_inc = TWO_PI / n;
double angle = 0.0;
csColoredVertices* vertices = GetCsVertices ();
vertices->SetSize (n);
size_t i;
for (i = 0; i < vertices->GetSize (); i++, angle += angle_inc)
{
(*vertices) [i].pos.y = cos (angle);
(*vertices) [i].pos.x = sin (angle);
if (setuv)
{
// reuse sin/cos values and scale to [0..1]
(*vertices) [i].u = (*vertices) [i].pos.x / 2.0f + 0.5f;
(*vertices) [i].v = (*vertices) [i].pos.y / 2.0f + 0.5f;
}
(*vertices) [i].color.Set (1, 1, 1);
(*vertices) [i].color_init.Set (1, 1, 1);
}
vertices_dirty = true;
texels_dirty = true;
colors_dirty = true;
ShapeChanged ();
}
void csSprite2DMeshObject::NextFrame (csTicks current_time,
const csVector3& /*pos*/, uint /*currentFrame*/)
{
if (uvani && !uvani->halted)
{
int old_frame_index = uvani->frameindex;
uvani->Advance (current_time);
texels_dirty |= (old_frame_index != uvani->frameindex);
}
}
void csSprite2DMeshObject::UpdateLighting (
const csSafeCopyArray<csLightInfluence>& lights,
const csReversibleTransform& transform)
{<|fim▁hole|>}
void csSprite2DMeshObject::AddColor (const csColor& col)
{
iColoredVertices* vertices = GetVertices ();
size_t i;
for (i = 0 ; i < vertices->GetSize(); i++)
vertices->Get (i).color_init += col;
if (!lighting)
for (i = 0 ; i < vertices->GetSize(); i++)
vertices->Get (i).color = vertices->Get (i).color_init;
colors_dirty = true;
}
bool csSprite2DMeshObject::SetColor (const csColor& col)
{
iColoredVertices* vertices = GetVertices ();
size_t i;
for (i = 0 ; i < vertices->GetSize(); i++)
vertices->Get (i).color_init = col;
if (!lighting)
for (i = 0 ; i < vertices->GetSize(); i++)
vertices->Get (i).color = col;
colors_dirty = true;
return true;
}
void csSprite2DMeshObject::ScaleBy (float factor)
{
iColoredVertices* vertices = GetVertices ();
size_t i;
for (i = 0 ; i < vertices->GetSize(); i++)
vertices->Get (i).pos *= factor;
vertices_dirty = true;
ShapeChanged ();
}
void csSprite2DMeshObject::Rotate (float angle)
{
iColoredVertices* vertices = GetVertices ();
size_t i;
for (i = 0 ; i < vertices->GetSize(); i++)
vertices->Get (i).pos.Rotate (angle);
vertices_dirty = true;
ShapeChanged ();
}
void csSprite2DMeshObject::SetUVAnimation (const char *name,
int style, bool loop)
{
if (name)
{
iSprite2DUVAnimation *ani = factory->GetUVAnimation (name);
if (ani && ani->GetFrameCount ())
{
uvani = new uvAnimationControl ();
uvani->ani = ani;
uvani->last_time = 0;
uvani->frameindex = 0;
uvani->framecount = ani->GetFrameCount ();
uvani->frame = ani->GetFrame (0);
uvani->style = style;
uvani->counter = 0;
uvani->loop = loop;
uvani->halted = false;
}
}
else
{
// stop animation and show the normal texture
delete uvani;
uvani = 0;
}
}
void csSprite2DMeshObject::StopUVAnimation (int idx)
{
if (uvani)
{
if (idx != -1)
{
uvani->frameindex = csMin (csMax (idx, 0), uvani->framecount-1);
uvani->frame = uvani->ani->GetFrame (uvani->frameindex);
}
uvani->halted = true;
}
}
void csSprite2DMeshObject::PlayUVAnimation (int idx, int style, bool loop)
{
if (uvani)
{
if (idx != -1)
{
uvani->frameindex = csMin (csMax (idx, 0), uvani->framecount-1);
uvani->frame = uvani->ani->GetFrame (uvani->frameindex);
}
uvani->halted = false;
uvani->counter = 0;
uvani->last_time = 0;
uvani->loop = loop;
uvani->style = style;
}
}
int csSprite2DMeshObject::GetUVAnimationCount () const
{
return factory->GetUVAnimationCount ();
}
iSprite2DUVAnimation *csSprite2DMeshObject::CreateUVAnimation ()
{
return factory->CreateUVAnimation ();
}
void csSprite2DMeshObject::RemoveUVAnimation (
iSprite2DUVAnimation *anim)
{
factory->RemoveUVAnimation (anim);
}
iSprite2DUVAnimation *csSprite2DMeshObject::GetUVAnimation (
const char *name) const
{
return factory->GetUVAnimation (name);
}
iSprite2DUVAnimation *csSprite2DMeshObject::GetUVAnimation (
int idx) const
{
return factory->GetUVAnimation (idx);
}
iSprite2DUVAnimation *csSprite2DMeshObject::GetUVAnimation (
int idx, int &style, bool &loop) const
{
style = uvani->style;
loop = uvani->loop;
return factory->GetUVAnimation (idx);
}
void csSprite2DMeshObject::EnsureVertexCopy ()
{
if (!scfVertices.IsValid())
{
scfVertices.AttachNew (new scfArrayWrap<iColoredVertices,
csColoredVertices> (vertices));
vertices = *(factory->GetCsVertices());
}
}
void csSprite2DMeshObject::uvAnimationControl::Advance (csTicks current_time)
{
int oldframeindex = frameindex;
// the goal is to find the next frame to show
if (style < 0)
{ // every (-1*style)-th frame show a new pic
counter--;
if (counter < style)
{
counter = 0;
frameindex++;
if (frameindex == framecount)
{
if (loop)
frameindex = 0;
else
{
frameindex = framecount-1;
halted = true;
}
}
}
}
else if (style > 0)
{ // skip to next frame every <style> millisecond
if (last_time == 0)
last_time = current_time;
counter += (current_time - last_time);
last_time = current_time;
while (counter > style)
{
counter -= style;
frameindex++;
if (frameindex == framecount)
{
if (loop)
frameindex = 0;
else
{
frameindex = framecount-1;
halted = true;
}
}
}
}
else
{ // style == 0 -> use time indices attached to the frames
if (last_time == 0)
last_time = current_time;
while (frame->GetDuration () + last_time < current_time)
{
frameindex++;
if (frameindex == framecount)
{
if (loop)
{
frameindex = 0;
}
else
{
frameindex = framecount-1;
halted = true;
break;
}
}
}
last_time += frame->GetDuration ();
frame = ani->GetFrame (frameindex);
}
if (oldframeindex != frameindex)
frame = ani->GetFrame (frameindex);
}
const csVector2 *csSprite2DMeshObject::uvAnimationControl::GetVertices (
int &num)
{
num = frame->GetUVCount ();
return frame->GetUVCoo ();
}
// The hit beam methods in sprite2d make a couple of small presumptions.
// 1) The sprite is always facing the start of the beam.
// 2) Since it is always facing the beam, only one side
// of its bounding box can be hit (if at all).
void csSprite2DMeshObject::CheckBeam (const csVector3& /*start*/,
const csVector3& pl, float sqr, csMatrix3& o2t)
{
// This method is an optimized version of LookAt() based on
// the presumption that the up vector is always (0,1,0).
// This is used to create a transform to move the intersection
// to the sprites vector space, then it is tested against the 2d
// coords, which are conveniently located at z=0.
// The transformation matrix is stored and used again if the
// start vector for the beam is in the same position. MHV.
csVector3 pl2 = pl * csQisqrt (sqr);
csVector3 v1( pl2.z, 0, -pl2.x);
sqr = v1*v1;
v1 *= csQisqrt(sqr);
csVector3 v2(pl2.y * v1.z, pl2.z * v1.x - pl2.x * v1.z, -pl2.y * v1.x);
o2t.Set (v1.x, v2.x, pl2.x,
v1.y, v2.y, pl2.y,
v1.z, v2.z, pl2.z);
}
bool csSprite2DMeshObject::HitBeamOutline(const csVector3& start,
const csVector3& end, csVector3& isect, float* pr)
{
csVector2 cen = bbox_2d.GetCenter();
csVector3 pl = start - csVector3(cen.x, cen.y, 0);
float sqr = pl * pl;
if (sqr < SMALL_EPSILON) return false; // Too close, Cannot intersect
float dist;
csIntersect3::SegmentPlane(start, end, pl, 0, isect, dist);
if (pr) { *pr = dist; }
csMatrix3 o2t;
CheckBeam (start, pl, sqr, o2t);
csVector3 r = o2t * isect;
csColoredVertices* vertices = GetCsVertices ();
int trail, len = (int)vertices->GetSize ();
trail = len - 1;
csVector2 isec(r.x, r.y);
int i;
for (i = 0; i < len; trail = i++)
{
if (csMath2::WhichSide2D(isec, (*vertices)[trail].pos, (*vertices)[i].pos) > 0)
return false;
}
return true;
}
bool csSprite2DMeshObject::HitBeamObject (const csVector3& start, const csVector3& end,
csVector3& isect, float* pr, int* polygon_idx,
iMaterialWrapper** material, bool bf)
{
if (material) *material = csSprite2DMeshObject::material;
if (polygon_idx) *polygon_idx = -1;
return HitBeamOutline (start, end, isect, pr);
}
//----------------------------------------------------------------------
csSprite2DMeshObjectFactory::csSprite2DMeshObjectFactory (iMeshObjectType* pParent,
iObjectRegistry* object_reg) : scfImplementationType (this, pParent),
material (0), logparent (0), spr2d_type (pParent), MixMode (0),
lighting (true), object_reg (object_reg)
{
light_mgr = csQueryRegistry<iLightManager> (object_reg);
g3d = csQueryRegistry<iGraphics3D> (object_reg);
scfVertices.AttachNew (new scfArrayWrap<iColoredVertices,
csColoredVertices> (vertices));
ax = -10;
}
csSprite2DMeshObjectFactory::~csSprite2DMeshObjectFactory ()
{
}
csPtr<iMeshObject> csSprite2DMeshObjectFactory::NewInstance ()
{
csRef<csSprite2DMeshObject> cm;
cm.AttachNew (new csSprite2DMeshObject (this));
csRef<iMeshObject> im (scfQueryInterface<iMeshObject> (cm));
return csPtr<iMeshObject> (im);
}
//----------------------------------------------------------------------
SCF_IMPLEMENT_FACTORY (csSprite2DMeshObjectType)
csSprite2DMeshObjectType::csSprite2DMeshObjectType (iBase* pParent) :
scfImplementationType (this, pParent)
{
}
csSprite2DMeshObjectType::~csSprite2DMeshObjectType ()
{
}
csPtr<iMeshObjectFactory> csSprite2DMeshObjectType::NewFactory ()
{
csRef<csSprite2DMeshObjectFactory> cm;
cm.AttachNew (new csSprite2DMeshObjectFactory (this,
object_reg));
csRef<iMeshObjectFactory> ifact =
scfQueryInterface<iMeshObjectFactory> (cm);
return csPtr<iMeshObjectFactory> (ifact);
}
bool csSprite2DMeshObjectType::Initialize (iObjectRegistry* object_reg)
{
csSprite2DMeshObjectType::object_reg = object_reg;
return true;
}
}
CS_PLUGIN_NAMESPACE_END(Spr2D)<|fim▁end|> | csVector3 new_pos = transform.This2Other (part_pos);
UpdateLighting (lights, new_pos); |
<|file_name|>lock.py<|end_file_name|><|fim▁begin|>from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-LockWorkStation',
'Author': ['@harmj0y'],
'Description': ("Locks the workstation's display."),
'Background' : False,
'OutputExtension' : None,
'NeedsAdmin' : False,
'OpsecSafe' : False,
'Language' : 'powershell',
'MinLanguageVersion' : '2',
'Comments': [
'http://poshcode.org/1640'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to run module on.',
'Required' : True,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self):
script = """
Function Invoke-LockWorkStation {
# region define P/Invoke types dynamically
# stolen from PowerSploit https://github.com/mattifestation/PowerSploit/blob/master/Mayhem/Mayhem.psm1
# thanks matt and chris :)
$DynAssembly = New-Object System.Reflection.AssemblyName('Win32')
$AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('Win32', $False)
$TypeBuilder = $ModuleBuilder.DefineType('Win32.User32', 'Public, Class')
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))<|fim▁hole|> @('User32.dll'),
[Reflection.FieldInfo[]]@($SetLastError),
@($True))
# Define [Win32.User32]::LockWorkStation()
$PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('LockWorkStation',
'User32.dll',
([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static),
[Reflection.CallingConventions]::Standard,
[Bool],
[Type[]]@(),
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Ansi)
$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
$User32 = $TypeBuilder.CreateType()
$Null = $User32::LockWorkStation()
}
Invoke-LockWorkStation; "Workstation locked."
"""
return script<|fim▁end|> | $SetLastError = [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor, |
<|file_name|>server.ts<|end_file_name|><|fim▁begin|>'use strict';<|fim▁hole|> createConnection, IConnection, TextDocumentSyncKind,
TextDocuments, Diagnostic, DiagnosticSeverity, TextDocumentPositionParams,
InitializeParams, InitializeResult,
CompletionItem, CompletionItemKind, Files, Definition, CodeActionParams, Command, DidChangeTextDocumentParams
} from 'vscode-languageserver';
import { CompletionItemFactory } from "./Factory/CompletionItemFactory";
import { TypescriptImporter } from "./Settings/TypeScriptImporterSettings";
import ImportCache = require('./Cache/ImportCache');
import ICacheFile = require('./Cache/ICacheFile');
import CommunicationMethods = require('./Methods/CommunicationMethods');
import IFramework = require('./Cache/IFramework');
import { CompletionGlobals } from "./Factory/Helper/CompletionGlobals";
import { PrototypeAdditions } from "./d";
import OS = require('os');
import fs = require('fs');
/// Can't seem to get this to self instantiate in a node context and actually apply
PrototypeAdditions();
// Create a connection for the server. The connection uses
// stdin / stdout for message passing
let connection: IConnection = createConnection(new IPCMessageReader(process), new IPCMessageWriter(process));
// After the server has started the client sends an initilize request. The server receives
// in the passed params the rootPath of the workspace plus the client capabilites.
connection.onInitialize((params): InitializeResult => {
CompletionGlobals.Root = params.rootPath.replace(/\\/g, '/');
return {
capabilities: {
// Tell the client that the server support code complete
completionProvider: {
resolveProvider: true
},
/// Need full sync
textDocumentSync: TextDocumentSyncKind.Full
}
}
});
// /// =================================
// /// Configuration
// /// =================================
/// Maximum amount of imports
let maxNumberOfImports: number;
/// Show namespace on imports
let showNamespaceOnImports: boolean;
// The settings have changed. Is send on server activation
// as well.
connection.onDidChangeConfiguration((change) => {
const settings = change.settings.TypeScriptImporter as TypescriptImporter;
showNamespaceOnImports = settings.showNamespaceOnImports || true;
CompletionItemFactory.ShowNamespace = showNamespaceOnImports;
});
/// =================================
/// Importer code
/// =================================
let _importCache = new ImportCache();
let _targetString: string;
let _targetLine: number;
let _fileArray: string[] = [];
let documents = new TextDocuments();
documents.listen(connection);
/// Listen for when we get a notification for a namespace update
connection.onNotification(CommunicationMethods.NAMESPACE_UPDATE, (params: ICacheFile) => {
if(params){
_importCache.register(params);
}
});
3
/// Listen for when we get a notification for a tsconfig update
connection.onNotification(CommunicationMethods.TSCONFIG_UPDATE, (params: IFramework) => {
if(params){
_importCache.registerFramework(params);
}
})
/// Listen for when we get a notification for a tsconfig update
connection.onNotification(CommunicationMethods.RESYNC, () => {
_importCache.reset();
})
/**
* When a completion is requested, see if it's an import
*/
connection.onCompletion((textDocumentPosition: TextDocumentPositionParams): CompletionItem[] => {
try {
// There's no quick way of getting this information without keeping the files permanently in memory...
// TODO: Can we add some validation here so that we bomb out quicker?
let text;
/// documents doesn't automatically update
if(_fileArray[textDocumentPosition.textDocument.uri]){
text = _fileArray[textDocumentPosition.textDocument.uri];
} else {
/// Get this if we don't have anything in cache
text = documents.get(textDocumentPosition.textDocument.uri).getText();
}
const input = text.split(OS.EOL);
_targetLine = textDocumentPosition.position.line;
_targetString = input[_targetLine];
CompletionGlobals.Uri = decodeURIComponent(textDocumentPosition.textDocument.uri).replace("file:///", "");
/// If we are not on an import, we don't care
if(_targetString.indexOf("import") !== -1){
return _importCache.getOnImport(CompletionItemFactory.getItemCommonJS, CompletionItemFactory.getItem);
/// Make sure it's not a comment (i think?)
} else if(!_targetString.match(/(\/\/|\*|\w\.$)/)) {
return _importCache.getOnImport(CompletionItemFactory.getInlineItemCommonJS, CompletionItemFactory.getInlineItem);
}
} catch(e) {
console.warn("Typescript Import: Unable to creation completion items");
return [];
}
});
/**
* This is now mandatory
*/
connection.onCompletionResolve((item: CompletionItem): CompletionItem => {
if(item.data && item.data === 365) {
item.detail = item.label;
}
return item;
});
/**
*
*/
connection.onDidChangeTextDocument((params: DidChangeTextDocumentParams) => {
/// We have to manually remember this on the server
/// NOTE: don't query doucments if this isn't available
_fileArray[params.textDocument.uri] = params.contentChanges[0].text;
/// If we have no target, make sure the user hasn't tried to undo and left behind our hidden characters, otherwise the plugin appears to stop working
if(!_targetString) {
if(_fileArray[params.textDocument.uri].indexOf("\u200B\u200B") > -1) {
/// Inform the client to do the change (faster than node FS)
connection.sendNotification(
CommunicationMethods.UNDO_SAVE_REQUEST,
/// CompletionGlobals.Uri?
[decodeURIComponent(params.textDocument.uri.replace("file:///", ""))]
);
}
} else {
const content = params.contentChanges[0].text;
const contentString = content.split(OS.EOL)[_targetLine];
/// If there has been a change, aka the user has selected the option
if(contentString && contentString !== _targetString && !contentString.match(/(\/\/|\*|\w\.$)/)) {
/// Get the type if we're typing inline
let result: RegExpExecArray;
let subString = contentString;
/// May be multiple results, loop over to see if any match
while(result = /([:|=]\s*?)?(\w+)[\u200B\u200B]/.exec(subString)) {
if(result.length >= 3) {
let target = _importCache.getFromMethodName(result[2]);
if(target){
/// Inform the client to do the change (faster than node FS)
connection.sendNotification(
CommunicationMethods.SAVE_REQUEST,
/// CompletionGlobals.Uri?
[decodeURIComponent(params.textDocument.uri.replace("file:///", "")),
target,
_targetLine]
);
_targetString = null;
_targetLine = 0;
break;
}
}
/// shorten
subString = subString.slice(result.index + result.length)
}
if(!contentString.match(/(\w+)[\)|\s]?/)) {
_targetString = null;
_targetLine = 0;
}
}
}
});
// Listen on the connection
connection.listen();<|fim▁end|> |
import {
IPCMessageReader, IPCMessageWriter, |
<|file_name|>listener.py<|end_file_name|><|fim▁begin|>from typing import Callable, Any
from ..model import MetaEvent, Event
from ..exceptions import PropertyStatechartError
__all__ = ['InternalEventListener', 'PropertyStatechartListener']
class InternalEventListener:
"""
Listener that filters and propagates internal events as external events.
"""
def __init__(self, callable: Callable[[Event], Any]) -> None:
self._callable = callable
def __call__(self, event: MetaEvent) -> None:
if event.name == 'event sent':
self._callable(Event(event.event.name, **event.event.data))
class PropertyStatechartListener:
"""
Listener that propagates meta-events to given property statechart, executes
the property statechart, and checks it.
"""<|fim▁hole|> self._interpreter = interpreter
def __call__(self, event: MetaEvent) -> None:
self._interpreter.queue(event)
self._interpreter.execute()
if self._interpreter.final:
raise PropertyStatechartError(self._interpreter)<|fim▁end|> |
def __init__(self, interpreter) -> None: |
<|file_name|>layer.go<|end_file_name|><|fim▁begin|>package storage
import (
"sync"
)
// layer is a storage primitive with optional passthrough
// to underlying layers.
//
// Layer stores values that were modified locally and
// uses recursive get() calls if the key wasn't found locally.
//
// When asked for commit(), the layer dumps its contents to the level
// under it and calls commit(). Commit wave recurses to the root level.
//
// When asked for rollback(), the parent layer is returned - and local changes are
// forgotten.
type layer struct {
// parentLayer is this layer's parent - either
// parent transaction or root layer.
parentLayer *layer
// data stores the values.
data map[string]*valueState
// valueCache keeps count for each unique value in the layer
// and caches the counts coming from the underlying layers.
valueCache map[string]uint64
// isClosed is true if this layer was committed or rolled back.
isClosed bool
mu sync.Mutex
}
func newLayer() *layer {
return &layer{
data: map[string]*valueState{},
valueCache: map[string]uint64{},
}
}
func (t *layer) set(key string, value valueState) {
var isLocal bool
value.Prev, isLocal = t.getIsLocal(key)
// Crop unneeded leaves, save memory
// 3 -> 2 -> 1 becomes 3 -> 1
// Don't cross the layer's boundaries
if isLocal && value.Prev != nil && value.Prev.Prev != nil {
value.Prev = value.Prev.Prev<|fim▁hole|>}
func (t *layer) unset(key string) {
newValue := valueState{Data: "", Prev: t.get(key), Deleted: true}
t.data[key] = &newValue
t.refreshCacheForValue(newValue)
}
// get returns the value by its key.
func (t *layer) get(key string) *valueState {
ret, _ := t.getIsLocal(key)
return ret
}
// getIsLocal returns a valueState for the key.
// Second param is true if the value was found locally.
func (t *layer) getIsLocal(key string) (*valueState, bool) {
// Try to return this layer's data
ret := t.data[key]
if ret != nil {
return ret, true
}
// if no underlying layer - return
if t.parentLayer == nil {
return nil, false
}
// recurse to underlying
return t.parentLayer.get(key), false
}
func (t *layer) numEqualTo(value string) (ret uint64) {
// Try local storage
val, ok := t.valueCache[value]
if ok {
return val
}
// Nowhere to recurse - return 0
if t.parentLayer == nil {
return 0
}
// Try to recurse to parentLayer
retCount := t.parentLayer.numEqualTo(value)
// And cache it
t.valueCache[value] = retCount
return retCount
}
// refreshCacheForValue actualizes the valueCache for changed values.
func (t *layer) refreshCacheForValue(value valueState) {
// Initiate the count for current and previous values
// from underlying layers first if exists
if t.parentLayer != nil {
// Init current value
if _, ok := t.valueCache[value.Data]; !ok {
t.valueCache[value.Data] = t.parentLayer.numEqualTo(value.Data)
}
// Init previous value
if value.Prev != nil {
if _, ok := t.valueCache[value.Prev.Data]; !ok {
t.valueCache[value.Prev.Data] = t.parentLayer.numEqualTo(value.Prev.Data)
}
}
}
// Decrement previous value's count
if value.Prev != nil && !value.Prev.Deleted {
t.valueCache[value.Prev.Data]--
}
if !value.Deleted {
t.valueCache[value.Data]++
}
}<|fim▁end|> | }
t.data[key] = &value
t.refreshCacheForValue(value) |
<|file_name|>LanguagePackage.java<|end_file_name|><|fim▁begin|>/**
*/
package org.w3._2001.smil20.language;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.w3._2001.smil20.Smil20Package;
/**
* <!-- begin-user-doc -->
* The <b>Package</b> for the model.
* It contains accessors for the meta objects to represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each operation of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
*
* <div xmlns="http://www.w3.org/1999/xhtml">
* <h1>About the XML namespace</h1>
*
* <div class="bodytext">
* <p>
* This schema document describes the XML namespace, in a form
* suitable for import by other schema documents.
* </p>
* <p>
* See <a href="http://www.w3.org/XML/1998/namespace.html">
* http://www.w3.org/XML/1998/namespace.html</a> and
* <a href="http://www.w3.org/TR/REC-xml">
* http://www.w3.org/TR/REC-xml</a> for information
* about this namespace.
* </p>
* <p>
* Note that local names in this namespace are intended to be
* defined only by the World Wide Web Consortium or its subgroups.
* The names currently defined in this namespace are listed below.
* They should not be used with conflicting semantics by any Working
* Group, specification, or document instance.
* </p>
* <p>
* See further below in this document for more information about <a href="#usage">how to refer to this schema document from your own
* XSD schema documents</a> and about <a href="#nsversioning">the
* namespace-versioning policy governing this schema document</a>.
* </p>
* </div>
* </div>
*
*
* <div xmlns="http://www.w3.org/1999/xhtml">
*
* <h3>Father (in any context at all)</h3>
*
* <div class="bodytext">
* <p>
* denotes Jon Bosak, the chair of
* the original XML Working Group. This name is reserved by
* the following decision of the W3C XML Plenary and
* XML Coordination groups:
* </p>
* <blockquote>
* <p>
* In appreciation for his vision, leadership and
* dedication the W3C XML Plenary on this 10th day of
* February, 2000, reserves for Jon Bosak in perpetuity
* the XML name "xml:Father".
* </p>
* </blockquote>
* </div>
* </div>
*
*
* <div id="usage" xml:id="usage" xmlns="http://www.w3.org/1999/xhtml">
* <h2>
* <a name="usage">About this schema document</a>
* </h2>
*
* <div class="bodytext">
* <p>
* This schema defines attributes and an attribute group suitable
* for use by schemas wishing to allow <code>xml:base</code>,
* <code>xml:lang</code>, <code>xml:space</code> or
* <code>xml:id</code> attributes on elements they define.
* </p>
* <p>
* To enable this, such a schema must import this schema for
* the XML namespace, e.g. as follows:
* </p>
* <pre>
* <schema . . .>
* . . .
* <import namespace="http://www.w3.org/XML/1998/namespace"
* schemaLocation="http://www.w3.org/2001/xml.xsd"/>
* </pre>
* <p>
* or
* </p>
* <pre>
* <import namespace="http://www.w3.org/XML/1998/namespace"
* schemaLocation="http://www.w3.org/2009/01/xml.xsd"/>
* </pre>
* <p>
* Subsequently, qualified reference to any of the attributes or the
* group defined below will have the desired effect, e.g.
* </p>
* <pre>
* <type . . .>
* . . .
* <attributeGroup ref="xml:specialAttrs"/>
* </pre>
* <p>
* will define a type which will schema-validate an instance element
* with any of those attributes.
* </p>
* </div>
* </div>
*
*
* <div id="nsversioning" xml:id="nsversioning" xmlns="http://www.w3.org/1999/xhtml">
* <h2>
* <a name="nsversioning">Versioning policy for this schema document</a>
* </h2>
* <div class="bodytext">
* <p>
* In keeping with the XML Schema WG's standard versioning
* policy, this schema document will persist at
* <a href="http://www.w3.org/2009/01/xml.xsd">
* http://www.w3.org/2009/01/xml.xsd</a>.
* </p>
* <p>
* At the date of issue it can also be found at
* <a href="http://www.w3.org/2001/xml.xsd">
* http://www.w3.org/2001/xml.xsd</a>.
* </p>
* <p>
* The schema document at that URI may however change in the future,
* in order to remain compatible with the latest version of XML
* Schema itself, or with the XML namespace itself. In other words,
* if the XML Schema or XML namespaces change, the version of this
* document at <a href="http://www.w3.org/2001/xml.xsd">
* http://www.w3.org/2001/xml.xsd
* </a>
* will change accordingly; the version at
* <a href="http://www.w3.org/2009/01/xml.xsd">
* http://www.w3.org/2009/01/xml.xsd
* </a>
* will not change.
* </p>
* <p>
* Previous dated (and unchanging) versions of this schema
* document are at:
* </p>
* <ul>
* <li>
* <a href="http://www.w3.org/2009/01/xml.xsd">
* http://www.w3.org/2009/01/xml.xsd</a>
* </li>
* <li>
* <a href="http://www.w3.org/2007/08/xml.xsd">
* http://www.w3.org/2007/08/xml.xsd</a>
* </li>
* <li>
* <a href="http://www.w3.org/2004/10/xml.xsd">
* http://www.w3.org/2004/10/xml.xsd</a>
* </li>
* <li>
* <a href="http://www.w3.org/2001/03/xml.xsd">
* http://www.w3.org/2001/03/xml.xsd</a>
* </li>
* </ul>
* </div>
* </div>
*
* <!-- end-model-doc -->
* @see org.w3._2001.smil20.language.LanguageFactory
* @model kind="package"
* @generated
*/
public interface LanguagePackage extends EPackage {
/**
* The package name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNAME = "language";
/**
* The package namespace URI.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_URI = "http://www.w3.org/2001/SMIL20/Language";
/**
* The package namespace name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_PREFIX = "language";
/**
* The singleton instance of the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
LanguagePackage eINSTANCE = org.w3._2001.smil20.language.impl.LanguagePackageImpl.init();
/**
* The meta object id for the '{@link org.w3._2001.smil20.language.impl.AnimateColorTypeImpl <em>Animate Color Type</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.w3._2001.smil20.language.impl.AnimateColorTypeImpl
* @see org.w3._2001.smil20.language.impl.LanguagePackageImpl#getAnimateColorType()
* @generated
*/
int ANIMATE_COLOR_TYPE = 0;
/**
* The feature id for the '<em><b>Accumulate</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__ACCUMULATE = Smil20Package.ANIMATE_COLOR_PROTOTYPE__ACCUMULATE;
/**
* The feature id for the '<em><b>Additive</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__ADDITIVE = Smil20Package.ANIMATE_COLOR_PROTOTYPE__ADDITIVE;
/**
* The feature id for the '<em><b>Attribute Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__ATTRIBUTE_NAME = Smil20Package.ANIMATE_COLOR_PROTOTYPE__ATTRIBUTE_NAME;
/**
* The feature id for the '<em><b>Attribute Type</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__ATTRIBUTE_TYPE = Smil20Package.ANIMATE_COLOR_PROTOTYPE__ATTRIBUTE_TYPE;
/**
* The feature id for the '<em><b>By</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__BY = Smil20Package.ANIMATE_COLOR_PROTOTYPE__BY;
/**
* The feature id for the '<em><b>From</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__FROM = Smil20Package.ANIMATE_COLOR_PROTOTYPE__FROM;
/**
* The feature id for the '<em><b>To</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__TO = Smil20Package.ANIMATE_COLOR_PROTOTYPE__TO;
/**
* The feature id for the '<em><b>Values</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__VALUES = Smil20Package.ANIMATE_COLOR_PROTOTYPE__VALUES;
/**
* The feature id for the '<em><b>Group</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__GROUP = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 0;
/**
* The feature id for the '<em><b>Any</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__ANY = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 1;
/**
* The feature id for the '<em><b>Alt</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__ALT = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 2;
/**
* The feature id for the '<em><b>Begin</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__BEGIN = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 3;
/**
* The feature id for the '<em><b>Calc Mode</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__CALC_MODE = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 4;
/**
* The feature id for the '<em><b>Class</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__CLASS = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 5;
/**
* The feature id for the '<em><b>Dur</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__DUR = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 6;
/**
* The feature id for the '<em><b>End</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__END = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 7;
/**
* The feature id for the '<em><b>Fill</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__FILL = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 8;
/**
* The feature id for the '<em><b>Fill Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__FILL_DEFAULT = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 9;
/**
* The feature id for the '<em><b>Id</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__ID = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 10;
/**
* The feature id for the '<em><b>Lang</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__LANG = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 11;
/**
* The feature id for the '<em><b>Longdesc</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__LONGDESC = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 12;
/**
* The feature id for the '<em><b>Max</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__MAX = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 13;
/**
* The feature id for the '<em><b>Min</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__MIN = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 14;
/**
* The feature id for the '<em><b>Repeat</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__REPEAT = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 15;
/**
* The feature id for the '<em><b>Repeat Count</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__REPEAT_COUNT = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 16;
/**
* The feature id for the '<em><b>Repeat Dur</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__REPEAT_DUR = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 17;
/**
* The feature id for the '<em><b>Restart</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__RESTART = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 18;
/**
* The feature id for the '<em><b>Restart Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__RESTART_DEFAULT = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 19;
/**
* The feature id for the '<em><b>Skip Content</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__SKIP_CONTENT = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 20;
/**
* The feature id for the '<em><b>Sync Behavior</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__SYNC_BEHAVIOR = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 21;
/**
* The feature id for the '<em><b>Sync Behavior Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__SYNC_BEHAVIOR_DEFAULT = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 22;
/**
* The feature id for the '<em><b>Sync Tolerance</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__SYNC_TOLERANCE = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 23;
/**
* The feature id for the '<em><b>Sync Tolerance Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__SYNC_TOLERANCE_DEFAULT = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 24;
/**
* The feature id for the '<em><b>Target Element</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__TARGET_ELEMENT = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 25;
/**
* The feature id for the '<em><b>Any Attribute</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE__ANY_ATTRIBUTE = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 26;
/**
* The number of structural features of the '<em>Animate Color Type</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE_FEATURE_COUNT = Smil20Package.ANIMATE_COLOR_PROTOTYPE_FEATURE_COUNT + 27;
/**
* The number of operations of the '<em>Animate Color Type</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_COLOR_TYPE_OPERATION_COUNT = Smil20Package.ANIMATE_COLOR_PROTOTYPE_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link org.w3._2001.smil20.language.impl.AnimateMotionTypeImpl <em>Animate Motion Type</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.w3._2001.smil20.language.impl.AnimateMotionTypeImpl
* @see org.w3._2001.smil20.language.impl.LanguagePackageImpl#getAnimateMotionType()
* @generated
*/
int ANIMATE_MOTION_TYPE = 1;
/**
* The feature id for the '<em><b>Accumulate</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__ACCUMULATE = Smil20Package.ANIMATE_MOTION_PROTOTYPE__ACCUMULATE;
/**
* The feature id for the '<em><b>Additive</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__ADDITIVE = Smil20Package.ANIMATE_MOTION_PROTOTYPE__ADDITIVE;
/**
* The feature id for the '<em><b>By</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__BY = Smil20Package.ANIMATE_MOTION_PROTOTYPE__BY;
/**
* The feature id for the '<em><b>From</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__FROM = Smil20Package.ANIMATE_MOTION_PROTOTYPE__FROM;
/**
* The feature id for the '<em><b>Origin</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__ORIGIN = Smil20Package.ANIMATE_MOTION_PROTOTYPE__ORIGIN;
/**
* The feature id for the '<em><b>To</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__TO = Smil20Package.ANIMATE_MOTION_PROTOTYPE__TO;
/**
* The feature id for the '<em><b>Values</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__VALUES = Smil20Package.ANIMATE_MOTION_PROTOTYPE__VALUES;
/**
* The feature id for the '<em><b>Group</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__GROUP = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 0;
/**
* The feature id for the '<em><b>Any</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__ANY = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 1;
/**
* The feature id for the '<em><b>Alt</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__ALT = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 2;
/**
* The feature id for the '<em><b>Begin</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__BEGIN = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 3;
/**
* The feature id for the '<em><b>Calc Mode</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__CALC_MODE = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 4;
/**
* The feature id for the '<em><b>Class</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__CLASS = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 5;
/**
* The feature id for the '<em><b>Dur</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__DUR = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 6;
/**
* The feature id for the '<em><b>End</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__END = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 7;
/**
* The feature id for the '<em><b>Fill</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__FILL = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 8;
/**
* The feature id for the '<em><b>Fill Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__FILL_DEFAULT = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 9;
/**
* The feature id for the '<em><b>Id</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__ID = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 10;
/**
* The feature id for the '<em><b>Lang</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__LANG = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 11;
/**
* The feature id for the '<em><b>Longdesc</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__LONGDESC = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 12;
/**
* The feature id for the '<em><b>Max</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__MAX = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 13;
/**
* The feature id for the '<em><b>Min</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__MIN = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 14;
/**
* The feature id for the '<em><b>Repeat</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__REPEAT = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 15;
/**
* The feature id for the '<em><b>Repeat Count</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__REPEAT_COUNT = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 16;
/**
* The feature id for the '<em><b>Repeat Dur</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__REPEAT_DUR = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 17;
/**
* The feature id for the '<em><b>Restart</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__RESTART = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 18;
/**
* The feature id for the '<em><b>Restart Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__RESTART_DEFAULT = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 19;
/**
* The feature id for the '<em><b>Skip Content</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__SKIP_CONTENT = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 20;
/**
* The feature id for the '<em><b>Sync Behavior</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__SYNC_BEHAVIOR = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 21;
/**
* The feature id for the '<em><b>Sync Behavior Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__SYNC_BEHAVIOR_DEFAULT = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 22;
/**
* The feature id for the '<em><b>Sync Tolerance</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__SYNC_TOLERANCE = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 23;
/**
* The feature id for the '<em><b>Sync Tolerance Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__SYNC_TOLERANCE_DEFAULT = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 24;
/**
* The feature id for the '<em><b>Target Element</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__TARGET_ELEMENT = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 25;
/**
* The feature id for the '<em><b>Any Attribute</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE__ANY_ATTRIBUTE = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 26;
/**
* The number of structural features of the '<em>Animate Motion Type</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE_FEATURE_COUNT = Smil20Package.ANIMATE_MOTION_PROTOTYPE_FEATURE_COUNT + 27;
/**
* The number of operations of the '<em>Animate Motion Type</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_MOTION_TYPE_OPERATION_COUNT = Smil20Package.ANIMATE_MOTION_PROTOTYPE_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link org.w3._2001.smil20.language.impl.AnimateTypeImpl <em>Animate Type</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.w3._2001.smil20.language.impl.AnimateTypeImpl
* @see org.w3._2001.smil20.language.impl.LanguagePackageImpl#getAnimateType()
* @generated
*/
int ANIMATE_TYPE = 2;
/**
* The feature id for the '<em><b>Accumulate</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__ACCUMULATE = Smil20Package.ANIMATE_PROTOTYPE__ACCUMULATE;
/**
* The feature id for the '<em><b>Additive</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__ADDITIVE = Smil20Package.ANIMATE_PROTOTYPE__ADDITIVE;
/**
* The feature id for the '<em><b>Attribute Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__ATTRIBUTE_NAME = Smil20Package.ANIMATE_PROTOTYPE__ATTRIBUTE_NAME;
/**
* The feature id for the '<em><b>Attribute Type</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__ATTRIBUTE_TYPE = Smil20Package.ANIMATE_PROTOTYPE__ATTRIBUTE_TYPE;
/**
* The feature id for the '<em><b>By</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__BY = Smil20Package.ANIMATE_PROTOTYPE__BY;
/**
* The feature id for the '<em><b>From</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__FROM = Smil20Package.ANIMATE_PROTOTYPE__FROM;
/**
* The feature id for the '<em><b>To</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__TO = Smil20Package.ANIMATE_PROTOTYPE__TO;
/**
* The feature id for the '<em><b>Values</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__VALUES = Smil20Package.ANIMATE_PROTOTYPE__VALUES;
/**
* The feature id for the '<em><b>Group</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__GROUP = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 0;
/**
* The feature id for the '<em><b>Any</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__ANY = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 1;
/**
* The feature id for the '<em><b>Alt</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__ALT = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 2;
/**
* The feature id for the '<em><b>Begin</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__BEGIN = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 3;
/**
* The feature id for the '<em><b>Calc Mode</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__CALC_MODE = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 4;
/**
* The feature id for the '<em><b>Class</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__CLASS = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 5;
/**
* The feature id for the '<em><b>Dur</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__DUR = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 6;
/**
* The feature id for the '<em><b>End</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__END = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 7;
/**
* The feature id for the '<em><b>Fill</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__FILL = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 8;
/**
* The feature id for the '<em><b>Fill Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__FILL_DEFAULT = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 9;
/**
* The feature id for the '<em><b>Id</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__ID = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 10;
/**
* The feature id for the '<em><b>Lang</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__LANG = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 11;
/**
* The feature id for the '<em><b>Longdesc</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__LONGDESC = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 12;
/**
* The feature id for the '<em><b>Max</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__MAX = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 13;
/**
* The feature id for the '<em><b>Min</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__MIN = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 14;
/**
* The feature id for the '<em><b>Repeat</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__REPEAT = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 15;
/**
* The feature id for the '<em><b>Repeat Count</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__REPEAT_COUNT = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 16;
/**
* The feature id for the '<em><b>Repeat Dur</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__REPEAT_DUR = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 17;
/**
* The feature id for the '<em><b>Restart</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__RESTART = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 18;
/**
* The feature id for the '<em><b>Restart Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__RESTART_DEFAULT = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 19;
/**
* The feature id for the '<em><b>Skip Content</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__SKIP_CONTENT = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 20;
/**
* The feature id for the '<em><b>Sync Behavior</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__SYNC_BEHAVIOR = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 21;
/**
* The feature id for the '<em><b>Sync Behavior Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__SYNC_BEHAVIOR_DEFAULT = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 22;
/**
* The feature id for the '<em><b>Sync Tolerance</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__SYNC_TOLERANCE = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 23;
/**
* The feature id for the '<em><b>Sync Tolerance Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__SYNC_TOLERANCE_DEFAULT = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 24;
/**
* The feature id for the '<em><b>Target Element</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__TARGET_ELEMENT = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 25;
/**
* The feature id for the '<em><b>Any Attribute</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE__ANY_ATTRIBUTE = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 26;
/**
* The number of structural features of the '<em>Animate Type</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE_FEATURE_COUNT = Smil20Package.ANIMATE_PROTOTYPE_FEATURE_COUNT + 27;
/**
* The number of operations of the '<em>Animate Type</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANIMATE_TYPE_OPERATION_COUNT = Smil20Package.ANIMATE_PROTOTYPE_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link org.w3._2001.smil20.language.impl.DocumentRootImpl <em>Document Root</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.w3._2001.smil20.language.impl.DocumentRootImpl
* @see org.w3._2001.smil20.language.impl.LanguagePackageImpl#getDocumentRoot()
* @generated
*/
int DOCUMENT_ROOT = 3;
/**
* The feature id for the '<em><b>Mixed</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__MIXED = 0;
/**
* The feature id for the '<em><b>XMLNS Prefix Map</b></em>' map.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__XMLNS_PREFIX_MAP = 1;
/**
* The feature id for the '<em><b>XSI Schema Location</b></em>' map.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__XSI_SCHEMA_LOCATION = 2;
/**
* The feature id for the '<em><b>Animate</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__ANIMATE = 3;
/**
* The feature id for the '<em><b>Animate Color</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__ANIMATE_COLOR = 4;
/**
* The feature id for the '<em><b>Animate Motion</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__ANIMATE_MOTION = 5;
/**
* The feature id for the '<em><b>Set</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__SET = 6;
/**
* The number of structural features of the '<em>Document Root</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT_FEATURE_COUNT = 7;
/**
* The number of operations of the '<em>Document Root</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT_OPERATION_COUNT = 0;
/**
* The meta object id for the '{@link org.w3._2001.smil20.language.impl.SetTypeImpl <em>Set Type</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.w3._2001.smil20.language.impl.SetTypeImpl
* @see org.w3._2001.smil20.language.impl.LanguagePackageImpl#getSetType()
* @generated
*/
int SET_TYPE = 4;
/**
* The feature id for the '<em><b>Attribute Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__ATTRIBUTE_NAME = Smil20Package.SET_PROTOTYPE__ATTRIBUTE_NAME;
/**
* The feature id for the '<em><b>Attribute Type</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__ATTRIBUTE_TYPE = Smil20Package.SET_PROTOTYPE__ATTRIBUTE_TYPE;
/**
* The feature id for the '<em><b>To</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__TO = Smil20Package.SET_PROTOTYPE__TO;
/**
* The feature id for the '<em><b>Group</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__GROUP = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 0;
/**
* The feature id for the '<em><b>Any</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__ANY = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 1;
/**
* The feature id for the '<em><b>Alt</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__ALT = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 2;
/**
* The feature id for the '<em><b>Begin</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__BEGIN = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 3;
/**
* The feature id for the '<em><b>Class</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__CLASS = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 4;
/**
* The feature id for the '<em><b>Dur</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__DUR = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 5;
/**
* The feature id for the '<em><b>End</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__END = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 6;
/**
* The feature id for the '<em><b>Fill</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__FILL = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 7;
/**
* The feature id for the '<em><b>Fill Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__FILL_DEFAULT = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 8;
/**
* The feature id for the '<em><b>Id</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__ID = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 9;
/**
* The feature id for the '<em><b>Lang</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__LANG = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 10;
/**
* The feature id for the '<em><b>Longdesc</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__LONGDESC = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 11;
/**
* The feature id for the '<em><b>Max</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__MAX = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 12;
/**
* The feature id for the '<em><b>Min</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__MIN = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 13;
/**
* The feature id for the '<em><b>Repeat</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__REPEAT = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 14;
/**
* The feature id for the '<em><b>Repeat Count</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__REPEAT_COUNT = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 15;
/**
* The feature id for the '<em><b>Repeat Dur</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__REPEAT_DUR = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 16;
/**
* The feature id for the '<em><b>Restart</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__RESTART = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 17;
/**
* The feature id for the '<em><b>Restart Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__RESTART_DEFAULT = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 18;
/**
* The feature id for the '<em><b>Skip Content</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__SKIP_CONTENT = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 19;
/**
* The feature id for the '<em><b>Sync Behavior</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__SYNC_BEHAVIOR = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 20;
/**<|fim▁hole|> * The feature id for the '<em><b>Sync Behavior Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__SYNC_BEHAVIOR_DEFAULT = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 21;
/**
* The feature id for the '<em><b>Sync Tolerance</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__SYNC_TOLERANCE = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 22;
/**
* The feature id for the '<em><b>Sync Tolerance Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__SYNC_TOLERANCE_DEFAULT = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 23;
/**
* The feature id for the '<em><b>Target Element</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__TARGET_ELEMENT = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 24;
/**
* The feature id for the '<em><b>Any Attribute</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE__ANY_ATTRIBUTE = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 25;
/**
* The number of structural features of the '<em>Set Type</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE_FEATURE_COUNT = Smil20Package.SET_PROTOTYPE_FEATURE_COUNT + 26;
/**
* The number of operations of the '<em>Set Type</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SET_TYPE_OPERATION_COUNT = Smil20Package.SET_PROTOTYPE_OPERATION_COUNT + 0;
/**
* Returns the meta object for class '{@link org.w3._2001.smil20.language.AnimateColorType <em>Animate Color Type</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Animate Color Type</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType
* @generated
*/
EClass getAnimateColorType();
/**
* Returns the meta object for the attribute list '{@link org.w3._2001.smil20.language.AnimateColorType#getGroup <em>Group</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Group</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getGroup()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Group();
/**
* Returns the meta object for the attribute list '{@link org.w3._2001.smil20.language.AnimateColorType#getAny <em>Any</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Any</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getAny()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Any();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getAlt <em>Alt</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Alt</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getAlt()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Alt();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getBegin <em>Begin</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Begin</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getBegin()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Begin();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getCalcMode <em>Calc Mode</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Calc Mode</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getCalcMode()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_CalcMode();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getClass_ <em>Class</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Class</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getClass_()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Class();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getDur <em>Dur</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Dur</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getDur()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Dur();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getEnd <em>End</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>End</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getEnd()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_End();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getFill <em>Fill</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Fill</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getFill()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Fill();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getFillDefault <em>Fill Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Fill Default</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getFillDefault()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_FillDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getId <em>Id</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Id</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getId()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Id();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getLang <em>Lang</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Lang</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getLang()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Lang();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getLongdesc <em>Longdesc</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Longdesc</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getLongdesc()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Longdesc();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getMax <em>Max</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Max</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getMax()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Max();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getMin <em>Min</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Min</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getMin()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Min();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getRepeat <em>Repeat</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Repeat</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getRepeat()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Repeat();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getRepeatCount <em>Repeat Count</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Repeat Count</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getRepeatCount()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_RepeatCount();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getRepeatDur <em>Repeat Dur</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Repeat Dur</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getRepeatDur()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_RepeatDur();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getRestart <em>Restart</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Restart</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getRestart()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_Restart();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getRestartDefault <em>Restart Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Restart Default</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getRestartDefault()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_RestartDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#isSkipContent <em>Skip Content</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Skip Content</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#isSkipContent()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_SkipContent();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getSyncBehavior <em>Sync Behavior</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Behavior</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getSyncBehavior()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_SyncBehavior();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getSyncBehaviorDefault <em>Sync Behavior Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Behavior Default</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getSyncBehaviorDefault()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_SyncBehaviorDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getSyncTolerance <em>Sync Tolerance</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Tolerance</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getSyncTolerance()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_SyncTolerance();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getSyncToleranceDefault <em>Sync Tolerance Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Tolerance Default</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getSyncToleranceDefault()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_SyncToleranceDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateColorType#getTargetElement <em>Target Element</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Target Element</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getTargetElement()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_TargetElement();
/**
* Returns the meta object for the attribute list '{@link org.w3._2001.smil20.language.AnimateColorType#getAnyAttribute <em>Any Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Any Attribute</em>'.
* @see org.w3._2001.smil20.language.AnimateColorType#getAnyAttribute()
* @see #getAnimateColorType()
* @generated
*/
EAttribute getAnimateColorType_AnyAttribute();
/**
* Returns the meta object for class '{@link org.w3._2001.smil20.language.AnimateMotionType <em>Animate Motion Type</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Animate Motion Type</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType
* @generated
*/
EClass getAnimateMotionType();
/**
* Returns the meta object for the attribute list '{@link org.w3._2001.smil20.language.AnimateMotionType#getGroup <em>Group</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Group</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getGroup()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Group();
/**
* Returns the meta object for the attribute list '{@link org.w3._2001.smil20.language.AnimateMotionType#getAny <em>Any</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Any</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getAny()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Any();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getAlt <em>Alt</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Alt</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getAlt()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Alt();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getBegin <em>Begin</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Begin</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getBegin()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Begin();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getCalcMode <em>Calc Mode</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Calc Mode</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getCalcMode()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_CalcMode();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getClass_ <em>Class</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Class</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getClass_()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Class();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getDur <em>Dur</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Dur</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getDur()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Dur();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getEnd <em>End</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>End</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getEnd()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_End();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getFill <em>Fill</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Fill</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getFill()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Fill();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getFillDefault <em>Fill Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Fill Default</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getFillDefault()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_FillDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getId <em>Id</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Id</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getId()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Id();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getLang <em>Lang</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Lang</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getLang()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Lang();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getLongdesc <em>Longdesc</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Longdesc</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getLongdesc()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Longdesc();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getMax <em>Max</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Max</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getMax()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Max();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getMin <em>Min</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Min</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getMin()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Min();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getRepeat <em>Repeat</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Repeat</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getRepeat()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Repeat();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getRepeatCount <em>Repeat Count</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Repeat Count</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getRepeatCount()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_RepeatCount();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getRepeatDur <em>Repeat Dur</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Repeat Dur</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getRepeatDur()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_RepeatDur();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getRestart <em>Restart</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Restart</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getRestart()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_Restart();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getRestartDefault <em>Restart Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Restart Default</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getRestartDefault()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_RestartDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#isSkipContent <em>Skip Content</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Skip Content</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#isSkipContent()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_SkipContent();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getSyncBehavior <em>Sync Behavior</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Behavior</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getSyncBehavior()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_SyncBehavior();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getSyncBehaviorDefault <em>Sync Behavior Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Behavior Default</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getSyncBehaviorDefault()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_SyncBehaviorDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getSyncTolerance <em>Sync Tolerance</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Tolerance</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getSyncTolerance()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_SyncTolerance();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getSyncToleranceDefault <em>Sync Tolerance Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Tolerance Default</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getSyncToleranceDefault()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_SyncToleranceDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateMotionType#getTargetElement <em>Target Element</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Target Element</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getTargetElement()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_TargetElement();
/**
* Returns the meta object for the attribute list '{@link org.w3._2001.smil20.language.AnimateMotionType#getAnyAttribute <em>Any Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Any Attribute</em>'.
* @see org.w3._2001.smil20.language.AnimateMotionType#getAnyAttribute()
* @see #getAnimateMotionType()
* @generated
*/
EAttribute getAnimateMotionType_AnyAttribute();
/**
* Returns the meta object for class '{@link org.w3._2001.smil20.language.AnimateType <em>Animate Type</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Animate Type</em>'.
* @see org.w3._2001.smil20.language.AnimateType
* @generated
*/
EClass getAnimateType();
/**
* Returns the meta object for the attribute list '{@link org.w3._2001.smil20.language.AnimateType#getGroup <em>Group</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Group</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getGroup()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Group();
/**
* Returns the meta object for the attribute list '{@link org.w3._2001.smil20.language.AnimateType#getAny <em>Any</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Any</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getAny()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Any();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getAlt <em>Alt</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Alt</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getAlt()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Alt();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getBegin <em>Begin</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Begin</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getBegin()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Begin();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getCalcMode <em>Calc Mode</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Calc Mode</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getCalcMode()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_CalcMode();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getClass_ <em>Class</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Class</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getClass_()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Class();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getDur <em>Dur</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Dur</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getDur()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Dur();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getEnd <em>End</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>End</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getEnd()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_End();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getFill <em>Fill</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Fill</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getFill()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Fill();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getFillDefault <em>Fill Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Fill Default</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getFillDefault()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_FillDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getId <em>Id</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Id</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getId()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Id();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getLang <em>Lang</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Lang</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getLang()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Lang();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getLongdesc <em>Longdesc</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Longdesc</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getLongdesc()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Longdesc();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getMax <em>Max</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Max</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getMax()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Max();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getMin <em>Min</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Min</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getMin()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Min();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getRepeat <em>Repeat</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Repeat</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getRepeat()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Repeat();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getRepeatCount <em>Repeat Count</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Repeat Count</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getRepeatCount()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_RepeatCount();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getRepeatDur <em>Repeat Dur</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Repeat Dur</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getRepeatDur()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_RepeatDur();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getRestart <em>Restart</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Restart</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getRestart()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_Restart();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getRestartDefault <em>Restart Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Restart Default</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getRestartDefault()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_RestartDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#isSkipContent <em>Skip Content</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Skip Content</em>'.
* @see org.w3._2001.smil20.language.AnimateType#isSkipContent()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_SkipContent();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getSyncBehavior <em>Sync Behavior</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Behavior</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getSyncBehavior()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_SyncBehavior();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getSyncBehaviorDefault <em>Sync Behavior Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Behavior Default</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getSyncBehaviorDefault()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_SyncBehaviorDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getSyncTolerance <em>Sync Tolerance</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Tolerance</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getSyncTolerance()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_SyncTolerance();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getSyncToleranceDefault <em>Sync Tolerance Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Tolerance Default</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getSyncToleranceDefault()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_SyncToleranceDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.AnimateType#getTargetElement <em>Target Element</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Target Element</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getTargetElement()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_TargetElement();
/**
* Returns the meta object for the attribute list '{@link org.w3._2001.smil20.language.AnimateType#getAnyAttribute <em>Any Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Any Attribute</em>'.
* @see org.w3._2001.smil20.language.AnimateType#getAnyAttribute()
* @see #getAnimateType()
* @generated
*/
EAttribute getAnimateType_AnyAttribute();
/**
* Returns the meta object for class '{@link org.w3._2001.smil20.language.DocumentRoot <em>Document Root</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Document Root</em>'.
* @see org.w3._2001.smil20.language.DocumentRoot
* @generated
*/
EClass getDocumentRoot();
/**
* Returns the meta object for the attribute list '{@link org.w3._2001.smil20.language.DocumentRoot#getMixed <em>Mixed</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Mixed</em>'.
* @see org.w3._2001.smil20.language.DocumentRoot#getMixed()
* @see #getDocumentRoot()
* @generated
*/
EAttribute getDocumentRoot_Mixed();
/**
* Returns the meta object for the map '{@link org.w3._2001.smil20.language.DocumentRoot#getXMLNSPrefixMap <em>XMLNS Prefix Map</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the map '<em>XMLNS Prefix Map</em>'.
* @see org.w3._2001.smil20.language.DocumentRoot#getXMLNSPrefixMap()
* @see #getDocumentRoot()
* @generated
*/
EReference getDocumentRoot_XMLNSPrefixMap();
/**
* Returns the meta object for the map '{@link org.w3._2001.smil20.language.DocumentRoot#getXSISchemaLocation <em>XSI Schema Location</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the map '<em>XSI Schema Location</em>'.
* @see org.w3._2001.smil20.language.DocumentRoot#getXSISchemaLocation()
* @see #getDocumentRoot()
* @generated
*/
EReference getDocumentRoot_XSISchemaLocation();
/**
* Returns the meta object for the containment reference '{@link org.w3._2001.smil20.language.DocumentRoot#getAnimate <em>Animate</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Animate</em>'.
* @see org.w3._2001.smil20.language.DocumentRoot#getAnimate()
* @see #getDocumentRoot()
* @generated
*/
EReference getDocumentRoot_Animate();
/**
* Returns the meta object for the containment reference '{@link org.w3._2001.smil20.language.DocumentRoot#getAnimateColor <em>Animate Color</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Animate Color</em>'.
* @see org.w3._2001.smil20.language.DocumentRoot#getAnimateColor()
* @see #getDocumentRoot()
* @generated
*/
EReference getDocumentRoot_AnimateColor();
/**
* Returns the meta object for the containment reference '{@link org.w3._2001.smil20.language.DocumentRoot#getAnimateMotion <em>Animate Motion</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Animate Motion</em>'.
* @see org.w3._2001.smil20.language.DocumentRoot#getAnimateMotion()
* @see #getDocumentRoot()
* @generated
*/
EReference getDocumentRoot_AnimateMotion();
/**
* Returns the meta object for the containment reference '{@link org.w3._2001.smil20.language.DocumentRoot#getSet <em>Set</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Set</em>'.
* @see org.w3._2001.smil20.language.DocumentRoot#getSet()
* @see #getDocumentRoot()
* @generated
*/
EReference getDocumentRoot_Set();
/**
* Returns the meta object for class '{@link org.w3._2001.smil20.language.SetType <em>Set Type</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Set Type</em>'.
* @see org.w3._2001.smil20.language.SetType
* @generated
*/
EClass getSetType();
/**
* Returns the meta object for the attribute list '{@link org.w3._2001.smil20.language.SetType#getGroup <em>Group</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Group</em>'.
* @see org.w3._2001.smil20.language.SetType#getGroup()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Group();
/**
* Returns the meta object for the attribute list '{@link org.w3._2001.smil20.language.SetType#getAny <em>Any</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Any</em>'.
* @see org.w3._2001.smil20.language.SetType#getAny()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Any();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getAlt <em>Alt</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Alt</em>'.
* @see org.w3._2001.smil20.language.SetType#getAlt()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Alt();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getBegin <em>Begin</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Begin</em>'.
* @see org.w3._2001.smil20.language.SetType#getBegin()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Begin();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getClass_ <em>Class</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Class</em>'.
* @see org.w3._2001.smil20.language.SetType#getClass_()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Class();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getDur <em>Dur</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Dur</em>'.
* @see org.w3._2001.smil20.language.SetType#getDur()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Dur();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getEnd <em>End</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>End</em>'.
* @see org.w3._2001.smil20.language.SetType#getEnd()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_End();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getFill <em>Fill</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Fill</em>'.
* @see org.w3._2001.smil20.language.SetType#getFill()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Fill();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getFillDefault <em>Fill Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Fill Default</em>'.
* @see org.w3._2001.smil20.language.SetType#getFillDefault()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_FillDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getId <em>Id</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Id</em>'.
* @see org.w3._2001.smil20.language.SetType#getId()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Id();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getLang <em>Lang</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Lang</em>'.
* @see org.w3._2001.smil20.language.SetType#getLang()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Lang();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getLongdesc <em>Longdesc</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Longdesc</em>'.
* @see org.w3._2001.smil20.language.SetType#getLongdesc()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Longdesc();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getMax <em>Max</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Max</em>'.
* @see org.w3._2001.smil20.language.SetType#getMax()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Max();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getMin <em>Min</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Min</em>'.
* @see org.w3._2001.smil20.language.SetType#getMin()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Min();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getRepeat <em>Repeat</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Repeat</em>'.
* @see org.w3._2001.smil20.language.SetType#getRepeat()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Repeat();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getRepeatCount <em>Repeat Count</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Repeat Count</em>'.
* @see org.w3._2001.smil20.language.SetType#getRepeatCount()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_RepeatCount();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getRepeatDur <em>Repeat Dur</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Repeat Dur</em>'.
* @see org.w3._2001.smil20.language.SetType#getRepeatDur()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_RepeatDur();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getRestart <em>Restart</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Restart</em>'.
* @see org.w3._2001.smil20.language.SetType#getRestart()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_Restart();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getRestartDefault <em>Restart Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Restart Default</em>'.
* @see org.w3._2001.smil20.language.SetType#getRestartDefault()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_RestartDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#isSkipContent <em>Skip Content</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Skip Content</em>'.
* @see org.w3._2001.smil20.language.SetType#isSkipContent()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_SkipContent();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getSyncBehavior <em>Sync Behavior</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Behavior</em>'.
* @see org.w3._2001.smil20.language.SetType#getSyncBehavior()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_SyncBehavior();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getSyncBehaviorDefault <em>Sync Behavior Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Behavior Default</em>'.
* @see org.w3._2001.smil20.language.SetType#getSyncBehaviorDefault()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_SyncBehaviorDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getSyncTolerance <em>Sync Tolerance</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Tolerance</em>'.
* @see org.w3._2001.smil20.language.SetType#getSyncTolerance()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_SyncTolerance();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getSyncToleranceDefault <em>Sync Tolerance Default</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Sync Tolerance Default</em>'.
* @see org.w3._2001.smil20.language.SetType#getSyncToleranceDefault()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_SyncToleranceDefault();
/**
* Returns the meta object for the attribute '{@link org.w3._2001.smil20.language.SetType#getTargetElement <em>Target Element</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Target Element</em>'.
* @see org.w3._2001.smil20.language.SetType#getTargetElement()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_TargetElement();
/**
* Returns the meta object for the attribute list '{@link org.w3._2001.smil20.language.SetType#getAnyAttribute <em>Any Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Any Attribute</em>'.
* @see org.w3._2001.smil20.language.SetType#getAnyAttribute()
* @see #getSetType()
* @generated
*/
EAttribute getSetType_AnyAttribute();
/**
* Returns the factory that creates the instances of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the factory that creates the instances of the model.
* @generated
*/
LanguageFactory getLanguageFactory();
/**
* <!-- begin-user-doc -->
* Defines literals for the meta objects that represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each operation of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @generated
*/
interface Literals {
/**
* The meta object literal for the '{@link org.w3._2001.smil20.language.impl.AnimateColorTypeImpl <em>Animate Color Type</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.w3._2001.smil20.language.impl.AnimateColorTypeImpl
* @see org.w3._2001.smil20.language.impl.LanguagePackageImpl#getAnimateColorType()
* @generated
*/
EClass ANIMATE_COLOR_TYPE = eINSTANCE.getAnimateColorType();
/**
* The meta object literal for the '<em><b>Group</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__GROUP = eINSTANCE.getAnimateColorType_Group();
/**
* The meta object literal for the '<em><b>Any</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__ANY = eINSTANCE.getAnimateColorType_Any();
/**
* The meta object literal for the '<em><b>Alt</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__ALT = eINSTANCE.getAnimateColorType_Alt();
/**
* The meta object literal for the '<em><b>Begin</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__BEGIN = eINSTANCE.getAnimateColorType_Begin();
/**
* The meta object literal for the '<em><b>Calc Mode</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__CALC_MODE = eINSTANCE.getAnimateColorType_CalcMode();
/**
* The meta object literal for the '<em><b>Class</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__CLASS = eINSTANCE.getAnimateColorType_Class();
/**
* The meta object literal for the '<em><b>Dur</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__DUR = eINSTANCE.getAnimateColorType_Dur();
/**
* The meta object literal for the '<em><b>End</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__END = eINSTANCE.getAnimateColorType_End();
/**
* The meta object literal for the '<em><b>Fill</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__FILL = eINSTANCE.getAnimateColorType_Fill();
/**
* The meta object literal for the '<em><b>Fill Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__FILL_DEFAULT = eINSTANCE.getAnimateColorType_FillDefault();
/**
* The meta object literal for the '<em><b>Id</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__ID = eINSTANCE.getAnimateColorType_Id();
/**
* The meta object literal for the '<em><b>Lang</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__LANG = eINSTANCE.getAnimateColorType_Lang();
/**
* The meta object literal for the '<em><b>Longdesc</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__LONGDESC = eINSTANCE.getAnimateColorType_Longdesc();
/**
* The meta object literal for the '<em><b>Max</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__MAX = eINSTANCE.getAnimateColorType_Max();
/**
* The meta object literal for the '<em><b>Min</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__MIN = eINSTANCE.getAnimateColorType_Min();
/**
* The meta object literal for the '<em><b>Repeat</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__REPEAT = eINSTANCE.getAnimateColorType_Repeat();
/**
* The meta object literal for the '<em><b>Repeat Count</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__REPEAT_COUNT = eINSTANCE.getAnimateColorType_RepeatCount();
/**
* The meta object literal for the '<em><b>Repeat Dur</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__REPEAT_DUR = eINSTANCE.getAnimateColorType_RepeatDur();
/**
* The meta object literal for the '<em><b>Restart</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__RESTART = eINSTANCE.getAnimateColorType_Restart();
/**
* The meta object literal for the '<em><b>Restart Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__RESTART_DEFAULT = eINSTANCE.getAnimateColorType_RestartDefault();
/**
* The meta object literal for the '<em><b>Skip Content</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__SKIP_CONTENT = eINSTANCE.getAnimateColorType_SkipContent();
/**
* The meta object literal for the '<em><b>Sync Behavior</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__SYNC_BEHAVIOR = eINSTANCE.getAnimateColorType_SyncBehavior();
/**
* The meta object literal for the '<em><b>Sync Behavior Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__SYNC_BEHAVIOR_DEFAULT = eINSTANCE.getAnimateColorType_SyncBehaviorDefault();
/**
* The meta object literal for the '<em><b>Sync Tolerance</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__SYNC_TOLERANCE = eINSTANCE.getAnimateColorType_SyncTolerance();
/**
* The meta object literal for the '<em><b>Sync Tolerance Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__SYNC_TOLERANCE_DEFAULT = eINSTANCE.getAnimateColorType_SyncToleranceDefault();
/**
* The meta object literal for the '<em><b>Target Element</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__TARGET_ELEMENT = eINSTANCE.getAnimateColorType_TargetElement();
/**
* The meta object literal for the '<em><b>Any Attribute</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_COLOR_TYPE__ANY_ATTRIBUTE = eINSTANCE.getAnimateColorType_AnyAttribute();
/**
* The meta object literal for the '{@link org.w3._2001.smil20.language.impl.AnimateMotionTypeImpl <em>Animate Motion Type</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.w3._2001.smil20.language.impl.AnimateMotionTypeImpl
* @see org.w3._2001.smil20.language.impl.LanguagePackageImpl#getAnimateMotionType()
* @generated
*/
EClass ANIMATE_MOTION_TYPE = eINSTANCE.getAnimateMotionType();
/**
* The meta object literal for the '<em><b>Group</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__GROUP = eINSTANCE.getAnimateMotionType_Group();
/**
* The meta object literal for the '<em><b>Any</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__ANY = eINSTANCE.getAnimateMotionType_Any();
/**
* The meta object literal for the '<em><b>Alt</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__ALT = eINSTANCE.getAnimateMotionType_Alt();
/**
* The meta object literal for the '<em><b>Begin</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__BEGIN = eINSTANCE.getAnimateMotionType_Begin();
/**
* The meta object literal for the '<em><b>Calc Mode</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__CALC_MODE = eINSTANCE.getAnimateMotionType_CalcMode();
/**
* The meta object literal for the '<em><b>Class</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__CLASS = eINSTANCE.getAnimateMotionType_Class();
/**
* The meta object literal for the '<em><b>Dur</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__DUR = eINSTANCE.getAnimateMotionType_Dur();
/**
* The meta object literal for the '<em><b>End</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__END = eINSTANCE.getAnimateMotionType_End();
/**
* The meta object literal for the '<em><b>Fill</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__FILL = eINSTANCE.getAnimateMotionType_Fill();
/**
* The meta object literal for the '<em><b>Fill Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__FILL_DEFAULT = eINSTANCE.getAnimateMotionType_FillDefault();
/**
* The meta object literal for the '<em><b>Id</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__ID = eINSTANCE.getAnimateMotionType_Id();
/**
* The meta object literal for the '<em><b>Lang</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__LANG = eINSTANCE.getAnimateMotionType_Lang();
/**
* The meta object literal for the '<em><b>Longdesc</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__LONGDESC = eINSTANCE.getAnimateMotionType_Longdesc();
/**
* The meta object literal for the '<em><b>Max</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__MAX = eINSTANCE.getAnimateMotionType_Max();
/**
* The meta object literal for the '<em><b>Min</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__MIN = eINSTANCE.getAnimateMotionType_Min();
/**
* The meta object literal for the '<em><b>Repeat</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__REPEAT = eINSTANCE.getAnimateMotionType_Repeat();
/**
* The meta object literal for the '<em><b>Repeat Count</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__REPEAT_COUNT = eINSTANCE.getAnimateMotionType_RepeatCount();
/**
* The meta object literal for the '<em><b>Repeat Dur</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__REPEAT_DUR = eINSTANCE.getAnimateMotionType_RepeatDur();
/**
* The meta object literal for the '<em><b>Restart</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__RESTART = eINSTANCE.getAnimateMotionType_Restart();
/**
* The meta object literal for the '<em><b>Restart Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__RESTART_DEFAULT = eINSTANCE.getAnimateMotionType_RestartDefault();
/**
* The meta object literal for the '<em><b>Skip Content</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__SKIP_CONTENT = eINSTANCE.getAnimateMotionType_SkipContent();
/**
* The meta object literal for the '<em><b>Sync Behavior</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__SYNC_BEHAVIOR = eINSTANCE.getAnimateMotionType_SyncBehavior();
/**
* The meta object literal for the '<em><b>Sync Behavior Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__SYNC_BEHAVIOR_DEFAULT = eINSTANCE.getAnimateMotionType_SyncBehaviorDefault();
/**
* The meta object literal for the '<em><b>Sync Tolerance</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__SYNC_TOLERANCE = eINSTANCE.getAnimateMotionType_SyncTolerance();
/**
* The meta object literal for the '<em><b>Sync Tolerance Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__SYNC_TOLERANCE_DEFAULT = eINSTANCE.getAnimateMotionType_SyncToleranceDefault();
/**
* The meta object literal for the '<em><b>Target Element</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__TARGET_ELEMENT = eINSTANCE.getAnimateMotionType_TargetElement();
/**
* The meta object literal for the '<em><b>Any Attribute</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_MOTION_TYPE__ANY_ATTRIBUTE = eINSTANCE.getAnimateMotionType_AnyAttribute();
/**
* The meta object literal for the '{@link org.w3._2001.smil20.language.impl.AnimateTypeImpl <em>Animate Type</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.w3._2001.smil20.language.impl.AnimateTypeImpl
* @see org.w3._2001.smil20.language.impl.LanguagePackageImpl#getAnimateType()
* @generated
*/
EClass ANIMATE_TYPE = eINSTANCE.getAnimateType();
/**
* The meta object literal for the '<em><b>Group</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__GROUP = eINSTANCE.getAnimateType_Group();
/**
* The meta object literal for the '<em><b>Any</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__ANY = eINSTANCE.getAnimateType_Any();
/**
* The meta object literal for the '<em><b>Alt</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__ALT = eINSTANCE.getAnimateType_Alt();
/**
* The meta object literal for the '<em><b>Begin</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__BEGIN = eINSTANCE.getAnimateType_Begin();
/**
* The meta object literal for the '<em><b>Calc Mode</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__CALC_MODE = eINSTANCE.getAnimateType_CalcMode();
/**
* The meta object literal for the '<em><b>Class</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__CLASS = eINSTANCE.getAnimateType_Class();
/**
* The meta object literal for the '<em><b>Dur</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__DUR = eINSTANCE.getAnimateType_Dur();
/**
* The meta object literal for the '<em><b>End</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__END = eINSTANCE.getAnimateType_End();
/**
* The meta object literal for the '<em><b>Fill</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__FILL = eINSTANCE.getAnimateType_Fill();
/**
* The meta object literal for the '<em><b>Fill Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__FILL_DEFAULT = eINSTANCE.getAnimateType_FillDefault();
/**
* The meta object literal for the '<em><b>Id</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__ID = eINSTANCE.getAnimateType_Id();
/**
* The meta object literal for the '<em><b>Lang</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__LANG = eINSTANCE.getAnimateType_Lang();
/**
* The meta object literal for the '<em><b>Longdesc</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__LONGDESC = eINSTANCE.getAnimateType_Longdesc();
/**
* The meta object literal for the '<em><b>Max</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__MAX = eINSTANCE.getAnimateType_Max();
/**
* The meta object literal for the '<em><b>Min</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__MIN = eINSTANCE.getAnimateType_Min();
/**
* The meta object literal for the '<em><b>Repeat</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__REPEAT = eINSTANCE.getAnimateType_Repeat();
/**
* The meta object literal for the '<em><b>Repeat Count</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__REPEAT_COUNT = eINSTANCE.getAnimateType_RepeatCount();
/**
* The meta object literal for the '<em><b>Repeat Dur</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__REPEAT_DUR = eINSTANCE.getAnimateType_RepeatDur();
/**
* The meta object literal for the '<em><b>Restart</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__RESTART = eINSTANCE.getAnimateType_Restart();
/**
* The meta object literal for the '<em><b>Restart Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__RESTART_DEFAULT = eINSTANCE.getAnimateType_RestartDefault();
/**
* The meta object literal for the '<em><b>Skip Content</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__SKIP_CONTENT = eINSTANCE.getAnimateType_SkipContent();
/**
* The meta object literal for the '<em><b>Sync Behavior</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__SYNC_BEHAVIOR = eINSTANCE.getAnimateType_SyncBehavior();
/**
* The meta object literal for the '<em><b>Sync Behavior Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__SYNC_BEHAVIOR_DEFAULT = eINSTANCE.getAnimateType_SyncBehaviorDefault();
/**
* The meta object literal for the '<em><b>Sync Tolerance</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__SYNC_TOLERANCE = eINSTANCE.getAnimateType_SyncTolerance();
/**
* The meta object literal for the '<em><b>Sync Tolerance Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__SYNC_TOLERANCE_DEFAULT = eINSTANCE.getAnimateType_SyncToleranceDefault();
/**
* The meta object literal for the '<em><b>Target Element</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__TARGET_ELEMENT = eINSTANCE.getAnimateType_TargetElement();
/**
* The meta object literal for the '<em><b>Any Attribute</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ANIMATE_TYPE__ANY_ATTRIBUTE = eINSTANCE.getAnimateType_AnyAttribute();
/**
* The meta object literal for the '{@link org.w3._2001.smil20.language.impl.DocumentRootImpl <em>Document Root</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.w3._2001.smil20.language.impl.DocumentRootImpl
* @see org.w3._2001.smil20.language.impl.LanguagePackageImpl#getDocumentRoot()
* @generated
*/
EClass DOCUMENT_ROOT = eINSTANCE.getDocumentRoot();
/**
* The meta object literal for the '<em><b>Mixed</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute DOCUMENT_ROOT__MIXED = eINSTANCE.getDocumentRoot_Mixed();
/**
* The meta object literal for the '<em><b>XMLNS Prefix Map</b></em>' map feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference DOCUMENT_ROOT__XMLNS_PREFIX_MAP = eINSTANCE.getDocumentRoot_XMLNSPrefixMap();
/**
* The meta object literal for the '<em><b>XSI Schema Location</b></em>' map feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference DOCUMENT_ROOT__XSI_SCHEMA_LOCATION = eINSTANCE.getDocumentRoot_XSISchemaLocation();
/**
* The meta object literal for the '<em><b>Animate</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference DOCUMENT_ROOT__ANIMATE = eINSTANCE.getDocumentRoot_Animate();
/**
* The meta object literal for the '<em><b>Animate Color</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference DOCUMENT_ROOT__ANIMATE_COLOR = eINSTANCE.getDocumentRoot_AnimateColor();
/**
* The meta object literal for the '<em><b>Animate Motion</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference DOCUMENT_ROOT__ANIMATE_MOTION = eINSTANCE.getDocumentRoot_AnimateMotion();
/**
* The meta object literal for the '<em><b>Set</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference DOCUMENT_ROOT__SET = eINSTANCE.getDocumentRoot_Set();
/**
* The meta object literal for the '{@link org.w3._2001.smil20.language.impl.SetTypeImpl <em>Set Type</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.w3._2001.smil20.language.impl.SetTypeImpl
* @see org.w3._2001.smil20.language.impl.LanguagePackageImpl#getSetType()
* @generated
*/
EClass SET_TYPE = eINSTANCE.getSetType();
/**
* The meta object literal for the '<em><b>Group</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__GROUP = eINSTANCE.getSetType_Group();
/**
* The meta object literal for the '<em><b>Any</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__ANY = eINSTANCE.getSetType_Any();
/**
* The meta object literal for the '<em><b>Alt</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__ALT = eINSTANCE.getSetType_Alt();
/**
* The meta object literal for the '<em><b>Begin</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__BEGIN = eINSTANCE.getSetType_Begin();
/**
* The meta object literal for the '<em><b>Class</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__CLASS = eINSTANCE.getSetType_Class();
/**
* The meta object literal for the '<em><b>Dur</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__DUR = eINSTANCE.getSetType_Dur();
/**
* The meta object literal for the '<em><b>End</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__END = eINSTANCE.getSetType_End();
/**
* The meta object literal for the '<em><b>Fill</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__FILL = eINSTANCE.getSetType_Fill();
/**
* The meta object literal for the '<em><b>Fill Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__FILL_DEFAULT = eINSTANCE.getSetType_FillDefault();
/**
* The meta object literal for the '<em><b>Id</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__ID = eINSTANCE.getSetType_Id();
/**
* The meta object literal for the '<em><b>Lang</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__LANG = eINSTANCE.getSetType_Lang();
/**
* The meta object literal for the '<em><b>Longdesc</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__LONGDESC = eINSTANCE.getSetType_Longdesc();
/**
* The meta object literal for the '<em><b>Max</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__MAX = eINSTANCE.getSetType_Max();
/**
* The meta object literal for the '<em><b>Min</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__MIN = eINSTANCE.getSetType_Min();
/**
* The meta object literal for the '<em><b>Repeat</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__REPEAT = eINSTANCE.getSetType_Repeat();
/**
* The meta object literal for the '<em><b>Repeat Count</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__REPEAT_COUNT = eINSTANCE.getSetType_RepeatCount();
/**
* The meta object literal for the '<em><b>Repeat Dur</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__REPEAT_DUR = eINSTANCE.getSetType_RepeatDur();
/**
* The meta object literal for the '<em><b>Restart</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__RESTART = eINSTANCE.getSetType_Restart();
/**
* The meta object literal for the '<em><b>Restart Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__RESTART_DEFAULT = eINSTANCE.getSetType_RestartDefault();
/**
* The meta object literal for the '<em><b>Skip Content</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__SKIP_CONTENT = eINSTANCE.getSetType_SkipContent();
/**
* The meta object literal for the '<em><b>Sync Behavior</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__SYNC_BEHAVIOR = eINSTANCE.getSetType_SyncBehavior();
/**
* The meta object literal for the '<em><b>Sync Behavior Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__SYNC_BEHAVIOR_DEFAULT = eINSTANCE.getSetType_SyncBehaviorDefault();
/**
* The meta object literal for the '<em><b>Sync Tolerance</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__SYNC_TOLERANCE = eINSTANCE.getSetType_SyncTolerance();
/**
* The meta object literal for the '<em><b>Sync Tolerance Default</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__SYNC_TOLERANCE_DEFAULT = eINSTANCE.getSetType_SyncToleranceDefault();
/**
* The meta object literal for the '<em><b>Target Element</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__TARGET_ELEMENT = eINSTANCE.getSetType_TargetElement();
/**
* The meta object literal for the '<em><b>Any Attribute</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SET_TYPE__ANY_ATTRIBUTE = eINSTANCE.getSetType_AnyAttribute();
}
} //LanguagePackage<|fim▁end|> | |
<|file_name|>0004_labmandeploygeneralsettings_background_color.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('labman_setup', '0003_googlesearchscript'),
]
operations = [
migrations.AddField(
model_name='labmandeploygeneralsettings',
name='background_color',<|fim▁hole|> preserve_default=True,
),
]<|fim▁end|> | field=models.CharField(max_length=25, null=True, blank=True), |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![crate_name = "aws"]
#![crate_type = "lib"]
#![feature(convert)]
#[macro_use]
extern crate hyper;
#[cfg(unix)] extern crate openssl;
extern crate rustc_serialize as serialize;
extern crate time;
extern crate url;
extern crate ini;
#[macro_use]
extern crate log;
pub mod credentials;<|fim▁hole|>pub mod signers;<|fim▁end|> | pub mod request; |
<|file_name|>jest.config.js<|end_file_name|><|fim▁begin|>/**
* @license Copyright 2018 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
module.exports = {
collectCoverage: false,
coverageReporters: ['none'],
collectCoverageFrom: [
'**/lighthouse-core/**/*.js',
'**/lighthouse-cli/**/*.js',
'**/lighthouse-viewer/**/*.js',
],
coveragePathIgnorePatterns: [<|fim▁hole|> '/scripts/',
],
setupFilesAfterEnv: ['./lighthouse-core/test/test-utils.js'],
testEnvironment: 'node',
testMatch: [
'**/lighthouse-core/**/*-test.js',
'**/lighthouse-cli/**/*-test.js',
'**/lighthouse-viewer/**/*-test.js',
'**/lighthouse-viewer/**/*-test-pptr.js',
'**/clients/test/**/*-test.js',
'**/docs/**/*.test.js',
],
};<|fim▁end|> | '/test/', |
<|file_name|>CacheFeederAgent.py<|end_file_name|><|fim▁begin|># $HeadURL: $
''' CacheFeederAgent
This agent feeds the Cache tables with the outputs of the cache commands.
'''
from DIRAC import S_OK#, S_ERROR, gConfig
from DIRAC.AccountingSystem.Client.ReportsClient import ReportsClient
from DIRAC.Core.Base.AgentModule import AgentModule
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.Core.LCG.GOCDBClient import GOCDBClient
from DIRAC.ResourceStatusSystem.Client.ResourceStatusClient import ResourceStatusClient
from DIRAC.ResourceStatusSystem.Command import CommandCaller
#from DIRAC.ResourceStatusSystem.Utilities import CSHelpers
from DIRAC.ResourceStatusSystem.Utilities import Utils
ResourceManagementClient = getattr(Utils.voimport( 'DIRAC.ResourceStatusSystem.Client.ResourceManagementClient' ),'ResourceManagementClient')
__RCSID__ = '$Id: $'
AGENT_NAME = 'ResourceStatus/CacheFeederAgent'
class CacheFeederAgent( AgentModule ):
'''<|fim▁hole|> The CacheFeederAgent feeds the cache tables for the client and the accounting.
It runs periodically a set of commands, and stores it's results on the
tables.
'''
# Too many public methods
# pylint: disable-msg=R0904
def __init__( self, *args, **kwargs ):
AgentModule.__init__( self, *args, **kwargs )
self.commands = {}
self.clients = {}
self.cCaller = None
self.rmClient = None
def initialize( self ):
self.am_setOption( 'shifterProxy', 'DataManager' )
self.rmClient = ResourceManagementClient()
self.commands[ 'Downtime' ] = [ { 'Downtime' : {} } ]
self.commands[ 'SpaceTokenOccupancy' ] = [ { 'SpaceTokenOccupancy' : {} } ]
#PilotsCommand
# self.commands[ 'Pilots' ] = [
# { 'PilotsWMS' : { 'element' : 'Site', 'siteName' : None } },
# { 'PilotsWMS' : { 'element' : 'Resource', 'siteName' : None } }
# ]
#FIXME: do not forget about hourly vs Always ...etc
#AccountingCacheCommand
# self.commands[ 'AccountingCache' ] = [
# {'SuccessfullJobsBySiteSplitted' :{'hours' :24, 'plotType' :'Job' }},
# {'FailedJobsBySiteSplitted' :{'hours' :24, 'plotType' :'Job' }},
# {'SuccessfullPilotsBySiteSplitted' :{'hours' :24, 'plotType' :'Pilot' }},
# {'FailedPilotsBySiteSplitted' :{'hours' :24, 'plotType' :'Pilot' }},
# {'SuccessfullPilotsByCESplitted' :{'hours' :24, 'plotType' :'Pilot' }},
# {'FailedPilotsByCESplitted' :{'hours' :24, 'plotType' :'Pilot' }},
# {'RunningJobsBySiteSplitted' :{'hours' :24, 'plotType' :'Job' }},
## {'RunningJobsBySiteSplitted' :{'hours' :168, 'plotType' :'Job' }},
## {'RunningJobsBySiteSplitted' :{'hours' :720, 'plotType' :'Job' }},
## {'RunningJobsBySiteSplitted' :{'hours' :8760, 'plotType' :'Job' }},
# ]
#VOBOXAvailability
# self.commands[ 'VOBOXAvailability' ] = [
# { 'VOBOXAvailability' : {} }
#
#Reuse clients for the commands
self.clients[ 'GOCDBClient' ] = GOCDBClient()
self.clients[ 'ReportGenerator' ] = RPCClient( 'Accounting/ReportGenerator' )
self.clients[ 'ReportsClient' ] = ReportsClient()
self.clients[ 'ResourceStatusClient' ] = ResourceStatusClient()
self.clients[ 'ResourceManagementClient' ] = ResourceManagementClient()
self.clients[ 'WMSAdministrator' ] = RPCClient( 'WorkloadManagement/WMSAdministrator' )
self.cCaller = CommandCaller
return S_OK()
def loadCommand( self, commandModule, commandDict ):
commandName = commandDict.keys()[ 0 ]
commandArgs = commandDict[ commandName ]
commandTuple = ( '%sCommand' % commandModule, '%sCommand' % commandName )
commandObject = self.cCaller.commandInvocation( commandTuple, pArgs = commandArgs,
clients = self.clients )
if not commandObject[ 'OK' ]:
self.log.error( 'Error initializing %s' % commandName )
return commandObject
commandObject = commandObject[ 'Value' ]
# Set master mode
commandObject.masterMode = True
self.log.info( '%s/%s' % ( commandModule, commandName ) )
return S_OK( commandObject )
def execute( self ):
for commandModule, commandList in self.commands.items():
self.log.info( '%s module initialization' % commandModule )
for commandDict in commandList:
commandObject = self.loadCommand( commandModule, commandDict )
if not commandObject[ 'OK' ]:
self.log.error( commandObject[ 'Message' ] )
continue
commandObject = commandObject[ 'Value' ]
results = commandObject.doCommand()
if not results[ 'OK' ]:
self.log.error( results[ 'Message' ] )
continue
results = results[ 'Value' ]
if not results:
self.log.info( 'Empty results' )
continue
self.log.verbose( 'Command OK Results' )
self.log.verbose( results )
return S_OK()
################################################################################
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF<|fim▁end|> | |
<|file_name|>BestScoreSubSingleStatistic.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2010 JBoss 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.
*/
package org.optaplanner.benchmark.impl.statistic.bestscore;
import java.util.List;
import org.optaplanner.benchmark.config.statistic.ProblemStatisticType;
import org.optaplanner.benchmark.impl.result.SubSingleBenchmarkResult;
import org.optaplanner.benchmark.impl.statistic.ProblemBasedSubSingleStatistic;
import org.optaplanner.core.api.domain.solution.Solution;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.api.solver.event.BestSolutionChangedEvent;
import org.optaplanner.core.api.solver.event.SolverEventListener;
import org.optaplanner.core.impl.score.definition.ScoreDefinition;
public class BestScoreSubSingleStatistic extends ProblemBasedSubSingleStatistic<BestScoreStatisticPoint> {
private final BestScoreSubSingleStatisticListener listener;
public BestScoreSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) {
super(subSingleBenchmarkResult, ProblemStatisticType.BEST_SCORE);<|fim▁hole|> // ************************************************************************
// Lifecycle methods
// ************************************************************************
public void open(Solver solver) {
solver.addEventListener(listener);
}
public void close(Solver solver) {
solver.removeEventListener(listener);
}
private class BestScoreSubSingleStatisticListener implements SolverEventListener<Solution> {
public void bestSolutionChanged(BestSolutionChangedEvent<Solution> event) {
pointList.add(new BestScoreStatisticPoint(
event.getTimeMillisSpent(), event.getNewBestSolution().getScore()));
}
}
// ************************************************************************
// CSV methods
// ************************************************************************
@Override
protected String getCsvHeader() {
return BestScoreStatisticPoint.buildCsvLine("timeMillisSpent", "score");
}
@Override
protected BestScoreStatisticPoint createPointFromCsvLine(ScoreDefinition scoreDefinition,
List<String> csvLine) {
return new BestScoreStatisticPoint(Long.valueOf(csvLine.get(0)),
scoreDefinition.parseScore(csvLine.get(1)));
}
}<|fim▁end|> | listener = new BestScoreSubSingleStatisticListener();
}
|
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from datetime import datetime
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View, ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView
from content.models import Sub, SubFollow, Post, Commit
from content.forms import SubForm, PostForm, CommitForm
from notify.models import Noty
from core.core import random_avatar_sub
class CreateSubView(CreateView):
template_name = 'content/sub_create.html'
form_class = SubForm
def form_valid(self, form):
obj = form.save(commit=False)
obj.save()
obj.image = 'sub/%s.png' % (obj.slug)
obj.save()
random_avatar_sub(obj.slug)
return HttpResponseRedirect('/sub')
<|fim▁hole|> template_name = 'content/sub.html'
model = Sub
class FrontView(ListView):
template_name = 'layouts/post_list.html'
paginate_by = 4
def get(self, request, *args, **kwargs):
if request.is_ajax(): self.template_name = 'ajax/post_list.html'
return super(FrontView, self).get(request, *args, **kwargs)
def get_queryset(self):
if self.kwargs['tab'] == 'top': return Post.objects.last_commited()
else: return Post.objects.created()
def get_context_data(self, **kwargs):
context = super(FrontView, self).get_context_data(**kwargs)
context['list'] = 'portada'
context['tab_show'] = self.kwargs['tab']
if self.kwargs['tab'] == 'top': context['list_url'] = '/'
else: context['list_url'] = '/new'
return context
class SubPostListView(ListView):
template_name = 'content/sub_post_list.html'
paginate_by = 4
def get(self, request, *args, **kwargs):
if request.is_ajax(): self.template_name = 'ajax/post_list.html'
return super(SubPostListView, self).get(request, *args, **kwargs)
def get_queryset(self):
if self.kwargs['tab'] == 'top': return Post.objects.sub_last_commited(self.kwargs['sub'])
else: return Post.objects.sub_created(self.kwargs['sub'])
def get_context_data(self, **kwargs):
context = super(SubPostListView, self).get_context_data(**kwargs)
sub = Sub.objects.get(pk=self.kwargs['sub'])
user = self.request.user
if self.kwargs['tab'] == 'followers': context['followers'] = True
context['tab_show'] = self.kwargs['tab']
context['list'] = sub
context['tab'] = self.kwargs['tab']
if self.kwargs['tab'] == 'top': context['list_url'] = '/sub/%s' % sub
else: context['list_url'] = '/sub/%s/new' % sub
context['action'] = 'follow'
if user.is_authenticated():
follow_state = SubFollow.objects.by_id(sub_followid='%s>%s' % (user.pk, sub.pk))
if follow_state: context['action'] = 'unfollow'
else: context['action'] = 'follow'
return context
class PostCommitView(CreateView):
template_name = 'layouts/post_detail.html'
form_class = CommitForm
def get_context_data(self, **kwargs):
context = super(PostCommitView, self).get_context_data(**kwargs)
pk, slug = self.kwargs['pk'], self.kwargs['slug']
context['object'] = Post.objects.by_post(pk, slug)
return context
def form_valid(self, form):
if self.request.user.is_authenticated():
user = self.request.user
post = Post.objects.get(postid=self.kwargs['pk'])
obj = form.save(commit=False)
obj.create_commit(user, post)
if not obj.post.user.pk == user.pk:
noty = Noty.objects.create(user_id=obj.post.user_id, category='C', commit=obj)
noty.create_noty()
return HttpResponseRedirect(obj.get_commit_url())
else:
commit_url = '/post/%s/%s/' % (self.kwargs['pk'], self.kwargs['slug'])
return HttpResponseRedirect('/login/?next=%s' % (commit_url))
class CreatePostView(CreateView):
template_name = 'layouts/post_create.html'
form_class = PostForm
def form_valid(self, form):
obj = form.save(commit=False)
obj.user = self.request.user
obj.save()
if obj.draft: return HttpResponseRedirect('/created')
else:
obj.user.last_commited = obj.created
obj.user.save()
obj.sub.last_commited = obj.created
obj.sub.save()
obj.last_commited = obj.created
obj.save()
return HttpResponseRedirect(obj.get_absolute_url())
class UpdatePostView(UpdateView):
template_name = 'layouts/post_create.html'
form_class = PostForm
def get_queryset(self):
return Post.objects.by_user(self.request.user)
def form_valid(self, form):
obj = form.save(commit=False)
if not obj.last_commited and not obj.draft:
now = datetime.now()
obj.last_commited = now
obj.user.last_commited = now
obj.user.save()
obj.sub.last_commited = now
obj.sub.save()
obj.save()
if obj.draft: return HttpResponseRedirect('/created')
else: return HttpResponseRedirect(obj.get_absolute_url())
class PostUserCreatedView(ListView):
template_name = 'content/post_user_created.html'
def get_queryset(self):
return Post.objects.by_user(self.request.user)
class SubFollowCreate(View):
def post(self, request, *args, **kwargs):
user = self.request.user
sub_followed = self.kwargs['followed']
sub_followed_obj = SubFollow.objects.create(follower=user, sub_id=sub_followed)
sub_followed_obj.save()
sub_followed_obj.follower.sub_following_number += 1
sub_followed_obj.follower.save()
sub_followed_obj.sub.follower_number += 1
sub_followed_obj.sub.save()
return HttpResponse(status=200)
class SubFollowDelete(View):
def post(self, request, *args, **kwargs):
sub_unfollowed = self.kwargs['unfollowed']
sub_unfollowed_obj = SubFollow.objects.get(follower=self.request.user, sub_id=sub_unfollowed)
sub_unfollowed_obj.follower.sub_following_number -= 1
sub_unfollowed_obj.follower.save()
sub_unfollowed_obj.sub.follower_number -= 1
sub_unfollowed_obj.sub.save()
sub_unfollowed_obj.delete()
return HttpResponse(status=200)<|fim▁end|> | class SubView(ListView): |
<|file_name|>shell.py<|end_file_name|><|fim▁begin|>"""Output formatters using shell syntax.
"""
from .base import SingleFormatter
import argparse
import six
class ShellFormatter(SingleFormatter):
def add_argument_group(self, parser):
group = parser.add_argument_group(
title='shell formatter',
description='a format a UNIX shell can parse (variable="value")',<|fim▁hole|> )
group.add_argument(
'--variable',
action='append',
default=[],
dest='variables',
metavar='VARIABLE',
help=argparse.SUPPRESS,
)
group.add_argument(
'--prefix',
action='store',
default='',
dest='prefix',
help='add a prefix to all variable names',
)
def emit_one(self, column_names, data, stdout, parsed_args):
variable_names = [c.lower().replace(' ', '_')
for c in column_names
]
desired_columns = parsed_args.variables
for name, value in zip(variable_names, data):
if name in desired_columns or not desired_columns:
if isinstance(value, six.string_types):
value = value.replace('"', '\\"')
stdout.write('%s%s="%s"\n' % (parsed_args.prefix, name, value))
return<|fim▁end|> | |
<|file_name|>nodejs_require.js<|end_file_name|><|fim▁begin|>var n = require('./nodejs');
n.a;
n.b.c;
exports.a2 = n.a;
exports.b2 = n.b;<|fim▁hole|><|fim▁end|> | exports.c2 = n.b.c; |
<|file_name|>make_colorscale_from_colors.py<|end_file_name|><|fim▁begin|>def make_colorscale_from_colors(colors):
<|fim▁hole|>
return tuple((i / (len(colors) - 1), color) for i, color in enumerate(colors))<|fim▁end|> | if len(colors) == 1:
colors *= 2 |
<|file_name|>api_versions_request.go<|end_file_name|><|fim▁begin|>package sarama
// ApiVersionsRequest ...
type ApiVersionsRequest struct{}
func (a *ApiVersionsRequest) encode(pe packetEncoder) error {<|fim▁hole|> return nil
}
func (a *ApiVersionsRequest) decode(pd packetDecoder, version int16) (err error) {
return nil
}
func (a *ApiVersionsRequest) key() int16 {
return 18
}
func (a *ApiVersionsRequest) version() int16 {
return 0
}
func (a *ApiVersionsRequest) headerVersion() int16 {
return 1
}
func (a *ApiVersionsRequest) requiredVersion() KafkaVersion {
return V0_10_0_0
}<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | """Subpackage with PS-specific BSMP objects.""" |
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|>"""
sentry.client.celery.tasks
~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from celery.decorators import task
from sentry.client.base import SentryClient
from sentry.client.celery import conf
@task(routing_key=conf.CELERY_ROUTING_KEY)<|fim▁hole|> return SentryClient().send(**data)<|fim▁end|> | def send(data): |
<|file_name|>stats.py<|end_file_name|><|fim▁begin|>import numpy as np
file = "/home/rishabh/IdeaProjects/jitd/java/benchmark_20151213_224704_freqWrites/benchmark_scatter_1024m.txt"
# data = np.genfromtxt(file, dtype=(int, float, None), delimiter=',', names=['x', 'y', 'z'],)
data = np.genfromtxt(file, dtype=None, delimiter=',', names=['x', 'y', 'z'], )
write = 0
read = 0
max_read = 0
max_write = 0
read_count = 0
write_count = 0
total_time = 0
for each in data:
if each[2] == 'WRITE':
write += float(each[1])
max_write = max(max_write, each[1])
write_count += 1
else:
read += float(each[1])
max_read = max(max_read, each[1])<|fim▁hole|> total_time += each[1]
print "average_write: " + str(write / write_count)
print "average_read: " + str(read / read_count)
print "max_write: " + str(max_write)
print "max_read: " + str(max_read)
print "total_time: " + str(total_time)<|fim▁end|> | read_count += 1 |
<|file_name|>selection.ts<|end_file_name|><|fim▁begin|>import NodeUtils from "../../components/graph/NodeUtils"
import {getProcessToDisplay} from "../../reducers/selectors/graph"
import {ThunkAction} from "../reduxTypes"
import {deleteNodes} from "./node"
import {reportEvent} from "./reportEvent"
type Event = { category: string, action: string }
type Callback = () => void
type ToggleSelectionAction = { type: "TOGGLE_SELECTION", nodeIds: string[] }
type ExpandSelectionAction = { type: "EXPAND_SELECTION", nodeIds: string[] }
type ResetSelectionAction = { type: "RESET_SELECTION", nodeIds: string[] }
export type SelectionActions =
| ToggleSelectionAction
| ExpandSelectionAction
| ResetSelectionAction
export function copySelection(copyFunction: Callback, event: Event): ThunkAction {
return (dispatch) => {
copyFunction()
dispatch(reportEvent({
category: event.category,
action: event.action,
name: "copy",
}))
return dispatch({
type: "COPY_SELECTION",
})
}
}
export function cutSelection(cutFunction: Callback, event: Event): ThunkAction {
return (dispatch) => {
cutFunction()
dispatch(reportEvent({
category: event.category,
action: event.action,
name: "cut",
}))
return dispatch({
type: "CUT_SELECTION",
})
}
}
export function pasteSelection(pasteFunction: Callback, event: Event): ThunkAction {
return (dispatch) => {
pasteFunction()
dispatch(reportEvent({
category: event.category,
action: event.action,
name: "paste",
}))
return dispatch({
type: "PASTE_SELECTION",
})
}
}
export function deleteSelection(selectionState: string[], event: Event): ThunkAction {
return (dispatch, getState) => {
const process = getProcessToDisplay(getState())
const selectedNodes = NodeUtils.getAllNodesById(selectionState, process).map(n => n.id)
dispatch(reportEvent({
category: event.category,
action: event.action,
name: "delete",
}))
dispatch(deleteNodes(selectedNodes))
return dispatch({
type: "DELETE_SELECTION",
})
}
}
//remove browser text selection to avoid interference with "copy"
const clearTextSelection = () => window.getSelection().removeAllRanges()
export function toggleSelection(...nodeIds: string[]): ThunkAction {
return dispatch => {<|fim▁hole|> dispatch({type: "TOGGLE_SELECTION", nodeIds})
}
}
export function expandSelection(...nodeIds: string[]): ThunkAction {
return dispatch => {
clearTextSelection()
dispatch({type: "EXPAND_SELECTION", nodeIds})
}
}
export function resetSelection(...nodeIds: string[]): ThunkAction {
return dispatch => {
clearTextSelection()
dispatch({type: "RESET_SELECTION", nodeIds})
}
}
export function selectAll(): ThunkAction {
return (dispatch, getState) => {
const state = getState()
const process = getProcessToDisplay(state)
const nodeIds = process.nodes.map(n => n.id)
dispatch(resetSelection(...nodeIds))
}
}<|fim▁end|> | clearTextSelection() |
<|file_name|>account_bank_statement.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from openerp import api, fields, models, _
from openerp.osv import expression
from openerp.tools import float_is_zero
from openerp.tools import float_compare, float_round
from openerp.tools.misc import formatLang
from openerp.exceptions import UserError, ValidationError
import time
import math
class AccountCashboxLine(models.Model):
""" Cash Box Details """
_name = 'account.cashbox.line'
_description = 'CashBox Line'
_rec_name = 'coin_value'
_order = 'coin_value'
@api.one
@api.depends('coin_value', 'number')
def _sub_total(self):
""" Calculates Sub total"""
self.subtotal = self.coin_value * self.number
coin_value = fields.Float(string='Coin/Bill Value', required=True, digits=0)
number = fields.Integer(string='Number of Coins/Bills', help='Opening Unit Numbers')
subtotal = fields.Float(compute='_sub_total', string='Subtotal', digits=0, readonly=True)
cashbox_id = fields.Many2one('account.bank.statement.cashbox')
class AccountBankStmtCashWizard(models.Model):
"""
Account Bank Statement popup that allows entering cash details.
"""
_name = 'account.bank.statement.cashbox'
_description = 'Account Bank Statement Cashbox Details'
cashbox_lines_ids = fields.One2many('account.cashbox.line', 'cashbox_id', string='Cashbox Lines')
@api.multi
def validate(self):
bnk_stmt_id = self.env.context.get('active_id', False)
bnk_stmt = self.env['account.bank.statement'].browse(bnk_stmt_id)
total = 0.0
for lines in self.cashbox_lines_ids:
total += lines.subtotal
if self.env.context.get('balance', False) == 'start':
#starting balance
bnk_stmt.write({'balance_start': total, 'cashbox_start_id': self.id})
else:
#closing balance
bnk_stmt.write({'balance_end_real': total, 'cashbox_end_id': self.id})
return {'type': 'ir.actions.act_window_close'}
class AccountBankStmtCloseCheck(models.TransientModel):
"""
Account Bank Statement wizard that check that closing balance is correct.
"""
_name = 'account.bank.statement.closebalance'
_description = 'Account Bank Statement closing balance'
@api.multi
def validate(self):
bnk_stmt_id = self.env.context.get('active_id', False)
if bnk_stmt_id:
self.env['account.bank.statement'].browse(bnk_stmt_id).button_confirm_bank()
return {'type': 'ir.actions.act_window_close'}
class AccountBankStatement(models.Model):
@api.one
@api.depends('line_ids', 'balance_start', 'line_ids.amount', 'balance_end_real')
def _end_balance(self):
self.total_entry_encoding = sum([line.amount for line in self.line_ids])
self.balance_end = self.balance_start + self.total_entry_encoding
self.difference = self.balance_end_real - self.balance_end
@api.one
@api.depends('journal_id')
def _compute_currency(self):
self.currency_id = self.journal_id.currency_id or self.env.user.company_id.currency_id
@api.one
@api.depends('line_ids.journal_entry_ids')
def _check_lines_reconciled(self):
self.all_lines_reconciled = all([line.journal_entry_ids.ids or line.account_id.id for line in self.line_ids])
@api.model
def _default_journal(self):
journal_type = self.env.context.get('journal_type', False)
company_id = self.env['res.company']._company_default_get('account.bank.statement').id
if journal_type:
journals = self.env['account.journal'].search([('type', '=', journal_type), ('company_id', '=', company_id)])
if journals:
return journals[0]
return False
@api.multi
def _set_opening_balance(self, journal_id):
last_bnk_stmt = self.search([('journal_id', '=', journal_id), ('state', '=', 'confirm')], order="date desc", limit=1)
for bank_stmt in self:
if last_bnk_stmt:
bank_stmt.balance_start = last_bnk_stmt.balance_end
else:
bank_stmt.balance_start = 0
@api.model
def _default_opening_balance(self):
#Search last bank statement and set current opening balance as closing balance of previous one
journal_id = self._context.get('default_journal_id', False) or self._context.get('journal_id', False)
if journal_id:
self._set_opening_balance(journal_id)
_name = "account.bank.statement"
_description = "Bank Statement"
_order = "date desc, id desc"
_inherit = ['mail.thread']
name = fields.Char(string='Reference', states={'open': [('readonly', False)]}, copy=False, readonly=True)
date = fields.Date(required=True, states={'confirm': [('readonly', True)]}, select=True, copy=False, default=fields.Date.context_today)
date_done = fields.Datetime(string="Closed On")
balance_start = fields.Monetary(string='Starting Balance', states={'confirm': [('readonly', True)]}, default=_default_opening_balance)
balance_end_real = fields.Monetary('Ending Balance', states={'confirm': [('readonly', True)]})
state = fields.Selection([('open', 'New'), ('confirm', 'Validated')], string='Status', required=True, readonly=True, copy=False, default='open')
currency_id = fields.Many2one('res.currency', compute='_compute_currency', oldname='currency')
journal_id = fields.Many2one('account.journal', string='Journal', required=True, states={'confirm': [('readonly', True)]}, default=_default_journal)
journal_type = fields.Selection(related='journal_id.type', help="Technical field used for usability purposes")
company_id = fields.Many2one('res.company', related='journal_id.company_id', string='Company', store=True, readonly=True,
default=lambda self: self.env['res.company']._company_default_get('account.bank.statement'))
total_entry_encoding = fields.Monetary('Transactions Subtotal', compute='_end_balance', store=True, help="Total of transaction lines.")
balance_end = fields.Monetary('Computed Balance', compute='_end_balance', store=True, help='Balance as calculated based on Opening Balance and transaction lines')
difference = fields.Monetary(compute='_end_balance', store=True, help="Difference between the computed ending balance and the specified ending balance.")
line_ids = fields.One2many('account.bank.statement.line', 'statement_id', string='Statement lines', states={'confirm': [('readonly', True)]}, copy=True)
move_line_ids = fields.One2many('account.move.line', 'statement_id', string='Entry lines', states={'confirm': [('readonly', True)]})
all_lines_reconciled = fields.Boolean(compute='_check_lines_reconciled')
user_id = fields.Many2one('res.users', string='Responsible', required=False, default=lambda self: self.env.user)
cashbox_start_id = fields.Many2one('account.bank.statement.cashbox')
cashbox_end_id = fields.Many2one('account.bank.statement.cashbox')
@api.onchange('journal_id')
def onchange_journal_id(self):
self._set_opening_balance(self.journal_id.id)
@api.multi
def _balance_check(self):
for stmt in self:
if not stmt.currency_id.is_zero(stmt.difference):
if stmt.journal_type == 'cash':
if stmt.difference < 0.0:
account = stmt.journal_id.loss_account_id
name = _('Loss')
else:
# statement.difference > 0.0
account = stmt.journal_id.profit_account_id
name = _('Profit')
if not account:
raise UserError(_('There is no account defined on the journal %s for %s involved in a cash difference.') % (stmt.journal_id.name, name))
values = {
'statement_id': stmt.id,
'account_id': account.id,
'amount': stmt.difference,
'name': _("Cash difference observed during the counting (%s)") % name,
}
self.env['account.bank.statement.line'].create(values)
else:
balance_end_real = formatLang(self.env, stmt.balance_end_real, currency_obj=stmt.currency_id)
balance_end = formatLang(self.env, stmt.balance_end, currency_obj=stmt.currency_id)
raise UserError(_('The ending balance is incorrect !\nThe expected balance (%s) is different from the computed one. (%s)')
% (balance_end_real, balance_end))
return True
@api.model
def create(self, vals):
if not vals.get('name'):
journal_id = vals.get('journal_id', self._context.get('default_journal_id', False))
journal = self.env['account.journal'].browse(journal_id)
vals['name'] = journal.sequence_id.with_context(ir_sequence_date=vals.get('date')).next_by_id()
return super(AccountBankStatement, self).create(vals)
@api.multi
def unlink(self):
for statement in self:
if statement.state != 'open':
raise UserError(_('In order to delete a bank statement, you must first cancel it to delete related journal items.'))
# Explicitly unlink bank statement lines so it will check that the related journal entries have been deleted first
statement.line_ids.unlink()
return super(AccountBankStatement, self).unlink()
@api.multi
def open_cashbox_id(self):
context = dict(self.env.context or {})
if context.get('cashbox_id'):
context['active_id'] = self.id
return {
'name': _('Cash Control'),
'view_type': 'form',
'view_mode': 'form',
'res_model': 'account.bank.statement.cashbox',
'view_id': self.env.ref('account.view_account_bnk_stmt_cashbox').id,
'type': 'ir.actions.act_window',
'res_id': self.env.context.get('cashbox_id'),
'context': context,
'target': 'new'
}
@api.multi
def button_cancel(self):
for statement in self:
if any(line.journal_entry_ids.ids for line in statement.line_ids):
raise UserError(_('A statement cannot be canceled when its lines are reconciled.'))
self.state = 'open'
@api.multi
def check_confirm_bank(self):
if self.journal_type == 'cash' and not self.currency_id.is_zero(self.difference):
action_rec = self.env['ir.model.data'].xmlid_to_object('account.action_view_account_bnk_stmt_check')
if action_rec:
action = action_rec.read([])[0]
return action
return self.button_confirm_bank()
@api.multi
def button_confirm_bank(self):
self._balance_check()
statements = self.filtered(lambda r: r.state == 'open')
for statement in statements:
moves = self.env['account.move']
for st_line in statement.line_ids:
if st_line.account_id and not st_line.journal_entry_ids.ids:
st_line.fast_counterpart_creation()
elif not st_line.journal_entry_ids.ids:
raise UserError(_('All the account entries lines must be processed in order to close the statement.'))
moves = (moves | st_line.journal_entry_ids)
if moves:
moves.post()
statement.message_post(body=_('Statement %s confirmed, journal items were created.') % (statement.name,))
statements.link_bank_to_partner()
statements.write({'state': 'confirm', 'date_done': time.strftime("%Y-%m-%d %H:%M:%S")})
@api.multi
def button_journal_entries(self):
context = dict(self._context or {})
context['journal_id'] = self.journal_id.id
return {
'name': _('Journal Items'),
'view_type': 'form',
'view_mode': 'tree',
'res_model': 'account.move.line',
'view_id': False,
'type': 'ir.actions.act_window',
'domain': [('statement_id', 'in', self.ids)],
'context': context,
}
@api.multi
def button_open(self):
""" Changes statement state to Running."""
for statement in self:
if not statement.name:
context = {'ir_sequence_date', statement.date}
if statement.journal_id.sequence_id:
st_number = statement.journal_id.sequence_id.with_context(context).next_by_id()
else:
SequenceObj = self.env['ir.sequence']
st_number = SequenceObj.with_context(context).next_by_code('account.bank.statement')
statement.name = st_number
statement.state = 'open'
@api.multi
def reconciliation_widget_preprocess(self):
""" Get statement lines of the specified statements or all unreconciled statement lines and try to automatically reconcile them / find them a partner.
Return ids of statement lines left to reconcile and other data for the reconciliation widget.
"""
statements = self
bsl_obj = self.env['account.bank.statement.line']
# NB : The field account_id can be used at the statement line creation/import to avoid the reconciliation process on it later on,
# this is why we filter out statements lines where account_id is set
st_lines_filter = [('journal_entry_ids', '=', False), ('account_id', '=', False)]
if statements:
st_lines_filter += [('statement_id', 'in', statements.ids)]
# Try to automatically reconcile statement lines
automatic_reconciliation_entries = []
st_lines_left = self.env['account.bank.statement.line']
for st_line in bsl_obj.search(st_lines_filter):
res = st_line.auto_reconcile()
if not res:
st_lines_left = (st_lines_left | st_line)
else:
automatic_reconciliation_entries.append(res.ids)
# Try to set statement line's partner
for st_line in st_lines_left:
if st_line.name and not st_line.partner_id:
additional_domain = [('ref', '=', st_line.name)]
match_recs = st_line.get_move_lines_for_reconciliation(limit=1, additional_domain=additional_domain, overlook_partner=True)
if match_recs and match_recs[0].partner_id:
st_line.write({'partner_id': match_recs[0].partner_id.id})
# Collect various informations for the reconciliation widget
notifications = []
num_auto_reconciled = len(automatic_reconciliation_entries)
if num_auto_reconciled > 0:
auto_reconciled_message = num_auto_reconciled > 1 \
and _("%d transactions were automatically reconciled.") % num_auto_reconciled \
or _("1 transaction was automatically reconciled.")
notifications += [{
'type': 'info',
'message': auto_reconciled_message,
'details': {
'name': _("Automatically reconciled items"),
'model': 'account.move',
'ids': automatic_reconciliation_entries
}
}]
lines = []
for el in statements:
lines.extend(el.line_ids.ids)
lines = list(set(lines))
return {
'st_lines_ids': st_lines_left.ids,
'notifications': notifications,
'statement_name': len(statements) == 1 and statements[0].name or False,
'num_already_reconciled_lines': statements and bsl_obj.search_count([('journal_entry_ids', '!=', False), ('id', 'in', lines)]) or 0,
}
@api.multi
def link_bank_to_partner(self):
for statement in self:
for st_line in statement.line_ids:
if st_line.bank_account_id and st_line.partner_id and st_line.bank_account_id.partner_id.id != st_line.partner_id.id:
bank_vals = st_line.bank_account_id.onchange_partner_id(st_line.partner_id.id)['value']
bank_vals.update({'partner_id': st_line.partner_id.id})
st_line.bank_account_id.write(bank_vals)
class AccountBankStatementLine(models.Model):
_name = "account.bank.statement.line"
_description = "Bank Statement Line"
_order = "statement_id desc, sequence"
_inherit = ['ir.needaction_mixin']
name = fields.Char(string='Memo', required=True)
date = fields.Date(required=True, default=lambda self: self._context.get('date', fields.Date.context_today(self)))
amount = fields.Monetary(digits=0, currency_field='journal_currency_id')
journal_currency_id = fields.Many2one('res.currency', related='statement_id.currency_id',
help='Utility field to express amount currency', readonly=True)
partner_id = fields.Many2one('res.partner', string='Partner')
bank_account_id = fields.Many2one('res.partner.bank', string='Bank Account')
account_id = fields.Many2one('account.account', string='Counterpart Account', domain=[('deprecated', '=', False)],
help="This technical field can be used at the statement line creation/import time in order to avoid the reconciliation"
" process on it later on. The statement line will simply create a counterpart on this account")
statement_id = fields.Many2one('account.bank.statement', string='Statement', index=True, required=True, ondelete='cascade')
journal_id = fields.Many2one('account.journal', related='statement_id.journal_id', string='Journal', store=True, readonly=True)
partner_name = fields.Char(help="This field is used to record the third party name when importing bank statement in electronic format,"
" when the partner doesn't exist yet in the database (or cannot be found).")
ref = fields.Char(string='Reference')
note = fields.Text(string='Notes')
sequence = fields.Integer(index=True, help="Gives the sequence order when displaying a list of bank statement lines.", default=1)
company_id = fields.Many2one('res.company', related='statement_id.company_id', string='Company', store=True, readonly=True)
journal_entry_ids = fields.One2many('account.move', 'statement_line_id', 'Journal Entries', copy=False, readonly=True)
amount_currency = fields.Monetary(help="The amount expressed in an optional other currency if it is a multi-currency entry.")
currency_id = fields.Many2one('res.currency', string='Currency', help="The optional other currency if it is a multi-currency entry.")
@api.one
@api.constrains('amount')
def _check_amount(self):
# This constraint could possibly underline flaws in bank statement import (eg. inability to
# support hacks such as using dummy transactions to give additional informations)
if self.amount == 0:
raise ValidationError(_('A transaction can\'t have a 0 amount.'))
@api.one
@api.constrains('amount', 'amount_currency')
def _check_amount_currency(self):
if self.amount_currency != 0 and self.amount == 0:
raise ValidationError(_('If "Amount Currency" is specified, then "Amount" must be as well.'))
@api.multi
def unlink(self):
for line in self:
if line.journal_entry_ids.ids:
raise UserError(_('In order to delete a bank statement line, you must first cancel it to delete related journal items.'))
return super(AccountBankStatementLine, self).unlink()
@api.model
def _needaction_domain_get(self):
return [('journal_entry_ids', '=', False), ('account_id', '=', False)]
@api.multi
def button_cancel_reconciliation(self):
# TOCKECK : might not behave as expected in case of reconciliations (match statement line with already
# registered payment) or partial reconciliations : it will completely remove the existing payment.
move_recs = self.env['account.move']
for st_line in self:
move_recs = (move_recs | st_line.journal_entry_ids)
if move_recs:
for move in move_recs:
move.line_ids.remove_move_reconcile()
move_recs.write({'statement_line_id': False})
move_recs.button_cancel()
move_recs.unlink()
####################################################
# Reconciliation interface methods
####################################################
@api.multi
def get_data_for_reconciliation_widget(self, excluded_ids=None):
""" Returns the data required to display a reconciliation widget, for each statement line in self """
excluded_ids = excluded_ids or []
ret = []
for st_line in self:
aml_recs = st_line.get_reconciliation_proposition(excluded_ids=excluded_ids)
target_currency = st_line.currency_id or st_line.journal_id.currency_id or st_line.journal_id.company_id.currency_id
rp = aml_recs.prepare_move_lines_for_reconciliation_widget(target_currency=target_currency, target_date=st_line.date)
excluded_ids += [move_line['id'] for move_line in rp]
ret.append({
'st_line': st_line.get_statement_line_for_reconciliation_widget(),
'reconciliation_proposition': rp
})
return ret
def get_statement_line_for_reconciliation_widget(self):
""" Returns the data required by the bank statement reconciliation widget to display a statement line """
statement_currency = self.journal_id.currency_id or self.journal_id.company_id.currency_id
if self.amount_currency and self.currency_id:
amount = self.amount_currency
amount_currency = self.amount
amount_currency_str = amount_currency > 0 and amount_currency or -amount_currency
amount_currency_str = formatLang(self.env, amount_currency_str, currency_obj=statement_currency)
else:
amount = self.amount
amount_currency_str = ""
amount_str = formatLang(self.env, abs(amount), currency_obj=self.currency_id or statement_currency)
data = {
'id': self.id,
'ref': self.ref,
'note': self.note or "",
'name': self.name,
'date': self.date,
'amount': amount,
'amount_str': amount_str, # Amount in the statement line currency
'currency_id': self.currency_id.id or statement_currency.id,
'partner_id': self.partner_id.id,
'journal_id': self.journal_id.id,
'statement_id': self.statement_id.id,
'account_code': self.journal_id.default_debit_account_id.code,
'account_name': self.journal_id.default_debit_account_id.name,
'partner_name': self.partner_id.name,
'communication_partner_name': self.partner_name,
'amount_currency_str': amount_currency_str, # Amount in the statement currency
'has_no_partner': not self.partner_id.id,
}
if self.partner_id:
if amount > 0:
data['open_balance_account_id'] = self.partner_id.property_account_receivable_id.id
else:
data['open_balance_account_id'] = self.partner_id.property_account_payable_id.id
return data
@api.multi
def get_move_lines_for_reconciliation_widget(self, excluded_ids=None, str=False, offset=0, limit=None):
""" Returns move lines for the bank statement reconciliation widget, formatted as a list of dicts
"""
aml_recs = self.get_move_lines_for_reconciliation(excluded_ids=excluded_ids, str=str, offset=offset, limit=limit)
target_currency = self.currency_id or self.journal_id.currency_id or self.journal_id.company_id.currency_id
return aml_recs.prepare_move_lines_for_reconciliation_widget(target_currency=target_currency, target_date=self.date)
####################################################
# Reconciliation methods
####################################################
def get_move_lines_for_reconciliation(self, excluded_ids=None, str=False, offset=0, limit=None, additional_domain=None, overlook_partner=False):
""" Return account.move.line records which can be used for bank statement reconciliation.
:param excluded_ids:
:param str:
:param offset:
:param limit:
:param additional_domain:
:param overlook_partner:<|fim▁hole|> domain_reconciliation = ['&', ('statement_id', '=', False), ('account_id', 'in', reconciliation_aml_accounts)]
# Domain to fetch unreconciled payables/receivables (use case where you close invoices/refunds by reconciling your bank statements)
domain_matching = [('reconciled', '=', False)]
if self.partner_id.id or overlook_partner:
domain_matching = expression.AND([domain_matching, [('account_id.internal_type', 'in', ['payable', 'receivable'])]])
else:
# TODO : find out what use case this permits (match a check payment, registered on a journal whose account type is other instead of liquidity)
domain_matching = expression.AND([domain_matching, [('account_id.reconcile', '=', True)]])
# Let's add what applies to both
domain = expression.OR([domain_reconciliation, domain_matching])
if self.partner_id.id and not overlook_partner:
domain = expression.AND([domain, [('partner_id', '=', self.partner_id.id)]])
# Domain factorized for all reconciliation use cases
ctx = dict(self._context or {})
ctx['bank_statement_line'] = self
generic_domain = self.env['account.move.line'].with_context(ctx).domain_move_lines_for_reconciliation(excluded_ids=excluded_ids, str=str)
domain = expression.AND([domain, generic_domain])
# Domain from caller
if additional_domain is None:
additional_domain = []
else:
additional_domain = expression.normalize_domain(additional_domain)
domain = expression.AND([domain, additional_domain])
return self.env['account.move.line'].search(domain, offset=offset, limit=limit, order="date_maturity asc, id asc")
def _get_domain_maker_move_line_amount(self):
""" Returns a function that can create the appropriate domain to search on move.line amount based on statement.line currency/amount """
company_currency = self.journal_id.company_id.currency_id
st_line_currency = self.currency_id or self.journal_id.currency_id
currency = (st_line_currency and st_line_currency != company_currency) and st_line_currency.id or False
field = currency and 'amount_residual_currency' or 'amount_residual'
precision = st_line_currency and st_line_currency.decimal_places or company_currency.decimal_places
def ret(comparator, amount, p=precision, f=field, c=currency):
if comparator == '<':
if amount < 0:
domain = [(f, '<', 0), (f, '>', amount)]
else:
domain = [(f, '>', 0), (f, '<', amount)]
elif comparator == '=':
domain = [(f, '=', float_round(amount, precision_digits=p))]
else:
raise UserError(_("Programmation error : domain_maker_move_line_amount requires comparator '=' or '<'"))
domain += [('currency_id', '=', c)]
return domain
return ret
def get_reconciliation_proposition(self, excluded_ids=None):
""" Returns move lines that constitute the best guess to reconcile a statement line
Note: it only looks for move lines in the same currency as the statement line.
"""
# Look for structured communication match
if self.name:
overlook_partner = not self.partner_id # If the transaction has no partner, look for match in payable and receivable account anyway
domain = [('ref', '=', self.name)]
match_recs = self.get_move_lines_for_reconciliation(excluded_ids=excluded_ids, limit=2, additional_domain=domain, overlook_partner=overlook_partner)
if match_recs and len(match_recs) == 1:
return match_recs
# How to compare statement line amount and move lines amount
amount_domain_maker = self._get_domain_maker_move_line_amount()
amount = self.amount_currency or self.amount
# Look for a single move line with the same amount
match_recs = self.get_move_lines_for_reconciliation(excluded_ids=excluded_ids, limit=1, additional_domain=amount_domain_maker('=', amount))
if match_recs:
return match_recs
if not self.partner_id:
return self.env['account.move.line']
# Select move lines until their total amount is greater than the statement line amount
domain = [('reconciled', '=', False)]
domain += [('account_id.user_type_id.type', '=', amount > 0 and 'receivable' or 'payable')] # Make sure we can't mix receivable and payable
domain += amount_domain_maker('<', amount) # Will also enforce > 0
mv_lines = self.get_move_lines_for_reconciliation(excluded_ids=excluded_ids, limit=5, additional_domain=domain)
st_line_currency = self.currency_id or self.journal_id.currency_id or self.journal_id.company_id.currency_id
ret = self.env['account.move.line']
total = 0
for line in mv_lines:
total += line.currency_id and line.amount_residual_currency or line.amount_residual
if float_compare(total, abs(amount), precision_digits=st_line_currency.rounding) != -1:
break
ret = (ret | line)
return ret
def _get_move_lines_for_auto_reconcile(self):
""" Returns the move lines that the method auto_reconcile can use to try to reconcile the statement line """
pass
@api.multi
def auto_reconcile(self):
""" Try to automatically reconcile the statement.line ; return the counterpart journal entry/ies if the automatic reconciliation succeeded, False otherwise.
TODO : this method could be greatly improved and made extensible
"""
self.ensure_one()
match_recs = self.env['account.move.line']
# How to compare statement line amount and move lines amount
amount_domain_maker = self._get_domain_maker_move_line_amount()
equal_amount_domain = amount_domain_maker('=', self.amount_currency or self.amount)
# Look for structured communication match
if self.name:
overlook_partner = not self.partner_id # If the transaction has no partner, look for match in payable and receivable account anyway
domain = equal_amount_domain + [('ref', '=', self.name)]
match_recs = self.get_move_lines_for_reconciliation(limit=2, additional_domain=domain, overlook_partner=overlook_partner)
if match_recs and len(match_recs) != 1:
return False
# Look for a single move line with the same partner, the same amount
if not match_recs:
if self.partner_id:
match_recs = self.get_move_lines_for_reconciliation(limit=2, additional_domain=equal_amount_domain)
if match_recs and len(match_recs) != 1:
return False
if not match_recs:
return False
# Now reconcile
counterpart_aml_dicts = []
payment_aml_rec = self.env['account.move.line']
for aml in match_recs:
if aml.account_id.internal_type == 'liquidity':
payment_aml_rec = (payment_aml_rec | aml)
else:
amount = aml.currency_id and aml.amount_residual_currency or aml.amount_residual
counterpart_aml_dicts.append({
'name': aml.name if aml.name != '/' else aml.move_id.name,
'debit': amount < 0 and -amount or 0,
'credit': amount > 0 and amount or 0,
'move_line': aml
})
try:
with self._cr.savepoint():
counterpart = self.process_reconciliation(counterpart_aml_dicts=counterpart_aml_dicts, payment_aml_rec=payment_aml_rec)
return counterpart
except UserError:
# A configuration / business logic error that makes it impossible to auto-reconcile should not be raised
# since automatic reconciliation is just an amenity and the user will get the same exception when manually
# reconciling. Other types of exception are (hopefully) programmation errors and should cause a stacktrace.
self.invalidate_cache()
self.env['account.move'].invalidate_cache()
self.env['account.move.line'].invalidate_cache()
return False
def _prepare_reconciliation_move(self, move_name):
""" Prepare the dict of values to create the move from a statement line. This method may be overridden to adapt domain logic
through model inheritance (make sure to call super() to establish a clean extension chain).
:param char st_line_number: will be used as the name of the generated account move
:return: dict of value to create() the account.move
"""
return {
'statement_line_id': self.id,
'journal_id': self.statement_id.journal_id.id,
'date': self.date,
'name': move_name,
'ref': self.ref,
}
def _prepare_reconciliation_move_line(self, move, amount):
""" Prepare the dict of values to create the move line from a statement line.
:param recordset move: the account.move to link the move line
:param float amount: the amount of transaction that wasn't already reconciled
"""
company_currency = self.journal_id.company_id.currency_id
statement_currency = self.journal_id.currency_id or company_currency
st_line_currency = self.currency_id or statement_currency
amount_currency = False
if statement_currency != company_currency or st_line_currency != company_currency:
# First get the ratio total mount / amount not already reconciled
if statement_currency == company_currency:
total_amount = self.amount
elif st_line_currency == company_currency:
total_amount = self.amount_currency
else:
total_amount = statement_currency.with_context({'date': self.date}).compute(self.amount, company_currency)
ratio = total_amount / amount
# Then use it to adjust the statement.line field that correspond to the move.line amount_currency
if statement_currency != company_currency:
amount_currency = self.amount * ratio
elif st_line_currency != company_currency:
amount_currency = self.amount_currency * ratio
return {
'name': self.name,
'date': self.date,
'ref': self.ref,
'move_id': move.id,
'partner_id': self.partner_id and self.partner_id.id or False,
'account_id': amount >= 0 \
and self.statement_id.journal_id.default_credit_account_id.id \
or self.statement_id.journal_id.default_debit_account_id.id,
'credit': amount < 0 and -amount or 0.0,
'debit': amount > 0 and amount or 0.0,
'statement_id': self.statement_id.id,
'journal_id': self.statement_id.journal_id.id,
'currency_id': statement_currency != company_currency and statement_currency.id or (st_line_currency != company_currency and st_line_currency.id or False),
'amount_currency': amount_currency,
}
@api.v7
def process_reconciliations(self, cr, uid, ids, data, context=None):
""" Handles data sent from the bank statement reconciliation widget (and can otherwise serve as an old-API bridge)
:param list of dicts data: must contains the keys 'counterpart_aml_dicts', 'payment_aml_ids' and 'new_aml_dicts',
whose value is the same as described in process_reconciliation except that ids are used instead of recordsets.
"""
aml_obj = self.pool['account.move.line']
for id, datum in zip(ids, data):
st_line = self.browse(cr, uid, id, context)
payment_aml_rec = aml_obj.browse(cr, uid, datum.get('payment_aml_ids', []), context)
for aml_dict in datum.get('counterpart_aml_dicts', []):
aml_dict['move_line'] = aml_obj.browse(cr, uid, aml_dict['counterpart_aml_id'], context)
del aml_dict['counterpart_aml_id']
st_line.process_reconciliation(datum.get('counterpart_aml_dicts', []), payment_aml_rec, datum.get('new_aml_dicts', []))
def fast_counterpart_creation(self):
for st_line in self:
# Technical functionality to automatically reconcile by creating a new move line
vals = {
'name': st_line.name,
'debit': st_line.amount < 0 and -st_line.amount or 0.0,
'credit': st_line.amount > 0 and st_line.amount or 0.0,
'account_id': st_line.account_id.id,
}
st_line.process_reconciliation(new_aml_dicts=[vals])
def process_reconciliation(self, counterpart_aml_dicts=None, payment_aml_rec=None, new_aml_dicts=None):
""" Match statement lines with existing payments (eg. checks) and/or payables/receivables (eg. invoices and refunds) and/or new move lines (eg. write-offs).
If any new journal item needs to be created (via new_aml_dicts or counterpart_aml_dicts), a new journal entry will be created and will contain those
items, as well as a journal item for the bank statement line.
Finally, mark the statement line as reconciled by putting the matched moves ids in the column journal_entry_ids.
:param (list of dicts) counterpart_aml_dicts: move lines to create to reconcile with existing payables/receivables.
The expected keys are :
- 'name'
- 'debit'
- 'credit'
- 'move_line'
# The move line to reconcile (partially if specified debit/credit is lower than move line's credit/debit)
:param (list of recordsets) payment_aml_rec: recordset move lines representing existing payments (which are already fully reconciled)
:param (list of dicts) new_aml_dicts: move lines to create. The expected keys are :
- 'name'
- 'debit'
- 'credit'
- 'account_id'
- (optional) 'tax_ids'
- (optional) Other account.move.line fields like analytic_account_id or analytics_id
:returns: The journal entries with which the transaction was matched. If there was at least an entry in counterpart_aml_dicts or new_aml_dicts, this list contains
the move created by the reconciliation, containing entries for the statement.line (1), the counterpart move lines (0..*) and the new move lines (0..*).
"""
counterpart_aml_dicts = counterpart_aml_dicts or []
payment_aml_rec = payment_aml_rec or self.env['account.move.line']
new_aml_dicts = new_aml_dicts or []
aml_obj = self.env['account.move.line']
company_currency = self.journal_id.company_id.currency_id
statement_currency = self.journal_id.currency_id or company_currency
st_line_currency = self.currency_id or statement_currency
counterpart_moves = self.env['account.move']
# Check and prepare received data
if self.journal_entry_ids.ids:
raise UserError(_('The bank statement line was already reconciled.'))
if any(rec.statement_id for rec in payment_aml_rec):
raise UserError(_('A selected move line was already reconciled.'))
for aml_dict in counterpart_aml_dicts:
if aml_dict['move_line'].reconciled:
raise UserError(_('A selected move line was already reconciled.'))
if isinstance(aml_dict['move_line'], (int, long)):
aml_dict['move_line'] = aml_obj.browse(aml_dict['move_line'])
for aml_dict in (counterpart_aml_dicts + new_aml_dicts):
if aml_dict.get('tax_ids') and aml_dict['tax_ids'] and isinstance(aml_dict['tax_ids'][0], (int, long)):
# Transform the value in the format required for One2many and Many2many fields
aml_dict['tax_ids'] = map(lambda id: (4, id, None), aml_dict['tax_ids'])
# Fully reconciled moves are just linked to the bank statement
for aml_rec in payment_aml_rec:
aml_rec.write({'statement_id': self.statement_id.id})
aml_rec.move_id.write({'statement_line_id': self.id})
counterpart_moves = (counterpart_moves | aml_rec.move_id)
# Create move line(s). Either matching an existing journal entry (eg. invoice), in which
# case we reconcile the existing and the new move lines together, or being a write-off.
if counterpart_aml_dicts or new_aml_dicts:
st_line_currency = self.currency_id or statement_currency
st_line_currency_rate = self.currency_id and (self.amount_currency / self.amount) or False
# Create the move
move_name = (self.statement_id.name or self.name) + "/" + str(self.sequence)
move_vals = self._prepare_reconciliation_move(move_name)
move = self.env['account.move'].create(move_vals)
move.post()
counterpart_moves = (counterpart_moves | move)
# Complete dicts to create both counterpart move lines and write-offs
to_create = (counterpart_aml_dicts + new_aml_dicts)
ctx = dict(self._context, date=self.date)
for aml_dict in to_create:
aml_dict['move_id'] = move.id
aml_dict['date'] = self.statement_id.date
aml_dict['partner_id'] = self.partner_id.id
aml_dict['journal_id'] = self.journal_id.id
aml_dict['company_id'] = self.company_id.id
aml_dict['statement_id'] = self.statement_id.id
if st_line_currency.id != company_currency.id:
aml_dict['amount_currency'] = aml_dict['debit'] - aml_dict['credit']
aml_dict['currency_id'] = st_line_currency.id
if self.currency_id and statement_currency.id == company_currency.id and st_line_currency_rate:
# Statement is in company currency but the transaction is in foreign currency
aml_dict['debit'] = company_currency.round(aml_dict['debit'] / st_line_currency_rate)
aml_dict['credit'] = company_currency.round(aml_dict['credit'] / st_line_currency_rate)
elif self.currency_id and st_line_currency_rate:
# Statement is in foreign currency and the transaction is in another one
aml_dict['debit'] = statement_currency.with_context(ctx).compute(aml_dict['debit'] / st_line_currency_rate, company_currency)
aml_dict['credit'] = statement_currency.with_context(ctx).compute(aml_dict['credit'] / st_line_currency_rate, company_currency)
else:
# Statement is in foreign currency and no extra currency is given for the transaction
aml_dict['debit'] = st_line_currency.with_context(ctx).compute(aml_dict['debit'], company_currency)
aml_dict['credit'] = st_line_currency.with_context(ctx).compute(aml_dict['credit'], company_currency)
elif statement_currency.id != company_currency.id:
# Statement is in foreign currency but the transaction is in company currency
prorata_factor = (aml_dict['debit'] - aml_dict['credit']) / self.amount_currency
aml_dict['amount_currency'] = prorata_factor * self.amount
aml_dict['currency_id'] = statement_currency.id
# Create the move line for the statement line using the total credit/debit of the counterpart
# This leaves out the amount already reconciled and avoids rounding errors from currency conversion
st_line_amount = sum(aml_dict['credit'] - aml_dict['debit'] for aml_dict in to_create)
aml_obj.with_context(check_move_validity=False).create(self._prepare_reconciliation_move_line(move, st_line_amount))
# Create write-offs
for aml_dict in new_aml_dicts:
aml_obj.with_context(check_move_validity=False).create(aml_dict)
# Create counterpart move lines and reconcile them
for aml_dict in counterpart_aml_dicts:
if aml_dict['move_line'].partner_id.id:
aml_dict['partner_id'] = aml_dict['move_line'].partner_id.id
aml_dict['account_id'] = aml_dict['move_line'].account_id.id
counterpart_move_line = aml_dict.pop('move_line')
if counterpart_move_line.currency_id and counterpart_move_line.currency_id != company_currency and not aml_dict.get('currency_id'):
aml_dict['currency_id'] = counterpart_move_line.currency_id.id
aml_dict['amount_currency'] = company_currency.with_context(ctx).compute(aml_dict['debit'] - aml_dict['credit'], counterpart_move_line.currency_id)
new_aml = aml_obj.with_context(check_move_validity=False).create(aml_dict)
(new_aml | counterpart_move_line).reconcile()
counterpart_moves.assert_balanced()
return counterpart_moves<|fim▁end|> | """
# Domain to fetch registered payments (use case where you encode the payment before you get the bank statement)
reconciliation_aml_accounts = [self.journal_id.default_credit_account_id.id, self.journal_id.default_debit_account_id.id] |
<|file_name|>test_lastpass.py<|end_file_name|><|fim▁begin|># (c)2016 Andrew Zenk <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from argparse import ArgumentParser
from units.compat import unittest
from units.compat.mock import patch
from ansible.errors import AnsibleError
from ansible.module_utils import six
from ansible.plugins.lookup.lastpass import LookupModule, LPass, LPassException
MOCK_ENTRIES = [{'username': 'user',
'name': 'Mock Entry',
'password': 't0pS3cret passphrase entry!',
'url': 'https://localhost/login',
'notes': 'Test\nnote with multiple lines.\n',
'id': '0123456789'}]
class MockLPass(LPass):
_mock_logged_out = False<|fim▁hole|> def _lookup_mock_entry(self, key):
for entry in MOCK_ENTRIES:
if key == entry['id'] or key == entry['name']:
return entry
def _run(self, args, stdin=None, expected_rc=0):
# Mock behavior of lpass executable
base_options = ArgumentParser(add_help=False)
base_options.add_argument('--color', default="auto", choices=['auto', 'always', 'never'])
p = ArgumentParser()
sp = p.add_subparsers(help='command', dest='subparser_name')
logout_p = sp.add_parser('logout', parents=[base_options], help='logout')
show_p = sp.add_parser('show', parents=[base_options], help='show entry details')
field_group = show_p.add_mutually_exclusive_group(required=True)
for field in MOCK_ENTRIES[0].keys():
field_group.add_argument("--{0}".format(field), default=False, action='store_true')
field_group.add_argument('--field', default=None)
show_p.add_argument('selector', help='Unique Name or ID')
args = p.parse_args(args)
def mock_exit(output='', error='', rc=0):
if rc != expected_rc:
raise LPassException(error)
return output, error
if args.color != 'never':
return mock_exit(error='Error: Mock only supports --color=never', rc=1)
if args.subparser_name == 'logout':
if self._mock_logged_out:
return mock_exit(error='Error: Not currently logged in', rc=1)
logged_in_error = 'Are you sure you would like to log out? [Y/n]'
if stdin and stdin.lower() == 'n\n':
return mock_exit(output='Log out: aborted.', error=logged_in_error, rc=1)
elif stdin and stdin.lower() == 'y\n':
return mock_exit(output='Log out: complete.', error=logged_in_error, rc=0)
else:
return mock_exit(error='Error: aborted response', rc=1)
if args.subparser_name == 'show':
if self._mock_logged_out:
return mock_exit(error='Error: Could not find decryption key.' +
' Perhaps you need to login with `lpass login`.', rc=1)
if self._mock_disconnected:
return mock_exit(error='Error: Couldn\'t resolve host name.', rc=1)
mock_entry = self._lookup_mock_entry(args.selector)
if args.field:
return mock_exit(output=mock_entry.get(args.field, ''))
elif args.password:
return mock_exit(output=mock_entry.get('password', ''))
elif args.username:
return mock_exit(output=mock_entry.get('username', ''))
elif args.url:
return mock_exit(output=mock_entry.get('url', ''))
elif args.name:
return mock_exit(output=mock_entry.get('name', ''))
elif args.id:
return mock_exit(output=mock_entry.get('id', ''))
elif args.notes:
return mock_exit(output=mock_entry.get('notes', ''))
raise LPassException('We should never get here')
class DisconnectedMockLPass(MockLPass):
_mock_disconnected = True
class LoggedOutMockLPass(MockLPass):
_mock_logged_out = True
class TestLPass(unittest.TestCase):
def test_lastpass_cli_path(self):
lp = MockLPass(path='/dev/null')
self.assertEqual('/dev/null', lp.cli_path)
def test_lastpass_build_args_logout(self):
lp = MockLPass()
self.assertEqual(['logout', '--color=never'], lp._build_args("logout"))
def test_lastpass_logged_in_true(self):
lp = MockLPass()
self.assertTrue(lp.logged_in)
def test_lastpass_logged_in_false(self):
lp = LoggedOutMockLPass()
self.assertFalse(lp.logged_in)
def test_lastpass_show_disconnected(self):
lp = DisconnectedMockLPass()
with self.assertRaises(LPassException):
lp.get_field('0123456789', 'username')
def test_lastpass_show(self):
lp = MockLPass()
for entry in MOCK_ENTRIES:
entry_id = entry.get('id')
for k, v in six.iteritems(entry):
self.assertEqual(v.strip(), lp.get_field(entry_id, k))
class TestLastpassPlugin(unittest.TestCase):
@patch('ansible.plugins.lookup.lastpass.LPass', new=MockLPass)
def test_lastpass_plugin_normal(self):
lookup_plugin = LookupModule()
for entry in MOCK_ENTRIES:
entry_id = entry.get('id')
for k, v in six.iteritems(entry):
self.assertEqual(v.strip(),
lookup_plugin.run([entry_id], field=k)[0])
@patch('ansible.plugins.lookup.lastpass.LPass', LoggedOutMockLPass)
def test_lastpass_plugin_logged_out(self):
lookup_plugin = LookupModule()
entry = MOCK_ENTRIES[0]
entry_id = entry.get('id')
with self.assertRaises(AnsibleError):
lookup_plugin.run([entry_id], field='password')
@patch('ansible.plugins.lookup.lastpass.LPass', DisconnectedMockLPass)
def test_lastpass_plugin_disconnected(self):
lookup_plugin = LookupModule()
entry = MOCK_ENTRIES[0]
entry_id = entry.get('id')
with self.assertRaises(AnsibleError):
lookup_plugin.run([entry_id], field='password')<|fim▁end|> | _mock_disconnected = False
|
<|file_name|>util_test.go<|end_file_name|><|fim▁begin|>package httpagent
import (
"testing"
"github.com/mesos/mesos-go/api/v1/lib/agent"
)
func TestClassifyResponse(t *testing.T) {
_, err := classifyResponse(nil)
if err == nil {
t.Fatal("expected error instead of nil")
}
for _, v := range agent.Call_Type_value {
ct := agent.Call_Type(v)<|fim▁hole|> if err == nil {
t.Fatal("expected error instead of nil")
}
} else {
if err != nil {
t.Fatalf("unexpected error %v", err)
}
}
}
}<|fim▁end|> | _, err = classifyResponse(&agent.Call{Type: ct})
if ct == agent.Call_UNKNOWN { |
<|file_name|>image.ts<|end_file_name|><|fim▁begin|>/**
* Entry point for Embed Images
*/
/// <reference path="./embed.d.ts" />
// require('html5shiv');
//import _ = require('underscore');
let pym = require('pym.js');
import ConfigService from '../components/embed/config/service';
import ResizeEl from '../components/utils/resizeEl';
export default class Embed {
private configService;
private resourceOriginalWidth;
private resourceOriginalHeight;
private $embedContainer;
private $embedResource;
private resizer;
private pymChild;
constructor() {
let that = this;
this.configService = new ConfigService();
this.$embedContainer = document.getElementById('embed-content');
this.$embedResource = document.getElementById('embed-image');
this.resourceOriginalWidth = this.configService.get('resource.width');
this.resourceOriginalHeight = this.configService.get('resource.height');
if( this.configService.get('isStandalone') === true ) {
this.initResizer();
} else {
this.$embedResource.style.width = '100%';
this.$embedResource.style.height = 'auto';
this.pymChild = new (<any>pym).Child({id: 'phraseanet-embed-frame', renderCallback: function(windowWidth) {
let ratio = that.resourceOriginalHeight / that.resourceOriginalWidth;
that.$embedResource.style.width = '100%';
that.$embedResource.style.height = 'auto';
// send image calculated height
that.$embedContainer.style.height = windowWidth * ratio + 'px';
}});
if (this.pymChild.parentUrl === '') {
// no parent pym:
this.initResizer();
}
}
}
initResizer() {<|fim▁hole|> this.resizer = new ResizeEl({
target: this.$embedResource,
container: this.$embedContainer,
resizeOnWindowChange: this.configService.get('resource.fitIn') === true ? true : false
});
this.resizer.setContainerDimensions({
width: <any>window.innerWidth,
height: <any>window.innerHeight
});
this.resizer.setTargetDimensions({
width: this.resourceOriginalWidth,
height: this.resourceOriginalHeight
});
this.resizer.resize();
}
}
(<any>window).embedPlugin = new Embed();<|fim▁end|> | |
<|file_name|>services.js<|end_file_name|><|fim▁begin|>[
{
"title": "Ventes véhicules",
"url": "",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg",
"language": "fr-FR",
"order": "1",
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "published",
"children": [
{
"title": "http://portail.inetpsa.com/sites/gpmobile/PublishingImages/car2.jpg",
"url": "http://portail.inetpsa.com/sites/gpmobile/PublishingImages/car2.jpg",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg",
"language": "fr-FR",
"order": 0,
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "published"
},
{
"title": "Ventes véhicules Peugeot",
"url": "https://docinfogroupe.psa-peugeot-citroen.com/ead/dom/1000788899.fd",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg",
"language": "fr-FR",
"order": 1,
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "edited"
},
{
"title": "Ventes véhicules DS",
"url": "https://docinfogroupe.psa-peugeot-citroen.com/ead/dom/1000779116.fd",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg",
"language": "fr-FR",
"order": 2,
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "published"
}
]
},
{
"title": "Webmail",
"url": "https://webmail.mpsa.com/",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/webmail.jpg",
"language": "en-US",
"order": "0",
"workplace": "All",
<|fim▁hole|> "categoryPro": "All",
"status": "published",
"children": []
},
{
"title": "Net'RH congés",
"url": "https://fr-rh.mpsa.com/rib00/ribdnins.nsf/fc583fb6947d633ac12569450031fbd2/755dcfb785421c6cc1256c7f003107c2?OpenDocument",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/holiday.jpg",
"language": "fr-FR",
"order": "3",
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "unpublished",
"children": []
}
]<|fim▁end|> | "department": "All",
|
<|file_name|>OutputStreamProxyFactory.java<|end_file_name|><|fim▁begin|>/*
* HA-JDBC: High-Availability JDBC
* Copyright (C) 2013 Paul Ferraro
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.hajdbc.sql.io;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.Map;
import net.sf.hajdbc.Database;
import net.sf.hajdbc.invocation.Invoker;
import net.sf.hajdbc.sql.ProxyFactory;
/**
* @author Paul Ferraro
*/
public class OutputStreamProxyFactory<Z, D extends Database<Z>, P> extends OutputProxyFactory<Z, D, P, OutputStream>
{
public OutputStreamProxyFactory(P parentProxy, ProxyFactory<Z, D, P, SQLException> parent, Invoker<Z, D, P, OutputStream, SQLException> invoker, Map<D, OutputStream> outputs)
{<|fim▁hole|> @Override
public OutputStream createProxy()
{
return new OutputStreamProxy<>(this);
}
}<|fim▁end|> | super(parentProxy, parent, invoker, outputs);
}
|
<|file_name|>TodoList.js<|end_file_name|><|fim▁begin|><|fim▁hole|>import TodoItem from './TodoItem';
const TodoList = ({todos}) => (
<ul className="todo-list">
{todos.map(todo =>
<TodoItem key={todo.id} {...todo} />
)}
</ul>
);
TodoList.propTypes = {
todos: PropTypes.array.isRequired
}
export default TodoList;<|fim▁end|> | import React, { PropTypes } from 'react'; |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>extern crate num_traits;<|fim▁hole|>// macro must be defined first to be usable in other modules
#[macro_use]
mod macros;
// Nullable container
mod nullvec;
// Nullable scalar
mod nullable;
// Generic types
mod generic;
// common
mod algos;
mod traits;
pub mod prelude;
// - Ops ToDo
//
// - Nullable + primitive (done)
// - Nullable + Nullable (done)
// - Nullable + NullVec
//
// - NullVec + primitive (done)
// - NullVec + Nullable (done)
// - NullVec + Vec (done)
// - NullVec + NullVec (done)
//
// - Conversion ToDo
//
// - float and Null
// - Nullable and Null
//
// - vec and NullVec
//
// - ToDo:
// - Add array and scalar
//<|fim▁end|> | |
<|file_name|>test_remove_duplicate_trackers.py<|end_file_name|><|fim▁begin|>import pytest
import unittest
from unittest import mock
from django.conf import settings
from django.core.management import call_command
from oppia.test import OppiaTestCase
from io import StringIO
from oppia.models import Tracker
class RemoveDuplicateTrackersTest(OppiaTestCase):
fixtures = ['tests/test_user.json',
'tests/test_oppia.json',
'default_gamification_events.json',
'tests/test_tracker.json',
'tests/test_permissions.json',
'default_badges.json',
'tests/test_course_permissions.json']
def test_remove_no_duplicates(self):
out = StringIO()
tracker_count_start = Tracker.objects.all().count()
call_command('remove_duplicate_trackers', stdout=out)
tracker_count_end = Tracker.objects.all().count()
self.assertEqual(tracker_count_start, tracker_count_end)
@mock.patch("oppia.management.commands.remove_duplicate_trackers.input")
def _call_wrapper(self, response_value, mock_input=None):
def input_response(message):
return response_value<|fim▁hole|> return out.getvalue().rstrip()
@pytest.mark.xfail(reason="works on local, but not on Github workflow")
@unittest.skipIf(settings.DATABASES['default']['ENGINE']
== 'django.db.backends.sqlite3',
"This is an sqlite-specific issue")
def test_remove_with_duplicates(self):
Tracker.objects.create(
user_id=1,
course_id=1,
type="page",
completed=True,
time_taken=280,
activity_title="{\"en\":"
"\"Calculating the uptake of antenatal care services\"}",
section_title="{\"en\": \"Planning Antenatal Care\"}",
uuid="835713f3-b85e-4960-9cdf-128f04014178")
tracker_count_start = Tracker.objects.all().count()
self._call_wrapper('y')
tracker_count_end = Tracker.objects.all().count()
self.assertEqual(tracker_count_start-1, tracker_count_end)<|fim▁end|> | mock_input.side_effect = input_response
out = StringIO()
call_command('remove_duplicate_trackers', stdout=out) |
<|file_name|>mac_notification.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# native notification on mac! needs Xcode (latest version) installed and pyobjc
# library from pip
import Foundation
import AppKit
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')<|fim▁hole|>def notifyMac(title, subtitle, info_text, delay=0):
notification = NSUserNotification.alloc().init()
notification.setTitle_(title)
notification.setSubtitle_(subtitle)
notification.setInformativeText_(info_text)
notification.setDeliveryDate_(Foundation.NSDate.dateWithTimeInterval_sinceDate_(
delay, Foundation.NSDate.date()))
NSUserNotificationCenter.defaultUserNotificationCenter(
).scheduleNotification_(notification)<|fim▁end|> | |
<|file_name|>jssip.js<|end_file_name|><|fim▁begin|>/*
* JsSIP v3.0.2
* the Javascript SIP library
* Copyright: 2012-2017 José Luis Millán <[email protected]> (https://github.com/jmillan)
* Homepage: http://jssip.net
* License: MIT
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JsSIP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var pkg = require('../package.json');
var C = {
USER_AGENT: pkg.title + ' ' + pkg.version,
// SIP scheme
SIP: 'sip',
SIPS: 'sips',
// End and Failure causes
causes: {
// Generic error causes
CONNECTION_ERROR: 'Connection Error',
REQUEST_TIMEOUT: 'Request Timeout',
SIP_FAILURE_CODE: 'SIP Failure Code',
INTERNAL_ERROR: 'Internal Error',
// SIP error causes
BUSY: 'Busy',
REJECTED: 'Rejected',
REDIRECTED: 'Redirected',
UNAVAILABLE: 'Unavailable',
NOT_FOUND: 'Not Found',
ADDRESS_INCOMPLETE: 'Address Incomplete',
INCOMPATIBLE_SDP: 'Incompatible SDP',
MISSING_SDP: 'Missing SDP',
AUTHENTICATION_ERROR: 'Authentication Error',
// Session error causes
BYE: 'Terminated',
WEBRTC_ERROR: 'WebRTC Error',
CANCELED: 'Canceled',
NO_ANSWER: 'No Answer',
EXPIRES: 'Expires',
NO_ACK: 'No ACK',
DIALOG_ERROR: 'Dialog Error',
USER_DENIED_MEDIA_ACCESS: 'User Denied Media Access',
BAD_MEDIA_DESCRIPTION: 'Bad Media Description',
RTP_TIMEOUT: 'RTP Timeout'
},
SIP_ERROR_CAUSES: {
REDIRECTED: [300,301,302,305,380],
BUSY: [486,600],
REJECTED: [403,603],
NOT_FOUND: [404,604],
UNAVAILABLE: [480,410,408,430],
ADDRESS_INCOMPLETE: [484, 424],
INCOMPATIBLE_SDP: [488,606],
AUTHENTICATION_ERROR:[401,407]
},
// SIP Methods
ACK: 'ACK',
BYE: 'BYE',
CANCEL: 'CANCEL',
INFO: 'INFO',
INVITE: 'INVITE',
MESSAGE: 'MESSAGE',
NOTIFY: 'NOTIFY',
OPTIONS: 'OPTIONS',
REGISTER: 'REGISTER',
REFER: 'REFER',
UPDATE: 'UPDATE',
SUBSCRIBE: 'SUBSCRIBE',
/* SIP Response Reasons
* DOC: http://www.iana.org/assignments/sip-parameters
* Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7
*/
REASON_PHRASE: {
100: 'Trying',
180: 'Ringing',
181: 'Call Is Being Forwarded',
182: 'Queued',
183: 'Session Progress',
199: 'Early Dialog Terminated', // draft-ietf-sipcore-199
200: 'OK',
202: 'Accepted', // RFC 3265
204: 'No Notification', //RFC 5839
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Moved Temporarily',
305: 'Use Proxy',
380: 'Alternative Service',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
410: 'Gone',
412: 'Conditional Request Failed', // RFC 3903
413: 'Request Entity Too Large',
414: 'Request-URI Too Long',
415: 'Unsupported Media Type',
416: 'Unsupported URI Scheme',
417: 'Unknown Resource-Priority', // RFC 4412
420: 'Bad Extension',
421: 'Extension Required',
422: 'Session Interval Too Small', // RFC 4028
423: 'Interval Too Brief',
424: 'Bad Location Information', // RFC 6442
428: 'Use Identity Header', // RFC 4474
429: 'Provide Referrer Identity', // RFC 3892
430: 'Flow Failed', // RFC 5626
433: 'Anonymity Disallowed', // RFC 5079
436: 'Bad Identity-Info', // RFC 4474
437: 'Unsupported Certificate', // RFC 4744
438: 'Invalid Identity Header', // RFC 4744
439: 'First Hop Lacks Outbound Support', // RFC 5626
440: 'Max-Breadth Exceeded', // RFC 5393
469: 'Bad Info Package', // draft-ietf-sipcore-info-events
470: 'Consent Needed', // RFC 5360
478: 'Unresolvable Destination', // Custom code copied from Kamailio.
480: 'Temporarily Unavailable',
481: 'Call/Transaction Does Not Exist',
482: 'Loop Detected',
483: 'Too Many Hops',
484: 'Address Incomplete',
485: 'Ambiguous',
486: 'Busy Here',
487: 'Request Terminated',
488: 'Not Acceptable Here',
489: 'Bad Event', // RFC 3265
491: 'Request Pending',
493: 'Undecipherable',
494: 'Security Agreement Required', // RFC 3329
500: 'JsSIP Internal Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Server Time-out',
505: 'Version Not Supported',
513: 'Message Too Large',
580: 'Precondition Failure', // RFC 3312
600: 'Busy Everywhere',
603: 'Decline',
604: 'Does Not Exist Anywhere',
606: 'Not Acceptable'
},
ALLOWED_METHODS: 'INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO',
ACCEPTED_BODY_TYPES: 'application/sdp, application/dtmf-relay',
MAX_FORWARDS: 69,
SESSION_EXPIRES: 90,
MIN_SESSION_EXPIRES: 60
};
module.exports = C;
},{"../package.json":50}],2:[function(require,module,exports){
module.exports = Dialog;
var C = {
// Dialog states
STATUS_EARLY: 1,
STATUS_CONFIRMED: 2
};
/**
* Expose C object.
*/
Dialog.C = C;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:Dialog');
var SIPMessage = require('./SIPMessage');
var JsSIP_C = require('./Constants');
var Transactions = require('./Transactions');
var Dialog_RequestSender = require('./Dialog/RequestSender');
// RFC 3261 12.1
function Dialog(owner, message, type, state) {
var contact;
this.uac_pending_reply = false;
this.uas_pending_reply = false;
if(!message.hasHeader('contact')) {
return {
error: 'unable to create a Dialog without Contact header field'
};
}
if(message instanceof SIPMessage.IncomingResponse) {
state = (message.status_code < 200) ? C.STATUS_EARLY : C.STATUS_CONFIRMED;
} else {
// Create confirmed dialog if state is not defined
state = state || C.STATUS_CONFIRMED;
}
contact = message.parseHeader('contact');
// RFC 3261 12.1.1
if(type === 'UAS') {
this.id = {
call_id: message.call_id,
local_tag: message.to_tag,
remote_tag: message.from_tag,
toString: function() {
return this.call_id + this.local_tag + this.remote_tag;
}
};
this.state = state;
this.remote_seqnum = message.cseq;
this.local_uri = message.parseHeader('to').uri;
this.remote_uri = message.parseHeader('from').uri;
this.remote_target = contact.uri;
this.route_set = message.getHeaders('record-route');
}
// RFC 3261 12.1.2
else if(type === 'UAC') {
this.id = {
call_id: message.call_id,
local_tag: message.from_tag,
remote_tag: message.to_tag,
toString: function() {
return this.call_id + this.local_tag + this.remote_tag;
}
};
this.state = state;
this.local_seqnum = message.cseq;
this.local_uri = message.parseHeader('from').uri;
this.remote_uri = message.parseHeader('to').uri;
this.remote_target = contact.uri;
this.route_set = message.getHeaders('record-route').reverse();
}
this.owner = owner;
owner.ua.dialogs[this.id.toString()] = this;
debug('new ' + type + ' dialog created with status ' + (this.state === C.STATUS_EARLY ? 'EARLY': 'CONFIRMED'));
}
Dialog.prototype = {
update: function(message, type) {
this.state = C.STATUS_CONFIRMED;
debug('dialog '+ this.id.toString() +' changed to CONFIRMED state');
if(type === 'UAC') {
// RFC 3261 13.2.2.4
this.route_set = message.getHeaders('record-route').reverse();
}
},
terminate: function() {
debug('dialog ' + this.id.toString() + ' deleted');
delete this.owner.ua.dialogs[this.id.toString()];
},
// RFC 3261 12.2.1.1
createRequest: function(method, extraHeaders, body) {
var cseq, request;
extraHeaders = extraHeaders && extraHeaders.slice() || [];
if(!this.local_seqnum) { this.local_seqnum = Math.floor(Math.random() * 10000); }
cseq = (method === JsSIP_C.CANCEL || method === JsSIP_C.ACK) ? this.local_seqnum : this.local_seqnum += 1;
request = new SIPMessage.OutgoingRequest(
method,
this.remote_target,
this.owner.ua, {
'cseq': cseq,
'call_id': this.id.call_id,
'from_uri': this.local_uri,
'from_tag': this.id.local_tag,
'to_uri': this.remote_uri,
'to_tag': this.id.remote_tag,
'route_set': this.route_set
}, extraHeaders, body);
request.dialog = this;
return request;
},
// RFC 3261 12.2.2
checkInDialogRequest: function(request) {
var self = this;
if(!this.remote_seqnum) {
this.remote_seqnum = request.cseq;
} else if(request.cseq < this.remote_seqnum) {
//Do not try to reply to an ACK request.
if (request.method !== JsSIP_C.ACK) {
request.reply(500);
}
return false;
} else if(request.cseq > this.remote_seqnum) {
this.remote_seqnum = request.cseq;
}
// RFC3261 14.2 Modifying an Existing Session -UAS BEHAVIOR-
if (request.method === JsSIP_C.INVITE || (request.method === JsSIP_C.UPDATE && request.body)) {
if (this.uac_pending_reply === true) {
request.reply(491);
} else if (this.uas_pending_reply === true) {
var retryAfter = (Math.random() * 10 | 0) + 1;
request.reply(500, null, ['Retry-After:'+ retryAfter]);
return false;
} else {
this.uas_pending_reply = true;
request.server_transaction.on('stateChanged', function stateChanged(){
if (this.state === Transactions.C.STATUS_ACCEPTED ||
this.state === Transactions.C.STATUS_COMPLETED ||
this.state === Transactions.C.STATUS_TERMINATED) {
request.server_transaction.removeListener('stateChanged', stateChanged);
self.uas_pending_reply = false;
}
});
}
// RFC3261 12.2.2 Replace the dialog`s remote target URI if the request is accepted
if(request.hasHeader('contact')) {
request.server_transaction.on('stateChanged', function(){
if (this.state === Transactions.C.STATUS_ACCEPTED) {
self.remote_target = request.parseHeader('contact').uri;
}
});
}
}
else if (request.method === JsSIP_C.NOTIFY) {
// RFC6665 3.2 Replace the dialog`s remote target URI if the request is accepted
if(request.hasHeader('contact')) {
request.server_transaction.on('stateChanged', function(){
if (this.state === Transactions.C.STATUS_COMPLETED) {
self.remote_target = request.parseHeader('contact').uri;
}
});
}
}
return true;
},
sendRequest: function(applicant, method, options) {
options = options || {};
var
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body || null,
request = this.createRequest(method, extraHeaders, body),
request_sender = new Dialog_RequestSender(this, applicant, request);
request_sender.send();
// Return the instance of OutgoingRequest
return request;
},
receiveRequest: function(request) {
//Check in-dialog request
if(!this.checkInDialogRequest(request)) {
return;
}
this.owner.receiveRequest(request);
}
};
},{"./Constants":1,"./Dialog/RequestSender":3,"./SIPMessage":18,"./Transactions":21,"debug":34}],3:[function(require,module,exports){
module.exports = DialogRequestSender;
/**
* Dependencies.
*/
var JsSIP_C = require('../Constants');
var Transactions = require('../Transactions');
var RTCSession = require('../RTCSession');
var RequestSender = require('../RequestSender');
function DialogRequestSender(dialog, applicant, request) {
this.dialog = dialog;
this.applicant = applicant;
this.request = request;
// RFC3261 14.1 Modifying an Existing Session. UAC Behavior.
this.reattempt = false;
this.reattemptTimer = null;
}
DialogRequestSender.prototype = {
send: function() {
var
self = this,
request_sender = new RequestSender(this, this.dialog.owner.ua);
request_sender.send();
// RFC3261 14.2 Modifying an Existing Session -UAC BEHAVIOR-
if ((this.request.method === JsSIP_C.INVITE || (this.request.method === JsSIP_C.UPDATE && this.request.body)) &&
request_sender.clientTransaction.state !== Transactions.C.STATUS_TERMINATED) {
this.dialog.uac_pending_reply = true;
request_sender.clientTransaction.on('stateChanged', function stateChanged(){
if (this.state === Transactions.C.STATUS_ACCEPTED ||
this.state === Transactions.C.STATUS_COMPLETED ||
this.state === Transactions.C.STATUS_TERMINATED) {
request_sender.clientTransaction.removeListener('stateChanged', stateChanged);
self.dialog.uac_pending_reply = false;
}
});
}
},
onRequestTimeout: function() {
this.applicant.onRequestTimeout();
},
onTransportError: function() {
this.applicant.onTransportError();
},
receiveResponse: function(response) {
var self = this;
// RFC3261 12.2.1.2 408 or 481 is received for a request within a dialog.
if (response.status_code === 408 || response.status_code === 481) {
this.applicant.onDialogError(response);
} else if (response.method === JsSIP_C.INVITE && response.status_code === 491) {
if (this.reattempt) {
this.applicant.receiveResponse(response);
} else {
this.request.cseq.value = this.dialog.local_seqnum += 1;
this.reattemptTimer = setTimeout(function() {
if (self.applicant.owner.status !== RTCSession.C.STATUS_TERMINATED) {
self.reattempt = true;
self.request_sender.send();
}
}, 1000);
}
} else {
this.applicant.receiveResponse(response);
}
}
};
},{"../Constants":1,"../RTCSession":11,"../RequestSender":17,"../Transactions":21}],4:[function(require,module,exports){
module.exports = DigestAuthentication;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:DigestAuthentication');
var debugerror = require('debug')('JsSIP:ERROR:DigestAuthentication');
debugerror.log = console.warn.bind(console);
var Utils = require('./Utils');
function DigestAuthentication(credentials) {
this.credentials = credentials;
this.cnonce = null;
this.nc = 0;
this.ncHex = '00000000';
this.algorithm = null;
this.realm = null;
this.nonce = null;
this.opaque = null;
this.stale = null;
this.qop = null;
this.method = null;
this.uri = null;
this.ha1 = null;
this.response = null;
}
DigestAuthentication.prototype.get = function(parameter) {
switch (parameter) {
case 'realm':
return this.realm;
case 'ha1':
return this.ha1;
default:
debugerror('get() | cannot get "%s" parameter', parameter);
return undefined;
}
};
/**
* Performs Digest authentication given a SIP request and the challenge
* received in a response to that request.
* Returns true if auth was successfully generated, false otherwise.
*/
DigestAuthentication.prototype.authenticate = function(request, challenge) {
var ha2, hex;
this.algorithm = challenge.algorithm;
this.realm = challenge.realm;
this.nonce = challenge.nonce;
this.opaque = challenge.opaque;
this.stale = challenge.stale;
if (this.algorithm) {
if (this.algorithm !== 'MD5') {
debugerror('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted');
return false;
}
} else {
this.algorithm = 'MD5';
}
if (!this.nonce) {
debugerror('authenticate() | challenge without Digest nonce, authentication aborted');
return false;
}
if (!this.realm) {
debugerror('authenticate() | challenge without Digest realm, authentication aborted');
return false;
}
// If no plain SIP password is provided.
if (!this.credentials.password) {
// If ha1 is not provided we cannot authenticate.
if (!this.credentials.ha1) {
debugerror('authenticate() | no plain SIP password nor ha1 provided, authentication aborted');
return false;
}
// If the realm does not match the stored realm we cannot authenticate.
if (this.credentials.realm !== this.realm) {
debugerror('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]', this.credentials.realm, this.realm);
return false;
}
}
// 'qop' can contain a list of values (Array). Let's choose just one.
if (challenge.qop) {
if (challenge.qop.indexOf('auth') > -1) {
this.qop = 'auth';
} else if (challenge.qop.indexOf('auth-int') > -1) {
this.qop = 'auth-int';
} else {
// Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here.
debugerror('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted');
return false;
}
} else {
this.qop = null;
}
// Fill other attributes.
this.method = request.method;
this.uri = request.ruri;
this.cnonce = Utils.createRandomToken(12);
this.nc += 1;
hex = Number(this.nc).toString(16);
this.ncHex = '00000000'.substr(0, 8-hex.length) + hex;
// nc-value = 8LHEX. Max value = 'FFFFFFFF'.
if (this.nc === 4294967296) {
this.nc = 1;
this.ncHex = '00000001';
}
// Calculate the Digest "response" value.
// If we have plain SIP password then regenerate ha1.
if (this.credentials.password) {
// HA1 = MD5(A1) = MD5(username:realm:password)
this.ha1 = Utils.calculateMD5(this.credentials.username + ':' + this.realm + ':' + this.credentials.password);
//
// Otherwise reuse the stored ha1.
} else {
this.ha1 = this.credentials.ha1;
}
if (this.qop === 'auth') {
// HA2 = MD5(A2) = MD5(method:digestURI)
ha2 = Utils.calculateMD5(this.method + ':' + this.uri);
// response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)
this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth:' + ha2);
} else if (this.qop === 'auth-int') {
// HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody))
ha2 = Utils.calculateMD5(this.method + ':' + this.uri + ':' + Utils.calculateMD5(this.body ? this.body : ''));
// response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)
this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth-int:' + ha2);
} else if (this.qop === null) {
// HA2 = MD5(A2) = MD5(method:digestURI)
ha2 = Utils.calculateMD5(this.method + ':' + this.uri);
// response = MD5(HA1:nonce:HA2)
this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + ha2);
}
debug('authenticate() | response generated');
return true;
};
/**
* Return the Proxy-Authorization or WWW-Authorization header value.
*/
DigestAuthentication.prototype.toString = function() {
var auth_params = [];
if (!this.response) {
throw new Error('response field does not exist, cannot generate Authorization header');
}
auth_params.push('algorithm=' + this.algorithm);
auth_params.push('username="' + this.credentials.username + '"');
auth_params.push('realm="' + this.realm + '"');
auth_params.push('nonce="' + this.nonce + '"');
auth_params.push('uri="' + this.uri + '"');
auth_params.push('response="' + this.response + '"');
if (this.opaque) {
auth_params.push('opaque="' + this.opaque + '"');
}
if (this.qop) {
auth_params.push('qop=' + this.qop);
auth_params.push('cnonce="' + this.cnonce + '"');
auth_params.push('nc=' + this.ncHex);
}
return 'Digest ' + auth_params.join(', ');
};
},{"./Utils":25,"debug":34}],5:[function(require,module,exports){
/**
* @namespace Exceptions
* @memberOf JsSIP
*/
var Exceptions = {
/**
* Exception thrown when a valid parameter is given to the JsSIP.UA constructor.
* @class ConfigurationError
* @memberOf JsSIP.Exceptions
*/
ConfigurationError: (function(){
var exception = function(parameter, value) {
this.code = 1;
this.name = 'CONFIGURATION_ERROR';
this.parameter = parameter;
this.value = value;
this.message = (!this.value)? 'Missing parameter: '+ this.parameter : 'Invalid value '+ JSON.stringify(this.value) +' for parameter "'+ this.parameter +'"';
};
exception.prototype = new Error();
return exception;
}()),
InvalidStateError: (function(){
var exception = function(status) {
this.code = 2;
this.name = 'INVALID_STATE_ERROR';
this.status = status;
this.message = 'Invalid status: '+ status;
};
exception.prototype = new Error();
return exception;
}()),
NotSupportedError: (function(){
var exception = function(message) {
this.code = 3;
this.name = 'NOT_SUPPORTED_ERROR';
this.message = message;
};
exception.prototype = new Error();
return exception;
}()),
NotReadyError: (function(){
var exception = function(message) {
this.code = 4;
this.name = 'NOT_READY_ERROR';
this.message = message;
};
exception.prototype = new Error();
return exception;
}())
};
module.exports = Exceptions;
},{}],6:[function(require,module,exports){
module.exports = (function(){
/*
* Generated by PEG.js 0.7.0.
*
* http://pegjs.majda.cz/
*/
function quote(s) {
/*
* ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a
* string literal except for the closing quote character, backslash,
* carriage return, line separator, paragraph separator, and line feed.
* Any character may appear in the form of an escape sequence.
*
* For portability, we also escape escape all control and non-ASCII
* characters. Note that "\0" and "\v" escape sequences are not used
* because JSHint does not like the first and IE the second.
*/
return '"' + s
.replace(/\\/g, '\\\\') // backslash
.replace(/"/g, '\\"') // closing quote character
.replace(/\x08/g, '\\b') // backspace
.replace(/\t/g, '\\t') // horizontal tab
.replace(/\n/g, '\\n') // line feed
.replace(/\f/g, '\\f') // form feed
.replace(/\r/g, '\\r') // carriage return
.replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape)
+ '"';
}
var result = {
/*
* Parses the input with a generated parser. If the parsing is successfull,
* returns a value explicitly or implicitly specified by the grammar from
* which the parser was generated (see |PEG.buildParser|). If the parsing is
* unsuccessful, throws |PEG.parser.SyntaxError| describing the error.
*/
parse: function(input, startRule) {
var parseFunctions = {
"CRLF": parse_CRLF,
"DIGIT": parse_DIGIT,
"ALPHA": parse_ALPHA,
"HEXDIG": parse_HEXDIG,
"WSP": parse_WSP,
"OCTET": parse_OCTET,
"DQUOTE": parse_DQUOTE,
"SP": parse_SP,
"HTAB": parse_HTAB,
"alphanum": parse_alphanum,
"reserved": parse_reserved,
"unreserved": parse_unreserved,
"mark": parse_mark,
"escaped": parse_escaped,
"LWS": parse_LWS,
"SWS": parse_SWS,
"HCOLON": parse_HCOLON,
"TEXT_UTF8_TRIM": parse_TEXT_UTF8_TRIM,
"TEXT_UTF8char": parse_TEXT_UTF8char,
"UTF8_NONASCII": parse_UTF8_NONASCII,
"UTF8_CONT": parse_UTF8_CONT,
"LHEX": parse_LHEX,
"token": parse_token,
"token_nodot": parse_token_nodot,
"separators": parse_separators,
"word": parse_word,
"STAR": parse_STAR,
"SLASH": parse_SLASH,
"EQUAL": parse_EQUAL,
"LPAREN": parse_LPAREN,
"RPAREN": parse_RPAREN,
"RAQUOT": parse_RAQUOT,
"LAQUOT": parse_LAQUOT,
"COMMA": parse_COMMA,
"SEMI": parse_SEMI,
"COLON": parse_COLON,
"LDQUOT": parse_LDQUOT,
"RDQUOT": parse_RDQUOT,
"comment": parse_comment,
"ctext": parse_ctext,
"quoted_string": parse_quoted_string,
"quoted_string_clean": parse_quoted_string_clean,
"qdtext": parse_qdtext,
"quoted_pair": parse_quoted_pair,
"SIP_URI_noparams": parse_SIP_URI_noparams,
"SIP_URI": parse_SIP_URI,
"uri_scheme": parse_uri_scheme,
"uri_scheme_sips": parse_uri_scheme_sips,
"uri_scheme_sip": parse_uri_scheme_sip,
"userinfo": parse_userinfo,
"user": parse_user,
"user_unreserved": parse_user_unreserved,
"password": parse_password,
"hostport": parse_hostport,
"host": parse_host,
"hostname": parse_hostname,
"domainlabel": parse_domainlabel,
"toplabel": parse_toplabel,
"IPv6reference": parse_IPv6reference,
"IPv6address": parse_IPv6address,
"h16": parse_h16,
"ls32": parse_ls32,
"IPv4address": parse_IPv4address,
"dec_octet": parse_dec_octet,
"port": parse_port,
"uri_parameters": parse_uri_parameters,
"uri_parameter": parse_uri_parameter,
"transport_param": parse_transport_param,
"user_param": parse_user_param,
"method_param": parse_method_param,
"ttl_param": parse_ttl_param,
"maddr_param": parse_maddr_param,
"lr_param": parse_lr_param,
"other_param": parse_other_param,
"pname": parse_pname,
"pvalue": parse_pvalue,
"paramchar": parse_paramchar,
"param_unreserved": parse_param_unreserved,
"headers": parse_headers,
"header": parse_header,
"hname": parse_hname,
"hvalue": parse_hvalue,
"hnv_unreserved": parse_hnv_unreserved,
"Request_Response": parse_Request_Response,
"Request_Line": parse_Request_Line,
"Request_URI": parse_Request_URI,
"absoluteURI": parse_absoluteURI,
"hier_part": parse_hier_part,
"net_path": parse_net_path,
"abs_path": parse_abs_path,
"opaque_part": parse_opaque_part,
"uric": parse_uric,
"uric_no_slash": parse_uric_no_slash,
"path_segments": parse_path_segments,
"segment": parse_segment,
"param": parse_param,
"pchar": parse_pchar,
"scheme": parse_scheme,
"authority": parse_authority,
"srvr": parse_srvr,
"reg_name": parse_reg_name,
"query": parse_query,
"SIP_Version": parse_SIP_Version,
"INVITEm": parse_INVITEm,
"ACKm": parse_ACKm,
"OPTIONSm": parse_OPTIONSm,
"BYEm": parse_BYEm,
"CANCELm": parse_CANCELm,
"REGISTERm": parse_REGISTERm,
"SUBSCRIBEm": parse_SUBSCRIBEm,
"NOTIFYm": parse_NOTIFYm,
"REFERm": parse_REFERm,
"Method": parse_Method,
"Status_Line": parse_Status_Line,
"Status_Code": parse_Status_Code,
"extension_code": parse_extension_code,
"Reason_Phrase": parse_Reason_Phrase,
"Allow_Events": parse_Allow_Events,
"Call_ID": parse_Call_ID,
"Contact": parse_Contact,
"contact_param": parse_contact_param,
"name_addr": parse_name_addr,
"display_name": parse_display_name,
"contact_params": parse_contact_params,
"c_p_q": parse_c_p_q,
"c_p_expires": parse_c_p_expires,
"delta_seconds": parse_delta_seconds,
"qvalue": parse_qvalue,
"generic_param": parse_generic_param,
"gen_value": parse_gen_value,
"Content_Disposition": parse_Content_Disposition,
"disp_type": parse_disp_type,
"disp_param": parse_disp_param,
"handling_param": parse_handling_param,
"Content_Encoding": parse_Content_Encoding,
"Content_Length": parse_Content_Length,
"Content_Type": parse_Content_Type,
"media_type": parse_media_type,
"m_type": parse_m_type,
"discrete_type": parse_discrete_type,
"composite_type": parse_composite_type,
"extension_token": parse_extension_token,
"x_token": parse_x_token,
"m_subtype": parse_m_subtype,
"m_parameter": parse_m_parameter,
"m_value": parse_m_value,
"CSeq": parse_CSeq,
"CSeq_value": parse_CSeq_value,
"Expires": parse_Expires,
"Event": parse_Event,
"event_type": parse_event_type,
"From": parse_From,
"from_param": parse_from_param,
"tag_param": parse_tag_param,
"Max_Forwards": parse_Max_Forwards,
"Min_Expires": parse_Min_Expires,
"Name_Addr_Header": parse_Name_Addr_Header,
"Proxy_Authenticate": parse_Proxy_Authenticate,
"challenge": parse_challenge,
"other_challenge": parse_other_challenge,
"auth_param": parse_auth_param,
"digest_cln": parse_digest_cln,
"realm": parse_realm,
"realm_value": parse_realm_value,
"domain": parse_domain,
"URI": parse_URI,
"nonce": parse_nonce,
"nonce_value": parse_nonce_value,
"opaque": parse_opaque,
"stale": parse_stale,
"algorithm": parse_algorithm,
"qop_options": parse_qop_options,
"qop_value": parse_qop_value,
"Proxy_Require": parse_Proxy_Require,
"Record_Route": parse_Record_Route,
"rec_route": parse_rec_route,
"Reason": parse_Reason,
"reason_param": parse_reason_param,
"reason_cause": parse_reason_cause,
"Require": parse_Require,
"Route": parse_Route,
"route_param": parse_route_param,
"Subscription_State": parse_Subscription_State,
"substate_value": parse_substate_value,
"subexp_params": parse_subexp_params,
"event_reason_value": parse_event_reason_value,
"Subject": parse_Subject,
"Supported": parse_Supported,
"To": parse_To,
"to_param": parse_to_param,
"Via": parse_Via,
"via_param": parse_via_param,
"via_params": parse_via_params,
"via_ttl": parse_via_ttl,
"via_maddr": parse_via_maddr,
"via_received": parse_via_received,
"via_branch": parse_via_branch,
"response_port": parse_response_port,
"sent_protocol": parse_sent_protocol,
"protocol_name": parse_protocol_name,
"transport": parse_transport,
"sent_by": parse_sent_by,
"via_host": parse_via_host,
"via_port": parse_via_port,
"ttl": parse_ttl,
"WWW_Authenticate": parse_WWW_Authenticate,
"Session_Expires": parse_Session_Expires,
"s_e_expires": parse_s_e_expires,
"s_e_params": parse_s_e_params,
"s_e_refresher": parse_s_e_refresher,
"extension_header": parse_extension_header,
"header_value": parse_header_value,
"message_body": parse_message_body,
"uuid_URI": parse_uuid_URI,
"uuid": parse_uuid,
"hex4": parse_hex4,
"hex8": parse_hex8,
"hex12": parse_hex12,
"Refer_To": parse_Refer_To,
"Replaces": parse_Replaces,
"call_id": parse_call_id,
"replaces_param": parse_replaces_param,
"to_tag": parse_to_tag,
"from_tag": parse_from_tag,
"early_flag": parse_early_flag
};
if (startRule !== undefined) {
if (parseFunctions[startRule] === undefined) {
throw new Error("Invalid rule name: " + quote(startRule) + ".");
}
} else {
startRule = "CRLF";
}
var pos = 0;
var reportFailures = 0;
var rightmostFailuresPos = 0;
var rightmostFailuresExpected = [];
function padLeft(input, padding, length) {
var result = input;
var padLength = length - input.length;
for (var i = 0; i < padLength; i++) {
result = padding + result;
}
return result;
}
function escape(ch) {
var charCode = ch.charCodeAt(0);
var escapeChar;
var length;
if (charCode <= 0xFF) {
escapeChar = 'x';
length = 2;
} else {
escapeChar = 'u';
length = 4;
}
return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length);
}
function matchFailed(failure) {
if (pos < rightmostFailuresPos) {
return;
}
if (pos > rightmostFailuresPos) {
rightmostFailuresPos = pos;
rightmostFailuresExpected = [];
}
rightmostFailuresExpected.push(failure);
}
function parse_CRLF() {
var result0;
if (input.substr(pos, 2) === "\r\n") {
result0 = "\r\n";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\r\\n\"");
}
}
return result0;
}
function parse_DIGIT() {
var result0;
if (/^[0-9]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
return result0;
}
function parse_ALPHA() {
var result0;
if (/^[a-zA-Z]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z]");
}
}
return result0;
}
function parse_HEXDIG() {
var result0;
if (/^[0-9a-fA-F]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[0-9a-fA-F]");
}
}
return result0;
}
function parse_WSP() {
var result0;
result0 = parse_SP();
if (result0 === null) {
result0 = parse_HTAB();
}
return result0;
}
function parse_OCTET() {
var result0;
if (/^[\0-\xFF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\0-\\xFF]");
}
}
return result0;
}
function parse_DQUOTE() {
var result0;
if (/^["]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\"]");
}
}
return result0;
}
function parse_SP() {
var result0;
if (input.charCodeAt(pos) === 32) {
result0 = " ";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\" \"");
}
}
return result0;
}
function parse_HTAB() {
var result0;
if (input.charCodeAt(pos) === 9) {
result0 = "\t";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\t\"");
}
}
return result0;
}
function parse_alphanum() {
var result0;
if (/^[a-zA-Z0-9]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9]");
}
}
return result0;
}
function parse_reserved() {
var result0;
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_unreserved() {
var result0;
result0 = parse_alphanum();
if (result0 === null) {
result0 = parse_mark();
}
return result0;
}
function parse_mark() {
var result0;
if (input.charCodeAt(pos) === 45) {
result0 = "-";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 95) {
result0 = "_";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 46) {
result0 = ".";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 33) {
result0 = "!";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 126) {
result0 = "~";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 42) {
result0 = "*";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 39) {
result0 = "'";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 40) {
result0 = "(";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 41) {
result0 = ")";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_escaped() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 37) {
result0 = "%";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result0 !== null) {
result1 = parse_HEXDIG();
if (result1 !== null) {
result2 = parse_HEXDIG();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, escaped) {return escaped.join(''); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LWS() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
pos2 = pos;
result0 = [];
result1 = parse_WSP();
while (result1 !== null) {
result0.push(result1);
result1 = parse_WSP();
}
if (result0 !== null) {
result1 = parse_CRLF();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos2;
}
} else {
result0 = null;
pos = pos2;
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result2 = parse_WSP();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_WSP();
}
} else {
result1 = null;
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return " "; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SWS() {
var result0;
result0 = parse_LWS();
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_HCOLON() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = [];
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ':'; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_TEXT_UTF8_TRIM() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result1 = parse_TEXT_UTF8char();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_TEXT_UTF8char();
}
} else {
result0 = null;
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = [];
result3 = parse_LWS();
while (result3 !== null) {
result2.push(result3);
result3 = parse_LWS();
}
if (result2 !== null) {
result3 = parse_TEXT_UTF8char();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = [];
result3 = parse_LWS();
while (result3 !== null) {
result2.push(result3);
result3 = parse_LWS();
}
if (result2 !== null) {
result3 = parse_TEXT_UTF8char();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_TEXT_UTF8char() {
var result0;
if (/^[!-~]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[!-~]");
}
}
if (result0 === null) {
result0 = parse_UTF8_NONASCII();
}
return result0;
}
function parse_UTF8_NONASCII() {
var result0;
if (/^[\x80-\uFFFF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\x80-\\uFFFF]");
}
}
return result0;
}
function parse_UTF8_CONT() {
var result0;
if (/^[\x80-\xBF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\x80-\\xBF]");
}
}
return result0;
}
function parse_LHEX() {
var result0;
result0 = parse_DIGIT();
if (result0 === null) {
if (/^[a-f]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-f]");
}
}
}
return result0;
}
function parse_token() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_token_nodot() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_separators() {
var result0;
if (input.charCodeAt(pos) === 40) {
result0 = "(";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 41) {
result0 = ")";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 60) {
result0 = "<";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 62) {
result0 = ">";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 92) {
result0 = "\\";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result0 === null) {
result0 = parse_DQUOTE();
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 93) {
result0 = "]";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 123) {
result0 = "{";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"{\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 125) {
result0 = "}";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
if (result0 === null) {
result0 = parse_SP();
if (result0 === null) {
result0 = parse_HTAB();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_word() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 41) {
result1 = ")";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 60) {
result1 = "<";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 62) {
result1 = ">";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 92) {
result1 = "\\";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result1 === null) {
result1 = parse_DQUOTE();
if (result1 === null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 91) {
result1 = "[";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 93) {
result1 = "]";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 63) {
result1 = "?";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 123) {
result1 = "{";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"{\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 125) {
result1 = "}";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 41) {
result1 = ")";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 60) {
result1 = "<";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 62) {
result1 = ">";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 92) {
result1 = "\\";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result1 === null) {
result1 = parse_DQUOTE();
if (result1 === null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 91) {
result1 = "[";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 93) {
result1 = "]";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 63) {
result1 = "?";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 123) {
result1 = "{";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"{\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 125) {
result1 = "}";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_STAR() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "*"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SLASH() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "/"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_EQUAL() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "="; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LPAREN() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "("; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_RPAREN() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 41) {
result1 = ")";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ")"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_RAQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 62) {
result0 = ">";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result0 !== null) {
result1 = parse_SWS();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ">"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LAQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 60) {
result1 = "<";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "<"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_COMMA() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ","; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SEMI() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ";"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_COLON() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ":"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LDQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
result1 = parse_DQUOTE();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "\""; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_RDQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DQUOTE();
if (result0 !== null) {
result1 = parse_SWS();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "\""; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_comment() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_LPAREN();
if (result0 !== null) {
result1 = [];
result2 = parse_ctext();
if (result2 === null) {
result2 = parse_quoted_pair();
if (result2 === null) {
result2 = parse_comment();
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_ctext();
if (result2 === null) {
result2 = parse_quoted_pair();
if (result2 === null) {
result2 = parse_comment();
}
}
}
if (result1 !== null) {
result2 = parse_RPAREN();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_ctext() {
var result0;
if (/^[!-']/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[!-']");
}
}
if (result0 === null) {
if (/^[*-[]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[*-[]");
}
}
if (result0 === null) {
if (/^[\]-~]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\]-~]");
}
}
if (result0 === null) {
result0 = parse_UTF8_NONASCII();
if (result0 === null) {
result0 = parse_LWS();
}
}
}
}
return result0;
}
function parse_quoted_string() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
result1 = parse_DQUOTE();
if (result1 !== null) {
result2 = [];
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
while (result3 !== null) {
result2.push(result3);
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
}
if (result2 !== null) {
result3 = parse_DQUOTE();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_quoted_string_clean() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
result1 = parse_DQUOTE();
if (result1 !== null) {
result2 = [];
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
while (result3 !== null) {
result2.push(result3);
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
}
if (result2 !== null) {
result3 = parse_DQUOTE();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos-1, offset+1); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_qdtext() {
var result0;
result0 = parse_LWS();
if (result0 === null) {
if (input.charCodeAt(pos) === 33) {
result0 = "!";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result0 === null) {
if (/^[#-[]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[#-[]");
}
}
if (result0 === null) {
if (/^[\]-~]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\]-~]");
}
}
if (result0 === null) {
result0 = parse_UTF8_NONASCII();
}
}
}
}
return result0;
}
function parse_quoted_pair() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.charCodeAt(pos) === 92) {
result0 = "\\";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result0 !== null) {
if (/^[\0-\t]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[\\0-\\t]");
}
}
if (result1 === null) {
if (/^[\x0B-\f]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[\\x0B-\\f]");
}
}
if (result1 === null) {
if (/^[\x0E-]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[\\x0E-]");
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_SIP_URI_noparams() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_uri_scheme();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_userinfo();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_hostport();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
try {
data.uri = new URI(data.scheme, data.user, data.host, data.port);
delete data.scheme;
delete data.user;
delete data.host;
delete data.host_type;
delete data.port;
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SIP_URI() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_uri_scheme();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_userinfo();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_hostport();
if (result3 !== null) {
result4 = parse_uri_parameters();
if (result4 !== null) {
result5 = parse_headers();
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var header;
try {
data.uri = new URI(data.scheme, data.user, data.host, data.port, data.uri_params, data.uri_headers);
delete data.scheme;
delete data.user;
delete data.host;
delete data.host_type;
delete data.port;
delete data.uri_params;
if (startRule === 'SIP_URI') { data = data.uri;}
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_uri_scheme() {
var result0;
result0 = parse_uri_scheme_sips();
if (result0 === null) {
result0 = parse_uri_scheme_sip();
}
return result0;
}
function parse_uri_scheme_sips() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 4).toLowerCase() === "sips") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"sips\"");
}
}
if (result0 !== null) {
result0 = (function(offset, scheme) {
data.scheme = scheme.toLowerCase(); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_uri_scheme_sip() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"sip\"");
}
}
if (result0 !== null) {
result0 = (function(offset, scheme) {
data.scheme = scheme.toLowerCase(); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_userinfo() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_user();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_password();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
if (input.charCodeAt(pos) === 64) {
result2 = "@";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.user = decodeURIComponent(input.substring(pos-1, offset));})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_user() {
var result0, result1;
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_user_unreserved();
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_user_unreserved();
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_user_unreserved() {
var result0;
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_password() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = [];
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.password = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hostport() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
result0 = parse_host();
if (result0 !== null) {
pos1 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_port();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos1;
}
} else {
result1 = null;
pos = pos1;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_host() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_hostname();
if (result0 === null) {
result0 = parse_IPv4address();
if (result0 === null) {
result0 = parse_IPv6reference();
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.host = input.substring(pos, offset).toLowerCase();
return data.host; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hostname() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = [];
pos2 = pos;
result1 = parse_domainlabel();
if (result1 !== null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
while (result1 !== null) {
result0.push(result1);
pos2 = pos;
result1 = parse_domainlabel();
if (result1 !== null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
}
if (result0 !== null) {
result1 = parse_toplabel();
if (result1 !== null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'domain';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_domainlabel() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_alphanum();
if (result0 !== null) {
result1 = [];
result2 = parse_alphanum();
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 95) {
result2 = "_";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_alphanum();
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 95) {
result2 = "_";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_toplabel() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_ALPHA();
if (result0 !== null) {
result1 = [];
result2 = parse_alphanum();
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 95) {
result2 = "_";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_alphanum();
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 95) {
result2 = "_";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_IPv6reference() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 !== null) {
result1 = parse_IPv6address();
if (result1 !== null) {
if (input.charCodeAt(pos) === 93) {
result2 = "]";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'IPv6';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_IPv6address() {
var result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
if (input.charCodeAt(pos) === 58) {
result7 = ":";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result7 !== null) {
result8 = parse_h16();
if (result8 !== null) {
if (input.charCodeAt(pos) === 58) {
result9 = ":";
pos++;
} else {
result9 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result9 !== null) {
result10 = parse_h16();
if (result10 !== null) {
if (input.charCodeAt(pos) === 58) {
result11 = ":";
pos++;
} else {
result11 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result11 !== null) {
result12 = parse_ls32();
if (result12 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
if (input.charCodeAt(pos) === 58) {
result8 = ":";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result8 !== null) {
result9 = parse_h16();
if (result9 !== null) {
if (input.charCodeAt(pos) === 58) {
result10 = ":";
pos++;
} else {
result10 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result10 !== null) {
result11 = parse_ls32();
if (result11 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
if (input.charCodeAt(pos) === 58) {
result8 = ":";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result8 !== null) {
result9 = parse_ls32();
if (result9 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_ls32();
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_ls32();
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_ls32();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_ls32();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
if (input.substr(pos, 2) === "::") {
result1 = "::";
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
if (input.charCodeAt(pos) === 58) {
result7 = ":";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result7 !== null) {
result8 = parse_h16();
if (result8 !== null) {
if (input.charCodeAt(pos) === 58) {
result9 = ":";
pos++;
} else {
result9 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result9 !== null) {
result10 = parse_ls32();
if (result10 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
if (input.substr(pos, 2) === "::") {
result2 = "::";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
if (input.charCodeAt(pos) === 58) {
result8 = ":";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result8 !== null) {
result9 = parse_ls32();
if (result9 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
if (input.substr(pos, 2) === "::") {
result3 = "::";
pos += 2;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
if (input.charCodeAt(pos) === 58) {
result7 = ":";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result7 !== null) {
result8 = parse_ls32();
if (result8 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
if (input.substr(pos, 2) === "::") {
result4 = "::";
pos += 2;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_ls32();
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
if (input.substr(pos, 2) === "::") {
result5 = "::";
pos += 2;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result5 !== null) {
result6 = parse_ls32();
if (result6 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
if (input.substr(pos, 2) === "::") {
result6 = "::";
pos += 2;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
result6 = [result6, result7];
} else {
result6 = null;
pos = pos2;
}
} else {
result6 = null;
pos = pos2;
}
result6 = result6 !== null ? result6 : "";
if (result6 !== null) {
if (input.substr(pos, 2) === "::") {
result7 = "::";
pos += 2;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'IPv6';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_h16() {
var result0, result1, result2, result3;
var pos0;
pos0 = pos;
result0 = parse_HEXDIG();
if (result0 !== null) {
result1 = parse_HEXDIG();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_HEXDIG();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_HEXDIG();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_ls32() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_h16();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
result0 = parse_IPv4address();
}
return result0;
}
function parse_IPv4address() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_dec_octet();
if (result0 !== null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 !== null) {
result2 = parse_dec_octet();
if (result2 !== null) {
if (input.charCodeAt(pos) === 46) {
result3 = ".";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result3 !== null) {
result4 = parse_dec_octet();
if (result4 !== null) {
if (input.charCodeAt(pos) === 46) {
result5 = ".";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result5 !== null) {
result6 = parse_dec_octet();
if (result6 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'IPv4';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_dec_octet() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 2) === "25") {
result0 = "25";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"25\"");
}
}
if (result0 !== null) {
if (/^[0-5]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-5]");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 50) {
result0 = "2";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"2\"");
}
}
if (result0 !== null) {
if (/^[0-4]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-4]");
}
}
if (result1 !== null) {
result2 = parse_DIGIT();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 49) {
result0 = "1";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"1\"");
}
}
if (result0 !== null) {
result1 = parse_DIGIT();
if (result1 !== null) {
result2 = parse_DIGIT();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (/^[1-9]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[1-9]");
}
}
if (result0 !== null) {
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
result0 = parse_DIGIT();
}
}
}
}
return result0;
}
function parse_port() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DIGIT();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_DIGIT();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_DIGIT();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_DIGIT();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, port) {
port = parseInt(port.join(''));
data.port = port;
return port; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_uri_parameters() {
var result0, result1, result2;
var pos0;
result0 = [];
pos0 = pos;
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse_uri_parameter();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos0;
}
} else {
result1 = null;
pos = pos0;
}
while (result1 !== null) {
result0.push(result1);
pos0 = pos;
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse_uri_parameter();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos0;
}
} else {
result1 = null;
pos = pos0;
}
}
return result0;
}
function parse_uri_parameter() {
var result0;
result0 = parse_transport_param();
if (result0 === null) {
result0 = parse_user_param();
if (result0 === null) {
result0 = parse_method_param();
if (result0 === null) {
result0 = parse_ttl_param();
if (result0 === null) {
result0 = parse_maddr_param();
if (result0 === null) {
result0 = parse_lr_param();
if (result0 === null) {
result0 = parse_other_param();
}
}
}
}
}
}
return result0;
}
function parse_transport_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 10).toLowerCase() === "transport=") {
result0 = input.substr(pos, 10);
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"transport=\"");
}
}
if (result0 !== null) {
if (input.substr(pos, 3).toLowerCase() === "udp") {
result1 = input.substr(pos, 3);
pos += 3;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"udp\"");
}
}
if (result1 === null) {
if (input.substr(pos, 3).toLowerCase() === "tcp") {
result1 = input.substr(pos, 3);
pos += 3;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"tcp\"");
}
}
if (result1 === null) {
if (input.substr(pos, 4).toLowerCase() === "sctp") {
result1 = input.substr(pos, 4);
pos += 4;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"sctp\"");
}
}
if (result1 === null) {
if (input.substr(pos, 3).toLowerCase() === "tls") {
result1 = input.substr(pos, 3);
pos += 3;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"tls\"");
}
}
if (result1 === null) {
result1 = parse_token();
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, transport) {
if(!data.uri_params) data.uri_params={};
data.uri_params['transport'] = transport.toLowerCase(); })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_user_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "user=") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"user=\"");
}
}
if (result0 !== null) {
if (input.substr(pos, 5).toLowerCase() === "phone") {
result1 = input.substr(pos, 5);
pos += 5;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"phone\"");
}
}
if (result1 === null) {
if (input.substr(pos, 2).toLowerCase() === "ip") {
result1 = input.substr(pos, 2);
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"ip\"");
}
}
if (result1 === null) {
result1 = parse_token();
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, user) {
if(!data.uri_params) data.uri_params={};
data.uri_params['user'] = user.toLowerCase(); })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_method_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 7).toLowerCase() === "method=") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"method=\"");
}
}
if (result0 !== null) {
result1 = parse_Method();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, method) {
if(!data.uri_params) data.uri_params={};
data.uri_params['method'] = method; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_ttl_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 4).toLowerCase() === "ttl=") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"ttl=\"");
}
}
if (result0 !== null) {
result1 = parse_ttl();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, ttl) {
if(!data.params) data.params={};
data.params['ttl'] = ttl; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_maddr_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "maddr=") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"maddr=\"");
}
}
if (result0 !== null) {
result1 = parse_host();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, maddr) {
if(!data.uri_params) data.uri_params={};
data.uri_params['maddr'] = maddr; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_lr_param() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 2).toLowerCase() === "lr") {
result0 = input.substr(pos, 2);
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"lr\"");
}
}
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
if(!data.uri_params) data.uri_params={};
data.uri_params['lr'] = undefined; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_other_param() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_pname();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_pvalue();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, param, value) {
if(!data.uri_params) data.uri_params = {};
if (typeof value === 'undefined'){
value = undefined;
}
else {
value = value[1];
}
data.uri_params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_pname() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_paramchar();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_paramchar();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, pname) {return pname.join(''); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_pvalue() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_paramchar();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_paramchar();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, pvalue) {return pvalue.join(''); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_paramchar() {
var result0;
result0 = parse_param_unreserved();
if (result0 === null) {
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
}
}
return result0;
}
function parse_param_unreserved() {
var result0;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 93) {
result0 = "]";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
}
}
}
}
}
}
return result0;
}
function parse_headers() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 !== null) {
result1 = parse_header();
if (result1 !== null) {
result2 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 38) {
result3 = "&";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result3 !== null) {
result4 = parse_header();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos1;
}
} else {
result3 = null;
pos = pos1;
}
while (result3 !== null) {
result2.push(result3);
pos1 = pos;
if (input.charCodeAt(pos) === 38) {
result3 = "&";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result3 !== null) {
result4 = parse_header();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos1;
}
} else {
result3 = null;
pos = pos1;
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_header() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_hname();
if (result0 !== null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_hvalue();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, hname, hvalue) {
hname = hname.join('').toLowerCase();
hvalue = hvalue.join('');
if(!data.uri_headers) data.uri_headers = {};
if (!data.uri_headers[hname]) {
data.uri_headers[hname] = [hvalue];
} else {
data.uri_headers[hname].push(hvalue);
}})(pos0, result0[0], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hname() {
var result0, result1;
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_hvalue() {
var result0, result1;
result0 = [];
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
}
return result0;
}
function parse_hnv_unreserved() {
var result0;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 93) {
result0 = "]";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
}
}
}
}
}
}
return result0;
}
function parse_Request_Response() {
var result0;
result0 = parse_Status_Line();
if (result0 === null) {
result0 = parse_Request_Line();
}
return result0;
}
function parse_Request_Line() {
var result0, result1, result2, result3, result4;
var pos0;
pos0 = pos;
result0 = parse_Method();
if (result0 !== null) {
result1 = parse_SP();
if (result1 !== null) {
result2 = parse_Request_URI();
if (result2 !== null) {
result3 = parse_SP();
if (result3 !== null) {
result4 = parse_SIP_Version();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Request_URI() {
var result0;
result0 = parse_SIP_URI();
if (result0 === null) {
result0 = parse_absoluteURI();
}
return result0;
}
function parse_absoluteURI() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_scheme();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_hier_part();
if (result2 === null) {
result2 = parse_opaque_part();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_hier_part() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
result0 = parse_net_path();
if (result0 === null) {
result0 = parse_abs_path();
}
if (result0 !== null) {
pos1 = pos;
if (input.charCodeAt(pos) === 63) {
result1 = "?";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result1 !== null) {
result2 = parse_query();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos1;
}
} else {
result1 = null;
pos = pos1;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_net_path() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 2) === "//") {
result0 = "//";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"//\"");
}
}
if (result0 !== null) {
result1 = parse_authority();
if (result1 !== null) {
result2 = parse_abs_path();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_abs_path() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 !== null) {
result1 = parse_path_segments();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_opaque_part() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_uric_no_slash();
if (result0 !== null) {
result1 = [];
result2 = parse_uric();
while (result2 !== null) {
result1.push(result2);
result2 = parse_uric();
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_uric() {
var result0;
result0 = parse_reserved();
if (result0 === null) {
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
}
}
return result0;
}
function parse_uric_no_slash() {
var result0;
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
if (result0 === null) {
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_path_segments() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_segment();
if (result0 !== null) {
result1 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 47) {
result2 = "/";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result2 !== null) {
result3 = parse_segment();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
if (input.charCodeAt(pos) === 47) {
result2 = "/";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result2 !== null) {
result3 = parse_segment();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_segment() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = [];
result1 = parse_pchar();
while (result1 !== null) {
result0.push(result1);
result1 = parse_pchar();
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 59) {
result2 = ";";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result2 !== null) {
result3 = parse_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
if (input.charCodeAt(pos) === 59) {
result2 = ";";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result2 !== null) {
result3 = parse_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_param() {
var result0, result1;
result0 = [];
result1 = parse_pchar();
while (result1 !== null) {
result0.push(result1);
result1 = parse_pchar();
}
return result0;
}
function parse_pchar() {
var result0;
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_scheme() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_ALPHA();
if (result0 !== null) {
result1 = [];
result2 = parse_ALPHA();
if (result2 === null) {
result2 = parse_DIGIT();
if (result2 === null) {
if (input.charCodeAt(pos) === 43) {
result2 = "+";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
}
}
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_ALPHA();
if (result2 === null) {
result2 = parse_DIGIT();
if (result2 === null) {
if (input.charCodeAt(pos) === 43) {
result2 = "+";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.scheme= input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_authority() {
var result0;
result0 = parse_srvr();
if (result0 === null) {
result0 = parse_reg_name();
}
return result0;
}
function parse_srvr() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_userinfo();
if (result0 !== null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_hostport();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_reg_name() {
var result0, result1;
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_query() {
var result0, result1;
result0 = [];
result1 = parse_uric();
while (result1 !== null) {
result0.push(result1);
result1 = parse_uric();
}
return result0;
}
function parse_SIP_Version() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SIP\"");
}
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 !== null) {
result3 = parse_DIGIT();
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
result3 = parse_DIGIT();
}
} else {
result2 = null;
}
if (result2 !== null) {
if (input.charCodeAt(pos) === 46) {
result3 = ".";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result3 !== null) {
result5 = parse_DIGIT();
if (result5 !== null) {
result4 = [];
while (result5 !== null) {
result4.push(result5);
result5 = parse_DIGIT();
}
} else {
result4 = null;
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.sip_version = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_INVITEm() {
var result0;
if (input.substr(pos, 6) === "INVITE") {
result0 = "INVITE";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"INVITE\"");
}
}
return result0;
}
function parse_ACKm() {
var result0;
if (input.substr(pos, 3) === "ACK") {
result0 = "ACK";
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"ACK\"");
}
}
return result0;
}
function parse_OPTIONSm() {
var result0;
if (input.substr(pos, 7) === "OPTIONS") {
result0 = "OPTIONS";
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"OPTIONS\"");
}
}
return result0;
}
function parse_BYEm() {
var result0;
if (input.substr(pos, 3) === "BYE") {
result0 = "BYE";
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"BYE\"");
}
}
return result0;
}
function parse_CANCELm() {
var result0;
if (input.substr(pos, 6) === "CANCEL") {
result0 = "CANCEL";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"CANCEL\"");
}
}
return result0;
}
function parse_REGISTERm() {
var result0;
if (input.substr(pos, 8) === "REGISTER") {
result0 = "REGISTER";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"REGISTER\"");
}
}
return result0;
}
function parse_SUBSCRIBEm() {
var result0;
if (input.substr(pos, 9) === "SUBSCRIBE") {
result0 = "SUBSCRIBE";
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SUBSCRIBE\"");
}
}
return result0;
}
function parse_NOTIFYm() {
var result0;
if (input.substr(pos, 6) === "NOTIFY") {
result0 = "NOTIFY";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"NOTIFY\"");
}
}
return result0;
}
function parse_REFERm() {
var result0;
if (input.substr(pos, 5) === "REFER") {
result0 = "REFER";
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"REFER\"");
}
}
return result0;
}
function parse_Method() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_INVITEm();
if (result0 === null) {
result0 = parse_ACKm();
if (result0 === null) {
result0 = parse_OPTIONSm();
if (result0 === null) {
result0 = parse_BYEm();
if (result0 === null) {
result0 = parse_CANCELm();
if (result0 === null) {
result0 = parse_REGISTERm();
if (result0 === null) {
result0 = parse_SUBSCRIBEm();
if (result0 === null) {
result0 = parse_NOTIFYm();
if (result0 === null) {
result0 = parse_REFERm();
if (result0 === null) {
result0 = parse_token();
}
}
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.method = input.substring(pos, offset);
return data.method; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Status_Line() {
var result0, result1, result2, result3, result4;
var pos0;
pos0 = pos;
result0 = parse_SIP_Version();
if (result0 !== null) {
result1 = parse_SP();
if (result1 !== null) {
result2 = parse_Status_Code();
if (result2 !== null) {
result3 = parse_SP();
if (result3 !== null) {
result4 = parse_Reason_Phrase();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Status_Code() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_extension_code();
if (result0 !== null) {
result0 = (function(offset, status_code) {
data.status_code = parseInt(status_code.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_extension_code() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_DIGIT();
if (result0 !== null) {
result1 = parse_DIGIT();
if (result1 !== null) {
result2 = parse_DIGIT();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Reason_Phrase() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = [];
result1 = parse_reserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_UTF8_NONASCII();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
}
}
}
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_reserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_UTF8_NONASCII();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.reason_phrase = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Allow_Events() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_event_type();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_event_type();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_event_type();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Call_ID() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_word();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
result2 = parse_word();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Contact() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
result0 = parse_STAR();
if (result0 === null) {
pos1 = pos;
result0 = parse_contact_param();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_contact_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_contact_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
}
if (result0 !== null) {
result0 = (function(offset) {
var idx, length;
length = data.multi_header.length;
for (idx = 0; idx < length; idx++) {
if (data.multi_header[idx].parsed === null) {
data = null;
break;
}
}
if (data !== null) {
data = data.multi_header;
} else {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_contact_param() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_contact_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_contact_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var header;
if(!data.multi_header) data.multi_header = [];
try {
header = new NameAddrHeader(data.uri, data.display_name, data.params);
delete data.uri;
delete data.display_name;
delete data.params;
} catch(e) {
header = null;
}
data.multi_header.push( { 'possition': pos,
'offset': offset,
'parsed': header
});})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_name_addr() {
var result0, result1, result2, result3;
var pos0;
pos0 = pos;
result0 = parse_display_name();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_LAQUOT();
if (result1 !== null) {
result2 = parse_SIP_URI();
if (result2 !== null) {
result3 = parse_RAQUOT();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_display_name() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_LWS();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_LWS();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
result0 = parse_quoted_string();
}
if (result0 !== null) {
result0 = (function(offset, display_name) {
display_name = input.substring(pos, offset).trim();
if (display_name[0] === '\"') {
display_name = display_name.substring(1, display_name.length-1);
}
data.display_name = display_name; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_contact_params() {
var result0;
result0 = parse_c_p_q();
if (result0 === null) {
result0 = parse_c_p_expires();
if (result0 === null) {
result0 = parse_generic_param();
}
}
return result0;
}
function parse_c_p_q() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 1).toLowerCase() === "q") {
result0 = input.substr(pos, 1);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"q\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_qvalue();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, q) {
if(!data.params) data.params = {};
data.params['q'] = q; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_c_p_expires() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 7).toLowerCase() === "expires") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"expires\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_delta_seconds();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, expires) {
if(!data.params) data.params = {};
data.params['expires'] = expires; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_delta_seconds() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, delta_seconds) {
return parseInt(delta_seconds.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_qvalue() {
var result0, result1, result2, result3, result4;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 48) {
result0 = "0";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"0\"");
}
}
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_DIGIT();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_DIGIT();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result1 = [result1, result2, result3, result4];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return parseFloat(input.substring(pos, offset)); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_generic_param() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_token();
if (result0 !== null) {
pos2 = pos;
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_gen_value();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, param, value) {
if(!data.params) data.params = {};
if (typeof value === 'undefined'){
value = undefined;
}
else {
value = value[1];
}
data.params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_gen_value() {
var result0;
result0 = parse_token();
if (result0 === null) {
result0 = parse_host();
if (result0 === null) {
result0 = parse_quoted_string();
}
}
return result0;
}
function parse_Content_Disposition() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_disp_type();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_disp_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_disp_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_disp_type() {
var result0;
if (input.substr(pos, 6).toLowerCase() === "render") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"render\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7).toLowerCase() === "session") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"session\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4).toLowerCase() === "icon") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"icon\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "alert") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"alert\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
}
return result0;
}
function parse_disp_param() {
var result0;
result0 = parse_handling_param();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_handling_param() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 8).toLowerCase() === "handling") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"handling\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
if (input.substr(pos, 8).toLowerCase() === "optional") {
result2 = input.substr(pos, 8);
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"optional\"");
}
}
if (result2 === null) {
if (input.substr(pos, 8).toLowerCase() === "required") {
result2 = input.substr(pos, 8);
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"required\"");
}
}
if (result2 === null) {
result2 = parse_token();
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Content_Encoding() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Content_Length() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, length) {
data = parseInt(length.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Content_Type() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_media_type();
if (result0 !== null) {
result0 = (function(offset) {
data = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_media_type() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
result0 = parse_m_type();
if (result0 !== null) {
result1 = parse_SLASH();
if (result1 !== null) {
result2 = parse_m_subtype();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_m_parameter();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_m_parameter();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_m_type() {
var result0;
result0 = parse_discrete_type();
if (result0 === null) {
result0 = parse_composite_type();
}
return result0;
}
function parse_discrete_type() {
var result0;
if (input.substr(pos, 4).toLowerCase() === "text") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"text\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "image") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"image\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "audio") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"audio\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "video") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"video\"");
}
}
if (result0 === null) {
if (input.substr(pos, 11).toLowerCase() === "application") {
result0 = input.substr(pos, 11);
pos += 11;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"application\"");
}
}
if (result0 === null) {
result0 = parse_extension_token();
}
}
}
}
}
return result0;
}
function parse_composite_type() {
var result0;
if (input.substr(pos, 7).toLowerCase() === "message") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"message\"");
}
}
if (result0 === null) {
if (input.substr(pos, 9).toLowerCase() === "multipart") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"multipart\"");
}
}
if (result0 === null) {
result0 = parse_extension_token();
}
}
return result0;
}
function parse_extension_token() {
var result0;
result0 = parse_token();
if (result0 === null) {
result0 = parse_x_token();
}
return result0;
}
function parse_x_token() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.substr(pos, 2).toLowerCase() === "x-") {
result0 = input.substr(pos, 2);
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"x-\"");
}
}
if (result0 !== null) {
result1 = parse_token();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_m_subtype() {
var result0;
result0 = parse_extension_token();
if (result0 === null) {
result0 = parse_token();
}
return result0;
}
function parse_m_parameter() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_m_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_m_value() {
var result0;
result0 = parse_token();
if (result0 === null) {
result0 = parse_quoted_string();
}
return result0;
}
function parse_CSeq() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_CSeq_value();
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_Method();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_CSeq_value() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, cseq_value) {
data.value=parseInt(cseq_value.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Expires() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_delta_seconds();
if (result0 !== null) {
result0 = (function(offset, expires) {data = expires; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Event() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_event_type();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, event_type) {
data.event = event_type.join('').toLowerCase(); })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_event_type() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token_nodot();
if (result0 !== null) {
result1 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result3 = parse_token_nodot();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result3 = parse_token_nodot();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_From() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_from_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_from_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var tag = data.tag;
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
if (tag) {data.setParam('tag',tag)}
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}<|fim▁hole|> result0 = parse_tag_param();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_tag_param() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "tag") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"tag\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, tag) {data.tag = tag; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Max_Forwards() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, forwards) {
data = parseInt(forwards.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Min_Expires() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_delta_seconds();
if (result0 !== null) {
result0 = (function(offset, min_expires) {data = min_expires; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Name_Addr_Header() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = [];
result1 = parse_display_name();
while (result1 !== null) {
result0.push(result1);
result1 = parse_display_name();
}
if (result0 !== null) {
result1 = parse_LAQUOT();
if (result1 !== null) {
result2 = parse_SIP_URI();
if (result2 !== null) {
result3 = parse_RAQUOT();
if (result3 !== null) {
result4 = [];
pos2 = pos;
result5 = parse_SEMI();
if (result5 !== null) {
result6 = parse_generic_param();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
while (result5 !== null) {
result4.push(result5);
pos2 = pos;
result5 = parse_SEMI();
if (result5 !== null) {
result6 = parse_generic_param();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Proxy_Authenticate() {
var result0;
result0 = parse_challenge();
return result0;
}
function parse_challenge() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
if (input.substr(pos, 6).toLowerCase() === "digest") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Digest\"");
}
}
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_digest_cln();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_digest_cln();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_digest_cln();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
result0 = parse_other_challenge();
}
return result0;
}
function parse_other_challenge() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_auth_param();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_auth_param();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_auth_param();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_auth_param() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 === null) {
result2 = parse_quoted_string();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_digest_cln() {
var result0;
result0 = parse_realm();
if (result0 === null) {
result0 = parse_domain();
if (result0 === null) {
result0 = parse_nonce();
if (result0 === null) {
result0 = parse_opaque();
if (result0 === null) {
result0 = parse_stale();
if (result0 === null) {
result0 = parse_algorithm();
if (result0 === null) {
result0 = parse_qop_options();
if (result0 === null) {
result0 = parse_auth_param();
}
}
}
}
}
}
}
return result0;
}
function parse_realm() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 5).toLowerCase() === "realm") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"realm\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_realm_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_realm_value() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_quoted_string_clean();
if (result0 !== null) {
result0 = (function(offset, realm) { data.realm = realm; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_domain() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1;
pos0 = pos;
if (input.substr(pos, 6).toLowerCase() === "domain") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"domain\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_LDQUOT();
if (result2 !== null) {
result3 = parse_URI();
if (result3 !== null) {
result4 = [];
pos1 = pos;
result6 = parse_SP();
if (result6 !== null) {
result5 = [];
while (result6 !== null) {
result5.push(result6);
result6 = parse_SP();
}
} else {
result5 = null;
}
if (result5 !== null) {
result6 = parse_URI();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos1;
}
} else {
result5 = null;
pos = pos1;
}
while (result5 !== null) {
result4.push(result5);
pos1 = pos;
result6 = parse_SP();
if (result6 !== null) {
result5 = [];
while (result6 !== null) {
result5.push(result6);
result6 = parse_SP();
}
} else {
result5 = null;
}
if (result5 !== null) {
result6 = parse_URI();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos1;
}
} else {
result5 = null;
pos = pos1;
}
}
if (result4 !== null) {
result5 = parse_RDQUOT();
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_URI() {
var result0;
result0 = parse_absoluteURI();
if (result0 === null) {
result0 = parse_abs_path();
}
return result0;
}
function parse_nonce() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 5).toLowerCase() === "nonce") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"nonce\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_nonce_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_nonce_value() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_quoted_string_clean();
if (result0 !== null) {
result0 = (function(offset, nonce) { data.nonce=nonce; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_opaque() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "opaque") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"opaque\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_quoted_string_clean();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, opaque) { data.opaque=opaque; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_stale() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
if (input.substr(pos, 5).toLowerCase() === "stale") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"stale\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
pos1 = pos;
if (input.substr(pos, 4).toLowerCase() === "true") {
result2 = input.substr(pos, 4);
pos += 4;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"true\"");
}
}
if (result2 !== null) {
result2 = (function(offset) { data.stale=true; })(pos1);
}
if (result2 === null) {
pos = pos1;
}
if (result2 === null) {
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "false") {
result2 = input.substr(pos, 5);
pos += 5;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"false\"");
}
}
if (result2 !== null) {
result2 = (function(offset) { data.stale=false; })(pos1);
}
if (result2 === null) {
pos = pos1;
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_algorithm() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 9).toLowerCase() === "algorithm") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"algorithm\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
if (input.substr(pos, 3).toLowerCase() === "md5") {
result2 = input.substr(pos, 3);
pos += 3;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"MD5\"");
}
}
if (result2 === null) {
if (input.substr(pos, 8).toLowerCase() === "md5-sess") {
result2 = input.substr(pos, 8);
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"MD5-sess\"");
}
}
if (result2 === null) {
result2 = parse_token();
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, algorithm) {
data.algorithm=algorithm.toUpperCase(); })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_qop_options() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1, pos2;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "qop") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"qop\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_LDQUOT();
if (result2 !== null) {
pos1 = pos;
result3 = parse_qop_value();
if (result3 !== null) {
result4 = [];
pos2 = pos;
if (input.charCodeAt(pos) === 44) {
result5 = ",";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result5 !== null) {
result6 = parse_qop_value();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
while (result5 !== null) {
result4.push(result5);
pos2 = pos;
if (input.charCodeAt(pos) === 44) {
result5 = ",";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result5 !== null) {
result6 = parse_qop_value();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
}
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos1;
}
} else {
result3 = null;
pos = pos1;
}
if (result3 !== null) {
result4 = parse_RDQUOT();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_qop_value() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 8).toLowerCase() === "auth-int") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"auth-int\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4).toLowerCase() === "auth") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"auth\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
if (result0 !== null) {
result0 = (function(offset, qop_value) {
data.qop || (data.qop=[]);
data.qop.push(qop_value.toLowerCase()); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Proxy_Require() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Record_Route() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_rec_route();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_rec_route();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_rec_route();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var idx, length;
length = data.multi_header.length;
for (idx = 0; idx < length; idx++) {
if (data.multi_header[idx].parsed === null) {
data = null;
break;
}
}
if (data !== null) {
data = data.multi_header;
} else {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_rec_route() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_name_addr();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var header;
if(!data.multi_header) data.multi_header = [];
try {
header = new NameAddrHeader(data.uri, data.display_name, data.params);
delete data.uri;
delete data.display_name;
delete data.params;
} catch(e) {
header = null;
}
data.multi_header.push( { 'possition': pos,
'offset': offset,
'parsed': header
});})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Reason() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SIP\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_reason_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_reason_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, protocol) {
data.protocol = protocol.toLowerCase();
if (!data.params) data.params = {};
if (data.params.text && data.params.text[0] === '"') {
var text = data.params.text;
data.text = text.substring(1, text.length-1);
delete data.params.text;
}
})(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_reason_param() {
var result0;
result0 = parse_reason_cause();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_reason_cause() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "cause") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"cause\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result3 = parse_DIGIT();
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
result3 = parse_DIGIT();
}
} else {
result2 = null;
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, cause) {
data.cause = parseInt(cause.join(''));
})(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Require() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Route() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_route_param();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_route_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_route_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_route_param() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_name_addr();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Subscription_State() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_substate_value();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_subexp_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_subexp_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_substate_value() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 6).toLowerCase() === "active") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"active\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7).toLowerCase() === "pending") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"pending\"");
}
}
if (result0 === null) {
if (input.substr(pos, 10).toLowerCase() === "terminated") {
result0 = input.substr(pos, 10);
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"terminated\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.state = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_subexp_params() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "reason") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"reason\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_event_reason_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, reason) {
if (typeof reason !== 'undefined') data.reason = reason; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 7).toLowerCase() === "expires") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"expires\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_delta_seconds();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, expires) {
if (typeof expires !== 'undefined') data.expires = expires; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 11).toLowerCase() === "retry_after") {
result0 = input.substr(pos, 11);
pos += 11;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"retry_after\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_delta_seconds();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, retry_after) {
if (typeof retry_after !== 'undefined') data.retry_after = retry_after; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
result0 = parse_generic_param();
}
}
}
return result0;
}
function parse_event_reason_value() {
var result0;
if (input.substr(pos, 11).toLowerCase() === "deactivated") {
result0 = input.substr(pos, 11);
pos += 11;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"deactivated\"");
}
}
if (result0 === null) {
if (input.substr(pos, 9).toLowerCase() === "probation") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"probation\"");
}
}
if (result0 === null) {
if (input.substr(pos, 8).toLowerCase() === "rejected") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"rejected\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7).toLowerCase() === "timeout") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"timeout\"");
}
}
if (result0 === null) {
if (input.substr(pos, 6).toLowerCase() === "giveup") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"giveup\"");
}
}
if (result0 === null) {
if (input.substr(pos, 10).toLowerCase() === "noresource") {
result0 = input.substr(pos, 10);
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"noresource\"");
}
}
if (result0 === null) {
if (input.substr(pos, 9).toLowerCase() === "invariant") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"invariant\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
}
}
}
}
return result0;
}
function parse_Subject() {
var result0;
result0 = parse_TEXT_UTF8_TRIM();
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_Supported() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_To() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_to_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_to_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var tag = data.tag;
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
if (tag) {data.setParam('tag',tag)}
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_to_param() {
var result0;
result0 = parse_tag_param();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_Via() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_via_param();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_via_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_via_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_via_param() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
result0 = parse_sent_protocol();
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_sent_by();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_via_params();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_via_params();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_via_params() {
var result0;
result0 = parse_via_ttl();
if (result0 === null) {
result0 = parse_via_maddr();
if (result0 === null) {
result0 = parse_via_received();
if (result0 === null) {
result0 = parse_via_branch();
if (result0 === null) {
result0 = parse_response_port();
if (result0 === null) {
result0 = parse_generic_param();
}
}
}
}
}
return result0;
}
function parse_via_ttl() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "ttl") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"ttl\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_ttl();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_ttl_value) {
data.ttl = via_ttl_value; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_maddr() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "maddr") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"maddr\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_host();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_maddr) {
data.maddr = via_maddr; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_received() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 8).toLowerCase() === "received") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"received\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_IPv4address();
if (result2 === null) {
result2 = parse_IPv6address();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_received) {
data.received = via_received; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_branch() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "branch") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"branch\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_branch) {
data.branch = via_branch; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_response_port() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "rport") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"rport\"");
}
}
if (result0 !== null) {
pos2 = pos;
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = [];
result3 = parse_DIGIT();
while (result3 !== null) {
result2.push(result3);
result3 = parse_DIGIT();
}
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
if(typeof response_port !== 'undefined')
data.rport = response_port.join(''); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_sent_protocol() {
var result0, result1, result2, result3, result4;
var pos0;
pos0 = pos;
result0 = parse_protocol_name();
if (result0 !== null) {
result1 = parse_SLASH();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result3 = parse_SLASH();
if (result3 !== null) {
result4 = parse_transport();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_protocol_name() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SIP\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
if (result0 !== null) {
result0 = (function(offset, via_protocol) {
data.protocol = via_protocol; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_transport() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "udp") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"UDP\"");
}
}
if (result0 === null) {
if (input.substr(pos, 3).toLowerCase() === "tcp") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"TCP\"");
}
}
if (result0 === null) {
if (input.substr(pos, 3).toLowerCase() === "tls") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"TLS\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4).toLowerCase() === "sctp") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SCTP\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
}
if (result0 !== null) {
result0 = (function(offset, via_transport) {
data.transport = via_transport; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_sent_by() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
result0 = parse_via_host();
if (result0 !== null) {
pos1 = pos;
result1 = parse_COLON();
if (result1 !== null) {
result2 = parse_via_port();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos1;
}
} else {
result1 = null;
pos = pos1;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_via_host() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_IPv4address();
if (result0 === null) {
result0 = parse_IPv6reference();
if (result0 === null) {
result0 = parse_hostname();
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.host = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_port() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DIGIT();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_DIGIT();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_DIGIT();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_DIGIT();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_sent_by_port) {
data.port = parseInt(via_sent_by_port.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_ttl() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DIGIT();
if (result0 !== null) {
result1 = parse_DIGIT();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, ttl) {
return parseInt(ttl.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_WWW_Authenticate() {
var result0;
result0 = parse_challenge();
return result0;
}
function parse_Session_Expires() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_s_e_expires();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_s_e_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_s_e_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_s_e_expires() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_delta_seconds();
if (result0 !== null) {
result0 = (function(offset, expires) { data.expires = expires; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_s_e_params() {
var result0;
result0 = parse_s_e_refresher();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_s_e_refresher() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 9).toLowerCase() === "refresher") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"refresher\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
if (input.substr(pos, 3).toLowerCase() === "uac") {
result2 = input.substr(pos, 3);
pos += 3;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"uac\"");
}
}
if (result2 === null) {
if (input.substr(pos, 3).toLowerCase() === "uas") {
result2 = input.substr(pos, 3);
pos += 3;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"uas\"");
}
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, s_e_refresher_value) { data.refresher = s_e_refresher_value.toLowerCase(); })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_extension_header() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_HCOLON();
if (result1 !== null) {
result2 = parse_header_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_header_value() {
var result0, result1;
result0 = [];
result1 = parse_TEXT_UTF8char();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_LWS();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_TEXT_UTF8char();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_LWS();
}
}
}
return result0;
}
function parse_message_body() {
var result0, result1;
result0 = [];
result1 = parse_OCTET();
while (result1 !== null) {
result0.push(result1);
result1 = parse_OCTET();
}
return result0;
}
function parse_uuid_URI() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.substr(pos, 5) === "uuid:") {
result0 = "uuid:";
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"uuid:\"");
}
}
if (result0 !== null) {
result1 = parse_uuid();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_uuid() {
var result0, result1, result2, result3, result4, result5, result6, result7, result8;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_hex8();
if (result0 !== null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 !== null) {
result2 = parse_hex4();
if (result2 !== null) {
if (input.charCodeAt(pos) === 45) {
result3 = "-";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result3 !== null) {
result4 = parse_hex4();
if (result4 !== null) {
if (input.charCodeAt(pos) === 45) {
result5 = "-";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result5 !== null) {
result6 = parse_hex4();
if (result6 !== null) {
if (input.charCodeAt(pos) === 45) {
result7 = "-";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result7 !== null) {
result8 = parse_hex12();
if (result8 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, uuid) {
data = input.substring(pos+5, offset); })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hex4() {
var result0, result1, result2, result3;
var pos0;
pos0 = pos;
result0 = parse_HEXDIG();
if (result0 !== null) {
result1 = parse_HEXDIG();
if (result1 !== null) {
result2 = parse_HEXDIG();
if (result2 !== null) {
result3 = parse_HEXDIG();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_hex8() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = parse_hex4();
if (result0 !== null) {
result1 = parse_hex4();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_hex12() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_hex4();
if (result0 !== null) {
result1 = parse_hex4();
if (result1 !== null) {
result2 = parse_hex4();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Refer_To() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Replaces() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_call_id();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_replaces_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_replaces_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_call_id() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_word();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
result2 = parse_word();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.call_id = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_replaces_param() {
var result0;
result0 = parse_to_tag();
if (result0 === null) {
result0 = parse_from_tag();
if (result0 === null) {
result0 = parse_early_flag();
if (result0 === null) {
result0 = parse_generic_param();
}
}
}
return result0;
}
function parse_to_tag() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6) === "to-tag") {
result0 = "to-tag";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"to-tag\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, to_tag) {
data.to_tag = to_tag; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_from_tag() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 8) === "from-tag") {
result0 = "from-tag";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"from-tag\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, from_tag) {
data.from_tag = from_tag; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_early_flag() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 10) === "early-only") {
result0 = "early-only";
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"early-only\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.early_only = true; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function cleanupExpected(expected) {
expected.sort();
var lastExpected = null;
var cleanExpected = [];
for (var i = 0; i < expected.length; i++) {
if (expected[i] !== lastExpected) {
cleanExpected.push(expected[i]);
lastExpected = expected[i];
}
}
return cleanExpected;
}
function computeErrorPosition() {
/*
* The first idea was to use |String.split| to break the input up to the
* error position along newlines and derive the line and column from
* there. However IE's |split| implementation is so broken that it was
* enough to prevent it.
*/
var line = 1;
var column = 1;
var seenCR = false;
for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) {
var ch = input.charAt(i);
if (ch === "\n") {
if (!seenCR) { line++; }
column = 1;
seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
line++;
column = 1;
seenCR = true;
} else {
column++;
seenCR = false;
}
}
return { line: line, column: column };
}
var URI = require('./URI');
var NameAddrHeader = require('./NameAddrHeader');
var data = {};
var result = parseFunctions[startRule]();
/*
* The parser is now in one of the following three states:
*
* 1. The parser successfully parsed the whole input.
*
* - |result !== null|
* - |pos === input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 2. The parser successfully parsed only a part of the input.
*
* - |result !== null|
* - |pos < input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 3. The parser did not successfully parse any part of the input.
*
* - |result === null|
* - |pos === 0|
* - |rightmostFailuresExpected| contains at least one failure
*
* All code following this comment (including called functions) must
* handle these states.
*/
if (result === null || pos !== input.length) {
var offset = Math.max(pos, rightmostFailuresPos);
var found = offset < input.length ? input.charAt(offset) : null;
var errorPosition = computeErrorPosition();
new this.SyntaxError(
cleanupExpected(rightmostFailuresExpected),
found,
offset,
errorPosition.line,
errorPosition.column
);
return -1;
}
return data;
},
/* Returns the parser source code. */
toSource: function() { return this._source; }
};
/* Thrown when a parser encounters a syntax error. */
result.SyntaxError = function(expected, found, offset, line, column) {
function buildMessage(expected, found) {
var expectedHumanized, foundHumanized;
switch (expected.length) {
case 0:
expectedHumanized = "end of input";
break;
case 1:
expectedHumanized = expected[0];
break;
default:
expectedHumanized = expected.slice(0, expected.length - 1).join(", ")
+ " or "
+ expected[expected.length - 1];
}
foundHumanized = found ? quote(found) : "end of input";
return "Expected " + expectedHumanized + " but " + foundHumanized + " found.";
}
this.name = "SyntaxError";
this.expected = expected;
this.found = found;
this.message = buildMessage(expected, found);
this.offset = offset;
this.line = line;
this.column = column;
};
result.SyntaxError.prototype = Error.prototype;
return result;
})();
},{"./NameAddrHeader":9,"./URI":24}],7:[function(require,module,exports){
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP');
var adapter = require('webrtc-adapter');
var pkg = require('../package.json');
debug('version %s', pkg.version);
var C = require('./Constants');
var Exceptions = require('./Exceptions');
var Utils = require('./Utils');
var UA = require('./UA');
var URI = require('./URI');
var NameAddrHeader = require('./NameAddrHeader');
var Grammar = require('./Grammar');
var WebSocketInterface = require('./WebSocketInterface');
/**
* Expose the JsSIP module.
*/
var JsSIP = module.exports = {
C: C,
Exceptions: Exceptions,
Utils: Utils,
UA: UA,
URI: URI,
NameAddrHeader: NameAddrHeader,
WebSocketInterface: WebSocketInterface,
Grammar: Grammar,
// Expose the debug module.
debug: require('debug'),
// Expose the adapter module.
adapter: adapter
};
Object.defineProperties(JsSIP, {
name: {
get: function() { return pkg.title; }
},
version: {
get: function() { return pkg.version; }
}
});
},{"../package.json":50,"./Constants":1,"./Exceptions":5,"./Grammar":6,"./NameAddrHeader":9,"./UA":23,"./URI":24,"./Utils":25,"./WebSocketInterface":26,"debug":34,"webrtc-adapter":41}],8:[function(require,module,exports){
module.exports = Message;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var JsSIP_C = require('./Constants');
var SIPMessage = require('./SIPMessage');
var Utils = require('./Utils');
var RequestSender = require('./RequestSender');
var Transactions = require('./Transactions');
var Exceptions = require('./Exceptions');
function Message(ua) {
this.ua = ua;
// Custom message empty object for high level use
this.data = {};
events.EventEmitter.call(this);
}
util.inherits(Message, events.EventEmitter);
Message.prototype.send = function(target, body, options) {
var request_sender, event, contentType, eventHandlers, extraHeaders,
originalTarget = target;
if (target === undefined || body === undefined) {
throw new TypeError('Not enough arguments');
}
// Check target validity
target = this.ua.normalizeTarget(target);
if (!target) {
throw new TypeError('Invalid target: '+ originalTarget);
}
// Get call options
options = options || {};
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [];
eventHandlers = options.eventHandlers || {};
contentType = options.contentType || 'text/plain';
this.content_type = contentType;
// Set event handlers
for (event in eventHandlers) {
this.on(event, eventHandlers[event]);
}
this.closed = false;
this.ua.applicants[this] = this;
extraHeaders.push('Content-Type: '+ contentType);
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.MESSAGE, target, this.ua, null, extraHeaders);
if(body) {
this.request.body = body;
this.content = body;
} else {
this.content = null;
}
request_sender = new RequestSender(this, this.ua);
this.newMessage('local', this.request);
request_sender.send();
};
Message.prototype.receiveResponse = function(response) {
var cause;
if(this.closed) {
return;
}
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
delete this.ua.applicants[this];
this.emit('succeeded', {
originator: 'remote',
response: response
});
break;
default:
delete this.ua.applicants[this];
cause = Utils.sipErrorCause(response.status_code);
this.emit('failed', {
originator: 'remote',
response: response,
cause: cause
});
break;
}
};
Message.prototype.onRequestTimeout = function() {
if(this.closed) {
return;
}
this.emit('failed', {
originator: 'system',
cause: JsSIP_C.causes.REQUEST_TIMEOUT
});
};
Message.prototype.onTransportError = function() {
if(this.closed) {
return;
}
this.emit('failed', {
originator: 'system',
cause: JsSIP_C.causes.CONNECTION_ERROR
});
};
Message.prototype.close = function() {
this.closed = true;
delete this.ua.applicants[this];
};
Message.prototype.init_incoming = function(request) {
var transaction;
this.request = request;
this.content_type = request.getHeader('Content-Type');
if (request.body) {
this.content = request.body;
} else {
this.content = null;
}
this.newMessage('remote', request);
transaction = this.ua.transactions.nist[request.via_branch];
if (transaction && (transaction.state === Transactions.C.STATUS_TRYING || transaction.state === Transactions.C.STATUS_PROCEEDING)) {
request.reply(200);
}
};
/**
* Accept the incoming Message
* Only valid for incoming Messages
*/
Message.prototype.accept = function(options) {
options = options || {};
var
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body;
if (this.direction !== 'incoming') {
throw new Exceptions.NotSupportedError('"accept" not supported for outgoing Message');
}
this.request.reply(200, null, extraHeaders, body);
};
/**
* Reject the incoming Message
* Only valid for incoming Messages
*/
Message.prototype.reject = function(options) {
options = options || {};
var
status_code = options.status_code || 480,
reason_phrase = options.reason_phrase,
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body;
if (this.direction !== 'incoming') {
throw new Exceptions.NotSupportedError('"reject" not supported for outgoing Message');
}
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
this.request.reply(status_code, reason_phrase, extraHeaders, body);
};
/**
* Internal Callbacks
*/
Message.prototype.newMessage = function(originator, request) {
if (originator === 'remote') {
this.direction = 'incoming';
this.local_identity = request.to;
this.remote_identity = request.from;
} else if (originator === 'local'){
this.direction = 'outgoing';
this.local_identity = request.from;
this.remote_identity = request.to;
}
this.ua.newMessage({
originator: originator,
message: this,
request: request
});
};
},{"./Constants":1,"./Exceptions":5,"./RequestSender":17,"./SIPMessage":18,"./Transactions":21,"./Utils":25,"events":28,"util":32}],9:[function(require,module,exports){
module.exports = NameAddrHeader;
/**
* Dependencies.
*/
var URI = require('./URI');
var Grammar = require('./Grammar');
function NameAddrHeader(uri, display_name, parameters) {
var param;
// Checks
if(!uri || !(uri instanceof URI)) {
throw new TypeError('missing or invalid "uri" parameter');
}
// Initialize parameters
this.uri = uri;
this.parameters = {};
for (param in parameters) {
this.setParam(param, parameters[param]);
}
Object.defineProperties(this, {
display_name: {
get: function() { return display_name; },
set: function(value) {
display_name = (value === 0) ? '0' : value;
}
}
});
}
NameAddrHeader.prototype = {
setParam: function(key, value) {
if (key) {
this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString();
}
},
getParam: function(key) {
if(key) {
return this.parameters[key.toLowerCase()];
}
},
hasParam: function(key) {
if(key) {
return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false;
}
},
deleteParam: function(parameter) {
var value;
parameter = parameter.toLowerCase();
if (this.parameters.hasOwnProperty(parameter)) {
value = this.parameters[parameter];
delete this.parameters[parameter];
return value;
}
},
clearParams: function() {
this.parameters = {};
},
clone: function() {
return new NameAddrHeader(
this.uri.clone(),
this.display_name,
JSON.parse(JSON.stringify(this.parameters)));
},
toString: function() {
var body, parameter;
body = (this.display_name || this.display_name === 0) ? '"' + this.display_name + '" ' : '';
body += '<' + this.uri.toString() + '>';
for (parameter in this.parameters) {
body += ';' + parameter;
if (this.parameters[parameter] !== null) {
body += '='+ this.parameters[parameter];
}
}
return body;
}
};
/**
* Parse the given string and returns a NameAddrHeader instance or undefined if
* it is an invalid NameAddrHeader.
*/
NameAddrHeader.parse = function(name_addr_header) {
name_addr_header = Grammar.parse(name_addr_header,'Name_Addr_Header');
if (name_addr_header !== -1) {
return name_addr_header;
} else {
return undefined;
}
};
},{"./Grammar":6,"./URI":24}],10:[function(require,module,exports){
var Parser = {};
module.exports = Parser;
/**
* Dependencies.
*/
var debugerror = require('debug')('JsSIP:ERROR:Parser');
debugerror.log = console.warn.bind(console);
var Grammar = require('./Grammar');
var SIPMessage = require('./SIPMessage');
/**
* Extract and parse every header of a SIP message.
*/
function getHeader(data, headerStart) {
var
// 'start' position of the header.
start = headerStart,
// 'end' position of the header.
end = 0,
// 'partial end' position of the header.
partialEnd = 0;
//End of message.
if (data.substring(start, start + 2).match(/(^\r\n)/)) {
return -2;
}
while(end === 0) {
// Partial End of Header.
partialEnd = data.indexOf('\r\n', start);
// 'indexOf' returns -1 if the value to be found never occurs.
if (partialEnd === -1) {
return partialEnd;
}
if(!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && data.charAt(partialEnd + 2).match(/(^\s+)/)) {
// Not the end of the message. Continue from the next position.
start = partialEnd + 2;
} else {
end = partialEnd;
}
}
return end;
}
function parseHeader(message, data, headerStart, headerEnd) {
var header, idx, length, parsed,
hcolonIndex = data.indexOf(':', headerStart),
headerName = data.substring(headerStart, hcolonIndex).trim(),
headerValue = data.substring(hcolonIndex + 1, headerEnd).trim();
// If header-field is well-known, parse it.
switch(headerName.toLowerCase()) {
case 'via':
case 'v':
message.addHeader('via', headerValue);
if(message.getHeaders('via').length === 1) {
parsed = message.parseHeader('Via');
if(parsed) {
message.via = parsed;
message.via_branch = parsed.branch;
}
} else {
parsed = 0;
}
break;
case 'from':
case 'f':
message.setHeader('from', headerValue);
parsed = message.parseHeader('from');
if(parsed) {
message.from = parsed;
message.from_tag = parsed.getParam('tag');
}
break;
case 'to':
case 't':
message.setHeader('to', headerValue);
parsed = message.parseHeader('to');
if(parsed) {
message.to = parsed;
message.to_tag = parsed.getParam('tag');
}
break;
case 'record-route':
parsed = Grammar.parse(headerValue, 'Record_Route');
if (parsed === -1) {
parsed = undefined;
} else {
length = parsed.length;
for (idx = 0; idx < length; idx++) {
header = parsed[idx];
message.addHeader('record-route', headerValue.substring(header.possition, header.offset));
message.headers['Record-Route'][message.getHeaders('record-route').length - 1].parsed = header.parsed;
}
}
break;
case 'call-id':
case 'i':
message.setHeader('call-id', headerValue);
parsed = message.parseHeader('call-id');
if(parsed) {
message.call_id = headerValue;
}
break;
case 'contact':
case 'm':
parsed = Grammar.parse(headerValue, 'Contact');
if (parsed === -1) {
parsed = undefined;
} else {
length = parsed.length;
for (idx = 0; idx < length; idx++) {
header = parsed[idx];
message.addHeader('contact', headerValue.substring(header.possition, header.offset));
message.headers.Contact[message.getHeaders('contact').length - 1].parsed = header.parsed;
}
}
break;
case 'content-length':
case 'l':
message.setHeader('content-length', headerValue);
parsed = message.parseHeader('content-length');
break;
case 'content-type':
case 'c':
message.setHeader('content-type', headerValue);
parsed = message.parseHeader('content-type');
break;
case 'cseq':
message.setHeader('cseq', headerValue);
parsed = message.parseHeader('cseq');
if(parsed) {
message.cseq = parsed.value;
}
if(message instanceof SIPMessage.IncomingResponse) {
message.method = parsed.method;
}
break;
case 'max-forwards':
message.setHeader('max-forwards', headerValue);
parsed = message.parseHeader('max-forwards');
break;
case 'www-authenticate':
message.setHeader('www-authenticate', headerValue);
parsed = message.parseHeader('www-authenticate');
break;
case 'proxy-authenticate':
message.setHeader('proxy-authenticate', headerValue);
parsed = message.parseHeader('proxy-authenticate');
break;
case 'session-expires':
case 'x':
message.setHeader('session-expires', headerValue);
parsed = message.parseHeader('session-expires');
if (parsed) {
message.session_expires = parsed.expires;
message.session_expires_refresher = parsed.refresher;
}
break;
case 'refer-to':
case 'r':
message.setHeader('refer-to', headerValue);
parsed = message.parseHeader('refer-to');
if(parsed) {
message.refer_to = parsed;
}
break;
case 'replaces':
message.setHeader('replaces', headerValue);
parsed = message.parseHeader('replaces');
if(parsed) {
message.replaces = parsed;
}
break;
case 'event':
case 'o':
message.setHeader('event', headerValue);
parsed = message.parseHeader('event');
if(parsed) {
message.event = parsed;
}
break;
default:
// Do not parse this header.
message.setHeader(headerName, headerValue);
parsed = 0;
}
if (parsed === undefined) {
return {
error: 'error parsing header "'+ headerName +'"'
};
} else {
return true;
}
}
/**
* Parse SIP Message
*/
Parser.parseMessage = function(data, ua) {
var message, firstLine, contentLength, bodyStart, parsed,
headerStart = 0,
headerEnd = data.indexOf('\r\n');
if(headerEnd === -1) {
debugerror('parseMessage() | no CRLF found, not a SIP message');
return;
}
// Parse first line. Check if it is a Request or a Reply.
firstLine = data.substring(0, headerEnd);
parsed = Grammar.parse(firstLine, 'Request_Response');
if(parsed === -1) {
debugerror('parseMessage() | error parsing first line of SIP message: "' + firstLine + '"');
return;
} else if(!parsed.status_code) {
message = new SIPMessage.IncomingRequest(ua);
message.method = parsed.method;
message.ruri = parsed.uri;
} else {
message = new SIPMessage.IncomingResponse();
message.status_code = parsed.status_code;
message.reason_phrase = parsed.reason_phrase;
}
message.data = data;
headerStart = headerEnd + 2;
/* Loop over every line in data. Detect the end of each header and parse
* it or simply add to the headers collection.
*/
while(true) {
headerEnd = getHeader(data, headerStart);
// The SIP message has normally finished.
if(headerEnd === -2) {
bodyStart = headerStart + 2;
break;
}
// data.indexOf returned -1 due to a malformed message.
else if(headerEnd === -1) {
debugerror('parseMessage() | malformed message');
return;
}
parsed = parseHeader(message, data, headerStart, headerEnd);
if(parsed !== true) {
debugerror('parseMessage() |', parsed.error);
return;
}
headerStart = headerEnd + 2;
}
/* RFC3261 18.3.
* If there are additional bytes in the transport packet
* beyond the end of the body, they MUST be discarded.
*/
if(message.hasHeader('content-length')) {
contentLength = message.getHeader('content-length');
message.body = data.substr(bodyStart, contentLength);
} else {
message.body = data.substring(bodyStart);
}
return message;
};
},{"./Grammar":6,"./SIPMessage":18,"debug":34}],11:[function(require,module,exports){
/* globals RTCPeerConnection: false, RTCSessionDescription: false */
module.exports = RTCSession;
var C = {
// RTCSession states
STATUS_NULL: 0,
STATUS_INVITE_SENT: 1,
STATUS_1XX_RECEIVED: 2,
STATUS_INVITE_RECEIVED: 3,
STATUS_WAITING_FOR_ANSWER: 4,
STATUS_ANSWERED: 5,
STATUS_WAITING_FOR_ACK: 6,
STATUS_CANCELED: 7,
STATUS_TERMINATED: 8,
STATUS_CONFIRMED: 9
};
/**
* Expose C object.
*/
RTCSession.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:RTCSession');
var debugerror = require('debug')('JsSIP:ERROR:RTCSession');
debugerror.log = console.warn.bind(console);
var sdp_transform = require('sdp-transform');
var JsSIP_C = require('./Constants');
var Exceptions = require('./Exceptions');
var Transactions = require('./Transactions');
var Utils = require('./Utils');
var Timers = require('./Timers');
var SIPMessage = require('./SIPMessage');
var Dialog = require('./Dialog');
var RequestSender = require('./RequestSender');
var RTCSession_Request = require('./RTCSession/Request');
var RTCSession_DTMF = require('./RTCSession/DTMF');
var RTCSession_ReferNotifier = require('./RTCSession/ReferNotifier');
var RTCSession_ReferSubscriber = require('./RTCSession/ReferSubscriber');
/**
* Local variables.
*/
var holdMediaTypes = ['audio', 'video'];
function RTCSession(ua) {
debug('new');
this.ua = ua;
this.status = C.STATUS_NULL;
this.dialog = null;
this.earlyDialogs = {};
this.connection = null; // The RTCPeerConnection instance (public attribute).
// RTCSession confirmation flag
this.is_confirmed = false;
// is late SDP being negotiated
this.late_sdp = false;
// Default rtcOfferConstraints and rtcAnswerConstrainsts (passed in connect() or answer()).
this.rtcOfferConstraints = null;
this.rtcAnswerConstraints = null;
// Local MediaStream.
this.localMediaStream = null;
this.localMediaStreamLocallyGenerated = false;
// Flag to indicate PeerConnection ready for new actions.
this.rtcReady = true;
// SIP Timers
this.timers = {
ackTimer: null,
expiresTimer: null,
invite2xxTimer: null,
userNoAnswerTimer: null
};
// Session info
this.direction = null;
this.local_identity = null;
this.remote_identity = null;
this.start_time = null;
this.end_time = null;
this.tones = null;
// Mute/Hold state
this.audioMuted = false;
this.videoMuted = false;
this.localHold = false;
this.remoteHold = false;
// Session Timers (RFC 4028)
this.sessionTimers = {
enabled: this.ua.configuration.session_timers,
defaultExpires: JsSIP_C.SESSION_EXPIRES,
currentExpires: null,
running: false,
refresher: false,
timer: null // A setTimeout.
};
// Map of ReferSubscriber instances indexed by the REFER's CSeq number
this.referSubscribers = {};
// Custom session empty object for high level use
this.data = {};
// Expose session failed/ended causes as a property of the RTCSession instance
this.causes = JsSIP_C.causes;
events.EventEmitter.call(this);
}
util.inherits(RTCSession, events.EventEmitter);
/**
* User API
*/
RTCSession.prototype.isInProgress = function() {
switch(this.status) {
case C.STATUS_NULL:
case C.STATUS_INVITE_SENT:
case C.STATUS_1XX_RECEIVED:
case C.STATUS_INVITE_RECEIVED:
case C.STATUS_WAITING_FOR_ANSWER:
return true;
default:
return false;
}
};
RTCSession.prototype.isEstablished = function() {
switch(this.status) {
case C.STATUS_ANSWERED:
case C.STATUS_WAITING_FOR_ACK:
case C.STATUS_CONFIRMED:
return true;
default:
return false;
}
};
RTCSession.prototype.isEnded = function() {
switch(this.status) {
case C.STATUS_CANCELED:
case C.STATUS_TERMINATED:
return true;
default:
return false;
}
};
RTCSession.prototype.isMuted = function() {
return {
audio: this.audioMuted,
video: this.videoMuted
};
};
RTCSession.prototype.isOnHold = function() {
return {
local: this.localHold,
remote: this.remoteHold
};
};
/**
* Check if RTCSession is ready for an outgoing re-INVITE or UPDATE with SDP.
*/
RTCSession.prototype.isReadyToReOffer = function() {
if (! this.rtcReady) {
debug('isReadyToReOffer() | internal WebRTC status not ready');
return false;
}
// No established yet.
if (! this.dialog) {
debug('isReadyToReOffer() | session not established yet');
return false;
}
// Another INVITE transaction is in progress
if (this.dialog.uac_pending_reply === true || this.dialog.uas_pending_reply === true) {
debug('isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress');
return false;
}
return true;
};
RTCSession.prototype.connect = function(target, options, initCallback) {
debug('connect()');
options = options || {};
var event, requestParams,
originalTarget = target,
eventHandlers = options.eventHandlers || {},
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
mediaConstraints = options.mediaConstraints || {audio: true, video: true},
mediaStream = options.mediaStream || null,
pcConfig = options.pcConfig || {iceServers:[]},
rtcConstraints = options.rtcConstraints || null,
rtcOfferConstraints = options.rtcOfferConstraints || null;
this.rtcOfferConstraints = rtcOfferConstraints;
this.rtcAnswerConstraints = options.rtcAnswerConstraints || null;
// Session Timers.
if (this.sessionTimers.enabled) {
if (Utils.isDecimal(options.sessionTimersExpires)) {
if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.defaultExpires = options.sessionTimersExpires;
}
else {
this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES;
}
}
}
this.data = options.data || this.data;
if (target === undefined) {
throw new TypeError('Not enough arguments');
}
// Check WebRTC support.
if (!window.RTCPeerConnection) {
throw new Exceptions.NotSupportedError('WebRTC not supported');
}
// Check target validity
target = this.ua.normalizeTarget(target);
if (!target) {
throw new TypeError('Invalid target: '+ originalTarget);
}
// Check Session Status
if (this.status !== C.STATUS_NULL) {
throw new Exceptions.InvalidStateError(this.status);
}
// Set event handlers
for (event in eventHandlers) {
this.on(event, eventHandlers[event]);
}
// Session parameter initialization
this.from_tag = Utils.newTag();
// Set anonymous property
this.anonymous = options.anonymous || false;
// OutgoingSession specific parameters
this.isCanceled = false;
requestParams = {from_tag: this.from_tag};
this.contact = this.ua.contact.toString({
anonymous: this.anonymous,
outbound: true
});
if (this.anonymous) {
requestParams.from_display_name = 'Anonymous';
requestParams.from_uri = 'sip:[email protected]';
extraHeaders.push('P-Preferred-Identity: '+ this.ua.configuration.uri.toString());
extraHeaders.push('Privacy: id');
}
extraHeaders.push('Contact: '+ this.contact);
extraHeaders.push('Content-Type: application/sdp');
if (this.sessionTimers.enabled) {
extraHeaders.push('Session-Expires: ' + this.sessionTimers.defaultExpires);
}
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.INVITE, target, this.ua, requestParams, extraHeaders);
this.id = this.request.call_id + this.from_tag;
// Create a new RTCPeerConnection instance.
createRTCConnection.call(this, pcConfig, rtcConstraints);
// Save the session into the ua sessions collection.
this.ua.sessions[this.id] = this;
// Set internal properties
this.direction = 'outgoing';
this.local_identity = this.request.from;
this.remote_identity = this.request.to;
// User explicitly provided a newRTCSession callback for this session
if (initCallback) {
initCallback(this);
} else {
newRTCSession.call(this, 'local', this.request);
}
sendInitialRequest.call(this, mediaConstraints, rtcOfferConstraints, mediaStream);
};
RTCSession.prototype.init_incoming = function(request, initCallback) {
debug('init_incoming()');
var expires,
self = this,
contentType = request.getHeader('Content-Type');
// Check body and content type
if (request.body && (contentType !== 'application/sdp')) {
request.reply(415);
return;
}
// Session parameter initialization
this.status = C.STATUS_INVITE_RECEIVED;
this.from_tag = request.from_tag;
this.id = request.call_id + this.from_tag;
this.request = request;
this.contact = this.ua.contact.toString();
// Save the session into the ua sessions collection.
this.ua.sessions[this.id] = this;
// Get the Expires header value if exists
if (request.hasHeader('expires')) {
expires = request.getHeader('expires') * 1000;
}
/* Set the to_tag before
* replying a response code that will create a dialog.
*/
request.to_tag = Utils.newTag();
// An error on dialog creation will fire 'failed' event
if (! createDialog.call(this, request, 'UAS', true)) {
request.reply(500, 'Missing Contact header field');
return;
}
if (request.body) {
this.late_sdp = false;
}
else {
this.late_sdp = true;
}
this.status = C.STATUS_WAITING_FOR_ANSWER;
// Set userNoAnswerTimer
this.timers.userNoAnswerTimer = setTimeout(function() {
request.reply(408);
failed.call(self, 'local',null, JsSIP_C.causes.NO_ANSWER);
}, this.ua.configuration.no_answer_timeout
);
/* Set expiresTimer
* RFC3261 13.3.1
*/
if (expires) {
this.timers.expiresTimer = setTimeout(function() {
if(self.status === C.STATUS_WAITING_FOR_ANSWER) {
request.reply(487);
failed.call(self, 'system', null, JsSIP_C.causes.EXPIRES);
}
}, expires
);
}
// Set internal properties
this.direction = 'incoming';
this.local_identity = request.to;
this.remote_identity = request.from;
// A init callback was specifically defined
if (initCallback) {
initCallback(this);
// Fire 'newRTCSession' event.
} else {
newRTCSession.call(this, 'remote', request);
}
// The user may have rejected the call in the 'newRTCSession' event.
if (this.status === C.STATUS_TERMINATED) {
return;
}
// Reply 180.
request.reply(180, null, ['Contact: ' + self.contact]);
// Fire 'progress' event.
// TODO: Document that 'response' field in 'progress' event is null for
// incoming calls.
progress.call(self, 'local', null);
};
/**
* Answer the call.
*/
RTCSession.prototype.answer = function(options) {
debug('answer()');
options = options || {};
var idx, length, sdp, tracks,
peerHasAudioLine = false,
peerHasVideoLine = false,
peerOffersFullAudio = false,
peerOffersFullVideo = false,
self = this,
request = this.request,
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
mediaConstraints = options.mediaConstraints || {},
mediaStream = options.mediaStream || null,
pcConfig = options.pcConfig || {iceServers:[]},
rtcConstraints = options.rtcConstraints || null,
rtcAnswerConstraints = options.rtcAnswerConstraints || null;
this.rtcAnswerConstraints = rtcAnswerConstraints;
this.rtcOfferConstraints = options.rtcOfferConstraints || null;
// Session Timers.
if (this.sessionTimers.enabled) {
if (Utils.isDecimal(options.sessionTimersExpires)) {
if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.defaultExpires = options.sessionTimersExpires;
}
else {
this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES;
}
}
}
this.data = options.data || this.data;
// Check Session Direction and Status
if (this.direction !== 'incoming') {
throw new Exceptions.NotSupportedError('"answer" not supported for outgoing RTCSession');
} else if (this.status !== C.STATUS_WAITING_FOR_ANSWER) {
throw new Exceptions.InvalidStateError(this.status);
}
this.status = C.STATUS_ANSWERED;
// An error on dialog creation will fire 'failed' event
if (! createDialog.call(this, request, 'UAS')) {
request.reply(500, 'Error creating dialog');
return;
}
clearTimeout(this.timers.userNoAnswerTimer);
extraHeaders.unshift('Contact: ' + self.contact);
// Determine incoming media from incoming SDP offer (if any).
sdp = request.parseSDP();
// Make sure sdp.media is an array, not the case if there is only one media
if (! Array.isArray(sdp.media)) {
sdp.media = [sdp.media];
}
// Go through all medias in SDP to find offered capabilities to answer with
idx = sdp.media.length;
while(idx--) {
var m = sdp.media[idx];
if (m.type === 'audio') {
peerHasAudioLine = true;
if (!m.direction || m.direction === 'sendrecv') {
peerOffersFullAudio = true;
}
}
if (m.type === 'video') {
peerHasVideoLine = true;
if (!m.direction || m.direction === 'sendrecv') {
peerOffersFullVideo = true;
}
}
}
// Remove audio from mediaStream if suggested by mediaConstraints
if (mediaStream && mediaConstraints.audio === false) {
tracks = mediaStream.getAudioTracks();
length = tracks.length;
for (idx=0; idx<length; idx++) {
mediaStream.removeTrack(tracks[idx]);
}
}
// Remove video from mediaStream if suggested by mediaConstraints
if (mediaStream && mediaConstraints.video === false) {
tracks = mediaStream.getVideoTracks();
length = tracks.length;
for (idx=0; idx<length; idx++) {
mediaStream.removeTrack(tracks[idx]);
}
}
// Set audio constraints based on incoming stream if not supplied
if (!mediaStream && mediaConstraints.audio === undefined) {
mediaConstraints.audio = peerOffersFullAudio;
}
// Set video constraints based on incoming stream if not supplied
if (!mediaStream && mediaConstraints.video === undefined) {
mediaConstraints.video = peerOffersFullVideo;
}
// Don't ask for audio if the incoming offer has no audio section
if (!mediaStream && !peerHasAudioLine) {
mediaConstraints.audio = false;
}
// Don't ask for video if the incoming offer has no video section
if (!mediaStream && !peerHasVideoLine) {
mediaConstraints.video = false;
}
// Create a new RTCPeerConnection instance.
// TODO: This may throw an error, should react.
createRTCConnection.call(this, pcConfig, rtcConstraints);
// If a local MediaStream is given use it.
if (mediaStream) {
userMediaSucceeded(mediaStream);
// If at least audio or video is requested prompt getUserMedia.
} else if (mediaConstraints.audio || mediaConstraints.video) {
self.localMediaStreamLocallyGenerated = true;
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then(userMediaSucceeded)
.catch(function(error) {
userMediaFailed(error);
self.emit('getusermediafailed', error);
});
// Otherwise don't prompt getUserMedia.
} else {
userMediaSucceeded(null);
}
// User media succeeded
function userMediaSucceeded(stream) {
if (self.status === C.STATUS_TERMINATED) { return; }
self.localMediaStream = stream;
if (stream) {
self.connection.addStream(stream);
}
// If it's an incoming INVITE without SDP notify the app with the
// RTCPeerConnection so it can do stuff on it before generating the offer.
if (! self.request.body) {
self.emit('peerconnection', {
peerconnection: self.connection
});
}
if (! self.late_sdp) {
var e = {originator:'remote', type:'offer', sdp:request.body};
var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp});
self.emit('sdp', e);
self.connection.setRemoteDescription(offer)
.then(remoteDescriptionSucceededOrNotNeeded)
.catch(function(error) {
request.reply(488);
failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR);
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
else {
remoteDescriptionSucceededOrNotNeeded();
}
}
// User media failed
function userMediaFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
request.reply(480);
failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS);
}
function remoteDescriptionSucceededOrNotNeeded() {
connecting.call(self, request);
if (! self.late_sdp) {
createLocalDescription.call(self, 'answer', rtcSucceeded, rtcFailed, rtcAnswerConstraints);
} else {
createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, self.rtcOfferConstraints);
}
}
function rtcSucceeded(desc) {
if (self.status === C.STATUS_TERMINATED) { return; }
// run for reply success callback
function replySucceeded() {
self.status = C.STATUS_WAITING_FOR_ACK;
setInvite2xxTimer.call(self, request, desc);
setACKTimer.call(self);
accepted.call(self, 'local');
}
// run for reply failure callback
function replyFailed() {
failed.call(self, 'system', null, JsSIP_C.causes.CONNECTION_ERROR);
}
handleSessionTimersInIncomingRequest.call(self, request, extraHeaders);
request.reply(200, null, extraHeaders,
desc,
replySucceeded,
replyFailed
);
}
function rtcFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
request.reply(500);
failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR);
}
};
/**
* Terminate the call.
*/
RTCSession.prototype.terminate = function(options) {
debug('terminate()');
options = options || {};
var cancel_reason, dialog,
cause = options.cause || JsSIP_C.causes.BYE,
status_code = options.status_code,
reason_phrase = options.reason_phrase,
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body,
self = this;
// Check Session Status
if (this.status === C.STATUS_TERMINATED) {
throw new Exceptions.InvalidStateError(this.status);
}
switch(this.status) {
// - UAC -
case C.STATUS_NULL:
case C.STATUS_INVITE_SENT:
case C.STATUS_1XX_RECEIVED:
debug('canceling session');
if (status_code && (status_code < 200 || status_code >= 700)) {
throw new TypeError('Invalid status_code: '+ status_code);
} else if (status_code) {
reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || '';
cancel_reason = 'SIP ;cause=' + status_code + ' ;text="' + reason_phrase + '"';
}
// Check Session Status
if (this.status === C.STATUS_NULL) {
this.isCanceled = true;
this.cancelReason = cancel_reason;
} else if (this.status === C.STATUS_INVITE_SENT) {
this.isCanceled = true;
this.cancelReason = cancel_reason;
} else if(this.status === C.STATUS_1XX_RECEIVED) {
this.request.cancel(cancel_reason);
}
this.status = C.STATUS_CANCELED;
failed.call(this, 'local', null, JsSIP_C.causes.CANCELED);
break;
// - UAS -
case C.STATUS_WAITING_FOR_ANSWER:
case C.STATUS_ANSWERED:
debug('rejecting session');
status_code = status_code || 480;
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
this.request.reply(status_code, reason_phrase, extraHeaders, body);
failed.call(this, 'local', null, JsSIP_C.causes.REJECTED);
break;
case C.STATUS_WAITING_FOR_ACK:
case C.STATUS_CONFIRMED:
debug('terminating session');
reason_phrase = options.reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || '';
if (status_code && (status_code < 200 || status_code >= 700)) {
throw new TypeError('Invalid status_code: '+ status_code);
} else if (status_code) {
extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"');
}
/* RFC 3261 section 15 (Terminating a session):
*
* "...the callee's UA MUST NOT send a BYE on a confirmed dialog
* until it has received an ACK for its 2xx response or until the server
* transaction times out."
*/
if (this.status === C.STATUS_WAITING_FOR_ACK &&
this.direction === 'incoming' &&
this.request.server_transaction.state !== Transactions.C.STATUS_TERMINATED) {
// Save the dialog for later restoration
dialog = this.dialog;
// Send the BYE as soon as the ACK is received...
this.receiveRequest = function(request) {
if(request.method === JsSIP_C.ACK) {
sendRequest.call(this, JsSIP_C.BYE, {
extraHeaders: extraHeaders,
body: body
});
dialog.terminate();
}
};
// .., or when the INVITE transaction times out
this.request.server_transaction.on('stateChanged', function(){
if (this.state === Transactions.C.STATUS_TERMINATED) {
sendRequest.call(self, JsSIP_C.BYE, {
extraHeaders: extraHeaders,
body: body
});
dialog.terminate();
}
});
ended.call(this, 'local', null, cause);
// Restore the dialog into 'this' in order to be able to send the in-dialog BYE :-)
this.dialog = dialog;
// Restore the dialog into 'ua' so the ACK can reach 'this' session
this.ua.dialogs[dialog.id.toString()] = dialog;
} else {
sendRequest.call(this, JsSIP_C.BYE, {
extraHeaders: extraHeaders,
body: body
});
ended.call(this, 'local', null, cause);
}
}
};
RTCSession.prototype.close = function() {
debug('close()');
var idx;
if (this.status === C.STATUS_TERMINATED) {
return;
}
// Terminate RTC.
if (this.connection) {
try {
this.connection.close();
} catch(error) {
debugerror('close() | error closing the RTCPeerConnection: %o', error);
}
}
// Close local MediaStream if it was not given by the user.
if (this.localMediaStream && this.localMediaStreamLocallyGenerated) {
debug('close() | closing local MediaStream');
Utils.closeMediaStream(this.localMediaStream);
}
// Terminate signaling.
// Clear SIP timers
for(idx in this.timers) {
clearTimeout(this.timers[idx]);
}
// Clear Session Timers.
clearTimeout(this.sessionTimers.timer);
// Terminate confirmed dialog
if (this.dialog) {
this.dialog.terminate();
delete this.dialog;
}
// Terminate early dialogs
for(idx in this.earlyDialogs) {
this.earlyDialogs[idx].terminate();
delete this.earlyDialogs[idx];
}
this.status = C.STATUS_TERMINATED;
delete this.ua.sessions[this.id];
};
RTCSession.prototype.sendDTMF = function(tones, options) {
debug('sendDTMF() | tones: %s', tones);
var duration, interToneGap,
position = 0,
self = this;
options = options || {};
duration = options.duration || null;
interToneGap = options.interToneGap || null;
if (tones === undefined) {
throw new TypeError('Not enough arguments');
}
// Check Session Status
if (this.status !== C.STATUS_CONFIRMED && this.status !== C.STATUS_WAITING_FOR_ACK) {
throw new Exceptions.InvalidStateError(this.status);
}
// Convert to string
if(typeof tones === 'number') {
tones = tones.toString();
}
// Check tones
if (!tones || typeof tones !== 'string' || !tones.match(/^[0-9A-DR#*,]+$/i)) {
throw new TypeError('Invalid tones: '+ tones);
}
// Check duration
if (duration && !Utils.isDecimal(duration)) {
throw new TypeError('Invalid tone duration: '+ duration);
} else if (!duration) {
duration = RTCSession_DTMF.C.DEFAULT_DURATION;
} else if (duration < RTCSession_DTMF.C.MIN_DURATION) {
debug('"duration" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_DURATION+ ' milliseconds');
duration = RTCSession_DTMF.C.MIN_DURATION;
} else if (duration > RTCSession_DTMF.C.MAX_DURATION) {
debug('"duration" value is greater than the maximum allowed, setting it to '+ RTCSession_DTMF.C.MAX_DURATION +' milliseconds');
duration = RTCSession_DTMF.C.MAX_DURATION;
} else {
duration = Math.abs(duration);
}
options.duration = duration;
// Check interToneGap
if (interToneGap && !Utils.isDecimal(interToneGap)) {
throw new TypeError('Invalid interToneGap: '+ interToneGap);
} else if (!interToneGap) {
interToneGap = RTCSession_DTMF.C.DEFAULT_INTER_TONE_GAP;
} else if (interToneGap < RTCSession_DTMF.C.MIN_INTER_TONE_GAP) {
debug('"interToneGap" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_INTER_TONE_GAP +' milliseconds');
interToneGap = RTCSession_DTMF.C.MIN_INTER_TONE_GAP;
} else {
interToneGap = Math.abs(interToneGap);
}
if (this.tones) {
// Tones are already queued, just add to the queue
this.tones += tones;
return;
}
this.tones = tones;
// Send the first tone
_sendDTMF();
function _sendDTMF() {
var tone, timeout;
if (self.status === C.STATUS_TERMINATED || !self.tones || position >= self.tones.length) {
// Stop sending DTMF
self.tones = null;
return;
}
tone = self.tones[position];
position += 1;
if (tone === ',') {
timeout = 2000;
} else {
var dtmf = new RTCSession_DTMF(self);
options.eventHandlers = {
onFailed: function() { self.tones = null; }
};
dtmf.send(tone, options);
timeout = duration + interToneGap;
}
// Set timeout for the next tone
setTimeout(_sendDTMF, timeout);
}
};
/**
* Mute
*/
RTCSession.prototype.mute = function(options) {
debug('mute()');
options = options || {audio:true, video:false};
var
audioMuted = false,
videoMuted = false;
if (this.audioMuted === false && options.audio) {
audioMuted = true;
this.audioMuted = true;
toogleMuteAudio.call(this, true);
}
if (this.videoMuted === false && options.video) {
videoMuted = true;
this.videoMuted = true;
toogleMuteVideo.call(this, true);
}
if (audioMuted === true || videoMuted === true) {
onmute.call(this, {
audio: audioMuted,
video: videoMuted
});
}
};
/**
* Unmute
*/
RTCSession.prototype.unmute = function(options) {
debug('unmute()');
options = options || {audio:true, video:true};
var
audioUnMuted = false,
videoUnMuted = false;
if (this.audioMuted === true && options.audio) {
audioUnMuted = true;
this.audioMuted = false;
if (this.localHold === false) {
toogleMuteAudio.call(this, false);
}
}
if (this.videoMuted === true && options.video) {
videoUnMuted = true;
this.videoMuted = false;
if (this.localHold === false) {
toogleMuteVideo.call(this, false);
}
}
if (audioUnMuted === true || videoUnMuted === true) {
onunmute.call(this, {
audio: audioUnMuted,
video: videoUnMuted
});
}
};
/**
* Hold
*/
RTCSession.prototype.hold = function(options, done) {
debug('hold()');
options = options || {};
var self = this,
eventHandlers;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (this.localHold === true) {
return false;
}
if (! this.isReadyToReOffer()) {
return false;
}
this.localHold = true;
onhold.call(this, 'local');
eventHandlers = {
succeeded: function() {
if (done) { done(); }
},
failed: function() {
self.terminate({
cause: JsSIP_C.causes.WEBRTC_ERROR,
status_code: 500,
reason_phrase: 'Hold Failed'
});
}
};
if (options.useUpdate) {
sendUpdate.call(this, {
sdpOffer: true,
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
} else {
sendReinvite.call(this, {
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
}
return true;
};
RTCSession.prototype.unhold = function(options, done) {
debug('unhold()');
options = options || {};
var self = this,
eventHandlers;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (this.localHold === false) {
return false;
}
if (! this.isReadyToReOffer()) {
return false;
}
this.localHold = false;
onunhold.call(this, 'local');
eventHandlers = {
succeeded: function() {
if (done) { done(); }
},
failed: function() {
self.terminate({
cause: JsSIP_C.causes.WEBRTC_ERROR,
status_code: 500,
reason_phrase: 'Unhold Failed'
});
}
};
if (options.useUpdate) {
sendUpdate.call(this, {
sdpOffer: true,
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
} else {
sendReinvite.call(this, {
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
}
return true;
};
RTCSession.prototype.renegotiate = function(options, done) {
debug('renegotiate()');
options = options || {};
var self = this,
eventHandlers,
rtcOfferConstraints = options.rtcOfferConstraints || null;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (! this.isReadyToReOffer()) {
return false;
}
eventHandlers = {
succeeded: function() {
if (done) { done(); }
},
failed: function() {
self.terminate({
cause: JsSIP_C.causes.WEBRTC_ERROR,
status_code: 500,
reason_phrase: 'Media Renegotiation Failed'
});
}
};
setLocalMediaStatus.call(this);
if (options.useUpdate) {
sendUpdate.call(this, {
sdpOffer: true,
eventHandlers: eventHandlers,
rtcOfferConstraints: rtcOfferConstraints,
extraHeaders: options.extraHeaders
});
} else {
sendReinvite.call(this, {
eventHandlers: eventHandlers,
rtcOfferConstraints: rtcOfferConstraints,
extraHeaders: options.extraHeaders
});
}
return true;
};
/**
* Refer
*/
RTCSession.prototype.refer = function(target, options) {
debug('refer()');
var self = this,
originalTarget = target,
referSubscriber,
id;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
// Check target validity
target = this.ua.normalizeTarget(target);
if (!target) {
throw new TypeError('Invalid target: '+ originalTarget);
}
referSubscriber = new RTCSession_ReferSubscriber(this);
referSubscriber.sendRefer(target, options);
// Store in the map
id = referSubscriber.outgoingRequest.cseq;
this.referSubscribers[id] = referSubscriber;
// Listen for ending events so we can remove it from the map
referSubscriber.on('requestFailed', function() {
delete self.referSubscribers[id];
});
referSubscriber.on('accepted', function() {
delete self.referSubscribers[id];
});
referSubscriber.on('failed', function() {
delete self.referSubscribers[id];
});
return referSubscriber;
};
/**
* In dialog Request Reception
*/
RTCSession.prototype.receiveRequest = function(request) {
debug('receiveRequest()');
var contentType,
self = this;
if(request.method === JsSIP_C.CANCEL) {
/* RFC3261 15 States that a UAS may have accepted an invitation while a CANCEL
* was in progress and that the UAC MAY continue with the session established by
* any 2xx response, or MAY terminate with BYE. JsSIP does continue with the
* established session. So the CANCEL is processed only if the session is not yet
* established.
*/
/*
* Terminate the whole session in case the user didn't accept (or yet send the answer)
* nor reject the request opening the session.
*/
if(this.status === C.STATUS_WAITING_FOR_ANSWER || this.status === C.STATUS_ANSWERED) {
this.status = C.STATUS_CANCELED;
this.request.reply(487);
failed.call(this, 'remote', request, JsSIP_C.causes.CANCELED);
}
} else {
// Requests arriving here are in-dialog requests.
switch(request.method) {
case JsSIP_C.ACK:
if (this.status !== C.STATUS_WAITING_FOR_ACK) {
return;
}
// Update signaling status.
this.status = C.STATUS_CONFIRMED;
clearTimeout(this.timers.ackTimer);
clearTimeout(this.timers.invite2xxTimer);
if (this.late_sdp) {
if (!request.body) {
this.terminate({
cause: JsSIP_C.causes.MISSING_SDP,
status_code: 400
});
break;
}
var e = {originator:'remote', type:'answer', sdp:request.body};
var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp});
this.emit('sdp', e);
this.connection.setRemoteDescription(answer)
.then(function() {
if (!self.is_confirmed) {
confirmed.call(self, 'remote', request);
}
})
.catch(function(error) {
self.terminate({
cause: JsSIP_C.causes.BAD_MEDIA_DESCRIPTION,
status_code: 488
});
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
else {
if (!this.is_confirmed) {
confirmed.call(this, 'remote', request);
}
}
break;
case JsSIP_C.BYE:
if(this.status === C.STATUS_CONFIRMED) {
request.reply(200);
ended.call(this, 'remote', request, JsSIP_C.causes.BYE);
}
else if (this.status === C.STATUS_INVITE_RECEIVED) {
request.reply(200);
this.request.reply(487, 'BYE Received');
ended.call(this, 'remote', request, JsSIP_C.causes.BYE);
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.INVITE:
if(this.status === C.STATUS_CONFIRMED) {
if (request.hasHeader('replaces')) {
receiveReplaces.call(this, request);
} else {
receiveReinvite.call(this, request);
}
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.INFO:
if(this.status === C.STATUS_CONFIRMED || this.status === C.STATUS_WAITING_FOR_ACK || this.status === C.STATUS_INVITE_RECEIVED) {
contentType = request.getHeader('content-type');
if (contentType && (contentType.match(/^application\/dtmf-relay/i))) {
new RTCSession_DTMF(this).init_incoming(request);
}
else {
request.reply(415);
}
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.UPDATE:
if(this.status === C.STATUS_CONFIRMED) {
receiveUpdate.call(this, request);
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.REFER:
if(this.status === C.STATUS_CONFIRMED) {
receiveRefer.call(this, request);
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.NOTIFY:
if(this.status === C.STATUS_CONFIRMED) {
receiveNotify.call(this, request);
}
else {
request.reply(403, 'Wrong Status');
}
break;
default:
request.reply(501);
}
}
};
/**
* Session Callbacks
*/
RTCSession.prototype.onTransportError = function() {
debugerror('onTransportError()');
if(this.status !== C.STATUS_TERMINATED) {
this.terminate({
status_code: 500,
reason_phrase: JsSIP_C.causes.CONNECTION_ERROR,
cause: JsSIP_C.causes.CONNECTION_ERROR
});
}
};
RTCSession.prototype.onRequestTimeout = function() {
debug('onRequestTimeout');
if(this.status !== C.STATUS_TERMINATED) {
this.terminate({
status_code: 408,
reason_phrase: JsSIP_C.causes.REQUEST_TIMEOUT,
cause: JsSIP_C.causes.REQUEST_TIMEOUT
});
}
};
RTCSession.prototype.onDialogError = function() {
debugerror('onDialogError()');
if(this.status !== C.STATUS_TERMINATED) {
this.terminate({
status_code: 500,
reason_phrase: JsSIP_C.causes.DIALOG_ERROR,
cause: JsSIP_C.causes.DIALOG_ERROR
});
}
};
// Called from DTMF handler.
RTCSession.prototype.newDTMF = function(data) {
debug('newDTMF()');
this.emit('newDTMF', data);
};
RTCSession.prototype.resetLocalMedia = function() {
debug('resetLocalMedia()');
// Reset all but remoteHold.
this.localHold = false;
this.audioMuted = false;
this.videoMuted = false;
setLocalMediaStatus.call(this);
};
/**
* Private API.
*/
/**
* RFC3261 13.3.1.4
* Response retransmissions cannot be accomplished by transaction layer
* since it is destroyed when receiving the first 2xx answer
*/
function setInvite2xxTimer(request, body) {
var
self = this,
timeout = Timers.T1;
this.timers.invite2xxTimer = setTimeout(function invite2xxRetransmission() {
if (self.status !== C.STATUS_WAITING_FOR_ACK) {
return;
}
request.reply(200, null, ['Contact: '+ self.contact], body);
if (timeout < Timers.T2) {
timeout = timeout * 2;
if (timeout > Timers.T2) {
timeout = Timers.T2;
}
}
self.timers.invite2xxTimer = setTimeout(
invite2xxRetransmission, timeout
);
}, timeout);
}
/**
* RFC3261 14.2
* If a UAS generates a 2xx response and never receives an ACK,
* it SHOULD generate a BYE to terminate the dialog.
*/
function setACKTimer() {
var self = this;
this.timers.ackTimer = setTimeout(function() {
if(self.status === C.STATUS_WAITING_FOR_ACK) {
debug('no ACK received, terminating the session');
clearTimeout(self.timers.invite2xxTimer);
sendRequest.call(self, JsSIP_C.BYE);
ended.call(self, 'remote', null, JsSIP_C.causes.NO_ACK);
}
}, Timers.TIMER_H);
}
function createRTCConnection(pcConfig, rtcConstraints) {
var self = this;
this.connection = new RTCPeerConnection(pcConfig, rtcConstraints);
this.connection.addEventListener('iceconnectionstatechange', function() {
var state = self.connection.iceConnectionState;
// TODO: Do more with different states.
if (state === 'failed') {
self.terminate({
cause: JsSIP_C.causes.RTP_TIMEOUT,
status_code: 200,
reason_phrase: JsSIP_C.causes.RTP_TIMEOUT
});
}
});
}
function createLocalDescription(type, onSuccess, onFailure, constraints) {
debug('createLocalDescription()');
var self = this;
var connection = this.connection;
this.rtcReady = false;
if (type === 'offer') {
connection.createOffer(constraints)
.then(createSucceeded)
.catch(function(error) {
self.rtcReady = true;
if (onFailure) { onFailure(error); }
self.emit('peerconnection:createofferfailed', error);
});
}
else if (type === 'answer') {
connection.createAnswer(constraints)
.then(createSucceeded)
.catch(function(error) {
self.rtcReady = true;
if (onFailure) { onFailure(error); }
self.emit('peerconnection:createanswerfailed', error);
});
}
else {
throw new Error('createLocalDescription() | type must be "offer" or "answer", but "' +type+ '" was given');
}
// createAnswer or createOffer succeeded
function createSucceeded(desc) {
var listener;
connection.addEventListener('icecandidate', listener = function(event) {
var candidate = event.candidate;
if (! candidate) {
connection.removeEventListener('icecandidate', listener);
self.rtcReady = true;
if (onSuccess) {
var e = {originator:'local', type:type, sdp:connection.localDescription.sdp};
self.emit('sdp', e);
onSuccess(e.sdp);
}
onSuccess = null;
}
});
connection.setLocalDescription(desc)
.then(function() {
if (connection.iceGatheringState === 'complete') {
self.rtcReady = true;
if (onSuccess) {
var e = {originator:'local', type:type, sdp:connection.localDescription.sdp};
self.emit('sdp', e);
onSuccess(e.sdp);
onSuccess = null;
}
}
})
.catch(function(error) {
self.rtcReady = true;
if (onFailure) { onFailure(error); }
self.emit('peerconnection:setlocaldescriptionfailed', error);
});
}
}
/**
* Dialog Management
*/
function createDialog(message, type, early) {
var dialog, early_dialog,
local_tag = (type === 'UAS') ? message.to_tag : message.from_tag,
remote_tag = (type === 'UAS') ? message.from_tag : message.to_tag,
id = message.call_id + local_tag + remote_tag;
early_dialog = this.earlyDialogs[id];
// Early Dialog
if (early) {
if (early_dialog) {
return true;
} else {
early_dialog = new Dialog(this, message, type, Dialog.C.STATUS_EARLY);
// Dialog has been successfully created.
if(early_dialog.error) {
debug(early_dialog.error);
failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR);
return false;
} else {
this.earlyDialogs[id] = early_dialog;
return true;
}
}
}
// Confirmed Dialog
else {
this.from_tag = message.from_tag;
this.to_tag = message.to_tag;
// In case the dialog is in _early_ state, update it
if (early_dialog) {
early_dialog.update(message, type);
this.dialog = early_dialog;
delete this.earlyDialogs[id];
return true;
}
// Otherwise, create a _confirmed_ dialog
dialog = new Dialog(this, message, type);
if(dialog.error) {
debug(dialog.error);
failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR);
return false;
} else {
this.dialog = dialog;
return true;
}
}
}
/**
* In dialog INVITE Reception
*/
function receiveReinvite(request) {
debug('receiveReinvite()');
var
sdp, idx, direction, m,
self = this,
contentType = request.getHeader('Content-Type'),
hold = false,
rejected = false,
data = {
request: request,
callback: undefined,
reject: reject.bind(this)
};
function reject(options) {
options = options || {};
rejected = true;
var
status_code = options.status_code || 403,
reason_phrase = options.reason_phrase || '',
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [];
if (this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
request.reply(status_code, reason_phrase, extraHeaders);
}
// Emit 'reinvite'.
this.emit('reinvite', data);
if (rejected) {
return;
}
if (request.body) {
this.late_sdp = false;
if (contentType !== 'application/sdp') {
debug('invalid Content-Type');
request.reply(415);
return;
}
sdp = request.parseSDP();
for (idx=0; idx < sdp.media.length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
direction = m.direction || sdp.direction || 'sendrecv';
if (direction === 'sendonly' || direction === 'inactive') {
hold = true;
}
// If at least one of the streams is active don't emit 'hold'.
else {
hold = false;
break;
}
}
var e = {originator:'remote', type:'offer', sdp:request.body};
var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp});
this.emit('sdp', e);
this.connection.setRemoteDescription(offer)
.then(doAnswer)
.catch(function(error) {
request.reply(488);
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
else {
this.late_sdp = true;
doAnswer();
}
function doAnswer() {
createSdp(
// onSuccess
function(sdp) {
var extraHeaders = ['Contact: ' + self.contact];
handleSessionTimersInIncomingRequest.call(self, request, extraHeaders);
if (self.late_sdp) {
sdp = mangleOffer.call(self, sdp);
}
request.reply(200, null, extraHeaders, sdp,
function() {
self.status = C.STATUS_WAITING_FOR_ACK;
setInvite2xxTimer.call(self, request, sdp);
setACKTimer.call(self);
}
);
// If callback is given execute it.
if (typeof data.callback === 'function') {
data.callback();
}
},
// onFailure
function() {
request.reply(500);
}
);
}
function createSdp(onSuccess, onFailure) {
if (! self.late_sdp) {
if (self.remoteHold === true && hold === false) {
self.remoteHold = false;
onunhold.call(self, 'remote');
} else if (self.remoteHold === false && hold === true) {
self.remoteHold = true;
onhold.call(self, 'remote');
}
createLocalDescription.call(self, 'answer', onSuccess, onFailure, self.rtcAnswerConstraints);
} else {
createLocalDescription.call(self, 'offer', onSuccess, onFailure, self.rtcOfferConstraints);
}
}
}
/**
* In dialog UPDATE Reception
*/
function receiveUpdate(request) {
debug('receiveUpdate()');
var
sdp, idx, direction, m,
self = this,
contentType = request.getHeader('Content-Type'),
rejected = false,
hold = false,
data = {
request: request,
callback: undefined,
reject: reject.bind(this)
};
function reject(options) {
options = options || {};
rejected = true;
var
status_code = options.status_code || 403,
reason_phrase = options.reason_phrase || '',
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [];
if (this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
request.reply(status_code, reason_phrase, extraHeaders);
}
// Emit 'update'.
this.emit('update', data);
if (rejected) {
return;
}
if (! request.body) {
var extraHeaders = [];
handleSessionTimersInIncomingRequest.call(this, request, extraHeaders);
request.reply(200, null, extraHeaders);
return;
}
if (contentType !== 'application/sdp') {
debug('invalid Content-Type');
request.reply(415);
return;
}
sdp = request.parseSDP();
for (idx=0; idx < sdp.media.length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
direction = m.direction || sdp.direction || 'sendrecv';
if (direction === 'sendonly' || direction === 'inactive') {
hold = true;
}
// If at least one of the streams is active don't emit 'hold'.
else {
hold = false;
break;
}
}
var e = {originator:'remote', type:'offer', sdp:request.body};
var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp});
this.emit('sdp', e);
this.connection.setRemoteDescription(offer)
.then(function() {
if (self.remoteHold === true && hold === false) {
self.remoteHold = false;
onunhold.call(self, 'remote');
} else if (self.remoteHold === false && hold === true) {
self.remoteHold = true;
onhold.call(self, 'remote');
}
createLocalDescription.call(self, 'answer',
// success
function(sdp) {
var extraHeaders = ['Contact: ' + self.contact];
handleSessionTimersInIncomingRequest.call(self, request, extraHeaders);
request.reply(200, null, extraHeaders, sdp);
// If callback is given execute it.
if (typeof data.callback === 'function') {
data.callback();
}
},
// failure
function() {
request.reply(500);
}
);
})
.catch(function(error) {
request.reply(488);
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
/**
* In dialog Refer Reception
*/
function receiveRefer(request) {
debug('receiveRefer()');
var notifier,
self = this;
function accept(initCallback, options) {
var session, replaces;
options = options || {};
initCallback = (typeof initCallback === 'function')? initCallback : null;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
session = new RTCSession(this.ua);
session.on('progress', function(e) {
notifier.notify(e.response.status_code, e.response.reason_phrase);
});
session.on('accepted', function(e) {
notifier.notify(e.response.status_code, e.response.reason_phrase);
});
session.on('failed', function(e) {
if (e.message) {
notifier.notify(e.message.status_code, e.message.reason_phrase);
} else {
notifier.notify(487, e.cause);
}
});
// Consider the Replaces header present in the Refer-To URI
if (request.refer_to.uri.hasHeader('replaces')) {
replaces = decodeURIComponent(request.refer_to.uri.getHeader('replaces'));
options.extraHeaders = options.extraHeaders || [];
options.extraHeaders.push('Replaces: '+ replaces);
}
session.connect(request.refer_to.uri.toAor(), options, initCallback);
}
function reject() {
notifier.notify(603);
}
if (typeof request.refer_to === undefined) {
debug('no Refer-To header field present in REFER');
request.reply(400);
return;
}
if (request.refer_to.uri.scheme !== JsSIP_C.SIP) {
debug('Refer-To header field points to a non-SIP URI scheme');
request.reply(416);
return;
}
// reply before the transaction timer expires
request.reply(202);
notifier = new RTCSession_ReferNotifier(this, request.cseq);
// Emit 'refer'.
this.emit('refer', {
request: request,
accept: function(initCallback, options) { accept.call(self, initCallback, options); },
reject: function() { reject.call(self); }
});
}
/**
* In dialog Notify Reception
*/
function receiveNotify(request) {
debug('receiveNotify()');
if (typeof request.event === undefined) {
request.reply(400);
}
switch (request.event.event) {
case 'refer': {
var id = request.event.params.id;
var referSubscriber = this.referSubscribers[id];
if (!referSubscriber) {
request.reply(481, 'Subscription does not exist');
return;
}
referSubscriber.receiveNotify(request);
request.reply(200);
break;
}
default: {
request.reply(489);
}
}
}
/**
* INVITE with Replaces Reception
*/
function receiveReplaces(request) {
debug('receiveReplaces()');
var self = this;
function accept(initCallback) {
var session;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
session = new RTCSession(this.ua);
// terminate the current session when the new one is confirmed
session.on('confirmed', function() {
self.terminate();
});
session.init_incoming(request, initCallback);
}
function reject() {
debug('Replaced INVITE rejected by the user');
request.reply(486);
}
// Emit 'replace'.
this.emit('replaces', {
request: request,
accept: function(initCallback) { accept.call(self, initCallback); },
reject: function() { reject.call(self); }
});
}
/**
* Initial Request Sender
*/
function sendInitialRequest(mediaConstraints, rtcOfferConstraints, mediaStream) {
var self = this;
var request_sender = new RequestSender(self, this.ua);
this.receiveResponse = function(response) {
receiveInviteResponse.call(self, response);
};
// If a local MediaStream is given use it.
if (mediaStream) {
// Wait a bit so the app can set events such as 'peerconnection' and 'connecting'.
setTimeout(function() {
userMediaSucceeded(mediaStream);
});
// If at least audio or video is requested prompt getUserMedia.
} else if (mediaConstraints.audio || mediaConstraints.video) {
this.localMediaStreamLocallyGenerated = true;
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then(userMediaSucceeded)
.catch(function(error)
{
userMediaFailed(error);
self.emit('getusermediafailed', error);
});
// Otherwise don't prompt getUserMedia.
} else {
userMediaSucceeded(null);
}
// User media succeeded
function userMediaSucceeded(stream) {
if (self.status === C.STATUS_TERMINATED) { return; }
self.localMediaStream = stream;
if (stream) {
self.connection.addStream(stream);
}
// Notify the app with the RTCPeerConnection so it can do stuff on it
// before generating the offer.
self.emit('peerconnection', {
peerconnection: self.connection
});
connecting.call(self, self.request);
createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, rtcOfferConstraints);
}
// User media failed
function userMediaFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS);
}
function rtcSucceeded(desc) {
if (self.isCanceled || self.status === C.STATUS_TERMINATED) { return; }
self.request.body = desc;
self.status = C.STATUS_INVITE_SENT;
// Emit 'sending' so the app can mangle the body before the request
// is sent.
self.emit('sending', {
request: self.request
});
request_sender.send();
}
function rtcFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR);
}
}
/**
* Reception of Response for Initial INVITE
*/
function receiveInviteResponse(response) {
debug('receiveInviteResponse()');
var cause, dialog, e,
self = this;
// Handle 2XX retransmissions and responses from forked requests
if (this.dialog && (response.status_code >=200 && response.status_code <=299)) {
/*
* If it is a retransmission from the endpoint that established
* the dialog, send an ACK
*/
if (this.dialog.id.call_id === response.call_id &&
this.dialog.id.local_tag === response.from_tag &&
this.dialog.id.remote_tag === response.to_tag) {
sendRequest.call(this, JsSIP_C.ACK);
return;
}
// If not, send an ACK and terminate
else {
dialog = new Dialog(this, response, 'UAC');
if (dialog.error !== undefined) {
debug(dialog.error);
return;
}
dialog.sendRequest({
owner: {status: C.STATUS_TERMINATED},
onRequestTimeout: function(){},
onTransportError: function(){},
onDialogError: function(){},
receiveResponse: function(){}
}, JsSIP_C.ACK);
dialog.sendRequest({
owner: {status: C.STATUS_TERMINATED},
onRequestTimeout: function(){},
onTransportError: function(){},
onDialogError: function(){},
receiveResponse: function(){}
}, JsSIP_C.BYE);
return;
}
}
// Proceed to cancellation if the user requested.
if(this.isCanceled) {
// Remove the flag. We are done.
this.isCanceled = false;
if(response.status_code >= 100 && response.status_code < 200) {
this.request.cancel(this.cancelReason);
} else if(response.status_code >= 200 && response.status_code < 299) {
acceptAndTerminate.call(this, response);
}
return;
}
if(this.status !== C.STATUS_INVITE_SENT && this.status !== C.STATUS_1XX_RECEIVED) {
return;
}
switch(true) {
case /^100$/.test(response.status_code):
this.status = C.STATUS_1XX_RECEIVED;
break;
case /^1[0-9]{2}$/.test(response.status_code):
// Do nothing with 1xx responses without To tag.
if (!response.to_tag) {
debug('1xx response received without to tag');
break;
}
// Create Early Dialog if 1XX comes with contact
if (response.hasHeader('contact')) {
// An error on dialog creation will fire 'failed' event
if(! createDialog.call(this, response, 'UAC', true)) {
break;
}
}
this.status = C.STATUS_1XX_RECEIVED;
progress.call(this, 'remote', response);
if (!response.body) {
break;
}
e = {originator:'remote', type:'pranswer', sdp:response.body};
this.emit('sdp', e);
var pranswer = new RTCSessionDescription({type:'pranswer', sdp:e.sdp});
this.connection.setRemoteDescription(pranswer)
.catch(function(error) {
self.emit('peerconnection:setremotedescriptionfailed', error);
});
break;
case /^2[0-9]{2}$/.test(response.status_code):
this.status = C.STATUS_CONFIRMED;
if(!response.body) {
acceptAndTerminate.call(this, response, 400, JsSIP_C.causes.MISSING_SDP);
failed.call(this, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION);
break;
}
// An error on dialog creation will fire 'failed' event
if (! createDialog.call(this, response, 'UAC')) {
break;
}
e = {originator:'remote', type:'answer', sdp:response.body};
this.emit('sdp', e);
var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp});
this.connection.setRemoteDescription(answer)
.then(function() {
// Handle Session Timers.
handleSessionTimersInIncomingResponse.call(self, response);
accepted.call(self, 'remote', response);
sendRequest.call(self, JsSIP_C.ACK);
confirmed.call(self, 'local', null);
})
.catch(function(error) {
acceptAndTerminate.call(self, response, 488, 'Not Acceptable Here');
failed.call(self, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION);
self.emit('peerconnection:setremotedescriptionfailed', error);
});
break;
default:
cause = Utils.sipErrorCause(response.status_code);
failed.call(this, 'remote', response, cause);
}
}
/**
* Send Re-INVITE
*/
function sendReinvite(options) {
debug('sendReinvite()');
options = options || {};
var
self = this,
extraHeaders = options.extraHeaders || [],
eventHandlers = options.eventHandlers || {},
rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null,
succeeded = false;
extraHeaders.push('Contact: ' + this.contact);
extraHeaders.push('Content-Type: application/sdp');
// Session Timers.
if (this.sessionTimers.running) {
extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas'));
}
createLocalDescription.call(this, 'offer',
// success
function(sdp) {
sdp = mangleOffer.call(self, sdp);
var request = new RTCSession_Request(self, JsSIP_C.INVITE);
request.send({
extraHeaders: extraHeaders,
body: sdp,
eventHandlers: {
onSuccessResponse: function(response) {
onSucceeded(response);
succeeded = true;
},
onErrorResponse: function(response) {
onFailed(response);
},
onTransportError: function() {
self.onTransportError(); // Do nothing because session ends.
},
onRequestTimeout: function() {
self.onRequestTimeout(); // Do nothing because session ends.
},
onDialogError: function() {
self.onDialogError(); // Do nothing because session ends.
}
}
});
},
// failure
function() {
onFailed();
},
// RTC constraints.
rtcOfferConstraints
);
function onSucceeded(response) {
if (self.status === C.STATUS_TERMINATED) {
return;
}
sendRequest.call(self, JsSIP_C.ACK);
// If it is a 2XX retransmission exit now.
if (succeeded) { return; }
// Handle Session Timers.
handleSessionTimersInIncomingResponse.call(self, response);
// Must have SDP answer.
if(! response.body) {
onFailed();
return;
} else if (response.getHeader('Content-Type') !== 'application/sdp') {
onFailed();
return;
}
var e = {originator:'remote', type:'answer', sdp:response.body};
var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp});
self.emit('sdp', e);
self.connection.setRemoteDescription(answer)
.then(function() {
if (eventHandlers.succeeded) {
eventHandlers.succeeded(response);
}
})
.catch(function(error) {
onFailed();
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
function onFailed(response) {
if (eventHandlers.failed) {
eventHandlers.failed(response);
}
}
}
/**
* Send UPDATE
*/
function sendUpdate(options) {
debug('sendUpdate()');
options = options || {};
var
self = this,
extraHeaders = options.extraHeaders || [],
eventHandlers = options.eventHandlers || {},
rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null,
sdpOffer = options.sdpOffer || false,
succeeded = false;
extraHeaders.push('Contact: ' + this.contact);
// Session Timers.
if (this.sessionTimers.running) {
extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas'));
}
if (sdpOffer) {
extraHeaders.push('Content-Type: application/sdp');
createLocalDescription.call(this, 'offer',
// success
function(sdp) {
sdp = mangleOffer.call(self, sdp);
var request = new RTCSession_Request(self, JsSIP_C.UPDATE);
request.send({
extraHeaders: extraHeaders,
body: sdp,
eventHandlers: {
onSuccessResponse: function(response) {
onSucceeded(response);
succeeded = true;
},
onErrorResponse: function(response) {
onFailed(response);
},
onTransportError: function() {
self.onTransportError(); // Do nothing because session ends.
},
onRequestTimeout: function() {
self.onRequestTimeout(); // Do nothing because session ends.
},
onDialogError: function() {
self.onDialogError(); // Do nothing because session ends.
}
}
});
},
// failure
function() {
onFailed();
},
// RTC constraints.
rtcOfferConstraints
);
}
// No SDP.
else {
var request = new RTCSession_Request(self, JsSIP_C.UPDATE);
request.send({
extraHeaders: extraHeaders,
eventHandlers: {
onSuccessResponse: function(response) {
onSucceeded(response);
},
onErrorResponse: function(response) {
onFailed(response);
},
onTransportError: function() {
self.onTransportError(); // Do nothing because session ends.
},
onRequestTimeout: function() {
self.onRequestTimeout(); // Do nothing because session ends.
},
onDialogError: function() {
self.onDialogError(); // Do nothing because session ends.
}
}
});
}
function onSucceeded(response) {
if (self.status === C.STATUS_TERMINATED) {
return;
}
// If it is a 2XX retransmission exit now.
if (succeeded) { return; }
// Handle Session Timers.
handleSessionTimersInIncomingResponse.call(self, response);
// Must have SDP answer.
if (sdpOffer) {
if(! response.body) {
onFailed();
return;
} else if (response.getHeader('Content-Type') !== 'application/sdp') {
onFailed();
return;
}
var e = {originator:'remote', type:'answer', sdp:response.body};
var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp});
self.emit('sdp', e);
self.connection.setRemoteDescription(answer)
.then(function() {
if (eventHandlers.succeeded) {
eventHandlers.succeeded(response);
}
})
.catch(function(error) {
onFailed();
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
// No SDP answer.
else {
if (eventHandlers.succeeded) {
eventHandlers.succeeded(response);
}
}
}
function onFailed(response) {
if (eventHandlers.failed) { eventHandlers.failed(response); }
}
}
function acceptAndTerminate(response, status_code, reason_phrase) {
debug('acceptAndTerminate()');
var extraHeaders = [];
if (status_code) {
reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || '';
extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"');
}
// An error on dialog creation will fire 'failed' event
if (this.dialog || createDialog.call(this, response, 'UAC')) {
sendRequest.call(this, JsSIP_C.ACK);
sendRequest.call(this, JsSIP_C.BYE, {
extraHeaders: extraHeaders
});
}
// Update session status.
this.status = C.STATUS_TERMINATED;
}
/**
* Send a generic in-dialog Request
*/
function sendRequest(method, options) {
debug('sendRequest()');
var request = new RTCSession_Request(this, method);
request.send(options);
}
/**
* Correctly set the SDP direction attributes if the call is on local hold
*/
function mangleOffer(sdp) {
var idx, length, m;
if (! this.localHold && ! this.remoteHold) {
return sdp;
}
sdp = sdp_transform.parse(sdp);
// Local hold.
if (this.localHold && ! this.remoteHold) {
debug('mangleOffer() | me on hold, mangling offer');
length = sdp.media.length;
for (idx=0; idx<length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
if (!m.direction) {
m.direction = 'sendonly';
} else if (m.direction === 'sendrecv') {
m.direction = 'sendonly';
} else if (m.direction === 'recvonly') {
m.direction = 'inactive';
}
}
}
// Local and remote hold.
else if (this.localHold && this.remoteHold) {
debug('mangleOffer() | both on hold, mangling offer');
length = sdp.media.length;
for (idx=0; idx<length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
m.direction = 'inactive';
}
}
// Remote hold.
else if (this.remoteHold) {
debug('mangleOffer() | remote on hold, mangling offer');
length = sdp.media.length;
for (idx=0; idx<length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
if (!m.direction) {
m.direction = 'recvonly';
} else if (m.direction === 'sendrecv') {
m.direction = 'recvonly';
} else if (m.direction === 'recvonly') {
m.direction = 'inactive';
}
}
}
return sdp_transform.write(sdp);
}
function setLocalMediaStatus() {
var enableAudio = true,
enableVideo = true;
if (this.localHold || this.remoteHold) {
enableAudio = false;
enableVideo = false;
}
if (this.audioMuted) {
enableAudio = false;
}
if (this.videoMuted) {
enableVideo = false;
}
toogleMuteAudio.call(this, !enableAudio);
toogleMuteVideo.call(this, !enableVideo);
}
/**
* Handle SessionTimers for an incoming INVITE or UPDATE.
* @param {IncomingRequest} request
* @param {Array} responseExtraHeaders Extra headers for the 200 response.
*/
function handleSessionTimersInIncomingRequest(request, responseExtraHeaders) {
if (! this.sessionTimers.enabled) { return; }
var session_expires_refresher;
if (request.session_expires && request.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.currentExpires = request.session_expires;
session_expires_refresher = request.session_expires_refresher || 'uas';
}
else {
this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires;
session_expires_refresher = 'uas';
}
responseExtraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + session_expires_refresher);
this.sessionTimers.refresher = (session_expires_refresher === 'uas');
runSessionTimer.call(this);
}
/**
* Handle SessionTimers for an incoming response to INVITE or UPDATE.
* @param {IncomingResponse} response
*/
function handleSessionTimersInIncomingResponse(response) {
if (! this.sessionTimers.enabled) { return; }
var session_expires_refresher;
if (response.session_expires && response.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.currentExpires = response.session_expires;
session_expires_refresher = response.session_expires_refresher || 'uac';
}
else {
this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires;
session_expires_refresher = 'uac';
}
this.sessionTimers.refresher = (session_expires_refresher === 'uac');
runSessionTimer.call(this);
}
function runSessionTimer() {
var self = this;
var expires = this.sessionTimers.currentExpires;
this.sessionTimers.running = true;
clearTimeout(this.sessionTimers.timer);
// I'm the refresher.
if (this.sessionTimers.refresher) {
this.sessionTimers.timer = setTimeout(function() {
if (self.status === C.STATUS_TERMINATED) { return; }
debug('runSessionTimer() | sending session refresh request');
sendUpdate.call(self, {
eventHandlers: {
succeeded: function(response) {
handleSessionTimersInIncomingResponse.call(self, response);
}
}
});
}, expires * 500); // Half the given interval (as the RFC states).
}
// I'm not the refresher.
else {
this.sessionTimers.timer = setTimeout(function() {
if (self.status === C.STATUS_TERMINATED) { return; }
debugerror('runSessionTimer() | timer expired, terminating the session');
self.terminate({
cause: JsSIP_C.causes.REQUEST_TIMEOUT,
status_code: 408,
reason_phrase: 'Session Timer Expired'
});
}, expires * 1100);
}
}
function toogleMuteAudio(mute) {
var streamIdx, trackIdx, streamsLength, tracksLength, tracks,
localStreams = this.connection.getLocalStreams();
streamsLength = localStreams.length;
for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) {
tracks = localStreams[streamIdx].getAudioTracks();
tracksLength = tracks.length;
for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) {
tracks[trackIdx].enabled = !mute;
}
}
}
function toogleMuteVideo(mute) {
var streamIdx, trackIdx, streamsLength, tracksLength, tracks,
localStreams = this.connection.getLocalStreams();
streamsLength = localStreams.length;
for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) {
tracks = localStreams[streamIdx].getVideoTracks();
tracksLength = tracks.length;
for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) {
tracks[trackIdx].enabled = !mute;
}
}
}
function newRTCSession(originator, request) {
debug('newRTCSession');
this.ua.newRTCSession({
originator: originator,
session: this,
request: request
});
}
function connecting(request) {
debug('session connecting');
this.emit('connecting', {
request: request
});
}
function progress(originator, response) {
debug('session progress');
this.emit('progress', {
originator: originator,
response: response || null
});
}
function accepted(originator, message) {
debug('session accepted');
this.start_time = new Date();
this.emit('accepted', {
originator: originator,
response: message || null
});
}
function confirmed(originator, ack) {
debug('session confirmed');
this.is_confirmed = true;
this.emit('confirmed', {
originator: originator,
ack: ack || null
});
}
function ended(originator, message, cause) {
debug('session ended');
this.end_time = new Date();
this.close();
this.emit('ended', {
originator: originator,
message: message || null,
cause: cause
});
}
function failed(originator, message, cause) {
debug('session failed');
this.close();
this.emit('failed', {
originator: originator,
message: message || null,
cause: cause
});
}
function onhold(originator) {
debug('session onhold');
setLocalMediaStatus.call(this);
this.emit('hold', {
originator: originator
});
}
function onunhold(originator) {
debug('session onunhold');
setLocalMediaStatus.call(this);
this.emit('unhold', {
originator: originator
});
}
function onmute(options) {
debug('session onmute');
setLocalMediaStatus.call(this);
this.emit('muted', {
audio: options.audio,
video: options.video
});
}
function onunmute(options) {
debug('session onunmute');
setLocalMediaStatus.call(this);
this.emit('unmuted', {
audio: options.audio,
video: options.video
});
}
},{"./Constants":1,"./Dialog":2,"./Exceptions":5,"./RTCSession/DTMF":12,"./RTCSession/ReferNotifier":13,"./RTCSession/ReferSubscriber":14,"./RTCSession/Request":15,"./RequestSender":17,"./SIPMessage":18,"./Timers":20,"./Transactions":21,"./Utils":25,"debug":34,"events":28,"sdp-transform":37,"util":32}],12:[function(require,module,exports){
module.exports = DTMF;
var C = {
MIN_DURATION: 70,
MAX_DURATION: 6000,
DEFAULT_DURATION: 100,
MIN_INTER_TONE_GAP: 50,
DEFAULT_INTER_TONE_GAP: 500
};
/**
* Expose C object.
*/
DTMF.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:RTCSession:DTMF');
var debugerror = require('debug')('JsSIP:ERROR:RTCSession:DTMF');
debugerror.log = console.warn.bind(console);
var JsSIP_C = require('../Constants');
var Exceptions = require('../Exceptions');
var RTCSession = require('../RTCSession');
function DTMF(session) {
this.owner = session;
this.direction = null;
this.tone = null;
this.duration = null;
events.EventEmitter.call(this);
}
util.inherits(DTMF, events.EventEmitter);
DTMF.prototype.send = function(tone, options) {
var extraHeaders, body;
if (tone === undefined) {
throw new TypeError('Not enough arguments');
}
this.direction = 'outgoing';
// Check RTCSession Status
if (this.owner.status !== RTCSession.C.STATUS_CONFIRMED &&
this.owner.status !== RTCSession.C.STATUS_WAITING_FOR_ACK) {
throw new Exceptions.InvalidStateError(this.owner.status);
}
// Get DTMF options
options = options || {};
extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : [];
this.eventHandlers = options.eventHandlers || {};
// Check tone type
if (typeof tone === 'string' ) {
tone = tone.toUpperCase();
} else if (typeof tone === 'number') {
tone = tone.toString();
} else {
throw new TypeError('Invalid tone: '+ tone);
}
// Check tone value
if (!tone.match(/^[0-9A-DR#*]$/)) {
throw new TypeError('Invalid tone: '+ tone);
} else {
this.tone = tone;
}
// Duration is checked/corrected in RTCSession
this.duration = options.duration;
extraHeaders.push('Content-Type: application/dtmf-relay');
body = 'Signal=' + this.tone + '\r\n';
body += 'Duration=' + this.duration;
this.owner.newDTMF({
originator: 'local',
dtmf: this,
request: this.request
});
this.owner.dialog.sendRequest(this, JsSIP_C.INFO, {
extraHeaders: extraHeaders,
body: body
});
};
DTMF.prototype.receiveResponse = function(response) {
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
this.emit('succeeded', {
originator: 'remote',
response: response
});
break;
default:
if (this.eventHandlers.onFailed) {
this.eventHandlers.onFailed();
}
this.emit('failed', {
originator: 'remote',
response: response
});
break;
}
};
DTMF.prototype.onRequestTimeout = function() {
debugerror('onRequestTimeout');
this.owner.onRequestTimeout();
};
DTMF.prototype.onTransportError = function() {
debugerror('onTransportError');
this.owner.onTransportError();
};
DTMF.prototype.onDialogError = function() {
debugerror('onDialogError');
this.owner.onDialogError();
};
DTMF.prototype.init_incoming = function(request) {
var body,
reg_tone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,
reg_duration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;
this.direction = 'incoming';
this.request = request;
request.reply(200);
if (request.body) {
body = request.body.split('\n');
if (body.length >= 1) {
if (reg_tone.test(body[0])) {
this.tone = body[0].replace(reg_tone,'$2');
}
}
if (body.length >=2) {
if (reg_duration.test(body[1])) {
this.duration = parseInt(body[1].replace(reg_duration,'$2'), 10);
}
}
}
if (!this.duration) {
this.duration = C.DEFAULT_DURATION;
}
if (!this.tone) {
debug('invalid INFO DTMF received, discarded');
} else {
this.owner.newDTMF({
originator: 'remote',
dtmf: this,
request: request
});
}
};
},{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":34,"events":28,"util":32}],13:[function(require,module,exports){
module.exports = ReferNotifier;
var C = {
event_type: 'refer',
body_type: 'message/sipfrag;version=2.0',
expires: 300
};
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:RTCSession:ReferNotifier');
var JsSIP_C = require('../Constants');
var RTCSession_Request = require('./Request');
function ReferNotifier(session, id, expires) {
this.session = session;
this.id = id;
this.expires = expires || C.expires;
this.active = true;
// The creation of a Notifier results in an immediate NOTIFY
this.notify(100);
}
ReferNotifier.prototype.notify = function(code, reason) {
debug('notify()');
var state,
self = this;
if (this.active === false) {
return;
}
reason = reason || JsSIP_C.REASON_PHRASE[code] || '';
if (code >= 200) {
state = 'terminated;reason=noresource';
} else {
state = 'active;expires='+ this.expires;
}
// put this in a try/catch block
var request = new RTCSession_Request(this.session, JsSIP_C.NOTIFY);
request.send({
extraHeaders: [
'Event: '+ C.event_type +';id='+ self.id,
'Subscription-State: '+ state,
'Content-Type: '+ C.body_type
],
body: 'SIP/2.0 ' + code + ' ' + reason,
eventHandlers: {
// if a negative response is received, subscription is canceled
onErrorResponse: function() { self.active = false; }
}
});
};
},{"../Constants":1,"./Request":15,"debug":34}],14:[function(require,module,exports){
module.exports = ReferSubscriber;
var C = {
expires: 120
};
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:RTCSession:ReferSubscriber');
var JsSIP_C = require('../Constants');
var Grammar = require('../Grammar');
var RTCSession_Request = require('./Request');
function ReferSubscriber(session) {
this.session = session;
this.timer = null;
// Instance of REFER OutgoingRequest
this.outgoingRequest = null;
events.EventEmitter.call(this);
}
util.inherits(ReferSubscriber, events.EventEmitter);
ReferSubscriber.prototype.sendRefer = function(target, options) {
debug('sendRefer()');
var extraHeaders, eventHandlers, referTo,
replaces = null,
self = this;
// Get REFER options
options = options || {};
extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : [];
eventHandlers = options.eventHandlers || {};
// Set event handlers
for (var event in eventHandlers) {
this.on(event, eventHandlers[event]);
}
// Replaces URI header field
if (options.replaces) {
replaces = options.replaces.request.call_id;
replaces += ';to-tag='+ options.replaces.to_tag;
replaces += ';from-tag='+ options.replaces.from_tag;
replaces = encodeURIComponent(replaces);
}
// Refer-To header field
referTo = 'Refer-To: <'+ target + (replaces?'?Replaces='+ replaces:'') +'>';
extraHeaders.push(referTo);
var request = new RTCSession_Request(this.session, JsSIP_C.REFER);
this.timer = setTimeout(function() {
removeSubscriber.call(self);
}, C.expires * 1000);
request.send({
extraHeaders: extraHeaders,
eventHandlers: {
onSuccessResponse: function(response) {
self.emit('requestSucceeded', {
response: response
});
},
onErrorResponse: function(response) {
self.emit('requestFailed', {
response: response,
cause: JsSIP_C.causes.REJECTED
});
},
onTransportError: function() {
removeSubscriber.call(self);
self.emit('requestFailed', {
response: null,
cause: JsSIP_C.causes.CONNECTION_ERROR
});
},
onRequestTimeout: function() {
removeSubscriber.call(self);
self.emit('requestFailed', {
response: null,
cause: JsSIP_C.causes.REQUEST_TIMEOUT
});
},
onDialogError: function() {
removeSubscriber.call(self);
self.emit('requestFailed', {
response: null,
cause: JsSIP_C.causes.DIALOG_ERROR
});
}
}
});
this.outgoingRequest = request.outgoingRequest;
};
ReferSubscriber.prototype.receiveNotify = function(request) {
debug('receiveNotify()');
var status_line;
if (!request.body) {
return;
}
status_line = Grammar.parse(request.body, 'Status_Line');
if(status_line === -1) {
debug('receiveNotify() | error parsing NOTIFY body: "' + request.body + '"');
return;
}
switch(true) {
case /^100$/.test(status_line.status_code):
this.emit('trying', {
request: request,
status_line: status_line
});
break;
case /^1[0-9]{2}$/.test(status_line.status_code):
this.emit('progress', {
request: request,
status_line: status_line
});
break;
case /^2[0-9]{2}$/.test(status_line.status_code):
removeSubscriber.call(this);
this.emit('accepted', {
request: request,
status_line: status_line
});
break;
default:
removeSubscriber.call(this);
this.emit('failed', {
request: request,
status_line: status_line
});
break;
}
};
// remove refer subscriber from the session
function removeSubscriber() {
console.log('removeSubscriber()');
clearTimeout(this.timer);
this.session.referSubscriber = null;
}
},{"../Constants":1,"../Grammar":6,"./Request":15,"debug":34,"events":28,"util":32}],15:[function(require,module,exports){
module.exports = Request;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:RTCSession:Request');
var debugerror = require('debug')('JsSIP:ERROR:RTCSession:Request');
debugerror.log = console.warn.bind(console);
var JsSIP_C = require('../Constants');
var Exceptions = require('../Exceptions');
var RTCSession = require('../RTCSession');
function Request(session, method) {
debug('new | %s', method);
this.session = session;
this.method = method;
// Instance of OutgoingRequest
this.outgoingRequest = null;
// Check RTCSession Status
if (this.session.status !== RTCSession.C.STATUS_1XX_RECEIVED &&
this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ANSWER &&
this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ACK &&
this.session.status !== RTCSession.C.STATUS_CONFIRMED &&
this.session.status !== RTCSession.C.STATUS_TERMINATED) {
throw new Exceptions.InvalidStateError(this.session.status);
}
/*
* Allow sending BYE in TERMINATED status since the RTCSession
* could had been terminated before the ACK had arrived.
* RFC3261 Section 15, Paragraph 2
*/
else if (this.session.status === RTCSession.C.STATUS_TERMINATED && method !== JsSIP_C.BYE) {
throw new Exceptions.InvalidStateError(this.session.status);
}
}
Request.prototype.send = function(options) {
options = options || {};
var
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body || null;
this.eventHandlers = options.eventHandlers || {};
this.outgoingRequest = this.session.dialog.sendRequest(this, this.method, {
extraHeaders: extraHeaders,
body: body
});
};
Request.prototype.receiveResponse = function(response) {
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
debug('onProgressResponse');
if (this.eventHandlers.onProgressResponse) { this.eventHandlers.onProgressResponse(response); }
break;
case /^2[0-9]{2}$/.test(response.status_code):
debug('onSuccessResponse');
if (this.eventHandlers.onSuccessResponse) { this.eventHandlers.onSuccessResponse(response); }
break;
default:
debug('onErrorResponse');
if (this.eventHandlers.onErrorResponse) { this.eventHandlers.onErrorResponse(response); }
break;
}
};
Request.prototype.onRequestTimeout = function() {
debugerror('onRequestTimeout');
if (this.eventHandlers.onRequestTimeout) { this.eventHandlers.onRequestTimeout(); }
};
Request.prototype.onTransportError = function() {
debugerror('onTransportError');
if (this.eventHandlers.onTransportError) { this.eventHandlers.onTransportError(); }
};
Request.prototype.onDialogError = function() {
debugerror('onDialogError');
if (this.eventHandlers.onDialogError) { this.eventHandlers.onDialogError(); }
};
},{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":34}],16:[function(require,module,exports){
module.exports = Registrator;
/**
* Dependecies
*/
var debug = require('debug')('JsSIP:Registrator');
var Utils = require('./Utils');
var JsSIP_C = require('./Constants');
var SIPMessage = require('./SIPMessage');
var RequestSender = require('./RequestSender');
function Registrator(ua, transport) {
var reg_id=1; //Force reg_id to 1.
this.ua = ua;
this.transport = transport;
this.registrar = ua.configuration.registrar_server;
this.expires = ua.configuration.register_expires;
// Call-ID and CSeq values RFC3261 10.2
this.call_id = Utils.createRandomToken(22);
this.cseq = 0;
// this.to_uri
this.to_uri = ua.configuration.uri;
this.registrationTimer = null;
// Set status
this.registered = false;
// Contact header
this.contact = this.ua.contact.toString();
// sip.ice media feature tag (RFC 5768)
this.contact += ';+sip.ice';
// Custom headers for REGISTER and un-REGISTER.
this.extraHeaders = [];
// Custom Contact header params for REGISTER and un-REGISTER.
this.extraContactParams = '';
if(reg_id) {
this.contact += ';reg-id='+ reg_id;
this.contact += ';+sip.instance="<urn:uuid:'+ this.ua.configuration.instance_id+'>"';
}
}
Registrator.prototype = {
setExtraHeaders: function(extraHeaders) {
if (! Array.isArray(extraHeaders)) {
extraHeaders = [];
}
this.extraHeaders = extraHeaders.slice();
},
setExtraContactParams: function(extraContactParams) {
if (! (extraContactParams instanceof Object)) {
extraContactParams = {};
}
// Reset it.
this.extraContactParams = '';
for(var param_key in extraContactParams) {
var param_value = extraContactParams[param_key];
this.extraContactParams += (';' + param_key);
if (param_value) {
this.extraContactParams += ('=' + param_value);
}
}
},
register: function() {
var request_sender, cause, extraHeaders,
self = this;
extraHeaders = this.extraHeaders.slice();
extraHeaders.push('Contact: ' + this.contact + ';expires=' + this.expires + this.extraContactParams);
extraHeaders.push('Expires: '+ this.expires);
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, {
'to_uri': this.to_uri,
'call_id': this.call_id,
'cseq': (this.cseq += 1)
}, extraHeaders);
request_sender = new RequestSender(this, this.ua);
this.receiveResponse = function(response) {
var contact, expires,
contacts = response.getHeaders('contact').length;
// Discard responses to older REGISTER/un-REGISTER requests.
if(response.cseq !== this.cseq) {
return;
}
// Clear registration timer
if (this.registrationTimer !== null) {
clearTimeout(this.registrationTimer);
this.registrationTimer = null;
}
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
if(response.hasHeader('expires')) {
expires = response.getHeader('expires');
}
// Search the Contact pointing to us and update the expires value accordingly.
if (!contacts) {
debug('no Contact header in response to REGISTER, response ignored');
break;
}
while(contacts--) {
contact = response.parseHeader('contact', contacts);
if(contact.uri.user === this.ua.contact.uri.user) {
expires = contact.getParam('expires');
break;
} else {
contact = null;
}
}
if (!contact) {
debug('no Contact header pointing to us, response ignored');
break;
}
if(!expires) {
expires = this.expires;
}
// Re-Register before the expiration interval has elapsed.
// For that, decrease the expires value. ie: 3 seconds
this.registrationTimer = setTimeout(function() {
self.registrationTimer = null;
self.register();
}, (expires * 1000) - 3000);
//Save gruu values
if (contact.hasParam('temp-gruu')) {
this.ua.contact.temp_gruu = contact.getParam('temp-gruu').replace(/"/g,'');
}
if (contact.hasParam('pub-gruu')) {
this.ua.contact.pub_gruu = contact.getParam('pub-gruu').replace(/"/g,'');
}
if (! this.registered) {
this.registered = true;
this.ua.registered({
response: response
});
}
break;
// Interval too brief RFC3261 10.2.8
case /^423$/.test(response.status_code):
if(response.hasHeader('min-expires')) {
// Increase our registration interval to the suggested minimum
this.expires = response.getHeader('min-expires');
// Attempt the registration again immediately
this.register();
} else { //This response MUST contain a Min-Expires header field
debug('423 response received for REGISTER without Min-Expires');
this.registrationFailure(response, JsSIP_C.causes.SIP_FAILURE_CODE);
}
break;
default:
cause = Utils.sipErrorCause(response.status_code);
this.registrationFailure(response, cause);
}
};
this.onRequestTimeout = function() {
this.registrationFailure(null, JsSIP_C.causes.REQUEST_TIMEOUT);
};
this.onTransportError = function() {
this.registrationFailure(null, JsSIP_C.causes.CONNECTION_ERROR);
};
request_sender.send();
},
unregister: function(options) {
var extraHeaders;
if(!this.registered) {
debug('already unregistered');
return;
}
options = options || {};
this.registered = false;
// Clear the registration timer.
if (this.registrationTimer !== null) {
clearTimeout(this.registrationTimer);
this.registrationTimer = null;
}
extraHeaders = this.extraHeaders.slice();
if(options.all) {
extraHeaders.push('Contact: *' + this.extraContactParams);
extraHeaders.push('Expires: 0');
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, {
'to_uri': this.to_uri,
'call_id': this.call_id,
'cseq': (this.cseq += 1)
}, extraHeaders);
} else {
extraHeaders.push('Contact: '+ this.contact + ';expires=0' + this.extraContactParams);
extraHeaders.push('Expires: 0');
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, {
'to_uri': this.to_uri,
'call_id': this.call_id,
'cseq': (this.cseq += 1)
}, extraHeaders);
}
var request_sender = new RequestSender(this, this.ua);
this.receiveResponse = function(response) {
var cause;
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
this.unregistered(response);
break;
default:
cause = Utils.sipErrorCause(response.status_code);
this.unregistered(response, cause);
}
};
this.onRequestTimeout = function() {
this.unregistered(null, JsSIP_C.causes.REQUEST_TIMEOUT);
};
this.onTransportError = function() {
this.unregistered(null, JsSIP_C.causes.CONNECTION_ERROR);
};
request_sender.send();
},
registrationFailure: function(response, cause) {
this.ua.registrationFailed({
response: response || null,
cause: cause
});
if (this.registered) {
this.registered = false;
this.ua.unregistered({
response: response || null,
cause: cause
});
}
},
unregistered: function(response, cause) {
this.registered = false;
this.ua.unregistered({
response: response || null,
cause: cause || null
});
},
onTransportClosed: function() {
if (this.registrationTimer !== null) {
clearTimeout(this.registrationTimer);
this.registrationTimer = null;
}
if(this.registered) {
this.registered = false;
this.ua.unregistered({});
}
},
close: function() {
if (this.registered) {
this.unregister();
}
}
};
},{"./Constants":1,"./RequestSender":17,"./SIPMessage":18,"./Utils":25,"debug":34}],17:[function(require,module,exports){
module.exports = RequestSender;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:RequestSender');
var JsSIP_C = require('./Constants');
var UA = require('./UA');
var DigestAuthentication = require('./DigestAuthentication');
var Transactions = require('./Transactions');
function RequestSender(applicant, ua) {
this.ua = ua;
this.applicant = applicant;
this.method = applicant.request.method;
this.request = applicant.request;
this.auth = null;
this.challenged = false;
this.staled = false;
// If ua is in closing process or even closed just allow sending Bye and ACK
if (ua.status === UA.C.STATUS_USER_CLOSED && (this.method !== JsSIP_C.BYE || this.method !== JsSIP_C.ACK)) {
this.onTransportError();
}
}
/**
* Create the client transaction and send the message.
*/
RequestSender.prototype = {
send: function() {
switch(this.method) {
case 'INVITE':
this.clientTransaction = new Transactions.InviteClientTransaction(this, this.request, this.ua.transport);
break;
case 'ACK':
this.clientTransaction = new Transactions.AckClientTransaction(this, this.request, this.ua.transport);
break;
default:
this.clientTransaction = new Transactions.NonInviteClientTransaction(this, this.request, this.ua.transport);
}
this.clientTransaction.send();
},
/**
* Callback fired when receiving a request timeout error from the client transaction.
* To be re-defined by the applicant.
*/
onRequestTimeout: function() {
this.applicant.onRequestTimeout();
},
/**
* Callback fired when receiving a transport error from the client transaction.
* To be re-defined by the applicant.
*/
onTransportError: function() {
this.applicant.onTransportError();
},
/**
* Called from client transaction when receiving a correct response to the request.
* Authenticate request if needed or pass the response back to the applicant.
*/
receiveResponse: function(response) {
var
cseq, challenge, authorization_header_name,
status_code = response.status_code;
/*
* Authentication
* Authenticate once. _challenged_ flag used to avoid infinite authentications.
*/
if ((status_code === 401 || status_code === 407) &&
(this.ua.configuration.password !== null || this.ua.configuration.ha1 !== null)) {
// Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header.
if (response.status_code === 401) {
challenge = response.parseHeader('www-authenticate');
authorization_header_name = 'authorization';
} else {
challenge = response.parseHeader('proxy-authenticate');
authorization_header_name = 'proxy-authorization';
}
// Verify it seems a valid challenge.
if (!challenge) {
debug(response.status_code + ' with wrong or missing challenge, cannot authenticate');
this.applicant.receiveResponse(response);
return;
}
if (!this.challenged || (!this.staled && challenge.stale === true)) {
if (!this.auth) {
this.auth = new DigestAuthentication({
username : this.ua.configuration.authorization_user,
password : this.ua.configuration.password,
realm : this.ua.configuration.realm,
ha1 : this.ua.configuration.ha1
});
}
// Verify that the challenge is really valid.
if (!this.auth.authenticate(this.request, challenge)) {
this.applicant.receiveResponse(response);
return;
}
this.challenged = true;
// Update ha1 and realm in the UA.
this.ua.set('realm', this.auth.get('realm'));
this.ua.set('ha1', this.auth.get('ha1'));
if (challenge.stale) {
this.staled = true;
}
if (response.method === JsSIP_C.REGISTER) {
cseq = this.applicant.cseq += 1;
} else if (this.request.dialog) {
cseq = this.request.dialog.local_seqnum += 1;
} else {
cseq = this.request.cseq + 1;
}
this.request = this.applicant.request = this.request.clone();
this.request.cseq = cseq;
this.request.setHeader('cseq', cseq +' '+ this.method);
this.request.setHeader(authorization_header_name, this.auth.toString());
this.send();
} else {
this.applicant.receiveResponse(response);
}
} else {
this.applicant.receiveResponse(response);
}
}
};
},{"./Constants":1,"./DigestAuthentication":4,"./Transactions":21,"./UA":23,"debug":34}],18:[function(require,module,exports){
module.exports = {
OutgoingRequest: OutgoingRequest,
IncomingRequest: IncomingRequest,
IncomingResponse: IncomingResponse
};
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:SIPMessage');
var sdp_transform = require('sdp-transform');
var JsSIP_C = require('./Constants');
var Utils = require('./Utils');
var NameAddrHeader = require('./NameAddrHeader');
var Grammar = require('./Grammar');
/**
* -param {String} method request method
* -param {String} ruri request uri
* -param {UA} ua
* -param {Object} params parameters that will have priority over ua.configuration parameters:
* <br>
* - cseq, call_id, from_tag, from_uri, from_display_name, to_uri, to_tag, route_set
* -param {Object} [headers] extra headers
* -param {String} [body]
*/
function OutgoingRequest(method, ruri, ua, params, extraHeaders, body) {
var
to,
from,
call_id,
cseq;
params = params || {};
// Mandatory parameters check
if(!method || !ruri || !ua) {
return null;
}
this.ua = ua;
this.headers = {};
this.method = method;
this.ruri = ruri;
this.body = body;
this.extraHeaders = extraHeaders && extraHeaders.slice() || [];
// Fill the Common SIP Request Headers
// Route
if (params.route_set) {
this.setHeader('route', params.route_set);
} else if (ua.configuration.use_preloaded_route) {
this.setHeader('route', '<' + ua.transport.sip_uri + ';lr>');
}
// Via
// Empty Via header. Will be filled by the client transaction.
this.setHeader('via', '');
// Max-Forwards
this.setHeader('max-forwards', JsSIP_C.MAX_FORWARDS);
// To
to = (params.to_display_name || params.to_display_name === 0) ? '"' + params.to_display_name + '" ' : '';
to += '<' + (params.to_uri || ruri) + '>';
to += params.to_tag ? ';tag=' + params.to_tag : '';
this.to = new NameAddrHeader.parse(to);
this.setHeader('to', to);
// From
if (params.from_display_name || params.from_display_name === 0) {
from = '"' + params.from_display_name + '" ';
} else if (ua.configuration.display_name) {
from = '"' + ua.configuration.display_name + '" ';
} else {
from = '';
}
from += '<' + (params.from_uri || ua.configuration.uri) + '>;tag=';
from += params.from_tag || Utils.newTag();
this.from = new NameAddrHeader.parse(from);
this.setHeader('from', from);
// Call-ID
call_id = params.call_id || (ua.configuration.jssip_id + Utils.createRandomToken(15));
this.call_id = call_id;
this.setHeader('call-id', call_id);
// CSeq
cseq = params.cseq || Math.floor(Math.random() * 10000);
this.cseq = cseq;
this.setHeader('cseq', cseq + ' ' + method);
}
OutgoingRequest.prototype = {
/**
* Replace the the given header by the given value.
* -param {String} name header name
* -param {String | Array} value header value
*/
setHeader: function(name, value) {
var regexp, idx;
// Remove the header from extraHeaders if present.
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<this.extraHeaders.length; idx++) {
if (regexp.test(this.extraHeaders[idx])) {
this.extraHeaders.splice(idx, 1);
}
}
this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value];
},
/**
* Get the value of the given header name at the given position.
* -param {String} name header name
* -returns {String|undefined} Returns the specified header, null if header doesn't exist.
*/
getHeader: function(name) {
var regexp, idx,
length = this.extraHeaders.length,
header = this.headers[Utils.headerize(name)];
if(header) {
if(header[0]) {
return header[0];
}
} else {
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<length; idx++) {
header = this.extraHeaders[idx];
if (regexp.test(header)) {
return header.substring(header.indexOf(':')+1).trim();
}
}
}
return;
},
/**
* Get the header/s of the given name.
* -param {String} name header name
* -returns {Array} Array with all the headers of the specified name.
*/
getHeaders: function(name) {
var idx, length, regexp,
header = this.headers[Utils.headerize(name)],
result = [];
if (header) {
length = header.length;
for (idx = 0; idx < length; idx++) {
result.push(header[idx]);
}
return result;
} else {
length = this.extraHeaders.length;
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<length; idx++) {
header = this.extraHeaders[idx];
if (regexp.test(header)) {
result.push(header.substring(header.indexOf(':')+1).trim());
}
}
return result;
}
},
/**
* Verify the existence of the given header.
* -param {String} name header name
* -returns {boolean} true if header with given name exists, false otherwise
*/
hasHeader: function(name) {
var regexp, idx,
length = this.extraHeaders.length;
if (this.headers[Utils.headerize(name)]) {
return true;
} else {
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<length; idx++) {
if (regexp.test(this.extraHeaders[idx])) {
return true;
}
}
}
return false;
},
/**
* Parse the current body as a SDP and store the resulting object
* into this.sdp.
* -param {Boolean} force: Parse even if this.sdp already exists.
*
* Returns this.sdp.
*/
parseSDP: function(force) {
if (!force && this.sdp) {
return this.sdp;
} else {
this.sdp = sdp_transform.parse(this.body || '');
return this.sdp;
}
},
toString: function() {
var msg = '', header, length, idx,
supported = [];
msg += this.method + ' ' + this.ruri + ' SIP/2.0\r\n';
for (header in this.headers) {
length = this.headers[header].length;
for (idx = 0; idx < length; idx++) {
msg += header + ': ' + this.headers[header][idx] + '\r\n';
}
}
length = this.extraHeaders.length;
for (idx = 0; idx < length; idx++) {
msg += this.extraHeaders[idx].trim() +'\r\n';
}
// Supported
switch (this.method) {
case JsSIP_C.REGISTER:
supported.push('path', 'gruu');
break;
case JsSIP_C.INVITE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) {
supported.push('gruu');
}
supported.push('ice','replaces');
break;
case JsSIP_C.UPDATE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
supported.push('ice');
break;
}
supported.push('outbound');
// Allow
msg += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n';
msg += 'Supported: ' + supported +'\r\n';
msg += 'User-Agent: ' + JsSIP_C.USER_AGENT +'\r\n';
if (this.body) {
length = Utils.str_utf8_length(this.body);
msg += 'Content-Length: ' + length + '\r\n\r\n';
msg += this.body;
} else {
msg += 'Content-Length: 0\r\n\r\n';
}
return msg;
},
clone: function() {
var request = new OutgoingRequest(this.method, this.ruri, this.ua);
Object.keys(this.headers).forEach(function(name) {
request.headers[name] = this.headers[name].slice();
}, this);
request.body = this.body;
request.extraHeaders = this.extraHeaders && this.extraHeaders.slice() || [];
request.to = this.to;
request.from = this.from;
request.call_id = this.call_id;
request.cseq = this.cseq;
return request;
}
};
function IncomingMessage(){
this.data = null;
this.headers = null;
this.method = null;
this.via = null;
this.via_branch = null;
this.call_id = null;
this.cseq = null;
this.from = null;
this.from_tag = null;
this.to = null;
this.to_tag = null;
this.body = null;
this.sdp = null;
}
IncomingMessage.prototype = {
/**
* Insert a header of the given name and value into the last position of the
* header array.
*/
addHeader: function(name, value) {
var header = { raw: value };
name = Utils.headerize(name);
if(this.headers[name]) {
this.headers[name].push(header);
} else {
this.headers[name] = [header];
}
},
/**
* Get the value of the given header name at the given position.
*/
getHeader: function(name) {
var header = this.headers[Utils.headerize(name)];
if(header) {
if(header[0]) {
return header[0].raw;
}
} else {
return;
}
},
/**
* Get the header/s of the given name.
*/
getHeaders: function(name) {
var idx, length,
header = this.headers[Utils.headerize(name)],
result = [];
if(!header) {
return [];
}
length = header.length;
for (idx = 0; idx < length; idx++) {
result.push(header[idx].raw);
}
return result;
},
/**
* Verify the existence of the given header.
*/
hasHeader: function(name) {
return(this.headers[Utils.headerize(name)]) ? true : false;
},
/**
* Parse the given header on the given index.
* -param {String} name header name
* -param {Number} [idx=0] header index
* -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error.
*/
parseHeader: function(name, idx) {
var header, value, parsed;
name = Utils.headerize(name);
idx = idx || 0;
if(!this.headers[name]) {
debug('header "' + name + '" not present');
return;
} else if(idx >= this.headers[name].length) {
debug('not so many "' + name + '" headers present');
return;
}
header = this.headers[name][idx];
value = header.raw;
if(header.parsed) {
return header.parsed;
}
//substitute '-' by '_' for grammar rule matching.
parsed = Grammar.parse(value, name.replace(/-/g, '_'));
if(parsed === -1) {
this.headers[name].splice(idx, 1); //delete from headers
debug('error parsing "' + name + '" header field with value "' + value + '"');
return;
} else {
header.parsed = parsed;
return parsed;
}
},
/**
* Message Header attribute selector. Alias of parseHeader.
* -param {String} name header name
* -param {Number} [idx=0] header index
* -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error.
*
* -example
* message.s('via',3).port
*/
s: function(name, idx) {
return this.parseHeader(name, idx);
},
/**
* Replace the value of the given header by the value.
* -param {String} name header name
* -param {String} value header value
*/
setHeader: function(name, value) {
var header = { raw: value };
this.headers[Utils.headerize(name)] = [header];
},
/**
* Parse the current body as a SDP and store the resulting object
* into this.sdp.
* -param {Boolean} force: Parse even if this.sdp already exists.
*
* Returns this.sdp.
*/
parseSDP: function(force) {
if (!force && this.sdp) {
return this.sdp;
} else {
this.sdp = sdp_transform.parse(this.body || '');
return this.sdp;
}
},
toString: function() {
return this.data;
}
};
function IncomingRequest(ua) {
this.ua = ua;
this.headers = {};
this.ruri = null;
this.transport = null;
this.server_transaction = null;
}
IncomingRequest.prototype = new IncomingMessage();
/**
* Stateful reply.
* -param {Number} code status code
* -param {String} reason reason phrase
* -param {Object} headers extra headers
* -param {String} body body
* -param {Function} [onSuccess] onSuccess callback
* -param {Function} [onFailure] onFailure callback
*/
IncomingRequest.prototype.reply = function(code, reason, extraHeaders, body, onSuccess, onFailure) {
var rr, vias, length, idx, response,
supported = [],
to = this.getHeader('To'),
r = 0,
v = 0;
code = code || null;
reason = reason || null;
// Validate code and reason values
if (!code || (code < 100 || code > 699)) {
throw new TypeError('Invalid status_code: '+ code);
} else if (reason && typeof reason !== 'string' && !(reason instanceof String)) {
throw new TypeError('Invalid reason_phrase: '+ reason);
}
reason = reason || JsSIP_C.REASON_PHRASE[code] || '';
extraHeaders = extraHeaders && extraHeaders.slice() || [];
response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n';
if(this.method === JsSIP_C.INVITE && code > 100 && code <= 200) {
rr = this.getHeaders('record-route');
length = rr.length;
for(r; r < length; r++) {
response += 'Record-Route: ' + rr[r] + '\r\n';
}
}
vias = this.getHeaders('via');
length = vias.length;
for(v; v < length; v++) {
response += 'Via: ' + vias[v] + '\r\n';
}
if(!this.to_tag && code > 100) {
to += ';tag=' + Utils.newTag();
} else if(this.to_tag && !this.s('to').hasParam('tag')) {
to += ';tag=' + this.to_tag;
}
response += 'To: ' + to + '\r\n';
response += 'From: ' + this.getHeader('From') + '\r\n';
response += 'Call-ID: ' + this.call_id + '\r\n';
response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n';
length = extraHeaders.length;
for (idx = 0; idx < length; idx++) {
response += extraHeaders[idx].trim() +'\r\n';
}
// Supported
switch (this.method) {
case JsSIP_C.INVITE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) {
supported.push('gruu');
}
supported.push('ice','replaces');
break;
case JsSIP_C.UPDATE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
if (body) {
supported.push('ice');
}
supported.push('replaces');
}
supported.push('outbound');
// Allow and Accept
if (this.method === JsSIP_C.OPTIONS) {
response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n';
response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n';
} else if (code === 405) {
response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n';
} else if (code === 415 ) {
response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n';
}
response += 'Supported: ' + supported +'\r\n';
if(body) {
length = Utils.str_utf8_length(body);
response += 'Content-Type: application/sdp\r\n';
response += 'Content-Length: ' + length + '\r\n\r\n';
response += body;
} else {
response += 'Content-Length: ' + 0 + '\r\n\r\n';
}
this.server_transaction.receiveResponse(code, response, onSuccess, onFailure);
};
/**
* Stateless reply.
* -param {Number} code status code
* -param {String} reason reason phrase
*/
IncomingRequest.prototype.reply_sl = function(code, reason) {
var to, response,
v = 0,
vias = this.getHeaders('via'),
length = vias.length;
code = code || null;
reason = reason || null;
// Validate code and reason values
if (!code || (code < 100 || code > 699)) {
throw new TypeError('Invalid status_code: '+ code);
} else if (reason && typeof reason !== 'string' && !(reason instanceof String)) {
throw new TypeError('Invalid reason_phrase: '+ reason);
}
reason = reason || JsSIP_C.REASON_PHRASE[code] || '';
response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n';
for(v; v < length; v++) {
response += 'Via: ' + vias[v] + '\r\n';
}
to = this.getHeader('To');
if(!this.to_tag && code > 100) {
to += ';tag=' + Utils.newTag();
} else if(this.to_tag && !this.s('to').hasParam('tag')) {
to += ';tag=' + this.to_tag;
}
response += 'To: ' + to + '\r\n';
response += 'From: ' + this.getHeader('From') + '\r\n';
response += 'Call-ID: ' + this.call_id + '\r\n';
response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n';
response += 'Content-Length: ' + 0 + '\r\n\r\n';
this.transport.send(response);
};
function IncomingResponse() {
this.headers = {};
this.status_code = null;
this.reason_phrase = null;
}
IncomingResponse.prototype = new IncomingMessage();
},{"./Constants":1,"./Grammar":6,"./NameAddrHeader":9,"./Utils":25,"debug":34,"sdp-transform":37}],19:[function(require,module,exports){
module.exports = Socket;
/**
* Interface documentation: http://jssip.net/documentation/$last_version/api/socket/
*
* interface Socket {
* attribute String via_transport
* attribute String url
* attribute String sip_uri
*
* method connect();
* method disconnect();
* method send(data);
*
* attribute EventHandler onconnect
* attribute EventHandler ondisconnect
* attribute EventHandler ondata
* }
*
*/
/**
* Dependencies.
*/
var Utils = require('./Utils');
var Grammar = require('./Grammar');
var debugerror = require('debug')('JsSIP:ERROR:Socket');
debugerror.log = console.warn.bind(console);
function Socket() {}
Socket.isSocket = function(socket) {
// Ignore if an array is given
if (Array.isArray(socket)) {
return false;
}
if (typeof socket === 'undefined') {
debugerror('undefined JsSIP.Socket instance');
return false;
}
// Check Properties
try {
if (!Utils.isString(socket.url)) {
debugerror('missing or invalid JsSIP.Socket url property');
throw new Error();
}
if (!Utils.isString(socket.via_transport)) {
debugerror('missing or invalid JsSIP.Socket via_transport property');
throw new Error();
}
if (Grammar.parse(socket.sip_uri, 'SIP_URI') === -1) {
debugerror('missing or invalid JsSIP.Socket sip_uri property');
throw new Error();
}
} catch(e) {
return false;
}
// Check Methods
try {
['connect', 'disconnect', 'send'].forEach(function(method) {
if (!Utils.isFunction(socket[method])) {
debugerror('missing or invalid JsSIP.Socket method: ' + method);
throw new Error();
}
});
} catch(e) {
return false;
}
return true;
};
},{"./Grammar":6,"./Utils":25,"debug":34}],20:[function(require,module,exports){
var T1 = 500,
T2 = 4000,
T4 = 5000;
var Timers = {
T1: T1,
T2: T2,
T4: T4,
TIMER_B: 64 * T1,
TIMER_D: 0 * T1,
TIMER_F: 64 * T1,
TIMER_H: 64 * T1,
TIMER_I: 0 * T1,
TIMER_J: 0 * T1,
TIMER_K: 0 * T4,
TIMER_L: 64 * T1,
TIMER_M: 64 * T1,
PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1
};
module.exports = Timers;
},{}],21:[function(require,module,exports){
module.exports = {
C: null,
NonInviteClientTransaction: NonInviteClientTransaction,
InviteClientTransaction: InviteClientTransaction,
AckClientTransaction: AckClientTransaction,
NonInviteServerTransaction: NonInviteServerTransaction,
InviteServerTransaction: InviteServerTransaction,
checkTransaction: checkTransaction
};
var C = {
// Transaction states
STATUS_TRYING: 1,
STATUS_PROCEEDING: 2,
STATUS_CALLING: 3,
STATUS_ACCEPTED: 4,
STATUS_COMPLETED: 5,
STATUS_TERMINATED: 6,
STATUS_CONFIRMED: 7,
// Transaction types
NON_INVITE_CLIENT: 'nict',
NON_INVITE_SERVER: 'nist',
INVITE_CLIENT: 'ict',
INVITE_SERVER: 'ist'
};
/**
* Expose C object.
*/
module.exports.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debugnict = require('debug')('JsSIP:NonInviteClientTransaction');
var debugict = require('debug')('JsSIP:InviteClientTransaction');
var debugact = require('debug')('JsSIP:AckClientTransaction');
var debugnist = require('debug')('JsSIP:NonInviteServerTransaction');
var debugist = require('debug')('JsSIP:InviteServerTransaction');
var JsSIP_C = require('./Constants');
var Timers = require('./Timers');
function NonInviteClientTransaction(request_sender, request, transport) {
var via;
this.type = C.NON_INVITE_CLIENT;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
via = 'SIP/2.0/' + transport.via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
this.request_sender.ua.newTransaction(this);
events.EventEmitter.call(this);
}
util.inherits(NonInviteClientTransaction, events.EventEmitter);
NonInviteClientTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
NonInviteClientTransaction.prototype.send = function() {
var tr = this;
this.stateChanged(C.STATUS_TRYING);
this.F = setTimeout(function() {tr.timer_F();}, Timers.TIMER_F);
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
NonInviteClientTransaction.prototype.onTransportError = function() {
debugnict('transport error occurred, deleting transaction ' + this.id);
clearTimeout(this.F);
clearTimeout(this.K);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onTransportError();
};
NonInviteClientTransaction.prototype.timer_F = function() {
debugnict('Timer F expired for transaction ' + this.id);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onRequestTimeout();
};
NonInviteClientTransaction.prototype.timer_K = function() {
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
NonInviteClientTransaction.prototype.receiveResponse = function(response) {
var
tr = this,
status_code = response.status_code;
if(status_code < 200) {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_PROCEEDING);
this.request_sender.receiveResponse(response);
break;
}
} else {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
clearTimeout(this.F);
if(status_code === 408) {
this.request_sender.onRequestTimeout();
} else {
this.request_sender.receiveResponse(response);
}
this.K = setTimeout(function() {tr.timer_K();}, Timers.TIMER_K);
break;
case C.STATUS_COMPLETED:
break;
}
}
};
function InviteClientTransaction(request_sender, request, transport) {
var via,
tr = this;
this.type = C.INVITE_CLIENT;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
via = 'SIP/2.0/' + transport.via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
this.request_sender.ua.newTransaction(this);
// TODO: Adding here the cancel() method is a hack that must be fixed.
// Add the cancel property to the request.
//Will be called from the request instance, not the transaction itself.
this.request.cancel = function(reason) {
tr.cancel_request(tr, reason);
};
events.EventEmitter.call(this);
}
util.inherits(InviteClientTransaction, events.EventEmitter);
InviteClientTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
InviteClientTransaction.prototype.send = function() {
var tr = this;
this.stateChanged(C.STATUS_CALLING);
this.B = setTimeout(function() {
tr.timer_B();
}, Timers.TIMER_B);
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
InviteClientTransaction.prototype.onTransportError = function() {
clearTimeout(this.B);
clearTimeout(this.D);
clearTimeout(this.M);
if (this.state !== C.STATUS_ACCEPTED) {
debugict('transport error occurred, deleting transaction ' + this.id);
this.request_sender.onTransportError();
}
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
// RFC 6026 7.2
InviteClientTransaction.prototype.timer_M = function() {
debugict('Timer M expired for transaction ' + this.id);
if(this.state === C.STATUS_ACCEPTED) {
clearTimeout(this.B);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
}
};
// RFC 3261 17.1.1
InviteClientTransaction.prototype.timer_B = function() {
debugict('Timer B expired for transaction ' + this.id);
if(this.state === C.STATUS_CALLING) {
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onRequestTimeout();
}
};
InviteClientTransaction.prototype.timer_D = function() {
debugict('Timer D expired for transaction ' + this.id);
clearTimeout(this.B);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
InviteClientTransaction.prototype.sendACK = function(response) {
var tr = this;
this.ack = 'ACK ' + this.request.ruri + ' SIP/2.0\r\n';
this.ack += 'Via: ' + this.request.headers.Via.toString() + '\r\n';
if(this.request.headers.Route) {
this.ack += 'Route: ' + this.request.headers.Route.toString() + '\r\n';
}
this.ack += 'To: ' + response.getHeader('to') + '\r\n';
this.ack += 'From: ' + this.request.headers.From.toString() + '\r\n';
this.ack += 'Call-ID: ' + this.request.headers['Call-ID'].toString() + '\r\n';
this.ack += 'CSeq: ' + this.request.headers.CSeq.toString().split(' ')[0];
this.ack += ' ACK\r\n';
this.ack += 'Content-Length: 0\r\n\r\n';
this.D = setTimeout(function() {tr.timer_D();}, Timers.TIMER_D);
this.transport.send(this.ack);
};
InviteClientTransaction.prototype.cancel_request = function(tr, reason) {
var request = tr.request;
this.cancel = JsSIP_C.CANCEL + ' ' + request.ruri + ' SIP/2.0\r\n';
this.cancel += 'Via: ' + request.headers.Via.toString() + '\r\n';
if(this.request.headers.Route) {
this.cancel += 'Route: ' + request.headers.Route.toString() + '\r\n';
}
this.cancel += 'To: ' + request.headers.To.toString() + '\r\n';
this.cancel += 'From: ' + request.headers.From.toString() + '\r\n';
this.cancel += 'Call-ID: ' + request.headers['Call-ID'].toString() + '\r\n';
this.cancel += 'CSeq: ' + request.headers.CSeq.toString().split(' ')[0] +
' CANCEL\r\n';
if(reason) {
this.cancel += 'Reason: ' + reason + '\r\n';
}
this.cancel += 'Content-Length: 0\r\n\r\n';
// Send only if a provisional response (>100) has been received.
if(this.state === C.STATUS_PROCEEDING) {
this.transport.send(this.cancel);
}
};
InviteClientTransaction.prototype.receiveResponse = function(response) {
var
tr = this,
status_code = response.status_code;
if(status_code >= 100 && status_code <= 199) {
switch(this.state) {
case C.STATUS_CALLING:
this.stateChanged(C.STATUS_PROCEEDING);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_PROCEEDING:
this.request_sender.receiveResponse(response);
break;
}
} else if(status_code >= 200 && status_code <= 299) {
switch(this.state) {
case C.STATUS_CALLING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_ACCEPTED);
this.M = setTimeout(function() {
tr.timer_M();
}, Timers.TIMER_M);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_ACCEPTED:
this.request_sender.receiveResponse(response);
break;
}
} else if(status_code >= 300 && status_code <= 699) {
switch(this.state) {
case C.STATUS_CALLING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
this.sendACK(response);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_COMPLETED:
this.sendACK(response);
break;
}
}
};
function AckClientTransaction(request_sender, request, transport) {
var via;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
via = 'SIP/2.0/' + transport.via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
events.EventEmitter.call(this);
}
util.inherits(AckClientTransaction, events.EventEmitter);
AckClientTransaction.prototype.send = function() {
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
AckClientTransaction.prototype.onTransportError = function() {
debugact('transport error occurred for transaction ' + this.id);
this.request_sender.onTransportError();
};
function NonInviteServerTransaction(request, ua) {
this.type = C.NON_INVITE_SERVER;
this.id = request.via_branch;
this.request = request;
this.transport = request.transport;
this.ua = ua;
this.last_response = '';
request.server_transaction = this;
this.state = C.STATUS_TRYING;
ua.newTransaction(this);
events.EventEmitter.call(this);
}
util.inherits(NonInviteServerTransaction, events.EventEmitter);
NonInviteServerTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
NonInviteServerTransaction.prototype.timer_J = function() {
debugnist('Timer J expired for transaction ' + this.id);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
};
NonInviteServerTransaction.prototype.onTransportError = function() {
if (!this.transportError) {
this.transportError = true;
debugnist('transport error occurred, deleting transaction ' + this.id);
clearTimeout(this.J);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
NonInviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) {
var tr = this;
if(status_code === 100) {
/* RFC 4320 4.1
* 'A SIP element MUST NOT
* send any provisional response with a
* Status-Code other than 100 to a non-INVITE request.'
*/
switch(this.state) {
case C.STATUS_TRYING:
this.stateChanged(C.STATUS_PROCEEDING);
if(!this.transport.send(response)) {
this.onTransportError();
}
break;
case C.STATUS_PROCEEDING:
this.last_response = response;
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
}
} else if(status_code >= 200 && status_code <= 699) {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
this.last_response = response;
this.J = setTimeout(function() {
tr.timer_J();
}, Timers.TIMER_J);
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
case C.STATUS_COMPLETED:
break;
}
}
};
function InviteServerTransaction(request, ua) {
this.type = C.INVITE_SERVER;
this.id = request.via_branch;
this.request = request;
this.transport = request.transport;
this.ua = ua;
this.last_response = '';
request.server_transaction = this;
this.state = C.STATUS_PROCEEDING;
ua.newTransaction(this);
this.resendProvisionalTimer = null;
request.reply(100);
events.EventEmitter.call(this);
}
util.inherits(InviteServerTransaction, events.EventEmitter);
InviteServerTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
InviteServerTransaction.prototype.timer_H = function() {
debugist('Timer H expired for transaction ' + this.id);
if(this.state === C.STATUS_COMPLETED) {
debugist('ACK not received, dialog will be terminated');
}
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
};
InviteServerTransaction.prototype.timer_I = function() {
this.stateChanged(C.STATUS_TERMINATED);
};
// RFC 6026 7.1
InviteServerTransaction.prototype.timer_L = function() {
debugist('Timer L expired for transaction ' + this.id);
if(this.state === C.STATUS_ACCEPTED) {
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
InviteServerTransaction.prototype.onTransportError = function() {
if (!this.transportError) {
this.transportError = true;
debugist('transport error occurred, deleting transaction ' + this.id);
if (this.resendProvisionalTimer !== null) {
clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
clearTimeout(this.L);
clearTimeout(this.H);
clearTimeout(this.I);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
InviteServerTransaction.prototype.resend_provisional = function() {
if(!this.transport.send(this.last_response)) {
this.onTransportError();
}
};
// INVITE Server Transaction RFC 3261 17.2.1
InviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) {
var tr = this;
if(status_code >= 100 && status_code <= 199) {
switch(this.state) {
case C.STATUS_PROCEEDING:
if(!this.transport.send(response)) {
this.onTransportError();
}
this.last_response = response;
break;
}
}
if(status_code > 100 && status_code <= 199 && this.state === C.STATUS_PROCEEDING) {
// Trigger the resendProvisionalTimer only for the first non 100 provisional response.
if(this.resendProvisionalTimer === null) {
this.resendProvisionalTimer = setInterval(function() {
tr.resend_provisional();}, Timers.PROVISIONAL_RESPONSE_INTERVAL);
}
} else if(status_code >= 200 && status_code <= 299) {
switch(this.state) {
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_ACCEPTED);
this.last_response = response;
this.L = setTimeout(function() {
tr.timer_L();
}, Timers.TIMER_L);
if (this.resendProvisionalTimer !== null) {
clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
/* falls through */
case C.STATUS_ACCEPTED:
// Note that this point will be reached for proceeding tr.state also.
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
}
} else if(status_code >= 300 && status_code <= 699) {
switch(this.state) {
case C.STATUS_PROCEEDING:
if (this.resendProvisionalTimer !== null) {
clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else {
this.stateChanged(C.STATUS_COMPLETED);
this.H = setTimeout(function() {
tr.timer_H();
}, Timers.TIMER_H);
if (onSuccess) {
onSuccess();
}
}
break;
}
}
};
/**
* INVITE:
* _true_ if retransmission
* _false_ new request
*
* ACK:
* _true_ ACK to non2xx response
* _false_ ACK must be passed to TU (accepted state)
* ACK to 2xx response
*
* CANCEL:
* _true_ no matching invite transaction
* _false_ matching invite transaction and no final response sent
*
* OTHER:
* _true_ retransmission
* _false_ new request
*/
function checkTransaction(ua, request) {
var tr;
switch(request.method) {
case JsSIP_C.INVITE:
tr = ua.transactions.ist[request.via_branch];
if(tr) {
switch(tr.state) {
case C.STATUS_PROCEEDING:
tr.transport.send(tr.last_response);
break;
// RFC 6026 7.1 Invite retransmission
//received while in C.STATUS_ACCEPTED state. Absorb it.
case C.STATUS_ACCEPTED:
break;
}
return true;
}
break;
case JsSIP_C.ACK:
tr = ua.transactions.ist[request.via_branch];
// RFC 6026 7.1
if(tr) {
if(tr.state === C.STATUS_ACCEPTED) {
return false;
} else if(tr.state === C.STATUS_COMPLETED) {
tr.state = C.STATUS_CONFIRMED;
tr.I = setTimeout(function() {tr.timer_I();}, Timers.TIMER_I);
return true;
}
}
// ACK to 2XX Response.
else {
return false;
}
break;
case JsSIP_C.CANCEL:
tr = ua.transactions.ist[request.via_branch];
if(tr) {
request.reply_sl(200);
if(tr.state === C.STATUS_PROCEEDING) {
return false;
} else {
return true;
}
} else {
request.reply_sl(481);
return true;
}
break;
default:
// Non-INVITE Server Transaction RFC 3261 17.2.2
tr = ua.transactions.nist[request.via_branch];
if(tr) {
switch(tr.state) {
case C.STATUS_TRYING:
break;
case C.STATUS_PROCEEDING:
case C.STATUS_COMPLETED:
tr.transport.send(tr.last_response);
break;
}
return true;
}
break;
}
}
},{"./Constants":1,"./Timers":20,"debug":34,"events":28,"util":32}],22:[function(require,module,exports){
module.exports = Transport;
/**
* Dependencies.
*/
var Socket = require('./Socket');
var debug = require('debug')('JsSIP:Transport');
var debugerror = require('debug')('JsSIP:ERROR:Transport');
/**
* Constants
*/
var C = {
// Transport status
STATUS_CONNECTED: 0,
STATUS_CONNECTING: 1,
STATUS_DISCONNECTED: 2,
// Socket status
SOCKET_STATUS_READY: 0,
SOCKET_STATUS_ERROR: 1,
// Recovery options
recovery_options: {
min_interval: 2, // minimum interval in seconds between recover attempts
max_interval: 30 // maximum interval in seconds between recover attempts
}
};
/*
* Manages one or multiple JsSIP.Socket instances.
* Is reponsible for transport recovery logic among all socket instances.
*
* @socket JsSIP::Socket instance
*/
function Transport(sockets, recovery_options) {
debug('new()');
this.status = C.STATUS_DISCONNECTED;
// current socket
this.socket = null;
// socket collection
this.sockets = [];
this.recovery_options = recovery_options || C.recovery_options;
this.recover_attempts = 0;
this.recovery_timer = null;
this.close_requested = false;
if (typeof sockets === 'undefined') {
throw new TypeError('Invalid argument.' +
' undefined \'sockets\' argument');
}
if (!(sockets instanceof Array)) {
sockets = [ sockets ];
}
sockets.forEach(function(socket) {
if (!Socket.isSocket(socket.socket)) {
throw new TypeError('Invalid argument.' +
' invalid \'JsSIP.Socket\' instance');
}
if (socket.weight && !Number(socket.weight)) {
throw new TypeError('Invalid argument.' +
' \'weight\' attribute is not a number');
}
this.sockets.push({
socket: socket.socket,
weight: socket.weight || 0,
status: C.SOCKET_STATUS_READY
});
}, this);
// read only properties
Object.defineProperties(this, {
via_transport: { get: function() { return this.socket.via_transport; } },
url: { get: function() { return this.socket.url; } },
sip_uri: { get: function() { return this.socket.sip_uri; } }
});
// get the socket with higher weight
getSocket.call(this);
}
/**
* Instance Methods
*/
Transport.prototype.connect = function() {
debug('connect()');
if (this.isConnected()) {
debug('Transport is already connected');
return;
} else if (this.isConnecting()) {
debug('Transport is connecting');
return;
}
this.close_requested = false;
this.status = C.STATUS_CONNECTING;
this.onconnecting({ socket:this.socket, attempts:this.recover_attempts });
if (!this.close_requested) {
// bind socket event callbacks
this.socket.onconnect = onConnect.bind(this);
this.socket.ondisconnect = onDisconnect.bind(this);
this.socket.ondata = onData.bind(this);
this.socket.connect();
}
return;
};
Transport.prototype.disconnect = function() {
debug('close()');
this.close_requested = true;
this.recover_attempts = 0;
this.status = C.STATUS_DISCONNECTED;
// clear recovery_timer
if (this.recovery_timer !== null) {
clearTimeout(this.recovery_timer);
this.recovery_timer = null;
}
// unbind socket event callbacks
this.socket.onconnect = function() {};
this.socket.ondisconnect = function() {};
this.socket.ondata = function() {};
this.socket.disconnect();
this.ondisconnect();
};
Transport.prototype.send = function(data) {
debug('send()');
if (!this.isConnected()) {
debugerror('unable to send message, transport is not connected');
return false;
}
var message = data.toString();
debug('sending message:\n\n' + message + '\n');
return this.socket.send(message);
};
Transport.prototype.isConnected = function() {
return this.status === C.STATUS_CONNECTED;
};
Transport.prototype.isConnecting = function() {
return this.status === C.STATUS_CONNECTING;
};
/**
* Socket Event Handlers
*/
function onConnect() {
this.recover_attempts = 0;
this.status = C.STATUS_CONNECTED;
// clear recovery_timer
if (this.recovery_timer !== null) {
clearTimeout(this.recovery_timer);
this.recovery_timer = null;
}
this.onconnect( {socket:this} );
}
function onDisconnect(error, code, reason) {
this.status = C.STATUS_DISCONNECTED;
this.ondisconnect({ socket:this.socket, error:error, code:code, reason:reason });
if (this.close_requested) {
return;
}
// update socket status
else {
this.sockets.forEach(function(socket) {
if (this.socket === socket.socket) {
socket.status = C.SOCKET_STATUS_ERROR;
}
}, this);
}
reconnect.call(this, error);
}
function onData(data) {
// CRLF Keep Alive response from server. Ignore it.
if(data === '\r\n') {
debug('received message with CRLF Keep Alive response');
return;
}
// binary message.
else if (typeof data !== 'string') {
try {
data = String.fromCharCode.apply(null, new Uint8Array(data));
} catch(evt) {
debug('received binary message failed to be converted into string,' +
' message discarded');
return;
}
debug('received binary message:\n\n' + data + '\n');
}
// text message.
else {
debug('received text message:\n\n' + data + '\n');
}
this.ondata({ transport:this, message:data });
}
function reconnect() {
var k,
self = this;
this.recover_attempts+=1;
k = Math.floor((Math.random() * Math.pow(2,this.recover_attempts)) +1);
if (k < this.recovery_options.min_interval) {
k = this.recovery_options.min_interval;
}
else if (k > this.recovery_options.max_interval) {
k = this.recovery_options.max_interval;
}
debug('reconnection attempt: '+ this.recover_attempts +
'. next connection attempt in '+ k +' seconds');
this.recovery_timer = setTimeout(function() {
if (!self.close_requested && !(self.isConnected() || self.isConnecting())) {
// get the next available socket with higher weight
getSocket.call(self);
// connect the socket
self.connect();
}
}, k * 1000);
}
/**
* get the next available socket with higher weight
*/
function getSocket() {
var candidates = [];
this.sockets.forEach(function(socket) {
if (socket.status === C.SOCKET_STATUS_ERROR) {
return; // continue the array iteration
} else if (candidates.length === 0) {
candidates.push(socket);
} else if (socket.weight > candidates[0].weight) {
candidates = [socket];
} else if (socket.weight === candidates[0].weight) {
candidates.push(socket);
}
});
if (candidates.length === 0) {
// all sockets have failed. reset sockets status
this.sockets.forEach(function(socket) {
socket.status = C.SOCKET_STATUS_READY;
});
// get next available socket
getSocket.call(this);
return;
}
var idx = Math.floor((Math.random()* candidates.length));
this.socket = candidates[idx].socket;
}
},{"./Socket":19,"debug":34}],23:[function(require,module,exports){
module.exports = UA;
var C = {
// UA status codes
STATUS_INIT : 0,
STATUS_READY: 1,
STATUS_USER_CLOSED: 2,
STATUS_NOT_READY: 3,
// UA error codes
CONFIGURATION_ERROR: 1,
NETWORK_ERROR: 2
};
/**
* Expose C object.
*/
UA.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:UA');
var debugerror = require('debug')('JsSIP:ERROR:UA');
debugerror.log = console.warn.bind(console);
var JsSIP_C = require('./Constants');
var Registrator = require('./Registrator');
var RTCSession = require('./RTCSession');
var Message = require('./Message');
var Transactions = require('./Transactions');
var Transport = require('./Transport');
var Socket = require('./Socket');
var Utils = require('./Utils');
var Exceptions = require('./Exceptions');
var URI = require('./URI');
var Grammar = require('./Grammar');
var Parser = require('./Parser');
var SIPMessage = require('./SIPMessage');
var sanityCheck = require('./sanityCheck');
/**
* The User-Agent class.
* @class JsSIP.UA
* @param {Object} configuration Configuration parameters.
* @throws {JsSIP.Exceptions.ConfigurationError} If a configuration parameter is invalid.
* @throws {TypeError} If no configuration is given.
*/
function UA(configuration) {
debug('new() [configuration:%o]', configuration);
this.cache = {
credentials: {}
};
this.configuration = {};
this.dynConfiguration = {};
this.dialogs = {};
//User actions outside any session/dialog (MESSAGE)
this.applicants = {};
this.sessions = {};
this.transport = null;
this.contact = null;
this.status = C.STATUS_INIT;
this.error = null;
this.transactions = {
nist: {},
nict: {},
ist: {},
ict: {}
};
// Custom UA empty object for high level use
this.data = {};
this.closeTimer = null;
Object.defineProperties(this, {
transactionsCount: {
get: function() {
var type,
transactions = ['nist','nict','ist','ict'],
count = 0;
for (type in transactions) {
count += Object.keys(this.transactions[transactions[type]]).length;
}
return count;
}
},
nictTransactionsCount: {
get: function() {
return Object.keys(this.transactions.nict).length;
}
},
nistTransactionsCount: {
get: function() {
return Object.keys(this.transactions.nist).length;
}
},
ictTransactionsCount: {
get: function() {
return Object.keys(this.transactions.ict).length;
}
},
istTransactionsCount: {
get: function() {
return Object.keys(this.transactions.ist).length;
}
}
});
/**
* Load configuration
*/
if(configuration === undefined) {
throw new TypeError('Not enough arguments');
}
try {
this.loadConfig(configuration);
} catch(e) {
this.status = C.STATUS_NOT_READY;
this.error = C.CONFIGURATION_ERROR;
throw e;
}
// Initialize registrator
this._registrator = new Registrator(this);
events.EventEmitter.call(this);
}
util.inherits(UA, events.EventEmitter);
//=================
// High Level API
//=================
/**
* Connect to the server if status = STATUS_INIT.
* Resume UA after being closed.
*/
UA.prototype.start = function() {
debug('start()');
if (this.status === C.STATUS_INIT) {
this.transport.connect();
} else if(this.status === C.STATUS_USER_CLOSED) {
debug('restarting UA');
// disconnect
if (this.closeTimer !== null) {
clearTimeout(this.closeTimer);
this.closeTimer = null;
this.transport.disconnect();
}
// reconnect
this.status = C.STATUS_INIT;
this.transport.connect();
} else if (this.status === C.STATUS_READY) {
debug('UA is in READY status, not restarted');
} else {
debug('ERROR: connection is down, Auto-Recovery system is trying to reconnect');
}
// Set dynamic configuration.
this.dynConfiguration.register = this.configuration.register;
};
/**
* Register.
*/
UA.prototype.register = function() {
debug('register()');
this.dynConfiguration.register = true;
this._registrator.register();
};
/**
* Unregister.
*/
UA.prototype.unregister = function(options) {
debug('unregister()');
this.dynConfiguration.register = false;
this._registrator.unregister(options);
};
/**
* Get the Registrator instance.
*/
UA.prototype.registrator = function() {
return this._registrator;
};
/**
* Registration state.
*/
UA.prototype.isRegistered = function() {
if(this._registrator.registered) {
return true;
} else {
return false;
}
};
/**
* Connection state.
*/
UA.prototype.isConnected = function() {
return this.transport.isConnected();
};
/**
* Make an outgoing call.
*
* -param {String} target
* -param {Object} views
* -param {Object} [options]
*
* -throws {TypeError}
*
*/
UA.prototype.call = function(target, options) {
debug('call()');
var session;
session = new RTCSession(this);
session.connect(target, options);
return session;
};
/**
* Send a message.
*
* -param {String} target
* -param {String} body
* -param {Object} [options]
*
* -throws {TypeError}
*
*/
UA.prototype.sendMessage = function(target, body, options) {
debug('sendMessage()');
var message;
message = new Message(this);
message.send(target, body, options);
return message;
};
/**
* Terminate ongoing sessions.
*/
UA.prototype.terminateSessions = function(options) {
debug('terminateSessions()');
for(var idx in this.sessions) {
if (!this.sessions[idx].isEnded()) {
this.sessions[idx].terminate(options);
}
}
};
/**
* Gracefully close.
*
*/
UA.prototype.stop = function() {
debug('stop()');
var session;
var applicant;
var num_sessions;
var ua = this;
// Remove dynamic settings.
this.dynConfiguration = {};
if(this.status === C.STATUS_USER_CLOSED) {
debug('UA already closed');
return;
}
// Close registrator
this._registrator.close();
// If there are session wait a bit so CANCEL/BYE can be sent and their responses received.
num_sessions = Object.keys(this.sessions).length;
// Run _terminate_ on every Session
for(session in this.sessions) {
debug('closing session ' + session);
try { this.sessions[session].terminate(); } catch(error) {}
}
// Run _close_ on every applicant
for(applicant in this.applicants) {
try { this.applicants[applicant].close(); } catch(error) {}
}
this.status = C.STATUS_USER_CLOSED;
if (this.nistTransactionsCount === 0 &&
this.nictTransactionsCount === 0 &&
this.ictTransactionsCount === 0 &&
this.istTransactionsCount === 0 &&
num_sessions === 0) {
ua.transport.disconnect();
}
else {
this.closeTimer = setTimeout(function() {
ua.closeTimer = null;
ua.transport.disconnect();
}, 2000);
}
};
/**
* Normalice a string into a valid SIP request URI
* -param {String} target
* -returns {JsSIP.URI|undefined}
*/
UA.prototype.normalizeTarget = function(target) {
return Utils.normalizeTarget(target, this.configuration.hostport_params);
};
/**
* Allow retrieving configuration and autogenerated fields in runtime.
*/
UA.prototype.get = function(parameter) {
switch(parameter) {
case 'realm':
return this.configuration.realm;
case 'ha1':
return this.configuration.ha1;
default:
debugerror('get() | cannot get "%s" parameter in runtime', parameter);
return undefined;
}
return true;
};
/**
* Allow configuration changes in runtime.
* Returns true if the parameter could be set.
*/
UA.prototype.set = function(parameter, value) {
switch(parameter) {
case 'password': {
this.configuration.password = String(value);
break;
}
case 'realm': {
this.configuration.realm = String(value);
break;
}
case 'ha1': {
this.configuration.ha1 = String(value);
// Delete the plain SIP password.
this.configuration.password = null;
break;
}
case 'display_name': {
if (Grammar.parse('"' + value + '"', 'display_name') === -1) {
debugerror('set() | wrong "display_name"');
return false;
}
this.configuration.display_name = value;
break;
}
default:
debugerror('set() | cannot set "%s" parameter in runtime', parameter);
return false;
}
return true;
};
//===============================
// Private (For internal use)
//===============================
// UA.prototype.saveCredentials = function(credentials) {
// this.cache.credentials[credentials.realm] = this.cache.credentials[credentials.realm] || {};
// this.cache.credentials[credentials.realm][credentials.uri] = credentials;
// };
// UA.prototype.getCredentials = function(request) {
// var realm, credentials;
// realm = request.ruri.host;
// if (this.cache.credentials[realm] && this.cache.credentials[realm][request.ruri]) {
// credentials = this.cache.credentials[realm][request.ruri];
// credentials.method = request.method;
// }
// return credentials;
// };
//==========================
// Event Handlers
//==========================
/**
* new Transaction
*/
UA.prototype.newTransaction = function(transaction) {
this.transactions[transaction.type][transaction.id] = transaction;
this.emit('newTransaction', {
transaction: transaction
});
};
/**
* Transaction destroyed.
*/
UA.prototype.destroyTransaction = function(transaction) {
delete this.transactions[transaction.type][transaction.id];
this.emit('transactionDestroyed', {
transaction: transaction
});
};
/**
* new Message
*/
UA.prototype.newMessage = function(data) {
this.emit('newMessage', data);
};
/**
* new RTCSession
*/
UA.prototype.newRTCSession = function(data) {
this.emit('newRTCSession', data);
};
/**
* Registered
*/
UA.prototype.registered = function(data) {
this.emit('registered', data);
};
/**
* Unregistered
*/
UA.prototype.unregistered = function(data) {
this.emit('unregistered', data);
};
/**
* Registration Failed
*/
UA.prototype.registrationFailed = function(data) {
this.emit('registrationFailed', data);
};
//=========================
// receiveRequest
//=========================
/**
* Request reception
*/
UA.prototype.receiveRequest = function(request) {
var dialog, session, message, replaces,
method = request.method;
// Check that request URI points to us
if(request.ruri.user !== this.configuration.uri.user && request.ruri.user !== this.contact.uri.user) {
debug('Request-URI does not point to us');
if (request.method !== JsSIP_C.ACK) {
request.reply_sl(404);
}
return;
}
// Check request URI scheme
if(request.ruri.scheme === JsSIP_C.SIPS) {
request.reply_sl(416);
return;
}
// Check transaction
if(Transactions.checkTransaction(this, request)) {
return;
}
// Create the server transaction
if(method === JsSIP_C.INVITE) {
new Transactions.InviteServerTransaction(request, this);
} else if(method !== JsSIP_C.ACK && method !== JsSIP_C.CANCEL) {
new Transactions.NonInviteServerTransaction(request, this);
}
/* RFC3261 12.2.2
* Requests that do not change in any way the state of a dialog may be
* received within a dialog (for example, an OPTIONS request).
* They are processed as if they had been received outside the dialog.
*/
if(method === JsSIP_C.OPTIONS) {
request.reply(200);
} else if (method === JsSIP_C.MESSAGE) {
if (this.listeners('newMessage').length === 0) {
request.reply(405);
return;
}
message = new Message(this);
message.init_incoming(request);
} else if (method === JsSIP_C.INVITE) {
// Initial INVITE
if(!request.to_tag && this.listeners('newRTCSession').length === 0) {
request.reply(405);
return;
}
}
// Initial Request
if(!request.to_tag) {
switch(method) {
case JsSIP_C.INVITE:
if (window.RTCPeerConnection) { // TODO
if (request.hasHeader('replaces')) {
replaces = request.replaces;
dialog = this.findDialog(replaces.call_id, replaces.from_tag, replaces.to_tag);
if (dialog) {
session = dialog.owner;
if (!session.isEnded()) {
session.receiveRequest(request);
} else {
request.reply(603);
}
} else {
request.reply(481);
}
} else {
session = new RTCSession(this);
session.init_incoming(request);
}
} else {
debugerror('INVITE received but WebRTC is not supported');
request.reply(488);
}
break;
case JsSIP_C.BYE:
// Out of dialog BYE received
request.reply(481);
break;
case JsSIP_C.CANCEL:
session = this.findSession(request);
if (session) {
session.receiveRequest(request);
} else {
debug('received CANCEL request for a non existent session');
}
break;
case JsSIP_C.ACK:
/* Absorb it.
* ACK request without a corresponding Invite Transaction
* and without To tag.
*/
break;
default:
request.reply(405);
break;
}
}
// In-dialog request
else {
dialog = this.findDialog(request.call_id, request.from_tag, request.to_tag);
if(dialog) {
dialog.receiveRequest(request);
} else if (method === JsSIP_C.NOTIFY) {
session = this.findSession(request);
if(session) {
session.receiveRequest(request);
} else {
debug('received NOTIFY request for a non existent subscription');
request.reply(481, 'Subscription does not exist');
}
}
/* RFC3261 12.2.2
* Request with to tag, but no matching dialog found.
* Exception: ACK for an Invite request for which a dialog has not
* been created.
*/
else {
if(method !== JsSIP_C.ACK) {
request.reply(481);
}
}
}
};
//=================
// Utils
//=================
/**
* Get the session to which the request belongs to, if any.
*/
UA.prototype.findSession = function(request) {
var
sessionIDa = request.call_id + request.from_tag,
sessionA = this.sessions[sessionIDa],
sessionIDb = request.call_id + request.to_tag,
sessionB = this.sessions[sessionIDb];
if(sessionA) {
return sessionA;
} else if(sessionB) {
return sessionB;
} else {
return null;
}
};
/**
* Get the dialog to which the request belongs to, if any.
*/
UA.prototype.findDialog = function(call_id, from_tag, to_tag) {
var
id = call_id + from_tag + to_tag,
dialog = this.dialogs[id];
if(dialog) {
return dialog;
} else {
id = call_id + to_tag + from_tag;
dialog = this.dialogs[id];
if(dialog) {
return dialog;
} else {
return null;
}
}
};
UA.prototype.loadConfig = function(configuration) {
// Settings and default values
var parameter, value, checked_value, hostport_params, registrar_server,
settings = {
/* Host address
* Value to be set in Via sent_by and host part of Contact FQDN
*/
via_host: Utils.createRandomToken(12) + '.invalid',
// SIP Contact URI
contact_uri: null,
// SIP authentication password
password: null,
// SIP authentication realm
realm: null,
// SIP authentication HA1 hash
ha1: null,
// Registration parameters
register_expires: 600,
register: true,
registrar_server: null,
use_preloaded_route: false,
// Session parameters
no_answer_timeout: 60,
session_timers: true,
};
// Pre-Configuration
// Check Mandatory parameters
for(parameter in UA.configuration_check.mandatory) {
if(!configuration.hasOwnProperty(parameter)) {
throw new Exceptions.ConfigurationError(parameter);
} else {
value = configuration[parameter];
checked_value = UA.configuration_check.mandatory[parameter].call(this, value);
if (checked_value !== undefined) {
settings[parameter] = checked_value;
} else {
throw new Exceptions.ConfigurationError(parameter, value);
}
}
}
// Check Optional parameters
for(parameter in UA.configuration_check.optional) {
if(configuration.hasOwnProperty(parameter)) {
value = configuration[parameter];
/* If the parameter value is null, empty string, undefined, empty array
* or it's a number with NaN value, then apply its default value.
*/
if (Utils.isEmpty(value)) {
continue;
}
checked_value = UA.configuration_check.optional[parameter].call(this, value, configuration);
if (checked_value !== undefined) {
settings[parameter] = checked_value;
} else {
throw new Exceptions.ConfigurationError(parameter, value);
}
}
}
// Post Configuration Process
// Allow passing 0 number as display_name.
if (settings.display_name === 0) {
settings.display_name = '0';
}
// Instance-id for GRUU.
if (!settings.instance_id) {
settings.instance_id = Utils.newUUID();
}
// jssip_id instance parameter. Static random tag of length 5.
settings.jssip_id = Utils.createRandomToken(5);
// String containing settings.uri without scheme and user.
hostport_params = settings.uri.clone();
hostport_params.user = null;
settings.hostport_params = hostport_params.toString().replace(/^sip:/i, '');
// Transport
var sockets = [];
if (settings.sockets && Array.isArray(settings.sockets)) {
sockets = sockets.concat(settings.sockets);
}
if (sockets.length === 0) {
throw new Exceptions.ConfigurationError('sockets');
}
try {
this.transport = new Transport(sockets, { /* recovery options */
max_interval: settings.connection_recovery_max_interval,
min_interval: settings.connection_recovery_min_interval
});
// Transport event callbacks
this.transport.onconnecting = onTransportConnecting.bind(this);
this.transport.onconnect = onTransportConnect.bind(this);
this.transport.ondisconnect = onTransportDisconnect.bind(this);
this.transport.ondata = onTransportData.bind(this);
// transport options not needed here anymore
delete settings.connection_recovery_max_interval;
delete settings.connection_recovery_min_interval;
delete settings.sockets;
} catch (e) {
debugerror(e);
throw new Exceptions.ConfigurationError('sockets', sockets);
}
// Check whether authorization_user is explicitly defined.
// Take 'settings.uri.user' value if not.
if (!settings.authorization_user) {
settings.authorization_user = settings.uri.user;
}
// If no 'registrar_server' is set use the 'uri' value without user portion and
// without URI params/headers.
if (!settings.registrar_server) {
registrar_server = settings.uri.clone();
registrar_server.user = null;
registrar_server.clearParams();
registrar_server.clearHeaders();
settings.registrar_server = registrar_server;
}
// User no_answer_timeout.
settings.no_answer_timeout = settings.no_answer_timeout * 1000;
// Via Host
if (settings.contact_uri) {
settings.via_host = settings.contact_uri.host;
}
// Contact URI
else {
settings.contact_uri = new URI('sip', Utils.createRandomToken(8), settings.via_host, null, {transport: 'ws'});
}
this.contact = {
pub_gruu: null,
temp_gruu: null,
uri: settings.contact_uri,
toString: function(options) {
options = options || {};
var
anonymous = options.anonymous || null,
outbound = options.outbound || null,
contact = '<';
if (anonymous) {
contact += this.temp_gruu || 'sip:[email protected];transport=ws';
} else {
contact += this.pub_gruu || this.uri.toString();
}
if (outbound && (anonymous ? !this.temp_gruu : !this.pub_gruu)) {
contact += ';ob';
}
contact += '>';
return contact;
}
};
// Fill the value of the configuration_skeleton
for(parameter in settings) {
UA.configuration_skeleton[parameter].value = settings[parameter];
}
Object.defineProperties(this.configuration, UA.configuration_skeleton);
// Clean UA.configuration_skeleton
for(parameter in settings) {
UA.configuration_skeleton[parameter].value = '';
}
debug('configuration parameters after validation:');
for(parameter in settings) {
switch(parameter) {
case 'uri':
case 'registrar_server':
debug('- ' + parameter + ': ' + settings[parameter]);
break;
case 'password':
case 'ha1':
debug('- ' + parameter + ': ' + 'NOT SHOWN');
break;
default:
debug('- ' + parameter + ': ' + JSON.stringify(settings[parameter]));
}
}
return;
};
/**
* Configuration Object skeleton.
*/
UA.configuration_skeleton = (function() {
var
idx, parameter, writable,
skeleton = {},
parameters = [
// Internal parameters
'jssip_id',
'hostport_params',
// Mandatory user configurable parameters
'uri',
// Optional user configurable parameters
'authorization_user',
'contact_uri',
'display_name',
'instance_id',
'no_answer_timeout', // 30 seconds
'session_timers', // true
'password',
'realm',
'ha1',
'register_expires', // 600 seconds
'registrar_server',
'sockets',
'use_preloaded_route',
// Post-configuration generated parameters
'via_core_value',
'via_host'
];
var writable_parameters = [
'password', 'realm', 'ha1', 'display_name'
];
for(idx in parameters) {
parameter = parameters[idx];
if (writable_parameters.indexOf(parameter) !== -1) {
writable = true;
} else {
writable = false;
}
skeleton[parameter] = {
value: '',
writable: writable,
configurable: false
};
}
skeleton.register = {
value: '',
writable: true,
configurable: false
};
return skeleton;
}());
/**
* Configuration checker.
*/
UA.configuration_check = {
mandatory: {
uri: function(uri) {
var parsed;
if (!/^sip:/i.test(uri)) {
uri = JsSIP_C.SIP + ':' + uri;
}
parsed = URI.parse(uri);
if(!parsed) {
return;
} else if(!parsed.user) {
return;
} else {
return parsed;
}
}
},
optional: {
authorization_user: function(authorization_user) {
if(Grammar.parse('"'+ authorization_user +'"', 'quoted_string') === -1) {
return;
} else {
return authorization_user;
}
},
connection_recovery_max_interval: function(connection_recovery_max_interval) {
var value;
if(Utils.isDecimal(connection_recovery_max_interval)) {
value = Number(connection_recovery_max_interval);
if(value > 0) {
return value;
}
}
},
connection_recovery_min_interval: function(connection_recovery_min_interval) {
var value;
if(Utils.isDecimal(connection_recovery_min_interval)) {
value = Number(connection_recovery_min_interval);
if(value > 0) {
return value;
}
}
},
contact_uri: function(contact_uri) {
if (typeof contact_uri === 'string') {
var uri = Grammar.parse(contact_uri,'SIP_URI');
if (uri !== -1) {
return uri;
}
}
},
display_name: function(display_name) {
if (Grammar.parse('"' + display_name + '"', 'display_name') === -1) {
return;
} else {
return display_name;
}
},
instance_id: function(instance_id) {
if ((/^uuid:/i.test(instance_id))) {
instance_id = instance_id.substr(5);
}
if(Grammar.parse(instance_id, 'uuid') === -1) {
return;
} else {
return instance_id;
}
},
no_answer_timeout: function(no_answer_timeout) {
var value;
if (Utils.isDecimal(no_answer_timeout)) {
value = Number(no_answer_timeout);
if (value > 0) {
return value;
}
}
},
session_timers: function(session_timers) {
if (typeof session_timers === 'boolean') {
return session_timers;
}
},
password: function(password) {
return String(password);
},
realm: function(realm) {
return String(realm);
},
ha1: function(ha1) {
return String(ha1);
},
register: function(register) {
if (typeof register === 'boolean') {
return register;
}
},
register_expires: function(register_expires) {
var value;
if (Utils.isDecimal(register_expires)) {
value = Number(register_expires);
if (value > 0) {
return value;
}
}
},
registrar_server: function(registrar_server) {
var parsed;
if (!/^sip:/i.test(registrar_server)) {
registrar_server = JsSIP_C.SIP + ':' + registrar_server;
}
parsed = URI.parse(registrar_server);
if(!parsed) {
return;
} else if(parsed.user) {
return;
} else {
return parsed;
}
},
sockets: function(sockets) {
var idx, length;
/* Allow defining sockets parameter as:
* Socket: socket
* Array of Socket: [socket1, socket2]
* Array of Objects: [{socket: socket1, weight:1}, {socket: Socket2, weight:0}]
* Array of Objects and Socket: [{socket: socket1}, socket2]
*/
if (Socket.isSocket(sockets)) {
sockets = [{socket: sockets}];
} else if (Array.isArray(sockets) && sockets.length) {
length = sockets.length;
for (idx = 0; idx < length; idx++) {
if (Socket.isSocket(sockets[idx])) {
sockets[idx] = {socket: sockets[idx]};
}
}
} else {
return;
}
return sockets;
},
use_preloaded_route: function(use_preloaded_route) {
if (typeof use_preloaded_route === 'boolean') {
return use_preloaded_route;
}
}
}
};
/**
* Transport event handlers
*/
// Transport connecting event
function onTransportConnecting(data) {
this.emit('connecting', data);
}
// Transport connected event.
function onTransportConnect(data) {
if(this.status === C.STATUS_USER_CLOSED) {
return;
}
this.status = C.STATUS_READY;
this.error = null;
this.emit('connected', data);
if(this.dynConfiguration.register) {
this._registrator.register();
}
}
// Transport disconnected event.
function onTransportDisconnect(data) {
// Run _onTransportError_ callback on every client transaction using _transport_
var type, idx, length,
client_transactions = ['nict', 'ict', 'nist', 'ist'];
length = client_transactions.length;
for (type = 0; type < length; type++) {
for(idx in this.transactions[client_transactions[type]]) {
this.transactions[client_transactions[type]][idx].onTransportError();
}
}
this.emit('disconnected', data);
// Call registrator _onTransportClosed_
this._registrator.onTransportClosed();
if (this.status !== C.STATUS_USER_CLOSED) {
this.status = C.STATUS_NOT_READY;
this.error = C.NETWORK_ERROR;
}
}
// Transport data event
function onTransportData(data) {
var transaction,
transport = data.transport,
message = data.message;
message = Parser.parseMessage(message, this);
if (! message) {
return;
}
if (this.status === UA.C.STATUS_USER_CLOSED &&
message instanceof SIPMessage.IncomingRequest) {
return;
}
// Do some sanity check
if(! sanityCheck(message, this, transport)) {
return;
}
if(message instanceof SIPMessage.IncomingRequest) {
message.transport = transport;
this.receiveRequest(message);
} else if(message instanceof SIPMessage.IncomingResponse) {
/* Unike stated in 18.1.2, if a response does not match
* any transaction, it is discarded here and no passed to the core
* in order to be discarded there.
*/
switch(message.method) {
case JsSIP_C.INVITE:
transaction = this.transactions.ict[message.via_branch];
if(transaction) {
transaction.receiveResponse(message);
}
break;
case JsSIP_C.ACK:
// Just in case ;-)
break;
default:
transaction = this.transactions.nict[message.via_branch];
if(transaction) {
transaction.receiveResponse(message);
}
break;
}
}
}
},{"./Constants":1,"./Exceptions":5,"./Grammar":6,"./Message":8,"./Parser":10,"./RTCSession":11,"./Registrator":16,"./SIPMessage":18,"./Socket":19,"./Transactions":21,"./Transport":22,"./URI":24,"./Utils":25,"./sanityCheck":27,"debug":34,"events":28,"util":32}],24:[function(require,module,exports){
module.exports = URI;
/**
* Dependencies.
*/
var JsSIP_C = require('./Constants');
var Utils = require('./Utils');
var Grammar = require('./Grammar');
/**
* -param {String} [scheme]
* -param {String} [user]
* -param {String} host
* -param {String} [port]
* -param {Object} [parameters]
* -param {Object} [headers]
*
*/
function URI(scheme, user, host, port, parameters, headers) {
var param, header;
// Checks
if(!host) {
throw new TypeError('missing or invalid "host" parameter');
}
// Initialize parameters
scheme = scheme || JsSIP_C.SIP;
this.parameters = {};
this.headers = {};
for (param in parameters) {
this.setParam(param, parameters[param]);
}
for (header in headers) {
this.setHeader(header, headers[header]);
}
Object.defineProperties(this, {
scheme: {
get: function(){ return scheme; },
set: function(value){
scheme = value.toLowerCase();
}
},
user: {
get: function(){ return user; },
set: function(value){
user = value;
}
},
host: {
get: function(){ return host; },
set: function(value){
host = value.toLowerCase();
}
},
port: {
get: function(){ return port; },
set: function(value){
port = value === 0 ? value : (parseInt(value,10) || null);
}
}
});
}
URI.prototype = {
setParam: function(key, value) {
if(key) {
this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString();
}
},
getParam: function(key) {
if(key) {
return this.parameters[key.toLowerCase()];
}
},
hasParam: function(key) {
if(key) {
return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false;
}
},
deleteParam: function(parameter) {
var value;
parameter = parameter.toLowerCase();
if (this.parameters.hasOwnProperty(parameter)) {
value = this.parameters[parameter];
delete this.parameters[parameter];
return value;
}
},
clearParams: function() {
this.parameters = {};
},
setHeader: function(name, value) {
this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value];
},
getHeader: function(name) {
if(name) {
return this.headers[Utils.headerize(name)];
}
},
hasHeader: function(name) {
if(name) {
return (this.headers.hasOwnProperty(Utils.headerize(name)) && true) || false;
}
},
deleteHeader: function(header) {
var value;
header = Utils.headerize(header);
if(this.headers.hasOwnProperty(header)) {
value = this.headers[header];
delete this.headers[header];
return value;
}
},
clearHeaders: function() {
this.headers = {};
},
clone: function() {
return new URI(
this.scheme,
this.user,
this.host,
this.port,
JSON.parse(JSON.stringify(this.parameters)),
JSON.parse(JSON.stringify(this.headers)));
},
toString: function(){
var header, parameter, idx, uri,
headers = [];
uri = this.scheme + ':';
if (this.user) {
uri += Utils.escapeUser(this.user) + '@';
}
uri += this.host;
if (this.port || this.port === 0) {
uri += ':' + this.port;
}
for (parameter in this.parameters) {
uri += ';' + parameter;
if (this.parameters[parameter] !== null) {
uri += '='+ this.parameters[parameter];
}
}
for(header in this.headers) {
for(idx = 0; idx < this.headers[header].length; idx++) {
headers.push(header + '=' + this.headers[header][idx]);
}
}
if (headers.length > 0) {
uri += '?' + headers.join('&');
}
return uri;
},
toAor: function(show_port){
var aor;
aor = this.scheme + ':';
if (this.user) {
aor += Utils.escapeUser(this.user) + '@';
}
aor += this.host;
if (show_port && (this.port || this.port === 0)) {
aor += ':' + this.port;
}
return aor;
}
};
/**
* Parse the given string and returns a JsSIP.URI instance or undefined if
* it is an invalid URI.
*/
URI.parse = function(uri) {
uri = Grammar.parse(uri,'SIP_URI');
if (uri !== -1) {
return uri;
} else {
return undefined;
}
};
},{"./Constants":1,"./Grammar":6,"./Utils":25}],25:[function(require,module,exports){
var Utils = {};
module.exports = Utils;
/**
* Dependencies.
*/
var JsSIP_C = require('./Constants');
var URI = require('./URI');
var Grammar = require('./Grammar');
Utils.str_utf8_length = function(string) {
return unescape(encodeURIComponent(string)).length;
};
Utils.isFunction = function(fn) {
if (fn !== undefined) {
return (Object.prototype.toString.call(fn) === '[object Function]')? true : false;
} else {
return false;
}
};
Utils.isString = function(str) {
if (str !== undefined) {
return (Object.prototype.toString.call(str) === '[object String]')? true : false;
} else {
return false;
}
};
Utils.isDecimal = function(num) {
return !isNaN(num) && (parseFloat(num) === parseInt(num,10));
};
Utils.isEmpty = function(value) {
if (value === null || value === '' || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof(value) === 'number' && isNaN(value))) {
return true;
}
};
Utils.hasMethods = function(obj /*, method list as strings */){
var i = 1, methodName;
while((methodName = arguments[i++])){
if(this.isFunction(obj[methodName])) {
return false;
}
}
return true;
};
Utils.createRandomToken = function(size, base) {
var i, r,
token = '';
base = base || 32;
for( i=0; i < size; i++ ) {
r = Math.random() * base|0;
token += r.toString(base);
}
return token;
};
Utils.newTag = function() {
return Utils.createRandomToken(10);
};
// http://stackoverflow.com/users/109538/broofa
Utils.newUUID = function() {
var UUID = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
return UUID;
};
Utils.hostType = function(host) {
if (!host) {
return;
} else {
host = Grammar.parse(host,'host');
if (host !== -1) {
return host.host_type;
}
}
};
/**
* Normalize SIP URI.
* NOTE: It does not allow a SIP URI without username.
* Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'.
* Detects the domain part (if given) and properly hex-escapes the user portion.
* If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators.
*/
Utils.normalizeTarget = function(target, domain) {
var uri, target_array, target_user, target_domain;
// If no target is given then raise an error.
if (!target) {
return;
// If a URI instance is given then return it.
} else if (target instanceof URI) {
return target;
// If a string is given split it by '@':
// - Last fragment is the desired domain.
// - Otherwise append the given domain argument.
} else if (typeof target === 'string') {
target_array = target.split('@');
switch(target_array.length) {
case 1:
if (!domain) {
return;
}
target_user = target;
target_domain = domain;
break;
case 2:
target_user = target_array[0];
target_domain = target_array[1];
break;
default:
target_user = target_array.slice(0, target_array.length-1).join('@');
target_domain = target_array[target_array.length-1];
}
// Remove the URI scheme (if present).
target_user = target_user.replace(/^(sips?|tel):/i, '');
// Remove 'tel' visual separators if the user portion just contains 'tel' number symbols.
if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(target_user)) {
target_user = target_user.replace(/[\-\.\(\)]/g, '');
}
// Build the complete SIP URI.
target = JsSIP_C.SIP + ':' + Utils.escapeUser(target_user) + '@' + target_domain;
// Finally parse the resulting URI.
if ((uri = URI.parse(target))) {
return uri;
} else {
return;
}
} else {
return;
}
};
/**
* Hex-escape a SIP URI user.
*/
Utils.escapeUser = function(user) {
// Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F).
return encodeURIComponent(decodeURIComponent(user)).replace(/%3A/ig, ':').replace(/%2B/ig, '+').replace(/%3F/ig, '?').replace(/%2F/ig, '/');
};
Utils.headerize = function(string) {
var exceptions = {
'Call-Id': 'Call-ID',
'Cseq': 'CSeq',
'Www-Authenticate': 'WWW-Authenticate'
},
name = string.toLowerCase().replace(/_/g,'-').split('-'),
hname = '',
parts = name.length, part;
for (part = 0; part < parts; part++) {
if (part !== 0) {
hname +='-';
}
hname += name[part].charAt(0).toUpperCase()+name[part].substring(1);
}
if (exceptions[hname]) {
hname = exceptions[hname];
}
return hname;
};
Utils.sipErrorCause = function(status_code) {
var cause;
for (cause in JsSIP_C.SIP_ERROR_CAUSES) {
if (JsSIP_C.SIP_ERROR_CAUSES[cause].indexOf(status_code) !== -1) {
return JsSIP_C.causes[cause];
}
}
return JsSIP_C.causes.SIP_FAILURE_CODE;
};
/**
* Generate a random Test-Net IP (http://tools.ietf.org/html/rfc5735)
*/
Utils.getRandomTestNetIP = function() {
function getOctet(from,to) {
return Math.floor(Math.random()*(to-from+1)+from);
}
return '192.0.2.' + getOctet(1, 254);
};
// MD5 (Message-Digest Algorithm) http://www.webtoolkit.info
Utils.calculateMD5 = function(string) {
function rotateLeft(lValue, iShiftBits) {
return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
}
function addUnsigned(lX,lY) {
var lX4,lY4,lX8,lY8,lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function doF(x,y,z) {
return (x & y) | ((~x) & z);
}
function doG(x,y,z) {
return (x & z) | (y & (~z));
}
function doH(x,y,z) {
return (x ^ y ^ z);
}
function doI(x,y,z) {
return (y ^ (x | (~z)));
}
function doFF(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doF(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function doGG(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doG(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function doHH(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doH(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function doII(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doI(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function convertToWordArray(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1=lMessageLength + 8;
var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
var lWordArray = new Array(lNumberOfWords-1);
var lBytePosition = 0;
var lByteCount = 0;
while ( lByteCount < lMessageLength ) {
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
lWordArray[lNumberOfWords-2] = lMessageLength<<3;
lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
return lWordArray;
}
function wordToHex(lValue) {
var wordToHexValue='',wordToHexValue_temp='',lByte,lCount;
for (lCount = 0;lCount<=3;lCount++) {
lByte = (lValue>>>(lCount*8)) & 255;
wordToHexValue_temp = '0' + lByte.toString(16);
wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length-2,2);
}
return wordToHexValue;
}
function utf8Encode(string) {
string = string.replace(/\r\n/g, '\n');
var utftext = '';
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
var x=[];
var k,AA,BB,CC,DD,a,b,c,d;
var S11=7, S12=12, S13=17, S14=22;
var S21=5, S22=9 , S23=14, S24=20;
var S31=4, S32=11, S33=16, S34=23;
var S41=6, S42=10, S43=15, S44=21;
string = utf8Encode(string);
x = convertToWordArray(string);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k=0;k<x.length;k+=16) {
AA=a; BB=b; CC=c; DD=d;
a=doFF(a,b,c,d,x[k+0], S11,0xD76AA478);
d=doFF(d,a,b,c,x[k+1], S12,0xE8C7B756);
c=doFF(c,d,a,b,x[k+2], S13,0x242070DB);
b=doFF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
a=doFF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
d=doFF(d,a,b,c,x[k+5], S12,0x4787C62A);
c=doFF(c,d,a,b,x[k+6], S13,0xA8304613);
b=doFF(b,c,d,a,x[k+7], S14,0xFD469501);
a=doFF(a,b,c,d,x[k+8], S11,0x698098D8);
d=doFF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
c=doFF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
b=doFF(b,c,d,a,x[k+11],S14,0x895CD7BE);
a=doFF(a,b,c,d,x[k+12],S11,0x6B901122);
d=doFF(d,a,b,c,x[k+13],S12,0xFD987193);
c=doFF(c,d,a,b,x[k+14],S13,0xA679438E);
b=doFF(b,c,d,a,x[k+15],S14,0x49B40821);
a=doGG(a,b,c,d,x[k+1], S21,0xF61E2562);
d=doGG(d,a,b,c,x[k+6], S22,0xC040B340);
c=doGG(c,d,a,b,x[k+11],S23,0x265E5A51);
b=doGG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
a=doGG(a,b,c,d,x[k+5], S21,0xD62F105D);
d=doGG(d,a,b,c,x[k+10],S22,0x2441453);
c=doGG(c,d,a,b,x[k+15],S23,0xD8A1E681);
b=doGG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
a=doGG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
d=doGG(d,a,b,c,x[k+14],S22,0xC33707D6);
c=doGG(c,d,a,b,x[k+3], S23,0xF4D50D87);
b=doGG(b,c,d,a,x[k+8], S24,0x455A14ED);
a=doGG(a,b,c,d,x[k+13],S21,0xA9E3E905);
d=doGG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
c=doGG(c,d,a,b,x[k+7], S23,0x676F02D9);
b=doGG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
a=doHH(a,b,c,d,x[k+5], S31,0xFFFA3942);
d=doHH(d,a,b,c,x[k+8], S32,0x8771F681);
c=doHH(c,d,a,b,x[k+11],S33,0x6D9D6122);
b=doHH(b,c,d,a,x[k+14],S34,0xFDE5380C);
a=doHH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
d=doHH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
c=doHH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
b=doHH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
a=doHH(a,b,c,d,x[k+13],S31,0x289B7EC6);
d=doHH(d,a,b,c,x[k+0], S32,0xEAA127FA);
c=doHH(c,d,a,b,x[k+3], S33,0xD4EF3085);
b=doHH(b,c,d,a,x[k+6], S34,0x4881D05);
a=doHH(a,b,c,d,x[k+9], S31,0xD9D4D039);
d=doHH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
c=doHH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
b=doHH(b,c,d,a,x[k+2], S34,0xC4AC5665);
a=doII(a,b,c,d,x[k+0], S41,0xF4292244);
d=doII(d,a,b,c,x[k+7], S42,0x432AFF97);
c=doII(c,d,a,b,x[k+14],S43,0xAB9423A7);
b=doII(b,c,d,a,x[k+5], S44,0xFC93A039);
a=doII(a,b,c,d,x[k+12],S41,0x655B59C3);
d=doII(d,a,b,c,x[k+3], S42,0x8F0CCC92);
c=doII(c,d,a,b,x[k+10],S43,0xFFEFF47D);
b=doII(b,c,d,a,x[k+1], S44,0x85845DD1);
a=doII(a,b,c,d,x[k+8], S41,0x6FA87E4F);
d=doII(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
c=doII(c,d,a,b,x[k+6], S43,0xA3014314);
b=doII(b,c,d,a,x[k+13],S44,0x4E0811A1);
a=doII(a,b,c,d,x[k+4], S41,0xF7537E82);
d=doII(d,a,b,c,x[k+11],S42,0xBD3AF235);
c=doII(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
b=doII(b,c,d,a,x[k+9], S44,0xEB86D391);
a=addUnsigned(a,AA);
b=addUnsigned(b,BB);
c=addUnsigned(c,CC);
d=addUnsigned(d,DD);
}
var temp = wordToHex(a)+wordToHex(b)+wordToHex(c)+wordToHex(d);
return temp.toLowerCase();
};
Utils.closeMediaStream = function(stream) {
if (!stream) {
return;
}
// Latest spec states that MediaStream has no stop() method and instead must
// call stop() on every MediaStreamTrack.
try {
var tracks, i, len;
if (stream.getTracks) {
tracks = stream.getTracks();
for (i = 0, len = tracks.length; i < len; i += 1) {
tracks[i].stop();
}
} else {
tracks = stream.getAudioTracks();
for (i = 0, len = tracks.length; i < len; i += 1) {
tracks[i].stop();
}
tracks = stream.getVideoTracks();
for (i = 0, len = tracks.length; i < len; i += 1) {
tracks[i].stop();
}
}
} catch (error) {
// Deprecated by the spec, but still in use.
// NOTE: In Temasys IE plugin stream.stop is a callable 'object'.
if (typeof stream.stop === 'function' || typeof stream.stop === 'object') {
stream.stop();
}
}
};
},{"./Constants":1,"./Grammar":6,"./URI":24}],26:[function(require,module,exports){
module.exports = WebSocketInterface;
/**
* Dependencies.
*/
var Grammar = require('./Grammar');
var debug = require('debug')('JsSIP:WebSocketInterface');
var debugerror = require('debug')('JsSIP:ERROR:WebSocketInterface');
debugerror.log = console.warn.bind(console);
function WebSocketInterface(url) {
debug('new() [url:"%s"]', url);
var sip_uri = null;
var via_transport = null;
this.ws = null;
// setting the 'scheme' alters the sip_uri too (used in SIP Route header field)
Object.defineProperties(this, {
via_transport: {
get: function() { return via_transport; },
set: function(transport) {
via_transport = transport.toUpperCase();
}
},
sip_uri: { get: function() { return sip_uri; }},
url: { get: function() { return url; }}
});
var parsed_url = Grammar.parse(url, 'absoluteURI');
if (parsed_url === -1) {
debugerror('invalid WebSocket URI: ' + url);
throw new TypeError('Invalid argument: ' + url);
} else if(parsed_url.scheme !== 'wss' && parsed_url.scheme !== 'ws') {
debugerror('invalid WebSocket URI scheme: ' + parsed_url.scheme);
throw new TypeError('Invalid argument: ' + url);
} else {
sip_uri = 'sip:' + parsed_url.host +
(parsed_url.port ? ':' + parsed_url.port : '') + ';transport=ws';
this.via_transport = parsed_url.scheme;
}
}
WebSocketInterface.prototype.connect = function () {
debug('connect()');
if (this.isConnected()) {
debug('WebSocket ' + this.url + ' is already connected');
return;
} else if (this.isConnecting()) {
debug('WebSocket ' + this.url + ' is connecting');
return;
}
if (this.ws) {
this.disconnect();
}
debug('connecting to WebSocket ' + this.url);
try {
this.ws = new WebSocket(this.url, 'sip');
this.ws.binaryType = 'arraybuffer';
this.ws.onopen = onOpen.bind(this);
this.ws.onclose = onClose.bind(this);
this.ws.onmessage = onMessage.bind(this);
this.ws.onerror = onError.bind(this);
} catch(e) {
onError.call(this, e);
}
};
WebSocketInterface.prototype.disconnect = function() {
debug('disconnect()');
if (this.ws) {
// unbind websocket event callbacks
this.ws.onopen = function() {};
this.ws.onclose = function() {};
this.ws.onmessage = function() {};
this.ws.onerror = function() {};
this.ws.close();
this.ws = null;
}
};
WebSocketInterface.prototype.send = function(message) {
debug('send()');
if (this.isConnected()) {
this.ws.send(message);
return true;
} else {
debugerror('unable to send message, WebSocket is not open');
return false;
}
};
WebSocketInterface.prototype.isConnected = function() {
return this.ws && this.ws.readyState === this.ws.OPEN;
};
WebSocketInterface.prototype.isConnecting = function() {
return this.ws && this.ws.readyState === this.ws.CONNECTING;
};
/**
* WebSocket Event Handlers
*/
function onOpen() {
debug('WebSocket ' + this.url + ' connected');
this.onconnect();
}
function onClose(e) {
debug('WebSocket ' + this.url + ' closed');
if (e.wasClean === false) {
debug('WebSocket abrupt disconnection');
}
this.ondisconnect(e.wasClean, e.code, e.reason);
}
function onMessage(e) {
debug('received WebSocket message');
this.ondata(e.data);
}
function onError(e) {
debugerror('WebSocket ' + this.url + ' error: '+ e);
}
},{"./Grammar":6,"debug":34}],27:[function(require,module,exports){
module.exports = sanityCheck;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:sanityCheck');
var JsSIP_C = require('./Constants');
var SIPMessage = require('./SIPMessage');
var Utils = require('./Utils');
var message, ua, transport,
requests = [],
responses = [],
all = [];
requests.push(rfc3261_8_2_2_1);
requests.push(rfc3261_16_3_4);
requests.push(rfc3261_18_3_request);
requests.push(rfc3261_8_2_2_2);
responses.push(rfc3261_8_1_3_3);
responses.push(rfc3261_18_3_response);
all.push(minimumHeaders);
function sanityCheck(m, u, t) {
var len, pass;
message = m;
ua = u;
transport = t;
len = all.length;
while(len--) {
pass = all[len](message);
if(pass === false) {
return false;
}
}
if(message instanceof SIPMessage.IncomingRequest) {
len = requests.length;
while(len--) {
pass = requests[len](message);
if(pass === false) {
return false;
}
}
}
else if(message instanceof SIPMessage.IncomingResponse) {
len = responses.length;
while(len--) {
pass = responses[len](message);
if(pass === false) {
return false;
}
}
}
//Everything is OK
return true;
}
/*
* Sanity Check for incoming Messages
*
* Requests:
* - _rfc3261_8_2_2_1_ Receive a Request with a non supported URI scheme
* - _rfc3261_16_3_4_ Receive a Request already sent by us
* Does not look at via sent-by but at jssip_id, which is inserted as
* a prefix in all initial requests generated by the ua
* - _rfc3261_18_3_request_ Body Content-Length
* - _rfc3261_8_2_2_2_ Merged Requests
*
* Responses:
* - _rfc3261_8_1_3_3_ Multiple Via headers
* - _rfc3261_18_3_response_ Body Content-Length
*
* All:
* - Minimum headers in a SIP message
*/
// Sanity Check functions for requests
function rfc3261_8_2_2_1() {
if(message.s('to').uri.scheme !== 'sip') {
reply(416);
return false;
}
}
function rfc3261_16_3_4() {
if(!message.to_tag) {
if(message.call_id.substr(0, 5) === ua.configuration.jssip_id) {
reply(482);
return false;
}
}
}
function rfc3261_18_3_request() {
var len = Utils.str_utf8_length(message.body),
contentLength = message.getHeader('content-length');
if(len < contentLength) {
reply(400);
return false;
}
}
function rfc3261_8_2_2_2() {
var tr, idx,
fromTag = message.from_tag,
call_id = message.call_id,
cseq = message.cseq;
// Accept any in-dialog request.
if(message.to_tag) {
return;
}
// INVITE request.
if (message.method === JsSIP_C.INVITE) {
// If the branch matches the key of any IST then assume it is a retransmission
// and ignore the INVITE.
// TODO: we should reply the last response.
if (ua.transactions.ist[message.via_branch]) {
return false;
}
// Otherwise check whether it is a merged request.
else {
for(idx in ua.transactions.ist) {
tr = ua.transactions.ist[idx];
if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) {
reply(482);
return false;
}
}
}
}
// Non INVITE request.
else {
// If the branch matches the key of any NIST then assume it is a retransmission
// and ignore the request.
// TODO: we should reply the last response.
if (ua.transactions.nist[message.via_branch]) {
return false;
}
// Otherwise check whether it is a merged request.
else {
for(idx in ua.transactions.nist) {
tr = ua.transactions.nist[idx];
if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) {
reply(482);
return false;
}
}
}
}
}
// Sanity Check functions for responses
function rfc3261_8_1_3_3() {
if(message.getHeaders('via').length > 1) {
debug('more than one Via header field present in the response, dropping the response');
return false;
}
}
function rfc3261_18_3_response() {
var
len = Utils.str_utf8_length(message.body),
contentLength = message.getHeader('content-length');
if(len < contentLength) {
debug('message body length is lower than the value in Content-Length header field, dropping the response');
return false;
}
}
// Sanity Check functions for requests and responses
function minimumHeaders() {
var
mandatoryHeaders = ['from', 'to', 'call_id', 'cseq', 'via'],
idx = mandatoryHeaders.length;
while(idx--) {
if(!message.hasHeader(mandatoryHeaders[idx])) {
debug('missing mandatory header field : ' + mandatoryHeaders[idx] + ', dropping the response');
return false;
}
}
}
// Reply
function reply(status_code) {
var to,
response = 'SIP/2.0 ' + status_code + ' ' + JsSIP_C.REASON_PHRASE[status_code] + '\r\n',
vias = message.getHeaders('via'),
length = vias.length,
idx = 0;
for(idx; idx < length; idx++) {
response += 'Via: ' + vias[idx] + '\r\n';
}
to = message.getHeader('To');
if(!message.to_tag) {
to += ';tag=' + Utils.newTag();
}
response += 'To: ' + to + '\r\n';
response += 'From: ' + message.getHeader('From') + '\r\n';
response += 'Call-ID: ' + message.call_id + '\r\n';
response += 'CSeq: ' + message.cseq + ' ' + message.method + '\r\n';
response += '\r\n';
transport.send(response);
}
},{"./Constants":1,"./SIPMessage":18,"./Utils":25,"debug":34}],28:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],29:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],30:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],31:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],32:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":31,"_process":29,"inherits":30}],33:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000
var m = s * 60
var h = m * 60
var d = h * 24
var y = d * 365.25
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {}
var type = typeof val
if (type === 'string' && val.length > 0) {
return parse(val)
} else if (type === 'number' && isNaN(val) === false) {
return options.long ?
fmtLong(val) :
fmtShort(val)
}
throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))
}
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str)
if (str.length > 10000) {
return
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)
if (!match) {
return
}
var n = parseFloat(match[1])
var type = (match[2] || 'ms').toLowerCase()
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y
case 'days':
case 'day':
case 'd':
return n * d
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n
default:
return undefined
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd'
}
if (ms >= h) {
return Math.round(ms / h) + 'h'
}
if (ms >= m) {
return Math.round(ms / m) + 'm'
}
if (ms >= s) {
return Math.round(ms / s) + 's'
}
return ms + 'ms'
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms'
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name
}
return Math.ceil(ms / n) + ' ' + name + 's'
}
},{}],34:[function(require,module,exports){
(function (process){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit')
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
try {
return exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (typeof process !== 'undefined' && 'env' in process) {
return process.env.DEBUG;
}
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}
}).call(this,require('_process'))
},{"./debug":35,"_process":29}],35:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug.default = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"ms":33}],36:[function(require,module,exports){
var grammar = module.exports = {
v: [{
name: 'version',
reg: /^(\d*)$/
}],
o: [{ //o=- 20518 0 IN IP4 203.0.113.1
// NB: sessionId will be a String in most cases because it is huge
name: 'origin',
reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
format: "%s %s %d %s IP%d %s"
}],
// default parsing of these only (though some of these feel outdated)
s: [{ name: 'name' }],
i: [{ name: 'description' }],
u: [{ name: 'uri' }],
e: [{ name: 'email' }],
p: [{ name: 'phone' }],
z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
//k: [{}], // outdated thing ignored
t: [{ //t=0 0
name: 'timing',
reg: /^(\d*) (\d*)/,
names: ['start', 'stop'],
format: "%d %d"
}],
c: [{ //c=IN IP4 10.47.197.26
name: 'connection',
reg: /^IN IP(\d) (\S*)/,
names: ['version', 'ip'],
format: "IN IP%d %s"
}],
b: [{ //b=AS:4000
push: 'bandwidth',
reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
names: ['type', 'limit'],
format: "%s:%s"
}],
m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
// NB: special - pushes to session
// TODO: rtp/fmtp should be filtered by the payloads found here?
reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
names: ['type', 'port', 'protocol', 'payloads'],
format: "%s %d %s %s"
}],
a: [
{ //a=rtpmap:110 opus/48000/2
push: 'rtp',
reg: /^rtpmap:(\d*) ([\w\-\.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
names: ['payload', 'codec', 'rate', 'encoding'],
format: function (o) {
return (o.encoding) ?
"rtpmap:%d %s/%s/%s":
o.rate ?
"rtpmap:%d %s/%s":
"rtpmap:%d %s";
}
},
{
//a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
//a=fmtp:111 minptime=10; useinbandfec=1
push: 'fmtp',
reg: /^fmtp:(\d*) ([\S| ]*)/,
names: ['payload', 'config'],
format: "fmtp:%d %s"
},
{ //a=control:streamid=0
name: 'control',
reg: /^control:(.*)/,
format: "control:%s"
},
{ //a=rtcp:65179 IN IP4 193.84.77.194
name: 'rtcp',
reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
names: ['port', 'netType', 'ipVer', 'address'],
format: function (o) {
return (o.address != null) ?
"rtcp:%d %s IP%d %s":
"rtcp:%d";
}
},
{ //a=rtcp-fb:98 trr-int 100
push: 'rtcpFbTrrInt',
reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
names: ['payload', 'value'],
format: "rtcp-fb:%d trr-int %d"
},
{ //a=rtcp-fb:98 nack rpsi
push: 'rtcpFb',
reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
names: ['payload', 'type', 'subtype'],
format: function (o) {
return (o.subtype != null) ?
"rtcp-fb:%s %s %s":
"rtcp-fb:%s %s";
}
},
{ //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
//a=extmap:1/recvonly URI-gps-string
push: 'ext',
reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
names: ['value', 'uri', 'config'], // value may include "/direction" suffix
format: function (o) {
return (o.config != null) ?
"extmap:%s %s %s":
"extmap:%s %s";
}
},
{
//a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
push: 'crypto',
reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
names: ['id', 'suite', 'config', 'sessionConfig'],
format: function (o) {
return (o.sessionConfig != null) ?
"crypto:%d %s %s %s":
"crypto:%d %s %s";
}
},
{ //a=setup:actpass
name: 'setup',
reg: /^setup:(\w*)/,
format: "setup:%s"
},
{ //a=mid:1
name: 'mid',
reg: /^mid:([^\s]*)/,
format: "mid:%s"
},
{ //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
name: 'msid',
reg: /^msid:(.*)/,
format: "msid:%s"
},
{ //a=ptime:20
name: 'ptime',
reg: /^ptime:(\d*)/,
format: "ptime:%d"
},
{ //a=maxptime:60
name: 'maxptime',
reg: /^maxptime:(\d*)/,
format: "maxptime:%d"
},
{ //a=sendrecv
name: 'direction',
reg: /^(sendrecv|recvonly|sendonly|inactive)/
},
{ //a=ice-lite
name: 'icelite',
reg: /^(ice-lite)/
},
{ //a=ice-ufrag:F7gI
name: 'iceUfrag',
reg: /^ice-ufrag:(\S*)/,
format: "ice-ufrag:%s"
},
{ //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
name: 'icePwd',
reg: /^ice-pwd:(\S*)/,
format: "ice-pwd:%s"
},
{ //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
name: 'fingerprint',
reg: /^fingerprint:(\S*) (\S*)/,
names: ['type', 'hash'],
format: "fingerprint:%s %s"
},
{
//a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
//a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
//a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
//a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
//a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
push:'candidates',
reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
format: function (o) {
var str = "candidate:%s %d %s %d %s %d typ %s";
str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
// NB: candidate has three optional chunks, so %void middles one if it's missing
str += (o.tcptype != null) ? " tcptype %s" : "%v";
if (o.generation != null) {
str += " generation %d";
}
return str;
}
},
{ //a=end-of-candidates (keep after the candidates line for readability)
name: 'endOfCandidates',
reg: /^(end-of-candidates)/
},
{ //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
name: 'remoteCandidates',
reg: /^remote-candidates:(.*)/,
format: "remote-candidates:%s"
},
{ //a=ice-options:google-ice
name: 'iceOptions',
reg: /^ice-options:(\S*)/,
format: "ice-options:%s"
},
{ //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
push: "ssrcs",
reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
names: ['id', 'attribute', 'value'],
format: "ssrc:%d %s:%s"
},
{ //a=ssrc-group:FEC 1 2
push: "ssrcGroups",
reg: /^ssrc-group:(\w*) (.*)/,
names: ['semantics', 'ssrcs'],
format: "ssrc-group:%s %s"
},
{ //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
name: "msidSemantic",
reg: /^msid-semantic:\s?(\w*) (\S*)/,
names: ['semantic', 'token'],
format: "msid-semantic: %s %s" // space after ":" is not accidental
},
{ //a=group:BUNDLE audio video
push: 'groups',
reg: /^group:(\w*) (.*)/,
names: ['type', 'mids'],
format: "group:%s %s"
},
{ //a=rtcp-mux
name: 'rtcpMux',
reg: /^(rtcp-mux)/
},
{ //a=rtcp-rsize
name: 'rtcpRsize',
reg: /^(rtcp-rsize)/
},
{ //a=sctpmap:5000 webrtc-datachannel 1024
name: 'sctpmap',
reg: /^sctpmap:([\w_\/]*) (\S*)(?: (\S*))?/,
names: ['sctpmapNumber', 'app', 'maxMessageSize'],
format: function (o) {
return (o.maxMessageSize != null) ?
"sctpmap:%s %s %s" :
"sctpmap:%s %s";
}
},
{ // any a= that we don't understand is kepts verbatim on media.invalid
push: 'invalid',
names: ["value"]
}
]
};
// set sensible defaults to avoid polluting the grammar with boring details
Object.keys(grammar).forEach(function (key) {
var objs = grammar[key];
objs.forEach(function (obj) {
if (!obj.reg) {
obj.reg = /(.*)/;
}
if (!obj.format) {
obj.format = "%s";
}
});
});
},{}],37:[function(require,module,exports){
var parser = require('./parser');
var writer = require('./writer');
exports.write = writer;
exports.parse = parser.parse;
exports.parseFmtpConfig = parser.parseFmtpConfig;
exports.parsePayloads = parser.parsePayloads;
exports.parseRemoteCandidates = parser.parseRemoteCandidates;
},{"./parser":38,"./writer":39}],38:[function(require,module,exports){
var toIntIfInt = function (v) {
return String(Number(v)) === v ? Number(v) : v;
};
var attachProperties = function (match, location, names, rawName) {
if (rawName && !names) {
location[rawName] = toIntIfInt(match[1]);
}
else {
for (var i = 0; i < names.length; i += 1) {
if (match[i+1] != null) {
location[names[i]] = toIntIfInt(match[i+1]);
}
}
}
};
var parseReg = function (obj, location, content) {
var needsBlank = obj.name && obj.names;
if (obj.push && !location[obj.push]) {
location[obj.push] = [];
}
else if (needsBlank && !location[obj.name]) {
location[obj.name] = {};
}
var keyLocation = obj.push ?
{} : // blank object that will be pushed
needsBlank ? location[obj.name] : location; // otherwise, named location or root
attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
if (obj.push) {
location[obj.push].push(keyLocation);
}
};
var grammar = require('./grammar');
var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
exports.parse = function (sdp) {
var session = {}
, media = []
, location = session; // points at where properties go under (one of the above)
// parse lines we understand
sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
var type = l[0];
var content = l.slice(2);
if (type === 'm') {
media.push({rtp: [], fmtp: []});
location = media[media.length-1]; // point at latest media line
}
for (var j = 0; j < (grammar[type] || []).length; j += 1) {
var obj = grammar[type][j];
if (obj.reg.test(content)) {
return parseReg(obj, location, content);
}
}
});
session.media = media; // link it up
return session;
};
var fmtpReducer = function (acc, expr) {
var s = expr.split(/=(.+)/, 2);
if (s.length === 2) {
acc[s[0]] = toIntIfInt(s[1]);
}
return acc;
};
exports.parseFmtpConfig = function (str) {
return str.split(/\;\s?/).reduce(fmtpReducer, {});
};
exports.parsePayloads = function (str) {
return str.split(' ').map(Number);
};
exports.parseRemoteCandidates = function (str) {
var candidates = [];
var parts = str.split(' ').map(toIntIfInt);
for (var i = 0; i < parts.length; i += 3) {
candidates.push({
component: parts[i],
ip: parts[i + 1],
port: parts[i + 2]
});
}
return candidates;
};
},{"./grammar":36}],39:[function(require,module,exports){
var grammar = require('./grammar');
// customized util.format - discards excess arguments and can void middle ones
var formatRegExp = /%[sdv%]/g;
var format = function (formatStr) {
var i = 1;
var args = arguments;
var len = args.length;
return formatStr.replace(formatRegExp, function (x) {
if (i >= len) {
return x; // missing argument
}
var arg = args[i];
i += 1;
switch (x) {
case '%%':
return '%';
case '%s':
return String(arg);
case '%d':
return Number(arg);
case '%v':
return '';
}
});
// NB: we discard excess arguments - they are typically undefined from makeLine
};
var makeLine = function (type, obj, location) {
var str = obj.format instanceof Function ?
(obj.format(obj.push ? location : location[obj.name])) :
obj.format;
var args = [type + '=' + str];
if (obj.names) {
for (var i = 0; i < obj.names.length; i += 1) {
var n = obj.names[i];
if (obj.name) {
args.push(location[obj.name][n]);
}
else { // for mLine and push attributes
args.push(location[obj.names[i]]);
}
}
}
else {
args.push(location[obj.name]);
}
return format.apply(null, args);
};
// RFC specified order
// TODO: extend this with all the rest
var defaultOuterOrder = [
'v', 'o', 's', 'i',
'u', 'e', 'p', 'c',
'b', 't', 'r', 'z', 'a'
];
var defaultInnerOrder = ['i', 'c', 'b', 'a'];
module.exports = function (session, opts) {
opts = opts || {};
// ensure certain properties exist
if (session.version == null) {
session.version = 0; // "v=0" must be there (only defined version atm)
}
if (session.name == null) {
session.name = " "; // "s= " must be there if no meaningful name set
}
session.media.forEach(function (mLine) {
if (mLine.payloads == null) {
mLine.payloads = "";
}
});
var outerOrder = opts.outerOrder || defaultOuterOrder;
var innerOrder = opts.innerOrder || defaultInnerOrder;
var sdp = [];
// loop through outerOrder for matching properties on session
outerOrder.forEach(function (type) {
grammar[type].forEach(function (obj) {
if (obj.name in session && session[obj.name] != null) {
sdp.push(makeLine(type, obj, session));
}
else if (obj.push in session && session[obj.push] != null) {
session[obj.push].forEach(function (el) {
sdp.push(makeLine(type, obj, el));
});
}
});
});
// then for each media line, follow the innerOrder
session.media.forEach(function (mLine) {
sdp.push(makeLine('m', grammar.m[0], mLine));
innerOrder.forEach(function (type) {
grammar[type].forEach(function (obj) {
if (obj.name in mLine && mLine[obj.name] != null) {
sdp.push(makeLine(type, obj, mLine));
}
else if (obj.push in mLine && mLine[obj.push] != null) {
mLine[obj.push].forEach(function (el) {
sdp.push(makeLine(type, obj, el));
});
}
});
});
});
return sdp.join('\r\n') + '\r\n';
};
},{"./grammar":36}],40:[function(require,module,exports){
/* eslint-env node */
'use strict';
// SDP helpers.
var SDPUtils = {};
// Generate an alphanumeric identifier for cname or mids.
// TODO: use UUIDs instead? https://gist.github.com/jed/982883
SDPUtils.generateIdentifier = function() {
return Math.random().toString(36).substr(2, 10);
};
// The RTCP CNAME used by all peerconnections from the same JS.
SDPUtils.localCName = SDPUtils.generateIdentifier();
// Splits SDP into lines, dealing with both CRLF and LF.
SDPUtils.splitLines = function(blob) {
return blob.trim().split('\n').map(function(line) {
return line.trim();
});
};
// Splits SDP into sessionpart and mediasections. Ensures CRLF.
SDPUtils.splitSections = function(blob) {
var parts = blob.split('\nm=');
return parts.map(function(part, index) {
return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
});
};
// Returns lines that start with a certain prefix.
SDPUtils.matchPrefix = function(blob, prefix) {
return SDPUtils.splitLines(blob).filter(function(line) {
return line.indexOf(prefix) === 0;
});
};
// Parses an ICE candidate line. Sample input:
// candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
// rport 55996"
SDPUtils.parseCandidate = function(line) {
var parts;
// Parse both variants.
if (line.indexOf('a=candidate:') === 0) {
parts = line.substring(12).split(' ');
} else {
parts = line.substring(10).split(' ');
}
var candidate = {
foundation: parts[0],
component: parts[1],
protocol: parts[2].toLowerCase(),
priority: parseInt(parts[3], 10),
ip: parts[4],
port: parseInt(parts[5], 10),
// skip parts[6] == 'typ'
type: parts[7]
};
for (var i = 8; i < parts.length; i += 2) {
switch (parts[i]) {
case 'raddr':
candidate.relatedAddress = parts[i + 1];
break;
case 'rport':
candidate.relatedPort = parseInt(parts[i + 1], 10);
break;
case 'tcptype':
candidate.tcpType = parts[i + 1];
break;
default: // Unknown extensions are silently ignored.
break;
}
}
return candidate;
};
// Translates a candidate object into SDP candidate attribute.
SDPUtils.writeCandidate = function(candidate) {
var sdp = [];
sdp.push(candidate.foundation);
sdp.push(candidate.component);
sdp.push(candidate.protocol.toUpperCase());
sdp.push(candidate.priority);
sdp.push(candidate.ip);
sdp.push(candidate.port);
var type = candidate.type;
sdp.push('typ');
sdp.push(type);
if (type !== 'host' && candidate.relatedAddress &&
candidate.relatedPort) {
sdp.push('raddr');
sdp.push(candidate.relatedAddress); // was: relAddr
sdp.push('rport');
sdp.push(candidate.relatedPort); // was: relPort
}
if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
sdp.push('tcptype');
sdp.push(candidate.tcpType);
}
return 'candidate:' + sdp.join(' ');
};
// Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input:
// a=rtpmap:111 opus/48000/2
SDPUtils.parseRtpMap = function(line) {
var parts = line.substr(9).split(' ');
var parsed = {
payloadType: parseInt(parts.shift(), 10) // was: id
};
parts = parts[0].split('/');
parsed.name = parts[0];
parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
// was: channels
parsed.numChannels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
return parsed;
};
// Generate an a=rtpmap line from RTCRtpCodecCapability or
// RTCRtpCodecParameters.
SDPUtils.writeRtpMap = function(codec) {
var pt = codec.payloadType;
if (codec.preferredPayloadType !== undefined) {
pt = codec.preferredPayloadType;
}
return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +
(codec.numChannels !== 1 ? '/' + codec.numChannels : '') + '\r\n';
};
// Parses an a=extmap line (headerextension from RFC 5285). Sample input:
// a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
SDPUtils.parseExtmap = function(line) {
var parts = line.substr(9).split(' ');
return {
id: parseInt(parts[0], 10),
uri: parts[1]
};
};
// Generates a=extmap line from RTCRtpHeaderExtensionParameters or
// RTCRtpHeaderExtension.
SDPUtils.writeExtmap = function(headerExtension) {
return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +
' ' + headerExtension.uri + '\r\n';
};
// Parses an ftmp line, returns dictionary. Sample input:
// a=fmtp:96 vbr=on;cng=on
// Also deals with vbr=on; cng=on
SDPUtils.parseFmtp = function(line) {
var parsed = {};
var kv;
var parts = line.substr(line.indexOf(' ') + 1).split(';');
for (var j = 0; j < parts.length; j++) {
kv = parts[j].trim().split('=');
parsed[kv[0].trim()] = kv[1];
}
return parsed;
};
// Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
SDPUtils.writeFmtp = function(codec) {
var line = '';
var pt = codec.payloadType;
if (codec.preferredPayloadType !== undefined) {
pt = codec.preferredPayloadType;
}
if (codec.parameters && Object.keys(codec.parameters).length) {
var params = [];
Object.keys(codec.parameters).forEach(function(param) {
params.push(param + '=' + codec.parameters[param]);
});
line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
}
return line;
};
// Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
// a=rtcp-fb:98 nack rpsi
SDPUtils.parseRtcpFb = function(line) {
var parts = line.substr(line.indexOf(' ') + 1).split(' ');
return {
type: parts.shift(),
parameter: parts.join(' ')
};
};
// Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
SDPUtils.writeRtcpFb = function(codec) {
var lines = '';
var pt = codec.payloadType;
if (codec.preferredPayloadType !== undefined) {
pt = codec.preferredPayloadType;
}
if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
// FIXME: special handling for trr-int?
codec.rtcpFeedback.forEach(function(fb) {
lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +
(fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +
'\r\n';
});
}
return lines;
};
// Parses an RFC 5576 ssrc media attribute. Sample input:
// a=ssrc:3735928559 cname:something
SDPUtils.parseSsrcMedia = function(line) {
var sp = line.indexOf(' ');
var parts = {
ssrc: parseInt(line.substr(7, sp - 7), 10)
};
var colon = line.indexOf(':', sp);
if (colon > -1) {
parts.attribute = line.substr(sp + 1, colon - sp - 1);
parts.value = line.substr(colon + 1);
} else {
parts.attribute = line.substr(sp + 1);
}
return parts;
};
// Extracts DTLS parameters from SDP media section or sessionpart.
// FIXME: for consistency with other functions this should only
// get the fingerprint line as input. See also getIceParameters.
SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
var lines = SDPUtils.splitLines(mediaSection);
// Search in session part, too.
lines = lines.concat(SDPUtils.splitLines(sessionpart));
var fpLine = lines.filter(function(line) {
return line.indexOf('a=fingerprint:') === 0;
})[0].substr(14);
// Note: a=setup line is ignored since we use the 'auto' role.
var dtlsParameters = {
role: 'auto',
fingerprints: [{
algorithm: fpLine.split(' ')[0],
value: fpLine.split(' ')[1]
}]
};
return dtlsParameters;
};
// Serializes DTLS parameters to SDP.
SDPUtils.writeDtlsParameters = function(params, setupType) {
var sdp = 'a=setup:' + setupType + '\r\n';
params.fingerprints.forEach(function(fp) {
sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
});
return sdp;
};
// Parses ICE information from SDP media section or sessionpart.
// FIXME: for consistency with other functions this should only
// get the ice-ufrag and ice-pwd lines as input.
SDPUtils.getIceParameters = function(mediaSection, sessionpart) {
var lines = SDPUtils.splitLines(mediaSection);
// Search in session part, too.
lines = lines.concat(SDPUtils.splitLines(sessionpart));
var iceParameters = {
usernameFragment: lines.filter(function(line) {
return line.indexOf('a=ice-ufrag:') === 0;
})[0].substr(12),
password: lines.filter(function(line) {
return line.indexOf('a=ice-pwd:') === 0;
})[0].substr(10)
};
return iceParameters;
};
// Serializes ICE parameters to SDP.
SDPUtils.writeIceParameters = function(params) {
return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' +
'a=ice-pwd:' + params.password + '\r\n';
};
// Parses the SDP media section and returns RTCRtpParameters.
SDPUtils.parseRtpParameters = function(mediaSection) {
var description = {
codecs: [],
headerExtensions: [],
fecMechanisms: [],
rtcp: []
};
var lines = SDPUtils.splitLines(mediaSection);
var mline = lines[0].split(' ');
for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..]
var pt = mline[i];
var rtpmapline = SDPUtils.matchPrefix(
mediaSection, 'a=rtpmap:' + pt + ' ')[0];
if (rtpmapline) {
var codec = SDPUtils.parseRtpMap(rtpmapline);
var fmtps = SDPUtils.matchPrefix(
mediaSection, 'a=fmtp:' + pt + ' ');
// Only the first a=fmtp:<pt> is considered.
codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
codec.rtcpFeedback = SDPUtils.matchPrefix(
mediaSection, 'a=rtcp-fb:' + pt + ' ')
.map(SDPUtils.parseRtcpFb);
description.codecs.push(codec);
// parse FEC mechanisms from rtpmap lines.
switch (codec.name.toUpperCase()) {
case 'RED':
case 'ULPFEC':
description.fecMechanisms.push(codec.name.toUpperCase());
break;
default: // only RED and ULPFEC are recognized as FEC mechanisms.
break;
}
}
}
SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) {
description.headerExtensions.push(SDPUtils.parseExtmap(line));
});
// FIXME: parse rtcp.
return description;
};
// Generates parts of the SDP media section describing the capabilities /
// parameters.
SDPUtils.writeRtpDescription = function(kind, caps) {
var sdp = '';
// Build the mline.
sdp += 'm=' + kind + ' ';
sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
sdp += ' UDP/TLS/RTP/SAVPF ';
sdp += caps.codecs.map(function(codec) {
if (codec.preferredPayloadType !== undefined) {
return codec.preferredPayloadType;
}
return codec.payloadType;
}).join(' ') + '\r\n';
sdp += 'c=IN IP4 0.0.0.0\r\n';
sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
// Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
caps.codecs.forEach(function(codec) {
sdp += SDPUtils.writeRtpMap(codec);
sdp += SDPUtils.writeFmtp(codec);
sdp += SDPUtils.writeRtcpFb(codec);
});
sdp += 'a=rtcp-mux\r\n';
caps.headerExtensions.forEach(function(extension) {
sdp += SDPUtils.writeExtmap(extension);
});
// FIXME: write fecMechanisms.
return sdp;
};
// Parses the SDP media section and returns an array of
// RTCRtpEncodingParameters.
SDPUtils.parseRtpEncodingParameters = function(mediaSection) {
var encodingParameters = [];
var description = SDPUtils.parseRtpParameters(mediaSection);
var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
// filter a=ssrc:... cname:, ignore PlanB-msid
var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
.map(function(line) {
return SDPUtils.parseSsrcMedia(line);
})
.filter(function(parts) {
return parts.attribute === 'cname';
});
var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
var secondarySsrc;
var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')
.map(function(line) {
var parts = line.split(' ');
parts.shift();
return parts.map(function(part) {
return parseInt(part, 10);
});
});
if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
secondarySsrc = flows[0][1];
}
description.codecs.forEach(function(codec) {
if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
var encParam = {
ssrc: primarySsrc,
codecPayloadType: parseInt(codec.parameters.apt, 10),
rtx: {
payloadType: codec.payloadType,
ssrc: secondarySsrc
}
};
encodingParameters.push(encParam);
if (hasRed) {
encParam = JSON.parse(JSON.stringify(encParam));
encParam.fec = {
ssrc: secondarySsrc,
mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
};
encodingParameters.push(encParam);
}
}
});
if (encodingParameters.length === 0 && primarySsrc) {
encodingParameters.push({
ssrc: primarySsrc
});
}
// we support both b=AS and b=TIAS but interpret AS as TIAS.
var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
if (bandwidth.length) {
if (bandwidth[0].indexOf('b=TIAS:') === 0) {
bandwidth = parseInt(bandwidth[0].substr(7), 10);
} else if (bandwidth[0].indexOf('b=AS:') === 0) {
bandwidth = parseInt(bandwidth[0].substr(5), 10);
}
encodingParameters.forEach(function(params) {
params.maxBitrate = bandwidth;
});
}
return encodingParameters;
};
SDPUtils.writeSessionBoilerplate = function() {
// FIXME: sess-id should be an NTP timestamp.
return 'v=0\r\n' +
'o=thisisadapterortc 8169639915646943137 2 IN IP4 127.0.0.1\r\n' +
's=-\r\n' +
't=0 0\r\n';
};
SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) {
var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
// Map ICE parameters (ufrag, pwd) to SDP.
sdp += SDPUtils.writeIceParameters(
transceiver.iceGatherer.getLocalParameters());
// Map DTLS parameters to SDP.
sdp += SDPUtils.writeDtlsParameters(
transceiver.dtlsTransport.getLocalParameters(),
type === 'offer' ? 'actpass' : 'active');
sdp += 'a=mid:' + transceiver.mid + '\r\n';
if (transceiver.rtpSender && transceiver.rtpReceiver) {
sdp += 'a=sendrecv\r\n';
} else if (transceiver.rtpSender) {
sdp += 'a=sendonly\r\n';
} else if (transceiver.rtpReceiver) {
sdp += 'a=recvonly\r\n';
} else {
sdp += 'a=inactive\r\n';
}
// FIXME: for RTX there might be multiple SSRCs. Not implemented in Edge yet.
if (transceiver.rtpSender) {
var msid = 'msid:' + stream.id + ' ' +
transceiver.rtpSender.track.id + '\r\n';
sdp += 'a=' + msid;
sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
' ' + msid;
}
// FIXME: this should be written by writeRtpDescription.
sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
' cname:' + SDPUtils.localCName + '\r\n';
return sdp;
};
// Gets the direction from the mediaSection or the sessionpart.
SDPUtils.getDirection = function(mediaSection, sessionpart) {
// Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
var lines = SDPUtils.splitLines(mediaSection);
for (var i = 0; i < lines.length; i++) {
switch (lines[i]) {
case 'a=sendrecv':
case 'a=sendonly':
case 'a=recvonly':
case 'a=inactive':
return lines[i].substr(2);
default:
// FIXME: What should happen here?
}
}
if (sessionpart) {
return SDPUtils.getDirection(sessionpart);
}
return 'sendrecv';
};
// Expose public methods.
module.exports = SDPUtils;
},{}],41:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
// Shimming starts here.
(function() {
// Utils.
var logging = require('./utils').log;
var browserDetails = require('./utils').browserDetails;
// Export to the adapter global object visible in the browser.
module.exports.browserDetails = browserDetails;
module.exports.extractVersion = require('./utils').extractVersion;
module.exports.disableLog = require('./utils').disableLog;
// Uncomment the line below if you want logging to occur, including logging
// for the switch statement below. Can also be turned on in the browser via
// adapter.disableLog(false), but then logging from the switch statement below
// will not appear.
// require('./utils').disableLog(false);
// Browser shims.
var chromeShim = require('./chrome/chrome_shim') || null;
var edgeShim = require('./edge/edge_shim') || null;
var firefoxShim = require('./firefox/firefox_shim') || null;
var safariShim = require('./safari/safari_shim') || null;
// Shim browser if found.
switch (browserDetails.browser) {
case 'opera': // fallthrough as it uses chrome shims
case 'chrome':
if (!chromeShim || !chromeShim.shimPeerConnection) {
logging('Chrome shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming chrome.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = chromeShim;
chromeShim.shimGetUserMedia();
chromeShim.shimMediaStream();
chromeShim.shimSourceObject();
chromeShim.shimPeerConnection();
chromeShim.shimOnTrack();
break;
case 'firefox':
if (!firefoxShim || !firefoxShim.shimPeerConnection) {
logging('Firefox shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming firefox.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = firefoxShim;
firefoxShim.shimGetUserMedia();
firefoxShim.shimSourceObject();
firefoxShim.shimPeerConnection();
firefoxShim.shimOnTrack();
break;
case 'edge':
if (!edgeShim || !edgeShim.shimPeerConnection) {
logging('MS edge shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming edge.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = edgeShim;
edgeShim.shimGetUserMedia();
edgeShim.shimPeerConnection();
break;
case 'safari':
if (!safariShim) {
logging('Safari shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming safari.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = safariShim;
safariShim.shimGetUserMedia();
break;
default:
logging('Unsupported browser!');
}
})();
},{"./chrome/chrome_shim":42,"./edge/edge_shim":44,"./firefox/firefox_shim":46,"./safari/safari_shim":48,"./utils":49}],42:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logging = require('../utils.js').log;
var browserDetails = require('../utils.js').browserDetails;
var chromeShim = {
shimMediaStream: function() {
window.MediaStream = window.MediaStream || window.webkitMediaStream;
},
shimOnTrack: function() {
if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
window.RTCPeerConnection.prototype)) {
Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
get: function() {
return this._ontrack;
},
set: function(f) {
var self = this;
if (this._ontrack) {
this.removeEventListener('track', this._ontrack);
this.removeEventListener('addstream', this._ontrackpoly);
}
this.addEventListener('track', this._ontrack = f);
this.addEventListener('addstream', this._ontrackpoly = function(e) {
// onaddstream does not fire when a track is added to an existing
// stream. But stream.onaddtrack is implemented so we use that.
e.stream.addEventListener('addtrack', function(te) {
var event = new Event('track');
event.track = te.track;
event.receiver = {track: te.track};
event.streams = [e.stream];
self.dispatchEvent(event);
});
e.stream.getTracks().forEach(function(track) {
var event = new Event('track');
event.track = track;
event.receiver = {track: track};
event.streams = [e.stream];
this.dispatchEvent(event);
}.bind(this));
}.bind(this));
}
});
}
},
shimSourceObject: function() {
if (typeof window === 'object') {
if (window.HTMLMediaElement &&
!('srcObject' in window.HTMLMediaElement.prototype)) {
// Shim the srcObject property, once, when HTMLMediaElement is found.
Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
get: function() {
return this._srcObject;
},
set: function(stream) {
var self = this;
// Use _srcObject as a private property for this shim
this._srcObject = stream;
if (this.src) {
URL.revokeObjectURL(this.src);
}
if (!stream) {
this.src = '';
return;
}
this.src = URL.createObjectURL(stream);
// We need to recreate the blob url when a track is added or
// removed. Doing it manually since we want to avoid a recursion.
stream.addEventListener('addtrack', function() {
if (self.src) {
URL.revokeObjectURL(self.src);
}
self.src = URL.createObjectURL(stream);
});
stream.addEventListener('removetrack', function() {
if (self.src) {
URL.revokeObjectURL(self.src);
}
self.src = URL.createObjectURL(stream);
});
}
});
}
}
},
shimPeerConnection: function() {
// The RTCPeerConnection object.
window.RTCPeerConnection = function(pcConfig, pcConstraints) {
// Translate iceTransportPolicy to iceTransports,
// see https://code.google.com/p/webrtc/issues/detail?id=4869
logging('PeerConnection');
if (pcConfig && pcConfig.iceTransportPolicy) {
pcConfig.iceTransports = pcConfig.iceTransportPolicy;
}
var pc = new webkitRTCPeerConnection(pcConfig, pcConstraints);
var origGetStats = pc.getStats.bind(pc);
pc.getStats = function(selector, successCallback, errorCallback) {
var self = this;
var args = arguments;
// If selector is a function then we are in the old style stats so just
// pass back the original getStats format to avoid breaking old users.
if (arguments.length > 0 && typeof selector === 'function') {
return origGetStats(selector, successCallback);
}
var fixChromeStats_ = function(response) {
var standardReport = {};
var reports = response.result();
reports.forEach(function(report) {
var standardStats = {
id: report.id,
timestamp: report.timestamp,
type: report.type
};
report.names().forEach(function(name) {
standardStats[name] = report.stat(name);
});
standardReport[standardStats.id] = standardStats;
});
return standardReport;
};
// shim getStats with maplike support
var makeMapStats = function(stats, legacyStats) {
var map = new Map(Object.keys(stats).map(function(key) {
return[key, stats[key]];
}));
legacyStats = legacyStats || stats;
Object.keys(legacyStats).forEach(function(key) {
map[key] = legacyStats[key];
});
return map;
};
if (arguments.length >= 2) {
var successCallbackWrapper_ = function(response) {
args[1](makeMapStats(fixChromeStats_(response)));
};
return origGetStats.apply(this, [successCallbackWrapper_,
arguments[0]]);
}
// promise-support
return new Promise(function(resolve, reject) {
if (args.length === 1 && typeof selector === 'object') {
origGetStats.apply(self, [
function(response) {
resolve(makeMapStats(fixChromeStats_(response)));
}, reject]);
} else {
// Preserve legacy chrome stats only on legacy access of stats obj
origGetStats.apply(self, [
function(response) {
resolve(makeMapStats(fixChromeStats_(response),
response.result()));
}, reject]);
}
}).then(successCallback, errorCallback);
};
return pc;
};
window.RTCPeerConnection.prototype = webkitRTCPeerConnection.prototype;
// wrap static methods. Currently just generateCertificate.
if (webkitRTCPeerConnection.generateCertificate) {
Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
get: function() {
return webkitRTCPeerConnection.generateCertificate;
}
});
}
['createOffer', 'createAnswer'].forEach(function(method) {
var nativeMethod = webkitRTCPeerConnection.prototype[method];
webkitRTCPeerConnection.prototype[method] = function() {
var self = this;
if (arguments.length < 1 || (arguments.length === 1 &&
typeof arguments[0] === 'object')) {
var opts = arguments.length === 1 ? arguments[0] : undefined;
return new Promise(function(resolve, reject) {
nativeMethod.apply(self, [resolve, reject, opts]);
});
}
return nativeMethod.apply(this, arguments);
};
});
// add promise support -- natively available in Chrome 51
if (browserDetails.version < 51) {
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
.forEach(function(method) {
var nativeMethod = webkitRTCPeerConnection.prototype[method];
webkitRTCPeerConnection.prototype[method] = function() {
var args = arguments;
var self = this;
var promise = new Promise(function(resolve, reject) {
nativeMethod.apply(self, [args[0], resolve, reject]);
});
if (args.length < 2) {
return promise;
}
return promise.then(function() {
args[1].apply(null, []);
},
function(err) {
if (args.length >= 3) {
args[2].apply(null, [err]);
}
});
};
});
}
// shim implicit creation of RTCSessionDescription/RTCIceCandidate
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
.forEach(function(method) {
var nativeMethod = webkitRTCPeerConnection.prototype[method];
webkitRTCPeerConnection.prototype[method] = function() {
arguments[0] = new ((method === 'addIceCandidate') ?
RTCIceCandidate : RTCSessionDescription)(arguments[0]);
return nativeMethod.apply(this, arguments);
};
});
// support for addIceCandidate(null or undefined)
var nativeAddIceCandidate =
RTCPeerConnection.prototype.addIceCandidate;
RTCPeerConnection.prototype.addIceCandidate = function() {
if (!arguments[0]) {
if (arguments[1]) {
arguments[1].apply(null);
}
return Promise.resolve();
}
return nativeAddIceCandidate.apply(this, arguments);
};
}
};
// Expose public methods.
module.exports = {
shimMediaStream: chromeShim.shimMediaStream,
shimOnTrack: chromeShim.shimOnTrack,
shimSourceObject: chromeShim.shimSourceObject,
shimPeerConnection: chromeShim.shimPeerConnection,
shimGetUserMedia: require('./getusermedia')
};
},{"../utils.js":49,"./getusermedia":43}],43:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logging = require('../utils.js').log;
// Expose public methods.
module.exports = function() {
var constraintsToChrome_ = function(c) {
if (typeof c !== 'object' || c.mandatory || c.optional) {
return c;
}
var cc = {};
Object.keys(c).forEach(function(key) {
if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
return;
}
var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
if (r.exact !== undefined && typeof r.exact === 'number') {
r.min = r.max = r.exact;
}
var oldname_ = function(prefix, name) {
if (prefix) {
return prefix + name.charAt(0).toUpperCase() + name.slice(1);
}
return (name === 'deviceId') ? 'sourceId' : name;
};
if (r.ideal !== undefined) {
cc.optional = cc.optional || [];
var oc = {};
if (typeof r.ideal === 'number') {
oc[oldname_('min', key)] = r.ideal;
cc.optional.push(oc);
oc = {};
oc[oldname_('max', key)] = r.ideal;
cc.optional.push(oc);
} else {
oc[oldname_('', key)] = r.ideal;
cc.optional.push(oc);
}
}
if (r.exact !== undefined && typeof r.exact !== 'number') {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname_('', key)] = r.exact;
} else {
['min', 'max'].forEach(function(mix) {
if (r[mix] !== undefined) {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname_(mix, key)] = r[mix];
}
});
}
});
if (c.advanced) {
cc.optional = (cc.optional || []).concat(c.advanced);
}
return cc;
};
var shimConstraints_ = function(constraints, func) {
constraints = JSON.parse(JSON.stringify(constraints));
if (constraints && constraints.audio) {
constraints.audio = constraintsToChrome_(constraints.audio);
}
if (constraints && typeof constraints.video === 'object') {
// Shim facingMode for mobile, where it defaults to "user".
var face = constraints.video.facingMode;
face = face && ((typeof face === 'object') ? face : {ideal: face});
if ((face && (face.exact === 'user' || face.exact === 'environment' ||
face.ideal === 'user' || face.ideal === 'environment')) &&
!(navigator.mediaDevices.getSupportedConstraints &&
navigator.mediaDevices.getSupportedConstraints().facingMode)) {
delete constraints.video.facingMode;
if (face.exact === 'environment' || face.ideal === 'environment') {
// Look for "back" in label, or use last cam (typically back cam).
return navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
devices = devices.filter(function(d) {
return d.kind === 'videoinput';
});
var back = devices.find(function(d) {
return d.label.toLowerCase().indexOf('back') !== -1;
}) || (devices.length && devices[devices.length - 1]);
if (back) {
constraints.video.deviceId = face.exact ? {exact: back.deviceId} :
{ideal: back.deviceId};
}
constraints.video = constraintsToChrome_(constraints.video);
logging('chrome: ' + JSON.stringify(constraints));
return func(constraints);
});
}
}
constraints.video = constraintsToChrome_(constraints.video);
}
logging('chrome: ' + JSON.stringify(constraints));
return func(constraints);
};
var shimError_ = function(e) {
return {
name: {
PermissionDeniedError: 'NotAllowedError',
ConstraintNotSatisfiedError: 'OverconstrainedError'
}[e.name] || e.name,
message: e.message,
constraint: e.constraintName,
toString: function() {
return this.name + (this.message && ': ') + this.message;
}
};
};
var getUserMedia_ = function(constraints, onSuccess, onError) {
shimConstraints_(constraints, function(c) {
navigator.webkitGetUserMedia(c, onSuccess, function(e) {
onError(shimError_(e));
});
});
};
navigator.getUserMedia = getUserMedia_;
// Returns the result of getUserMedia as a Promise.
var getUserMediaPromise_ = function(constraints) {
return new Promise(function(resolve, reject) {
navigator.getUserMedia(constraints, resolve, reject);
});
};
if (!navigator.mediaDevices) {
navigator.mediaDevices = {
getUserMedia: getUserMediaPromise_,
enumerateDevices: function() {
return new Promise(function(resolve) {
var kinds = {audio: 'audioinput', video: 'videoinput'};
return MediaStreamTrack.getSources(function(devices) {
resolve(devices.map(function(device) {
return {label: device.label,
kind: kinds[device.kind],
deviceId: device.id,
groupId: ''};
}));
});
});
}
};
}
// A shim for getUserMedia method on the mediaDevices object.
// TODO(KaptenJansson) remove once implemented in Chrome stable.
if (!navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia = function(constraints) {
return getUserMediaPromise_(constraints);
};
} else {
// Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
// function which returns a Promise, it does not accept spec-style
// constraints.
var origGetUserMedia = navigator.mediaDevices.getUserMedia.
bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function(cs) {
return shimConstraints_(cs, function(c) {
return origGetUserMedia(c).then(function(stream) {
if (c.audio && !stream.getAudioTracks().length ||
c.video && !stream.getVideoTracks().length) {
stream.getTracks().forEach(function(track) {
track.stop();
});
throw new DOMException('', 'NotFoundError');
}
return stream;
}, function(e) {
return Promise.reject(shimError_(e));
});
});
};
}
// Dummy devicechange event methods.
// TODO(KaptenJansson) remove once implemented in Chrome stable.
if (typeof navigator.mediaDevices.addEventListener === 'undefined') {
navigator.mediaDevices.addEventListener = function() {
logging('Dummy mediaDevices.addEventListener called.');
};
}
if (typeof navigator.mediaDevices.removeEventListener === 'undefined') {
navigator.mediaDevices.removeEventListener = function() {
logging('Dummy mediaDevices.removeEventListener called.');
};
}
};
},{"../utils.js":49}],44:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var SDPUtils = require('sdp');
var browserDetails = require('../utils').browserDetails;
var edgeShim = {
shimPeerConnection: function() {
if (window.RTCIceGatherer) {
// ORTC defines an RTCIceCandidate object but no constructor.
// Not implemented in Edge.
if (!window.RTCIceCandidate) {
window.RTCIceCandidate = function(args) {
return args;
};
}
// ORTC does not have a session description object but
// other browsers (i.e. Chrome) that will support both PC and ORTC
// in the future might have this defined already.
if (!window.RTCSessionDescription) {
window.RTCSessionDescription = function(args) {
return args;
};
}
// this adds an additional event listener to MediaStrackTrack that signals
// when a tracks enabled property was changed.
var origMSTEnabled = Object.getOwnPropertyDescriptor(
MediaStreamTrack.prototype, 'enabled');
Object.defineProperty(MediaStreamTrack.prototype, 'enabled', {
set: function(value) {
origMSTEnabled.set.call(this, value);
var ev = new Event('enabled');
ev.enabled = value;
this.dispatchEvent(ev);
}
});
}
window.RTCPeerConnection = function(config) {
var self = this;
var _eventTarget = document.createDocumentFragment();
['addEventListener', 'removeEventListener', 'dispatchEvent']
.forEach(function(method) {
self[method] = _eventTarget[method].bind(_eventTarget);
});
this.onicecandidate = null;
this.onaddstream = null;
this.ontrack = null;
this.onremovestream = null;
this.onsignalingstatechange = null;
this.oniceconnectionstatechange = null;
this.onnegotiationneeded = null;
this.ondatachannel = null;
this.localStreams = [];
this.remoteStreams = [];
this.getLocalStreams = function() {
return self.localStreams;
};
this.getRemoteStreams = function() {
return self.remoteStreams;
};
this.localDescription = new RTCSessionDescription({
type: '',
sdp: ''
});
this.remoteDescription = new RTCSessionDescription({
type: '',
sdp: ''
});
this.signalingState = 'stable';
this.iceConnectionState = 'new';
this.iceGatheringState = 'new';
this.iceOptions = {
gatherPolicy: 'all',
iceServers: []
};
if (config && config.iceTransportPolicy) {
switch (config.iceTransportPolicy) {
case 'all':
case 'relay':
this.iceOptions.gatherPolicy = config.iceTransportPolicy;
break;
case 'none':
// FIXME: remove once implementation and spec have added this.
throw new TypeError('iceTransportPolicy "none" not supported');
default:
// don't set iceTransportPolicy.
break;
}
}
this.usingBundle = config && config.bundlePolicy === 'max-bundle';
if (config && config.iceServers) {
// Edge does not like
// 1) stun:
// 2) turn: that does not have all of turn:host:port?transport=udp
// 3) turn: with ipv6 addresses
var iceServers = JSON.parse(JSON.stringify(config.iceServers));
this.iceOptions.iceServers = iceServers.filter(function(server) {
if (server && server.urls) {
var urls = server.urls;
if (typeof urls === 'string') {
urls = [urls];
}
urls = urls.filter(function(url) {
return (url.indexOf('turn:') === 0 &&
url.indexOf('transport=udp') !== -1 &&
url.indexOf('turn:[') === -1) ||
(url.indexOf('stun:') === 0 &&
browserDetails.version >= 14393);
})[0];
return !!urls;
}
return false;
});
}
this._config = config;
// per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ...
// everything that is needed to describe a SDP m-line.
this.transceivers = [];
// since the iceGatherer is currently created in createOffer but we
// must not emit candidates until after setLocalDescription we buffer
// them in this array.
this._localIceCandidatesBuffer = [];
};
window.RTCPeerConnection.prototype._emitBufferedCandidates = function() {
var self = this;
var sections = SDPUtils.splitSections(self.localDescription.sdp);
// FIXME: need to apply ice candidates in a way which is async but
// in-order
this._localIceCandidatesBuffer.forEach(function(event) {
var end = !event.candidate || Object.keys(event.candidate).length === 0;
if (end) {
for (var j = 1; j < sections.length; j++) {
if (sections[j].indexOf('\r\na=end-of-candidates\r\n') === -1) {
sections[j] += 'a=end-of-candidates\r\n';
}
}
} else if (event.candidate.candidate.indexOf('typ endOfCandidates')
=== -1) {
sections[event.candidate.sdpMLineIndex + 1] +=
'a=' + event.candidate.candidate + '\r\n';
}
self.localDescription.sdp = sections.join('');
self.dispatchEvent(event);
if (self.onicecandidate !== null) {
self.onicecandidate(event);
}
if (!event.candidate && self.iceGatheringState !== 'complete') {
var complete = self.transceivers.every(function(transceiver) {
return transceiver.iceGatherer &&
transceiver.iceGatherer.state === 'completed';
});
if (complete) {
self.iceGatheringState = 'complete';
}
}
});
this._localIceCandidatesBuffer = [];
};
window.RTCPeerConnection.prototype.getConfiguration = function() {
return this._config;
};
window.RTCPeerConnection.prototype.addStream = function(stream) {
// Clone is necessary for local demos mostly, attaching directly
// to two different senders does not work (build 10547).
var clonedStream = stream.clone();
stream.getTracks().forEach(function(track, idx) {
var clonedTrack = clonedStream.getTracks()[idx];
track.addEventListener('enabled', function(event) {
clonedTrack.enabled = event.enabled;
});
});
this.localStreams.push(clonedStream);
this._maybeFireNegotiationNeeded();
};
window.RTCPeerConnection.prototype.removeStream = function(stream) {
var idx = this.localStreams.indexOf(stream);
if (idx > -1) {
this.localStreams.splice(idx, 1);
this._maybeFireNegotiationNeeded();
}
};
window.RTCPeerConnection.prototype.getSenders = function() {
return this.transceivers.filter(function(transceiver) {
return !!transceiver.rtpSender;
})
.map(function(transceiver) {
return transceiver.rtpSender;
});
};
window.RTCPeerConnection.prototype.getReceivers = function() {
return this.transceivers.filter(function(transceiver) {
return !!transceiver.rtpReceiver;
})
.map(function(transceiver) {
return transceiver.rtpReceiver;
});
};
// Determines the intersection of local and remote capabilities.
window.RTCPeerConnection.prototype._getCommonCapabilities =
function(localCapabilities, remoteCapabilities) {
var commonCapabilities = {
codecs: [],
headerExtensions: [],
fecMechanisms: []
};
localCapabilities.codecs.forEach(function(lCodec) {
for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
var rCodec = remoteCapabilities.codecs[i];
if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
lCodec.clockRate === rCodec.clockRate) {
// number of channels is the highest common number of channels
rCodec.numChannels = Math.min(lCodec.numChannels,
rCodec.numChannels);
// push rCodec so we reply with offerer payload type
commonCapabilities.codecs.push(rCodec);
// determine common feedback mechanisms
rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) {
for (var j = 0; j < lCodec.rtcpFeedback.length; j++) {
if (lCodec.rtcpFeedback[j].type === fb.type &&
lCodec.rtcpFeedback[j].parameter === fb.parameter) {
return true;
}
}
return false;
});
// FIXME: also need to determine .parameters
// see https://github.com/openpeer/ortc/issues/569
break;
}
}
});
localCapabilities.headerExtensions
.forEach(function(lHeaderExtension) {
for (var i = 0; i < remoteCapabilities.headerExtensions.length;
i++) {
var rHeaderExtension = remoteCapabilities.headerExtensions[i];
if (lHeaderExtension.uri === rHeaderExtension.uri) {
commonCapabilities.headerExtensions.push(rHeaderExtension);
break;
}
}
});
// FIXME: fecMechanisms
return commonCapabilities;
};
// Create ICE gatherer, ICE transport and DTLS transport.
window.RTCPeerConnection.prototype._createIceAndDtlsTransports =
function(mid, sdpMLineIndex) {
var self = this;
var iceGatherer = new RTCIceGatherer(self.iceOptions);
var iceTransport = new RTCIceTransport(iceGatherer);
iceGatherer.onlocalcandidate = function(evt) {
var event = new Event('icecandidate');
event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex};
var cand = evt.candidate;
var end = !cand || Object.keys(cand).length === 0;
// Edge emits an empty object for RTCIceCandidateComplete‥
if (end) {
// polyfill since RTCIceGatherer.state is not implemented in
// Edge 10547 yet.
if (iceGatherer.state === undefined) {
iceGatherer.state = 'completed';
}
// Emit a candidate with type endOfCandidates to make the samples
// work. Edge requires addIceCandidate with this empty candidate
// to start checking. The real solution is to signal
// end-of-candidates to the other side when getting the null
// candidate but some apps (like the samples) don't do that.
event.candidate.candidate =
'candidate:1 1 udp 1 0.0.0.0 9 typ endOfCandidates';
} else {
// RTCIceCandidate doesn't have a component, needs to be added
cand.component = iceTransport.component === 'RTCP' ? 2 : 1;
event.candidate.candidate = SDPUtils.writeCandidate(cand);
}
// update local description.
var sections = SDPUtils.splitSections(self.localDescription.sdp);
if (event.candidate.candidate.indexOf('typ endOfCandidates')
=== -1) {
sections[event.candidate.sdpMLineIndex + 1] +=
'a=' + event.candidate.candidate + '\r\n';
} else {
sections[event.candidate.sdpMLineIndex + 1] +=
'a=end-of-candidates\r\n';
}
self.localDescription.sdp = sections.join('');
var complete = self.transceivers.every(function(transceiver) {
return transceiver.iceGatherer &&
transceiver.iceGatherer.state === 'completed';
});
// Emit candidate if localDescription is set.
// Also emits null candidate when all gatherers are complete.
switch (self.iceGatheringState) {
case 'new':
self._localIceCandidatesBuffer.push(event);
if (end && complete) {
self._localIceCandidatesBuffer.push(
new Event('icecandidate'));
}
break;
case 'gathering':
self._emitBufferedCandidates();
self.dispatchEvent(event);
if (self.onicecandidate !== null) {
self.onicecandidate(event);
}
if (complete) {
self.dispatchEvent(new Event('icecandidate'));
if (self.onicecandidate !== null) {
self.onicecandidate(new Event('icecandidate'));
}
self.iceGatheringState = 'complete';
}
break;
case 'complete':
// should not happen... currently!
break;
default: // no-op.
break;
}
};
iceTransport.onicestatechange = function() {
self._updateConnectionState();
};
var dtlsTransport = new RTCDtlsTransport(iceTransport);
dtlsTransport.ondtlsstatechange = function() {
self._updateConnectionState();
};
dtlsTransport.onerror = function() {
// onerror does not set state to failed by itself.
dtlsTransport.state = 'failed';
self._updateConnectionState();
};
return {
iceGatherer: iceGatherer,
iceTransport: iceTransport,
dtlsTransport: dtlsTransport
};
};
// Start the RTP Sender and Receiver for a transceiver.
window.RTCPeerConnection.prototype._transceive = function(transceiver,
send, recv) {
var params = this._getCommonCapabilities(transceiver.localCapabilities,
transceiver.remoteCapabilities);
if (send && transceiver.rtpSender) {
params.encodings = transceiver.sendEncodingParameters;
params.rtcp = {
cname: SDPUtils.localCName
};
if (transceiver.recvEncodingParameters.length) {
params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc;
}
transceiver.rtpSender.send(params);
}
if (recv && transceiver.rtpReceiver) {
// remove RTX field in Edge 14942
if (transceiver.kind === 'video'
&& transceiver.recvEncodingParameters) {
transceiver.recvEncodingParameters.forEach(function(p) {
delete p.rtx;
});
}
params.encodings = transceiver.recvEncodingParameters;
params.rtcp = {
cname: transceiver.cname
};
if (transceiver.sendEncodingParameters.length) {
params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc;
}
transceiver.rtpReceiver.receive(params);
}
};
window.RTCPeerConnection.prototype.setLocalDescription =
function(description) {
var self = this;
var sections;
var sessionpart;
if (description.type === 'offer') {
// FIXME: What was the purpose of this empty if statement?
// if (!this._pendingOffer) {
// } else {
if (this._pendingOffer) {
// VERY limited support for SDP munging. Limited to:
// * changing the order of codecs
sections = SDPUtils.splitSections(description.sdp);
sessionpart = sections.shift();
sections.forEach(function(mediaSection, sdpMLineIndex) {
var caps = SDPUtils.parseRtpParameters(mediaSection);
self._pendingOffer[sdpMLineIndex].localCapabilities = caps;
});
this.transceivers = this._pendingOffer;
delete this._pendingOffer;
}
} else if (description.type === 'answer') {
sections = SDPUtils.splitSections(self.remoteDescription.sdp);
sessionpart = sections.shift();
var isIceLite = SDPUtils.matchPrefix(sessionpart,
'a=ice-lite').length > 0;
sections.forEach(function(mediaSection, sdpMLineIndex) {
var transceiver = self.transceivers[sdpMLineIndex];
var iceGatherer = transceiver.iceGatherer;
var iceTransport = transceiver.iceTransport;
var dtlsTransport = transceiver.dtlsTransport;
var localCapabilities = transceiver.localCapabilities;
var remoteCapabilities = transceiver.remoteCapabilities;
var rejected = mediaSection.split('\n', 1)[0]
.split(' ', 2)[1] === '0';
if (!rejected && !transceiver.isDatachannel) {
var remoteIceParameters = SDPUtils.getIceParameters(
mediaSection, sessionpart);
if (isIceLite) {
var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
.map(function(cand) {
return SDPUtils.parseCandidate(cand);
})
.filter(function(cand) {
return cand.component === '1';
});
// ice-lite only includes host candidates in the SDP so we can
// use setRemoteCandidates (which implies an
// RTCIceCandidateComplete)
if (cands.length) {
iceTransport.setRemoteCandidates(cands);
}
}
var remoteDtlsParameters = SDPUtils.getDtlsParameters(
mediaSection, sessionpart);
if (isIceLite) {
remoteDtlsParameters.role = 'server';
}
if (!self.usingBundle || sdpMLineIndex === 0) {
iceTransport.start(iceGatherer, remoteIceParameters,
isIceLite ? 'controlling' : 'controlled');
dtlsTransport.start(remoteDtlsParameters);
}
// Calculate intersection of capabilities.
var params = self._getCommonCapabilities(localCapabilities,
remoteCapabilities);
// Start the RTCRtpSender. The RTCRtpReceiver for this
// transceiver has already been started in setRemoteDescription.
self._transceive(transceiver,
params.codecs.length > 0,
false);
}
});
}
this.localDescription = {
type: description.type,
sdp: description.sdp
};
switch (description.type) {
case 'offer':
this._updateSignalingState('have-local-offer');
break;
case 'answer':
this._updateSignalingState('stable');
break;
default:
throw new TypeError('unsupported type "' + description.type +
'"');
}
// If a success callback was provided, emit ICE candidates after it
// has been executed. Otherwise, emit callback after the Promise is
// resolved.
var hasCallback = arguments.length > 1 &&
typeof arguments[1] === 'function';
if (hasCallback) {
var cb = arguments[1];
window.setTimeout(function() {
cb();
if (self.iceGatheringState === 'new') {
self.iceGatheringState = 'gathering';
}
self._emitBufferedCandidates();
}, 0);
}
var p = Promise.resolve();
p.then(function() {
if (!hasCallback) {
if (self.iceGatheringState === 'new') {
self.iceGatheringState = 'gathering';
}
// Usually candidates will be emitted earlier.
window.setTimeout(self._emitBufferedCandidates.bind(self), 500);
}
});
return p;
};
window.RTCPeerConnection.prototype.setRemoteDescription =
function(description) {
var self = this;
var stream = new MediaStream();
var receiverList = [];
var sections = SDPUtils.splitSections(description.sdp);
var sessionpart = sections.shift();
var isIceLite = SDPUtils.matchPrefix(sessionpart,
'a=ice-lite').length > 0;
this.usingBundle = SDPUtils.matchPrefix(sessionpart,
'a=group:BUNDLE ').length > 0;
sections.forEach(function(mediaSection, sdpMLineIndex) {
var lines = SDPUtils.splitLines(mediaSection);
var mline = lines[0].substr(2).split(' ');
var kind = mline[0];
var rejected = mline[1] === '0';
var direction = SDPUtils.getDirection(mediaSection, sessionpart);
var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:');
if (mid.length) {
mid = mid[0].substr(6);
} else {
mid = SDPUtils.generateIdentifier();
}
// Reject datachannels which are not implemented yet.
if (kind === 'application' && mline[2] === 'DTLS/SCTP') {
self.transceivers[sdpMLineIndex] = {
mid: mid,
isDatachannel: true
};
return;
}
var transceiver;
var iceGatherer;
var iceTransport;
var dtlsTransport;
var rtpSender;
var rtpReceiver;
var sendEncodingParameters;
var recvEncodingParameters;
var localCapabilities;
var track;
// FIXME: ensure the mediaSection has rtcp-mux set.
var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection);
var remoteIceParameters;
var remoteDtlsParameters;
if (!rejected) {
remoteIceParameters = SDPUtils.getIceParameters(mediaSection,
sessionpart);
remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection,
sessionpart);
remoteDtlsParameters.role = 'client';
}
recvEncodingParameters =
SDPUtils.parseRtpEncodingParameters(mediaSection);
var cname;
// Gets the first SSRC. Note that with RTX there might be multiple
// SSRCs.
var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
.map(function(line) {
return SDPUtils.parseSsrcMedia(line);
})
.filter(function(obj) {
return obj.attribute === 'cname';
})[0];
if (remoteSsrc) {
cname = remoteSsrc.value;
}
var isComplete = SDPUtils.matchPrefix(mediaSection,
'a=end-of-candidates', sessionpart).length > 0;
var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
.map(function(cand) {
return SDPUtils.parseCandidate(cand);
})
.filter(function(cand) {
return cand.component === '1';
});
if (description.type === 'offer' && !rejected) {
var transports = self.usingBundle && sdpMLineIndex > 0 ? {
iceGatherer: self.transceivers[0].iceGatherer,
iceTransport: self.transceivers[0].iceTransport,
dtlsTransport: self.transceivers[0].dtlsTransport
} : self._createIceAndDtlsTransports(mid, sdpMLineIndex);
if (isComplete) {
transports.iceTransport.setRemoteCandidates(cands);
}
localCapabilities = RTCRtpReceiver.getCapabilities(kind);
// filter RTX until additional stuff needed for RTX is implemented
// in adapter.js
localCapabilities.codecs = localCapabilities.codecs.filter(
function(codec) {
return codec.name !== 'rtx';
});
sendEncodingParameters = [{
ssrc: (2 * sdpMLineIndex + 2) * 1001
}];
rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind);
track = rtpReceiver.track;
receiverList.push([track, rtpReceiver]);
// FIXME: not correct when there are multiple streams but that is
// not currently supported in this shim.
stream.addTrack(track);
// FIXME: look at direction.
if (self.localStreams.length > 0 &&
self.localStreams[0].getTracks().length >= sdpMLineIndex) {
var localTrack;
if (kind === 'audio') {
localTrack = self.localStreams[0].getAudioTracks()[0];
} else if (kind === 'video') {
localTrack = self.localStreams[0].getVideoTracks()[0];
}
if (localTrack) {
rtpSender = new RTCRtpSender(localTrack,
transports.dtlsTransport);
}
}
self.transceivers[sdpMLineIndex] = {
iceGatherer: transports.iceGatherer,
iceTransport: transports.iceTransport,
dtlsTransport: transports.dtlsTransport,
localCapabilities: localCapabilities,
remoteCapabilities: remoteCapabilities,
rtpSender: rtpSender,
rtpReceiver: rtpReceiver,
kind: kind,
mid: mid,
cname: cname,
sendEncodingParameters: sendEncodingParameters,
recvEncodingParameters: recvEncodingParameters
};
// Start the RTCRtpReceiver now. The RTPSender is started in
// setLocalDescription.
self._transceive(self.transceivers[sdpMLineIndex],
false,
direction === 'sendrecv' || direction === 'sendonly');
} else if (description.type === 'answer' && !rejected) {
transceiver = self.transceivers[sdpMLineIndex];
iceGatherer = transceiver.iceGatherer;
iceTransport = transceiver.iceTransport;
dtlsTransport = transceiver.dtlsTransport;
rtpSender = transceiver.rtpSender;
rtpReceiver = transceiver.rtpReceiver;
sendEncodingParameters = transceiver.sendEncodingParameters;
localCapabilities = transceiver.localCapabilities;
self.transceivers[sdpMLineIndex].recvEncodingParameters =
recvEncodingParameters;
self.transceivers[sdpMLineIndex].remoteCapabilities =
remoteCapabilities;
self.transceivers[sdpMLineIndex].cname = cname;
if ((isIceLite || isComplete) && cands.length) {
iceTransport.setRemoteCandidates(cands);
}
if (!self.usingBundle || sdpMLineIndex === 0) {
iceTransport.start(iceGatherer, remoteIceParameters,
'controlling');
dtlsTransport.start(remoteDtlsParameters);
}
self._transceive(transceiver,
direction === 'sendrecv' || direction === 'recvonly',
direction === 'sendrecv' || direction === 'sendonly');
if (rtpReceiver &&
(direction === 'sendrecv' || direction === 'sendonly')) {
track = rtpReceiver.track;
receiverList.push([track, rtpReceiver]);
stream.addTrack(track);
} else {
// FIXME: actually the receiver should be created later.
delete transceiver.rtpReceiver;
}
}
});
this.remoteDescription = {
type: description.type,
sdp: description.sdp
};
switch (description.type) {
case 'offer':
this._updateSignalingState('have-remote-offer');
break;
case 'answer':
this._updateSignalingState('stable');
break;
default:
throw new TypeError('unsupported type "' + description.type +
'"');
}
if (stream.getTracks().length) {
self.remoteStreams.push(stream);
window.setTimeout(function() {
var event = new Event('addstream');
event.stream = stream;
self.dispatchEvent(event);
if (self.onaddstream !== null) {
window.setTimeout(function() {
self.onaddstream(event);
}, 0);
}
receiverList.forEach(function(item) {
var track = item[0];
var receiver = item[1];
var trackEvent = new Event('track');
trackEvent.track = track;
trackEvent.receiver = receiver;
trackEvent.streams = [stream];
self.dispatchEvent(event);
if (self.ontrack !== null) {
window.setTimeout(function() {
self.ontrack(trackEvent);
}, 0);
}
});
}, 0);
}
if (arguments.length > 1 && typeof arguments[1] === 'function') {
window.setTimeout(arguments[1], 0);
}
return Promise.resolve();
};
window.RTCPeerConnection.prototype.close = function() {
this.transceivers.forEach(function(transceiver) {
/* not yet
if (transceiver.iceGatherer) {
transceiver.iceGatherer.close();
}
*/
if (transceiver.iceTransport) {
transceiver.iceTransport.stop();
}
if (transceiver.dtlsTransport) {
transceiver.dtlsTransport.stop();
}
if (transceiver.rtpSender) {
transceiver.rtpSender.stop();
}
if (transceiver.rtpReceiver) {
transceiver.rtpReceiver.stop();
}
});
// FIXME: clean up tracks, local streams, remote streams, etc
this._updateSignalingState('closed');
};
// Update the signaling state.
window.RTCPeerConnection.prototype._updateSignalingState =
function(newState) {
this.signalingState = newState;
var event = new Event('signalingstatechange');
this.dispatchEvent(event);
if (this.onsignalingstatechange !== null) {
this.onsignalingstatechange(event);
}
};
// Determine whether to fire the negotiationneeded event.
window.RTCPeerConnection.prototype._maybeFireNegotiationNeeded =
function() {
// Fire away (for now).
var event = new Event('negotiationneeded');
this.dispatchEvent(event);
if (this.onnegotiationneeded !== null) {
this.onnegotiationneeded(event);
}
};
// Update the connection state.
window.RTCPeerConnection.prototype._updateConnectionState = function() {
var self = this;
var newState;
var states = {
'new': 0,
closed: 0,
connecting: 0,
checking: 0,
connected: 0,
completed: 0,
failed: 0
};
this.transceivers.forEach(function(transceiver) {
states[transceiver.iceTransport.state]++;
states[transceiver.dtlsTransport.state]++;
});
// ICETransport.completed and connected are the same for this purpose.
states.connected += states.completed;
newState = 'new';
if (states.failed > 0) {
newState = 'failed';
} else if (states.connecting > 0 || states.checking > 0) {
newState = 'connecting';
} else if (states.disconnected > 0) {
newState = 'disconnected';
} else if (states.new > 0) {
newState = 'new';
} else if (states.connected > 0 || states.completed > 0) {
newState = 'connected';
}
if (newState !== self.iceConnectionState) {
self.iceConnectionState = newState;
var event = new Event('iceconnectionstatechange');
this.dispatchEvent(event);
if (this.oniceconnectionstatechange !== null) {
this.oniceconnectionstatechange(event);
}
}
};
window.RTCPeerConnection.prototype.createOffer = function() {
var self = this;
if (this._pendingOffer) {
throw new Error('createOffer called while there is a pending offer.');
}
var offerOptions;
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
offerOptions = arguments[0];
} else if (arguments.length === 3) {
offerOptions = arguments[2];
}
var tracks = [];
var numAudioTracks = 0;
var numVideoTracks = 0;
// Default to sendrecv.
if (this.localStreams.length) {
numAudioTracks = this.localStreams[0].getAudioTracks().length;
numVideoTracks = this.localStreams[0].getVideoTracks().length;
}
// Determine number of audio and video tracks we need to send/recv.
if (offerOptions) {
// Reject Chrome legacy constraints.
if (offerOptions.mandatory || offerOptions.optional) {
throw new TypeError(
'Legacy mandatory/optional constraints not supported.');
}
if (offerOptions.offerToReceiveAudio !== undefined) {
numAudioTracks = offerOptions.offerToReceiveAudio;
}
if (offerOptions.offerToReceiveVideo !== undefined) {
numVideoTracks = offerOptions.offerToReceiveVideo;
}
}
if (this.localStreams.length) {
// Push local streams.
this.localStreams[0].getTracks().forEach(function(track) {
tracks.push({
kind: track.kind,
track: track,
wantReceive: track.kind === 'audio' ?
numAudioTracks > 0 : numVideoTracks > 0
});
if (track.kind === 'audio') {
numAudioTracks--;
} else if (track.kind === 'video') {
numVideoTracks--;
}
});
}
// Create M-lines for recvonly streams.
while (numAudioTracks > 0 || numVideoTracks > 0) {
if (numAudioTracks > 0) {
tracks.push({
kind: 'audio',
wantReceive: true
});
numAudioTracks--;
}
if (numVideoTracks > 0) {
tracks.push({
kind: 'video',
wantReceive: true
});
numVideoTracks--;
}
}
var sdp = SDPUtils.writeSessionBoilerplate();
var transceivers = [];
tracks.forEach(function(mline, sdpMLineIndex) {
// For each track, create an ice gatherer, ice transport,
// dtls transport, potentially rtpsender and rtpreceiver.
var track = mline.track;
var kind = mline.kind;
var mid = SDPUtils.generateIdentifier();
var transports = self.usingBundle && sdpMLineIndex > 0 ? {
iceGatherer: transceivers[0].iceGatherer,
iceTransport: transceivers[0].iceTransport,
dtlsTransport: transceivers[0].dtlsTransport
} : self._createIceAndDtlsTransports(mid, sdpMLineIndex);
var localCapabilities = RTCRtpSender.getCapabilities(kind);
// filter RTX until additional stuff needed for RTX is implemented
// in adapter.js
localCapabilities.codecs = localCapabilities.codecs.filter(
function(codec) {
return codec.name !== 'rtx';
});
localCapabilities.codecs.forEach(function(codec) {
// work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552
// by adding level-asymmetry-allowed=1
if (codec.name === 'H264' &&
codec.parameters['level-asymmetry-allowed'] === undefined) {
codec.parameters['level-asymmetry-allowed'] = '1';
}
});
var rtpSender;
var rtpReceiver;
// generate an ssrc now, to be used later in rtpSender.send
var sendEncodingParameters = [{
ssrc: (2 * sdpMLineIndex + 1) * 1001
}];
if (track) {
rtpSender = new RTCRtpSender(track, transports.dtlsTransport);
}
if (mline.wantReceive) {
rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind);
}
transceivers[sdpMLineIndex] = {
iceGatherer: transports.iceGatherer,
iceTransport: transports.iceTransport,
dtlsTransport: transports.dtlsTransport,
localCapabilities: localCapabilities,
remoteCapabilities: null,
rtpSender: rtpSender,
rtpReceiver: rtpReceiver,
kind: kind,
mid: mid,
sendEncodingParameters: sendEncodingParameters,
recvEncodingParameters: null
};
});
if (this.usingBundle) {
sdp += 'a=group:BUNDLE ' + transceivers.map(function(t) {
return t.mid;
}).join(' ') + '\r\n';
}
tracks.forEach(function(mline, sdpMLineIndex) {
var transceiver = transceivers[sdpMLineIndex];
sdp += SDPUtils.writeMediaSection(transceiver,
transceiver.localCapabilities, 'offer', self.localStreams[0]);
});
this._pendingOffer = transceivers;
var desc = new RTCSessionDescription({
type: 'offer',
sdp: sdp
});
if (arguments.length && typeof arguments[0] === 'function') {
window.setTimeout(arguments[0], 0, desc);
}
return Promise.resolve(desc);
};
window.RTCPeerConnection.prototype.createAnswer = function() {
var self = this;
var sdp = SDPUtils.writeSessionBoilerplate();
if (this.usingBundle) {
sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) {
return t.mid;
}).join(' ') + '\r\n';
}
this.transceivers.forEach(function(transceiver) {
if (transceiver.isDatachannel) {
sdp += 'm=application 0 DTLS/SCTP 5000\r\n' +
'c=IN IP4 0.0.0.0\r\n' +
'a=mid:' + transceiver.mid + '\r\n';
return;
}
// Calculate intersection of capabilities.
var commonCapabilities = self._getCommonCapabilities(
transceiver.localCapabilities,
transceiver.remoteCapabilities);
sdp += SDPUtils.writeMediaSection(transceiver, commonCapabilities,
'answer', self.localStreams[0]);
});
var desc = new RTCSessionDescription({
type: 'answer',
sdp: sdp
});
if (arguments.length && typeof arguments[0] === 'function') {
window.setTimeout(arguments[0], 0, desc);
}
return Promise.resolve(desc);
};
window.RTCPeerConnection.prototype.addIceCandidate = function(candidate) {
if (!candidate) {
this.transceivers.forEach(function(transceiver) {
transceiver.iceTransport.addRemoteCandidate({});
});
} else {
var mLineIndex = candidate.sdpMLineIndex;
if (candidate.sdpMid) {
for (var i = 0; i < this.transceivers.length; i++) {
if (this.transceivers[i].mid === candidate.sdpMid) {
mLineIndex = i;
break;
}
}
}
var transceiver = this.transceivers[mLineIndex];
if (transceiver) {
var cand = Object.keys(candidate.candidate).length > 0 ?
SDPUtils.parseCandidate(candidate.candidate) : {};
// Ignore Chrome's invalid candidates since Edge does not like them.
if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) {
return;
}
// Ignore RTCP candidates, we assume RTCP-MUX.
if (cand.component !== '1') {
return;
}
// A dirty hack to make samples work.
if (cand.type === 'endOfCandidates') {
cand = {};
}
transceiver.iceTransport.addRemoteCandidate(cand);
// update the remoteDescription.
var sections = SDPUtils.splitSections(this.remoteDescription.sdp);
sections[mLineIndex + 1] += (cand.type ? candidate.candidate.trim()
: 'a=end-of-candidates') + '\r\n';
this.remoteDescription.sdp = sections.join('');
}
}
if (arguments.length > 1 && typeof arguments[1] === 'function') {
window.setTimeout(arguments[1], 0);
}
return Promise.resolve();
};
window.RTCPeerConnection.prototype.getStats = function() {
var promises = [];
this.transceivers.forEach(function(transceiver) {
['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport',
'dtlsTransport'].forEach(function(method) {
if (transceiver[method]) {
promises.push(transceiver[method].getStats());
}
});
});
var cb = arguments.length > 1 && typeof arguments[1] === 'function' &&
arguments[1];
return new Promise(function(resolve) {
// shim getStats with maplike support
var results = new Map();
Promise.all(promises).then(function(res) {
res.forEach(function(result) {
Object.keys(result).forEach(function(id) {
results.set(id, result[id]);
results[id] = result[id];
});
});
if (cb) {
window.setTimeout(cb, 0, results);
}
resolve(results);
});
});
};
}
};
// Expose public methods.
module.exports = {
shimPeerConnection: edgeShim.shimPeerConnection,
shimGetUserMedia: require('./getusermedia')
};
},{"../utils":49,"./getusermedia":45,"sdp":40}],45:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
// Expose public methods.
module.exports = function() {
var shimError_ = function(e) {
return {
name: {PermissionDeniedError: 'NotAllowedError'}[e.name] || e.name,
message: e.message,
constraint: e.constraint,
toString: function() {
return this.name;
}
};
};
// getUserMedia error shim.
var origGetUserMedia = navigator.mediaDevices.getUserMedia.
bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function(c) {
return origGetUserMedia(c).catch(function(e) {
return Promise.reject(shimError_(e));
});
};
};
},{}],46:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var browserDetails = require('../utils').browserDetails;
var firefoxShim = {
shimOnTrack: function() {
if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
window.RTCPeerConnection.prototype)) {
Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
get: function() {
return this._ontrack;
},
set: function(f) {
if (this._ontrack) {
this.removeEventListener('track', this._ontrack);
this.removeEventListener('addstream', this._ontrackpoly);
}
this.addEventListener('track', this._ontrack = f);
this.addEventListener('addstream', this._ontrackpoly = function(e) {
e.stream.getTracks().forEach(function(track) {
var event = new Event('track');
event.track = track;
event.receiver = {track: track};
event.streams = [e.stream];
this.dispatchEvent(event);
}.bind(this));
}.bind(this));
}
});
}
},
shimSourceObject: function() {
// Firefox has supported mozSrcObject since FF22, unprefixed in 42.
if (typeof window === 'object') {
if (window.HTMLMediaElement &&
!('srcObject' in window.HTMLMediaElement.prototype)) {
// Shim the srcObject property, once, when HTMLMediaElement is found.
Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
get: function() {
return this.mozSrcObject;
},
set: function(stream) {
this.mozSrcObject = stream;
}
});
}
}
},
shimPeerConnection: function() {
if (typeof window !== 'object' || !(window.RTCPeerConnection ||
window.mozRTCPeerConnection)) {
return; // probably media.peerconnection.enabled=false in about:config
}
// The RTCPeerConnection object.
if (!window.RTCPeerConnection) {
window.RTCPeerConnection = function(pcConfig, pcConstraints) {
if (browserDetails.version < 38) {
// .urls is not supported in FF < 38.
// create RTCIceServers with a single url.
if (pcConfig && pcConfig.iceServers) {
var newIceServers = [];
for (var i = 0; i < pcConfig.iceServers.length; i++) {
var server = pcConfig.iceServers[i];
if (server.hasOwnProperty('urls')) {
for (var j = 0; j < server.urls.length; j++) {
var newServer = {
url: server.urls[j]
};
if (server.urls[j].indexOf('turn') === 0) {
newServer.username = server.username;
newServer.credential = server.credential;
}
newIceServers.push(newServer);
}
} else {
newIceServers.push(pcConfig.iceServers[i]);
}
}
pcConfig.iceServers = newIceServers;
}
}
return new mozRTCPeerConnection(pcConfig, pcConstraints);
};
window.RTCPeerConnection.prototype = mozRTCPeerConnection.prototype;
// wrap static methods. Currently just generateCertificate.
if (mozRTCPeerConnection.generateCertificate) {
Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
get: function() {
return mozRTCPeerConnection.generateCertificate;
}
});
}
window.RTCSessionDescription = mozRTCSessionDescription;
window.RTCIceCandidate = mozRTCIceCandidate;
}
// shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
.forEach(function(method) {
var nativeMethod = RTCPeerConnection.prototype[method];
RTCPeerConnection.prototype[method] = function() {
arguments[0] = new ((method === 'addIceCandidate') ?
RTCIceCandidate : RTCSessionDescription)(arguments[0]);
return nativeMethod.apply(this, arguments);
};
});
// support for addIceCandidate(null or undefined)
var nativeAddIceCandidate =
RTCPeerConnection.prototype.addIceCandidate;
RTCPeerConnection.prototype.addIceCandidate = function() {
if (!arguments[0]) {
if (arguments[1]) {
arguments[1].apply(null);
}
return Promise.resolve();
}
return nativeAddIceCandidate.apply(this, arguments);
};
if (browserDetails.version < 48) {
// shim getStats with maplike support
var makeMapStats = function(stats) {
var map = new Map();
Object.keys(stats).forEach(function(key) {
map.set(key, stats[key]);
map[key] = stats[key];
});
return map;
};
var nativeGetStats = RTCPeerConnection.prototype.getStats;
RTCPeerConnection.prototype.getStats = function(selector, onSucc, onErr) {
return nativeGetStats.apply(this, [selector || null])
.then(function(stats) {
return makeMapStats(stats);
})
.then(onSucc, onErr);
};
}
}
};
// Expose public methods.
module.exports = {
shimOnTrack: firefoxShim.shimOnTrack,
shimSourceObject: firefoxShim.shimSourceObject,
shimPeerConnection: firefoxShim.shimPeerConnection,
shimGetUserMedia: require('./getusermedia')
};
},{"../utils":49,"./getusermedia":47}],47:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logging = require('../utils').log;
var browserDetails = require('../utils').browserDetails;
// Expose public methods.
module.exports = function() {
var shimError_ = function(e) {
return {
name: {
SecurityError: 'NotAllowedError',
PermissionDeniedError: 'NotAllowedError'
}[e.name] || e.name,
message: {
'The operation is insecure.': 'The request is not allowed by the ' +
'user agent or the platform in the current context.'
}[e.message] || e.message,
constraint: e.constraint,
toString: function() {
return this.name + (this.message && ': ') + this.message;
}
};
};
// getUserMedia constraints shim.
var getUserMedia_ = function(constraints, onSuccess, onError) {
var constraintsToFF37_ = function(c) {
if (typeof c !== 'object' || c.require) {
return c;
}
var require = [];
Object.keys(c).forEach(function(key) {
if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
return;
}
var r = c[key] = (typeof c[key] === 'object') ?
c[key] : {ideal: c[key]};
if (r.min !== undefined ||
r.max !== undefined || r.exact !== undefined) {
require.push(key);
}
if (r.exact !== undefined) {
if (typeof r.exact === 'number') {
r. min = r.max = r.exact;
} else {
c[key] = r.exact;
}
delete r.exact;
}
if (r.ideal !== undefined) {
c.advanced = c.advanced || [];
var oc = {};
if (typeof r.ideal === 'number') {
oc[key] = {min: r.ideal, max: r.ideal};
} else {
oc[key] = r.ideal;
}
c.advanced.push(oc);
delete r.ideal;
if (!Object.keys(r).length) {
delete c[key];
}
}
});
if (require.length) {
c.require = require;
}
return c;
};
constraints = JSON.parse(JSON.stringify(constraints));
if (browserDetails.version < 38) {
logging('spec: ' + JSON.stringify(constraints));
if (constraints.audio) {
constraints.audio = constraintsToFF37_(constraints.audio);
}
if (constraints.video) {
constraints.video = constraintsToFF37_(constraints.video);
}
logging('ff37: ' + JSON.stringify(constraints));
}
return navigator.mozGetUserMedia(constraints, onSuccess, function(e) {
onError(shimError_(e));
});
};
// Returns the result of getUserMedia as a Promise.
var getUserMediaPromise_ = function(constraints) {
return new Promise(function(resolve, reject) {
getUserMedia_(constraints, resolve, reject);
});
};
// Shim for mediaDevices on older versions.
if (!navigator.mediaDevices) {
navigator.mediaDevices = {getUserMedia: getUserMediaPromise_,
addEventListener: function() { },
removeEventListener: function() { }
};
}
navigator.mediaDevices.enumerateDevices =
navigator.mediaDevices.enumerateDevices || function() {
return new Promise(function(resolve) {
var infos = [
{kind: 'audioinput', deviceId: 'default', label: '', groupId: ''},
{kind: 'videoinput', deviceId: 'default', label: '', groupId: ''}
];
resolve(infos);
});
};
if (browserDetails.version < 41) {
// Work around http://bugzil.la/1169665
var orgEnumerateDevices =
navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
navigator.mediaDevices.enumerateDevices = function() {
return orgEnumerateDevices().then(undefined, function(e) {
if (e.name === 'NotFoundError') {
return [];
}
throw e;
});
};
}
if (browserDetails.version < 49) {
var origGetUserMedia = navigator.mediaDevices.getUserMedia.
bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function(c) {
return origGetUserMedia(c).then(function(stream) {
// Work around https://bugzil.la/802326
if (c.audio && !stream.getAudioTracks().length ||
c.video && !stream.getVideoTracks().length) {
stream.getTracks().forEach(function(track) {
track.stop();
});
throw new DOMException('The object can not be found here.',
'NotFoundError');
}
return stream;
}, function(e) {
return Promise.reject(shimError_(e));
});
};
}
navigator.getUserMedia = function(constraints, onSuccess, onError) {
if (browserDetails.version < 44) {
return getUserMedia_(constraints, onSuccess, onError);
}
// Replace Firefox 44+'s deprecation warning with unprefixed version.
console.warn('navigator.getUserMedia has been replaced by ' +
'navigator.mediaDevices.getUserMedia');
navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
};
};
},{"../utils":49}],48:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
'use strict';
var safariShim = {
// TODO: DrAlex, should be here, double check against LayoutTests
// shimOnTrack: function() { },
// TODO: once the back-end for the mac port is done, add.
// TODO: check for webkitGTK+
// shimPeerConnection: function() { },
shimGetUserMedia: function() {
navigator.getUserMedia = navigator.webkitGetUserMedia;
}
};
// Expose public methods.
module.exports = {
shimGetUserMedia: safariShim.shimGetUserMedia
// TODO
// shimOnTrack: safariShim.shimOnTrack,
// shimPeerConnection: safariShim.shimPeerConnection
};
},{}],49:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logDisabled_ = true;
// Utility methods.
var utils = {
disableLog: function(bool) {
if (typeof bool !== 'boolean') {
return new Error('Argument type: ' + typeof bool +
'. Please use a boolean.');
}
logDisabled_ = bool;
return (bool) ? 'adapter.js logging disabled' :
'adapter.js logging enabled';
},
log: function() {
if (typeof window === 'object') {
if (logDisabled_) {
return;
}
if (typeof console !== 'undefined' && typeof console.log === 'function') {
console.log.apply(console, arguments);
}
}
},
/**
* Extract browser version out of the provided user agent string.
*
* @param {!string} uastring userAgent string.
* @param {!string} expr Regular expression used as match criteria.
* @param {!number} pos position in the version string to be returned.
* @return {!number} browser version.
*/
extractVersion: function(uastring, expr, pos) {
var match = uastring.match(expr);
return match && match.length >= pos && parseInt(match[pos], 10);
},
/**
* Browser detector.
*
* @return {object} result containing browser and version
* properties.
*/
detectBrowser: function() {
// Returned result object.
var result = {};
result.browser = null;
result.version = null;
// Fail early if it's not a browser
if (typeof window === 'undefined' || !window.navigator) {
result.browser = 'Not a browser.';
return result;
}
// Firefox.
if (navigator.mozGetUserMedia) {
result.browser = 'firefox';
result.version = this.extractVersion(navigator.userAgent,
/Firefox\/([0-9]+)\./, 1);
// all webkit-based browsers
} else if (navigator.webkitGetUserMedia) {
// Chrome, Chromium, Webview, Opera, all use the chrome shim for now
if (window.webkitRTCPeerConnection) {
result.browser = 'chrome';
result.version = this.extractVersion(navigator.userAgent,
/Chrom(e|ium)\/([0-9]+)\./, 2);
// Safari or unknown webkit-based
// for the time being Safari has support for MediaStreams but not webRTC
} else {
// Safari UA substrings of interest for reference:
// - webkit version: AppleWebKit/602.1.25 (also used in Op,Cr)
// - safari UI version: Version/9.0.3 (unique to Safari)
// - safari UI webkit version: Safari/601.4.4 (also used in Op,Cr)
//
// if the webkit version and safari UI webkit versions are equals,
// ... this is a stable version.
//
// only the internal webkit version is important today to know if
// media streams are supported
//
if (navigator.userAgent.match(/Version\/(\d+).(\d+)/)) {
result.browser = 'safari';
result.version = this.extractVersion(navigator.userAgent,
/AppleWebKit\/([0-9]+)\./, 1);
// unknown webkit-based browser
} else {
result.browser = 'Unsupported webkit-based browser ' +
'with GUM support but no WebRTC support.';
return result;
}
}
// Edge.
} else if (navigator.mediaDevices &&
navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) {
result.browser = 'edge';
result.version = this.extractVersion(navigator.userAgent,
/Edge\/(\d+).(\d+)$/, 2);
// Default fallthrough: not supported.
} else {
result.browser = 'Not a supported browser.';
return result;
}
return result;
}
};
// Export.
module.exports = {
log: utils.log,
disableLog: utils.disableLog,
browserDetails: utils.detectBrowser(),
extractVersion: utils.extractVersion
};
},{}],50:[function(require,module,exports){
module.exports={
"name": "jssip",
"title": "JsSIP",
"description": "the Javascript SIP library",
"version": "3.0.2",
"homepage": "http://jssip.net",
"author": "José Luis Millán <[email protected]> (https://github.com/jmillan)",
"contributors": [
"Iñaki Baz Castillo <[email protected]> (https://github.com/ibc)",
"Saúl Ibarra Corretgé <[email protected]> (https://github.com/saghul)"
],
"main": "lib/JsSIP.js",
"keywords": [
"sip",
"websocket",
"webrtc",
"node",
"browser",
"library"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/versatica/JsSIP.git"
},
"bugs": {
"url": "https://github.com/versatica/JsSIP/issues"
},
"dependencies": {
"debug": "^2.3.3",
"sdp-transform": "^1.6.2",
"webrtc-adapter": "^2.0.8"
},
"devDependencies": {
"browserify": "^13.1.1",
"gulp": "git+https://github.com/gulpjs/gulp.git#4.0",
"gulp-expect-file": "0.0.7",
"gulp-header": "1.8.8",
"gulp-jshint": "^2.0.4",
"gulp-nodeunit-runner": "^0.2.2",
"gulp-rename": "^1.2.2",
"gulp-uglify": "^2.0.0",
"gulp-util": "^3.0.7",
"jshint": "^2.9.4",
"jshint-stylish": "^2.2.1",
"pegjs": "0.7.0",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0"
},
"scripts": {
"test": "gulp test"
}
}
},{}]},{},[7])(7)
});<|fim▁end|> | function parse_from_param() {
var result0; |
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smarturl.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.<|fim▁hole|> except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)<|fim▁end|> | try:
import django |
<|file_name|>PackageJammerTask.java<|end_file_name|><|fim▁begin|>/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Web Client
* Copyright (C) 2006, 2007, 2009, 2010 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.webClient.build;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.types.*;
public class PackageJammerTask
extends Task {
//
// Constants
//
private static final Pattern RE_DEFINE = Pattern.compile("^AjxPackage\\.define\\(['\"]([^'\"]+)['\"]\\);?");
private static final Pattern RE_UNDEFINE = Pattern.compile("^AjxPackage\\.undefine\\(['\"]([^'\"]+)['\"]\\);?");
private static final Pattern RE_REQUIRE = Pattern.compile("^AjxPackage\\.require\\(['\"]([^'\"]+)['\"](.*?)\\);?");
private static final Pattern RE_REQUIRE_OBJ = Pattern.compile("^AjxPackage\\.require\\((\\s*\\{\\s*name\\s*:\")?([^'\"]+)['\"](.*?)\\);?");
private static final String OUTPUT_JS = "js";
private static final String OUTPUT_HTML = "html";
private static final String OUTPUT_ALL = "all";
//
// Data
//
// attributes
private File destFile;
private File jsFile;
private File htmlFile;
private List<Source> sources = new LinkedList<Source>();
private File dependsFile;
private String output = OUTPUT_JS;
private String basepath = "";
private String extension = ".js";
private boolean verbose = false;
// children
private Text prefix;
private Text suffix;
private List<JammerFiles> files = new LinkedList<JammerFiles>();
// internal state
private String depth;
private Map<String,Boolean> defines;
private boolean isJs = true;
private boolean isHtml = false;
private boolean isAll = false;
//
// Public methods
//
// attributes
public void setDestFile(File file) {
this.destFile = file;
}
public void setJsDestFile(File file) {
this.jsFile = file;
}
public void setHtmlDestFile(File file) {
this.htmlFile = file;
}
public void setJsDir(File dir) {
Source source = new Source();
source.setDir(dir);
this.sources.clear();
this.sources.add(source);
}
public void setDependsFile(File file) {
this.dependsFile = file;
}
public void setOutput(String output) {
this.output = output;
this.isAll = OUTPUT_ALL.equals(output);
this.isHtml = this.isAll || OUTPUT_HTML.equals(output);
this.isJs = this.isAll || OUTPUT_JS.equals(output) || !this.isHtml;
}
public void setBasePath(String basepath) {
this.basepath = basepath;
}
public void setExtension(String extension) {
this.extension = extension;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
// children
public Text createPrefix() {
return this.prefix = new Text();
}
public Text createSuffix() {
return this.suffix = new Text();
}
public FileList createFileList() {
JammerFileList fileList = new JammerFileList();
this.files.add(fileList);
return fileList;
}
public FileSet createFileSet() {
JammerFileSet fileSet = new JammerFileSet();
this.files.add(fileSet);
return fileSet;
}
public Source createSrc() {
Source source = new Source();
this.sources.add(source);
return source;
}
//
// Task methods
//
public void execute() throws BuildException {
this.depth = "";
this.defines = new HashMap<String,Boolean>();
PrintWriter jsOut = null;
PrintWriter htmlOut = null;
PrintWriter dependsOut = null;
try {
if (this.isJs) {
File file = this.jsFile != null ? this.jsFile : this.destFile;
log("Jamming to ",file.toString());
jsOut = new PrintWriter(new FileWriter(file));
}
if (this.isHtml) {
File file = this.htmlFile != null ? this.htmlFile : this.destFile;
log("Jamming to ",file.toString());
htmlOut = new PrintWriter(new FileWriter(file));
}
if (this.dependsFile != null) {
log("Dependencies saved to "+this.dependsFile);
dependsOut = new PrintWriter(new FileWriter(this.dependsFile));
}
if (this.prefix != null) {
PrintWriter out = OUTPUT_JS.equals(this.prefix.output) ? jsOut : htmlOut;
if (out != null) {
out.println(this.prefix.toString());
}
}
List<String> packages = new LinkedList<String>();
for (JammerFiles files : this.files) {
boolean wrap = files.isWrapped();
boolean isManifest = files.isManifest();
File dir = files.getDir(this.getProject());
for (String filename : files.getFiles(this.getProject())) {
File file = new File(dir, filename);
String pkg = path2package(stripExt(filename).replace(File.separatorChar, '/'));
packages.add(pkg);
if (this.isHtml && !isManifest) {
printHTML(htmlOut, pkg, files.getBasePath(), files.getExtension());
}
jamFile(jsOut, htmlOut, file, pkg, packages, wrap, true, dependsOut);
}
}
if (this.isHtml && packages.size() > 0 && htmlOut != null) {
htmlOut.println("<script type=\"text/javascript\">");
for (String pkg : packages) {
htmlOut.print("AjxPackage.define(\"");
htmlOut.print(pkg);
htmlOut.println("\");");
}
htmlOut.println("</script>");
}
if (this.suffix != null) {
PrintWriter out = OUTPUT_JS.equals(this.prefix.output) ? jsOut : htmlOut;
if (out != null) {
out.println(this.suffix.toString());
}
}
}
catch (IOException e) {
throw new BuildException(e);
}
finally {
if (jsOut != null) jsOut.close();
if (htmlOut != null) htmlOut.close();
if (dependsOut != null) dependsOut.close();
}
}
//
// Private methods
//
private void jamFile(PrintWriter jsOut, PrintWriter htmlOut, File ifile,
String pkg, List<String> packages,
boolean wrap, boolean top, PrintWriter dependsOut)
throws IOException {
if (this.verbose) log("file: ",ifile.toString());
BufferedReader in = new BufferedReader(new FileReader(ifile));
boolean isJS = ifile.getName().endsWith(".js");
// "wrap" source
if (this.isJs && isJS && pkg != null && wrap && jsOut != null) {
jsOut.print("if (AjxPackage.define(\"");
jsOut.print(pkg);
jsOut.println("\")) {");
}
// remember this file
if (dependsOut != null) {
dependsOut.println(ifile.getCanonicalPath());
dependsOut.flush();
}
// read file
String line;
while ((line = in.readLine()) != null) {
// define package
String define = matchDefine(line);
if (define != null) {
if (this.verbose) log("define ", define);
this.defines.put(package2path(define), true);
continue;
}
// undefine package
String undefine = matchUndefine(line);
if (undefine != null) {
if (this.verbose) log("undefine ", undefine);
this.defines.remove(package2path(undefine));
continue;
}
// require package
String require = matchRequire(line);
if (require != null) {
if (this.verbose) log("require ", require);
String path = package2path(require);
if (this.defines.get(path) == null) {
packages.add(require);
// output script tag
if (this.isHtml && !path.endsWith("__all__")) {
printHTML(htmlOut, require, null, null);
}
// implicitly define and jam on!
this.defines.put(path, true);
File file = this.getFileForPath(path);
String odepth = this.verbose ? this.depth : null;
if (this.verbose) this.depth += " ";
jamFile(jsOut, htmlOut, file, path2package(require), packages, wrap, false, dependsOut);
if (this.verbose) this.depth = odepth;
}
continue;
}
// leave line intact
if (this.isJs && isJS && jsOut != null) {
jsOut.println(line);
}
}
if (this.isJs && isJS && pkg != null && wrap && jsOut != null) {
jsOut.println("}");
}
in.close();
}
private File getFileForPath(String path) {
String name = path.replace('/',File.separatorChar)+".js";
File file = null;
for (Source source : this.sources) {
String filename = name;
if (source.prefix != null && name.startsWith(source.prefix+"/")) {
filename = name.substring(source.prefix.length() + 1);
}
file = new File(source.dir, filename);
if (file.exists()) {
break;
}
}
return file;
}
private void printHTML(PrintWriter out, String pkg, String basePath, String extension) {
if (out == null) return;
String path = package2path(pkg);
out.print("<script type=\"text/javascript\" src=\"");
out.print(basePath != null ? basePath : this.basepath);
out.print(path);
out.print(extension != null ? extension : this.extension);
out.println("\"></script>");
}
private String matchDefine(String s) {
Matcher m = RE_DEFINE.matcher(s);
return m.matches() ? m.group(1) : null;
}
private String matchUndefine(String s) {
Matcher m = RE_UNDEFINE.matcher(s);
return m.matches() ? m.group(1) : null;
}
private String matchRequire(String s) {
Matcher m = RE_REQUIRE.matcher(s);
if (m.matches()){
return m.group(1);
}
m = RE_REQUIRE_OBJ.matcher(s);
if (m.matches()){
return m.group(2);
}
return null;
}
private void log(String... ss) {
System.out.print(this.depth);
for (String s : ss) {
System.out.print(s);
}
System.out.println();
}
//
// Private functions
//
private static String package2path(String pkg) {
return pkg.replace('.', '/').replaceAll("\\*$", "__all__");
}
private static String path2package(String path) {
return path.replace('/', '.').replaceAll("\\*$", "__all__");
}
private static String stripExt(String fname) {
return fname.replaceAll("\\..+$", "");
}
//
// Classes
//
private static interface JammerFiles {
public boolean isWrapped();
public boolean isManifest();
public String getBasePath();
public String getExtension();
public File getDir(Project project);
public String[] getFiles(Project project);
}
public static class JammerFileList
extends FileList
implements JammerFiles {
//
// Data
//
private boolean wrap = true;
private boolean manifest = true;
private String basePath;
private String extension;
//
// Public methods
//
public void setWrap(boolean wrap) {
this.wrap = wrap;
}<|fim▁hole|> public void setManifest(boolean manifest) {
this.manifest = manifest;
}
public boolean isManifest() {
return this.manifest;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return this.basePath;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getExtension() {
return this.extension;
}
} // class JammerFileList
public static class JammerFileSet
extends FileSet
implements JammerFiles {
//
// Data
//
private boolean wrap = true;
private boolean manifest = true;
private String basePath;
private String extension;
//
// Public methods
//
public String[] getFiles(Project project) {
return this.getDirectoryScanner(project).getIncludedFiles();
}
public void setWrap(boolean wrap) {
this.wrap = wrap;
}
public boolean isWrapped() {
return wrap;
}
public void setManifest(boolean manifest) {
this.manifest = manifest;
}
public boolean isManifest() {
return this.manifest;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return this.basePath;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getExtension() {
return this.extension;
}
} // class JammerFileList
public static class Text {
public String output = PackageJammerTask.OUTPUT_JS;
private StringBuilder str = new StringBuilder();
public void setOutput(String output) {
this.output = output;
}
public void addText(String s) {
str.append(s);
}
public String toString() { return str.toString(); }
}
public class Source {
public File dir;
public String prefix;
public void setDir(File dir) {
this.dir = dir;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
}
} // class PackageJammerTask<|fim▁end|> | public boolean isWrapped() {
return this.wrap;
}
|
<|file_name|>legacy.py<|end_file_name|><|fim▁begin|>"""
Instructor Views
"""
## NOTE: This is the code for the legacy instructor dashboard
## We are no longer supporting this file or accepting changes into it.
from contextlib import contextmanager
import csv
import json
import logging
import os
import re
import requests
from collections import defaultdict, OrderedDict
from markupsafe import escape
from requests.status_codes import codes
from StringIO import StringIO
from django.conf import settings
from django.contrib.auth.models import User
from django.http import HttpResponse
from django_future.csrf import ensure_csrf_cookie
from django.views.decorators.cache import cache_control
from django.core.urlresolvers import reverse
from django.core.mail import send_mail
from django.utils import timezone
from xmodule_modifiers import wrap_xblock, request_token
import xmodule.graders as xmgraders
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from xmodule.modulestore.exceptions import ItemNotFoundError
from xmodule.html_module import HtmlDescriptor
from opaque_keys import InvalidKeyError
from lms.lib.xblock.runtime import quote_slashes
from submissions import api as sub_api # installed from the edx-submissions repository
from bulk_email.models import CourseEmail, CourseAuthorization
from courseware import grades
from courseware.access import has_access
from courseware.courses import get_course_with_access, get_cms_course_link
from student.roles import (
CourseStaffRole, CourseInstructorRole, CourseBetaTesterRole, GlobalStaff
)
from courseware.models import StudentModule
from django_comment_common.models import (
Role, FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA
)
from django_comment_client.utils import has_forum_access
from instructor.offline_gradecalc import student_grades, offline_grades_available
from instructor.views.tools import strip_if_string, bulk_email_is_enabled_for_course
from instructor_task.api import (
get_running_instructor_tasks,
get_instructor_task_history,
submit_rescore_problem_for_all_students,
submit_rescore_problem_for_student,
submit_reset_problem_attempts_for_all_students,
submit_bulk_course_email
)
from instructor_task.views import get_task_completion_info
from edxmako.shortcuts import render_to_response, render_to_string
from class_dashboard import dashboard_data
from psychometrics import psychoanalyze
from student.models import (
CourseEnrollment,
CourseEnrollmentAllowed,
unique_id_for_user,
anonymous_id_for_user
)
import track.views
from xblock.field_data import DictFieldData
from xblock.fields import ScopeIds
from django.utils.translation import ugettext as _
from microsite_configuration import microsite
from opaque_keys.edx.locations import i4xEncoder
log = logging.getLogger(__name__)
# internal commands for managing forum roles:
FORUM_ROLE_ADD = 'add'
FORUM_ROLE_REMOVE = 'remove'
# For determining if a shibboleth course
SHIBBOLETH_DOMAIN_PREFIX = 'shib:'
def split_by_comma_and_whitespace(a_str):
"""
Return string a_str, split by , or whitespace
"""
return re.split(r'[\s,]', a_str)
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def instructor_dashboard(request, course_id):
"""Display the instructor dashboard for a course."""
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
course = get_course_with_access(request.user, 'staff', course_key, depth=None)
instructor_access = has_access(request.user, 'instructor', course) # an instructor can manage staff lists
forum_admin_access = has_forum_access(request.user, course_key, FORUM_ROLE_ADMINISTRATOR)
msg = ''
email_msg = ''
email_to_option = None
email_subject = None
html_message = ''
show_email_tab = False
problems = []
plots = []
datatable = {}
# the instructor dashboard page is modal: grades, psychometrics, admin
# keep that state in request.session (defaults to grades mode)
idash_mode = request.POST.get('idash_mode', '')
idash_mode_key = u'idash_mode:{0}'.format(course_id)
if idash_mode:
request.session[idash_mode_key] = idash_mode
else:
idash_mode = request.session.get(idash_mode_key, 'Grades')
enrollment_number = CourseEnrollment.num_enrolled_in(course_key)
# assemble some course statistics for output to instructor
def get_course_stats_table():
datatable = {
'header': ['Statistic', 'Value'],
'title': _('Course Statistics At A Glance'),
}
data = [['# Enrolled', enrollment_number]]
data += [['Date', timezone.now().isoformat()]]
data += compute_course_stats(course).items()
if request.user.is_staff:
for field in course.fields.values():
if getattr(field.scope, 'user', False):
continue
data.append([
field.name,
json.dumps(field.read_json(course), cls=i4xEncoder)
])
datatable['data'] = data
return datatable
def return_csv(func, datatable, file_pointer=None):
"""Outputs a CSV file from the contents of a datatable."""
if file_pointer is None:
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = (u'attachment; filename={0}'.format(func)).encode('utf-8')
else:
response = file_pointer
writer = csv.writer(response, dialect='excel', quotechar='"', quoting=csv.QUOTE_ALL)
encoded_row = [unicode(s).encode('utf-8') for s in datatable['header']]
writer.writerow(encoded_row)
for datarow in datatable['data']:
# 's' here may be an integer, float (eg score) or string (eg student name)
encoded_row = [
# If s is already a UTF-8 string, trying to make a unicode
# object out of it will fail unless we pass in an encoding to
# the constructor. But we can't do that across the board,
# because s is often a numeric type. So just do this.
s if isinstance(s, str) else unicode(s).encode('utf-8')
for s in datarow
]
writer.writerow(encoded_row)
return response
def get_student_from_identifier(unique_student_identifier):
"""Gets a student object using either an email address or username"""
unique_student_identifier = strip_if_string(unique_student_identifier)
msg = ""
try:
if "@" in unique_student_identifier:
student = User.objects.get(email=unique_student_identifier)
else:
student = User.objects.get(username=unique_student_identifier)
msg += _("Found a single student. ")
except User.DoesNotExist:
student = None
msg += "<font color='red'>{text}</font>".format(
text=_("Couldn't find student with that email or username.")
)
return msg, student
# process actions from form POST
action = request.POST.get('action', '')
use_offline = request.POST.get('use_offline_grades', False)
if settings.FEATURES['ENABLE_MANUAL_GIT_RELOAD']:
if 'GIT pull' in action:
data_dir = course.data_dir
log.debug('git pull {0}'.format(data_dir))
gdir = settings.DATA_DIR / data_dir
if not os.path.exists(gdir):
msg += "====> ERROR in gitreload - no such directory {0}".format(gdir)
else:
cmd = "cd {0}; git reset --hard HEAD; git clean -f -d; git pull origin; chmod g+w course.xml".format(gdir)
msg += "git pull on {0}:<p>".format(data_dir)
msg += "<pre>{0}</pre></p>".format(escape(os.popen(cmd).read()))
track.views.server_track(request, "git-pull", {"directory": data_dir}, page="idashboard")
if 'Reload course' in action:
log.debug('reloading {0} ({1})'.format(course_key, course))
try:
data_dir = course.data_dir
modulestore().try_load_course(data_dir)
msg += "<br/><p>Course reloaded from {0}</p>".format(data_dir)
track.views.server_track(request, "reload", {"directory": data_dir}, page="idashboard")
course_errors = modulestore().get_course_errors(course.id)
msg += '<ul>'
for cmsg, cerr in course_errors:
msg += "<li>{0}: <pre>{1}</pre>".format(cmsg, escape(cerr))
msg += '</ul>'
except Exception as err: # pylint: disable=broad-except
msg += '<br/><p>Error: {0}</p>'.format(escape(err))
if action == 'Dump list of enrolled students' or action == 'List enrolled students':
log.debug(action)
datatable = get_student_grade_summary_data(request, course, get_grades=False, use_offline=use_offline)
datatable['title'] = _('List of students enrolled in {course_key}').format(course_key=course_key.to_deprecated_string())
track.views.server_track(request, "list-students", {}, page="idashboard")
elif 'Dump Grades' in action:
log.debug(action)
datatable = get_student_grade_summary_data(request, course, get_grades=True, use_offline=use_offline)
datatable['title'] = _('Summary Grades of students enrolled in {course_key}').format(course_key=course_key.to_deprecated_string())
track.views.server_track(request, "dump-grades", {}, page="idashboard")
elif 'Dump all RAW grades' in action:
log.debug(action)
datatable = get_student_grade_summary_data(request, course, get_grades=True,
get_raw_scores=True, use_offline=use_offline)
datatable['title'] = _('Raw Grades of students enrolled in {course_key}').format(course_key=course_key)
track.views.server_track(request, "dump-grades-raw", {}, page="idashboard")
elif 'Download CSV of all student grades' in action:
track.views.server_track(request, "dump-grades-csv", {}, page="idashboard")
return return_csv('grades_{0}.csv'.format(course_key.to_deprecated_string()),
get_student_grade_summary_data(request, course, use_offline=use_offline))
elif 'Download CSV of all RAW grades' in action:
track.views.server_track(request, "dump-grades-csv-raw", {}, page="idashboard")
return return_csv('grades_{0}_raw.csv'.format(course_key.to_deprecated_string()),
get_student_grade_summary_data(request, course, get_raw_scores=True, use_offline=use_offline))
elif 'Download CSV of answer distributions' in action:
track.views.server_track(request, "dump-answer-dist-csv", {}, page="idashboard")
return return_csv('answer_dist_{0}.csv'.format(course_key.to_deprecated_string()), get_answers_distribution(request, course_key))
elif 'Dump description of graded assignments configuration' in action:
# what is "graded assignments configuration"?
track.views.server_track(request, "dump-graded-assignments-config", {}, page="idashboard")
msg += dump_grading_context(course)
elif "Rescore ALL students' problem submissions" in action:
problem_location_str = strip_if_string(request.POST.get('problem_for_all_students', ''))
try:
problem_location = course_key.make_usage_key_from_deprecated_string(problem_location_str)
instructor_task = submit_rescore_problem_for_all_students(request, problem_location)
if instructor_task is None:
msg += '<font color="red">{text}</font>'.format(
text=_('Failed to create a background task for rescoring "{problem_url}".').format(
problem_url=problem_location_str
)
)
else:
track.views.server_track(
request,
"rescore-all-submissions",
{
"problem": problem_location_str,
"course": course_key.to_deprecated_string()
},
page="idashboard"
)
except (InvalidKeyError, ItemNotFoundError) as err:
msg += '<font color="red">{text}</font>'.format(
text=_('Failed to create a background task for rescoring "{problem_url}": problem not found.').format(
problem_url=problem_location_str
)
)
except Exception as err: # pylint: disable=broad-except
log.error("Encountered exception from rescore: {0}".format(err))
msg += '<font color="red">{text}</font>'.format(
text=_('Failed to create a background task for rescoring "{url}": {message}.').format(
url=problem_location_str, message=err.message
)
)
elif "Reset ALL students' attempts" in action:
problem_location_str = strip_if_string(request.POST.get('problem_for_all_students', ''))
try:
problem_location = course_key.make_usage_key_from_deprecated_string(problem_location_str)
instructor_task = submit_reset_problem_attempts_for_all_students(request, problem_location)
if instructor_task is None:
msg += '<font color="red">{text}</font>'.format(
text=_('Failed to create a background task for resetting "{problem_url}".').format(problem_url=problem_location_str)
)
else:
track.views.server_track(
request,
"reset-all-attempts",
{
"problem": problem_location_str,
"course": course_key.to_deprecated_string()
},
page="idashboard"
)
except (InvalidKeyError, ItemNotFoundError) as err:
log.error('Failure to reset: unknown problem "{0}"'.format(err))
msg += '<font color="red">{text}</font>'.format(
text=_('Failed to create a background task for resetting "{problem_url}": problem not found.').format(
problem_url=problem_location_str
)
)
except Exception as err: # pylint: disable=broad-except
log.error("Encountered exception from reset: {0}".format(err))
msg += '<font color="red">{text}</font>'.format(
text=_('Failed to create a background task for resetting "{url}": {message}.').format(
url=problem_location_str, message=err.message
)
)
elif "Show Background Task History for Student" in action:
# put this before the non-student case, since the use of "in" will cause this to be missed
unique_student_identifier = request.POST.get('unique_student_identifier', '')
message, student = get_student_from_identifier(unique_student_identifier)
if student is None:
msg += message
else:
problem_location_str = strip_if_string(request.POST.get('problem_for_student', ''))
try:
problem_location = course_key.make_usage_key_from_deprecated_string(problem_location_str)
except InvalidKeyError:
msg += '<font color="red">{text}</font>'.format(
text=_('Could not find problem location "{url}".').format(
url=problem_location_str
)
)
else:
message, datatable = get_background_task_table(course_key, problem_location, student)
msg += message
elif "Show Background Task History" in action:
problem_location_str = strip_if_string(request.POST.get('problem_for_all_students', ''))
try:
problem_location = course_key.make_usage_key_from_deprecated_string(problem_location_str)
except InvalidKeyError:
msg += '<font color="red">{text}</font>'.format(
text=_('Could not find problem location "{url}".').format(
url=problem_location_str
)
)
else:
message, datatable = get_background_task_table(course_key, problem_location)
msg += message
elif ("Reset student's attempts" in action or
"Delete student state for module" in action or
"Rescore student's problem submission" in action):
# get the form data
unique_student_identifier = request.POST.get(
'unique_student_identifier', ''
)
problem_location_str = strip_if_string(request.POST.get('problem_for_student', ''))
try:
module_state_key = course_key.make_usage_key_from_deprecated_string(problem_location_str)
except InvalidKeyError:
msg += '<font color="red">{text}</font>'.format(
text=_('Could not find problem location "{url}".').format(
url=problem_location_str
)
)
else:
# try to uniquely id student by email address or username
message, student = get_student_from_identifier(unique_student_identifier)
msg += message
student_module = None
if student is not None:
# Reset the student's score in the submissions API
# Currently this is used only by open assessment (ORA 2)
# We need to do this *before* retrieving the `StudentModule` model,
# because it's possible for a score to exist even if no student module exists.
if "Delete student state for module" in action:
try:
sub_api.reset_score(
anonymous_id_for_user(student, course_key),
course_key.to_deprecated_string(),
module_state_key.to_deprecated_string(),
)
except sub_api.SubmissionError:
# Trust the submissions API to log the error
error_msg = _("An error occurred while deleting the score.")
msg += "<font color='red'>{err}</font> ".format(err=error_msg)
# find the module in question
try:
student_module = StudentModule.objects.get(
student_id=student.id,
course_id=course_key,
module_state_key=module_state_key
)
msg += _("Found module. ")
except StudentModule.DoesNotExist as err:
error_msg = _("Couldn't find module with that urlname: {url}. ").format(url=problem_location_str)
msg += "<font color='red'>{err_msg} ({err})</font>".format(err_msg=error_msg, err=err)
log.debug(error_msg)
if student_module is not None:
if "Delete student state for module" in action:
# delete the state
try:
student_module.delete()
msg += "<font color='red'>{text}</font>".format(
text=_("Deleted student module state for {state}!").format(state=module_state_key)
)
event = {
"problem": problem_location_str,
"student": unique_student_identifier,
"course": course_key.to_deprecated_string()
}
track.views.server_track(
request,
"delete-student-module-state",
event,
page="idashboard"
)
except Exception as err: # pylint: disable=broad-except
error_msg = _("Failed to delete module state for {id}/{url}. ").format(
id=unique_student_identifier, url=problem_location_str
)
msg += "<font color='red'>{err_msg} ({err})</font>".format(err_msg=error_msg, err=err)
log.exception(error_msg)
elif "Reset student's attempts" in action:
# modify the problem's state
try:
# load the state json
problem_state = json.loads(student_module.state)
old_number_of_attempts = problem_state["attempts"]
problem_state["attempts"] = 0
# save
student_module.state = json.dumps(problem_state)
student_module.save()
event = {
"old_attempts": old_number_of_attempts,
"student": unicode(student),
"problem": student_module.module_state_key,
"instructor": unicode(request.user),
"course": course_key.to_deprecated_string()
}
track.views.server_track(request, "reset-student-attempts", event, page="idashboard")
msg += "<font color='green'>{text}</font>".format(
text=_("Module state successfully reset!")
)
except Exception as err: # pylint: disable=broad-except
error_msg = _("Couldn't reset module state for {id}/{url}. ").format(
id=unique_student_identifier, url=problem_location_str
)
msg += "<font color='red'>{err_msg} ({err})</font>".format(err_msg=error_msg, err=err)
log.exception(error_msg)
else:
# "Rescore student's problem submission" case
try:
instructor_task = submit_rescore_problem_for_student(request, module_state_key, student)
if instructor_task is None:
msg += '<font color="red">{text}</font>'.format(
text=_('Failed to create a background task for rescoring "{key}" for student {id}.').format(
key=module_state_key, id=unique_student_identifier
)
)
else:
track.views.server_track(
request,
"rescore-student-submission",
{
"problem": module_state_key,
"student": unique_student_identifier,
"course": course_key.to_deprecated_string()
},
page="idashboard"
)
except Exception as err: # pylint: disable=broad-except
msg += '<font color="red">{text}</font>'.format(
text=_('Failed to create a background task for rescoring "{key}": {id}.').format(
key=module_state_key, id=err.message
)
)
log.exception("Encountered exception from rescore: student '{0}' problem '{1}'".format(
unique_student_identifier, module_state_key
)
)
elif "Get link to student's progress page" in action:
unique_student_identifier = request.POST.get('unique_student_identifier', '')
# try to uniquely id student by email address or username
message, student = get_student_from_identifier(unique_student_identifier)
msg += message
if student is not None:
progress_url = reverse('student_progress', kwargs={
'course_id': course_key.to_deprecated_string(),
'student_id': student.id
})
track.views.server_track(
request,
"get-student-progress-page",
{
"student": unicode(student),
"instructor": unicode(request.user),
"course": course_key.to_deprecated_string()
},
page="idashboard"
)
msg += "<a href='{url}' target='_blank'>{text}</a>.".format(
url=progress_url,
text=_("Progress page for username: {username} with email address: {email}").format(
username=student.username, email=student.email
)
)
#----------------------------------------
# export grades to remote gradebook
elif action == 'List assignments available in remote gradebook':
msg2, datatable = _do_remote_gradebook(request.user, course, 'get-assignments')
msg += msg2
elif action == 'List assignments available for this course':
log.debug(action)
allgrades = get_student_grade_summary_data(request, course, get_grades=True, use_offline=use_offline)
assignments = [[x] for x in allgrades['assignments']]
datatable = {'header': [_('Assignment Name')]}
datatable['data'] = assignments
datatable['title'] = action
msg += 'assignments=<pre>%s</pre>' % assignments
elif action == 'List enrolled students matching remote gradebook':
stud_data = get_student_grade_summary_data(request, course, get_grades=False, use_offline=use_offline)
msg2, rg_stud_data = _do_remote_gradebook(request.user, course, 'get-membership')
datatable = {'header': ['Student email', 'Match?']}
rg_students = [x['email'] for x in rg_stud_data['retdata']]
def domatch(x):
return 'yes' if x.email in rg_students else 'No'
datatable['data'] = [[x.email, domatch(x)] for x in stud_data['students']]
datatable['title'] = action
elif action in ['Display grades for assignment', 'Export grades for assignment to remote gradebook',
'Export CSV file of grades for assignment']:
log.debug(action)
datatable = {}
aname = request.POST.get('assignment_name', '')
if not aname:
msg += "<font color='red'>{text}</font>".format(text=_("Please enter an assignment name"))
else:
allgrades = get_student_grade_summary_data(request, course, get_grades=True, use_offline=use_offline)
if aname not in allgrades['assignments']:
msg += "<font color='red'>{text}</font>".format(
text=_("Invalid assignment name '{name}'").format(name=aname)
)
else:
aidx = allgrades['assignments'].index(aname)
datatable = {'header': [_('External email'), aname]}
ddata = []
for student in allgrades['students']: # do one by one in case there is a student who has only partial grades
try:
ddata.append([student.email, student.grades[aidx]])
except IndexError:
log.debug('No grade for assignment {idx} ({name}) for student {email}'.format(
idx=aidx, name=aname, email=student.email)
)
datatable['data'] = ddata
datatable['title'] = _('Grades for assignment "{name}"').format(name=aname)
if 'Export CSV' in action:<|fim▁hole|> elif 'remote gradebook' in action:
file_pointer = StringIO()
return_csv('', datatable, file_pointer=file_pointer)
file_pointer.seek(0)
files = {'datafile': file_pointer}
msg2, __ = _do_remote_gradebook(request.user, course, 'post-grades', files=files)
msg += msg2
#----------------------------------------
# Admin
elif 'List course staff' in action:
role = CourseStaffRole(course.id)
datatable = _role_members_table(role, _("List of Staff"), course_key)
track.views.server_track(request, "list-staff", {}, page="idashboard")
elif 'List course instructors' in action and GlobalStaff().has_user(request.user):
role = CourseInstructorRole(course.id)
datatable = _role_members_table(role, _("List of Instructors"), course_key)
track.views.server_track(request, "list-instructors", {}, page="idashboard")
elif action == 'Add course staff':
uname = request.POST['staffuser']
role = CourseStaffRole(course.id)
msg += add_user_to_role(request, uname, role, 'staff', 'staff')
elif action == 'Add instructor' and request.user.is_staff:
uname = request.POST['instructor']
role = CourseInstructorRole(course.id)
msg += add_user_to_role(request, uname, role, 'instructor', 'instructor')
elif action == 'Remove course staff':
uname = request.POST['staffuser']
role = CourseStaffRole(course.id)
msg += remove_user_from_role(request, uname, role, 'staff', 'staff')
elif action == 'Remove instructor' and request.user.is_staff:
uname = request.POST['instructor']
role = CourseInstructorRole(course.id)
msg += remove_user_from_role(request, uname, role, 'instructor', 'instructor')
#----------------------------------------
# DataDump
elif 'Download CSV of all student profile data' in action:
enrolled_students = User.objects.filter(
courseenrollment__course_id=course_key,
courseenrollment__is_active=1,
).order_by('username').select_related("profile")
profkeys = ['name', 'language', 'location', 'year_of_birth', 'gender', 'level_of_education',
'mailing_address', 'goals']
datatable = {'header': ['username', 'email'] + profkeys}
def getdat(user):
"""
Return a list of profile data for the given user.
"""
profile = user.profile
return [user.username, user.email] + [getattr(profile, xkey, '') for xkey in profkeys]
datatable['data'] = [getdat(u) for u in enrolled_students]
datatable['title'] = _('Student profile data for course {course_id}').format(
course_id=course_key.to_deprecated_string()
)
return return_csv(
'profiledata_{course_id}.csv'.format(course_id=course_key.to_deprecated_string()),
datatable
)
elif 'Download CSV of all responses to problem' in action:
problem_to_dump = request.POST.get('problem_to_dump', '')
if problem_to_dump[-4:] == ".xml":
problem_to_dump = problem_to_dump[:-4]
try:
module_state_key = course_key.make_usage_key_from_deprecated_string(problem_to_dump)
smdat = StudentModule.objects.filter(
course_id=course_key,
module_state_key=module_state_key
)
smdat = smdat.order_by('student')
msg += _("Found {num} records to dump.").format(num=smdat)
except Exception as err: # pylint: disable=broad-except
msg += "<font color='red'>{text}</font><pre>{err}</pre>".format(
text=_("Couldn't find module with that urlname."),
err=escape(err)
)
smdat = []
if smdat:
datatable = {'header': ['username', 'state']}
datatable['data'] = [[x.student.username, x.state] for x in smdat]
datatable['title'] = _('Student state for problem {problem}').format(problem=problem_to_dump)
return return_csv('student_state_from_{problem}.csv'.format(problem=problem_to_dump), datatable)
elif 'Download CSV of all student anonymized IDs' in action:
students = User.objects.filter(
courseenrollment__course_id=course_key,
).order_by('id')
datatable = {'header': ['User ID', 'Anonymized User ID', 'Course Specific Anonymized User ID']}
datatable['data'] = [[s.id, unique_id_for_user(s, save=False), anonymous_id_for_user(s, course_key, save=False)] for s in students]
return return_csv(course_key.to_deprecated_string().replace('/', '-') + '-anon-ids.csv', datatable)
#----------------------------------------
# Group management
elif 'List beta testers' in action:
role = CourseBetaTesterRole(course.id)
datatable = _role_members_table(role, _("List of Beta Testers"), course_key)
track.views.server_track(request, "list-beta-testers", {}, page="idashboard")
elif action == 'Add beta testers':
users = request.POST['betausers']
log.debug("users: {0!r}".format(users))
role = CourseBetaTesterRole(course.id)
for username_or_email in split_by_comma_and_whitespace(users):
msg += "<p>{0}</p>".format(
add_user_to_role(request, username_or_email, role, 'beta testers', 'beta-tester'))
elif action == 'Remove beta testers':
users = request.POST['betausers']
role = CourseBetaTesterRole(course.id)
for username_or_email in split_by_comma_and_whitespace(users):
msg += "<p>{0}</p>".format(
remove_user_from_role(request, username_or_email, role, 'beta testers', 'beta-tester'))
#----------------------------------------
# forum administration
elif action == 'List course forum admins':
rolename = FORUM_ROLE_ADMINISTRATOR
datatable = {}
msg += _list_course_forum_members(course_key, rolename, datatable)
track.views.server_track(
request, "list-forum-admins", {"course": course_key.to_deprecated_string()}, page="idashboard"
)
elif action == 'Remove forum admin':
uname = request.POST['forumadmin']
msg += _update_forum_role_membership(uname, course, FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_REMOVE)
track.views.server_track(
request, "remove-forum-admin", {"username": uname, "course": course_key.to_deprecated_string()},
page="idashboard"
)
elif action == 'Add forum admin':
uname = request.POST['forumadmin']
msg += _update_forum_role_membership(uname, course, FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_ADD)
track.views.server_track(
request, "add-forum-admin", {"username": uname, "course": course_key.to_deprecated_string()},
page="idashboard"
)
elif action == 'List course forum moderators':
rolename = FORUM_ROLE_MODERATOR
datatable = {}
msg += _list_course_forum_members(course_key, rolename, datatable)
track.views.server_track(
request, "list-forum-mods", {"course": course_key.to_deprecated_string()}, page="idashboard"
)
elif action == 'Remove forum moderator':
uname = request.POST['forummoderator']
msg += _update_forum_role_membership(uname, course, FORUM_ROLE_MODERATOR, FORUM_ROLE_REMOVE)
track.views.server_track(
request, "remove-forum-mod", {"username": uname, "course": course_key.to_deprecated_string()},
page="idashboard"
)
elif action == 'Add forum moderator':
uname = request.POST['forummoderator']
msg += _update_forum_role_membership(uname, course, FORUM_ROLE_MODERATOR, FORUM_ROLE_ADD)
track.views.server_track(
request, "add-forum-mod", {"username": uname, "course": course_key.to_deprecated_string()},
page="idashboard"
)
elif action == 'List course forum community TAs':
rolename = FORUM_ROLE_COMMUNITY_TA
datatable = {}
msg += _list_course_forum_members(course_key, rolename, datatable)
track.views.server_track(
request, "list-forum-community-TAs", {"course": course_key.to_deprecated_string()},
page="idashboard"
)
elif action == 'Remove forum community TA':
uname = request.POST['forummoderator']
msg += _update_forum_role_membership(uname, course, FORUM_ROLE_COMMUNITY_TA, FORUM_ROLE_REMOVE)
track.views.server_track(
request, "remove-forum-community-TA", {
"username": uname, "course": course_key.to_deprecated_string()
},
page="idashboard"
)
elif action == 'Add forum community TA':
uname = request.POST['forummoderator']
msg += _update_forum_role_membership(uname, course, FORUM_ROLE_COMMUNITY_TA, FORUM_ROLE_ADD)
track.views.server_track(
request, "add-forum-community-TA", {
"username": uname, "course": course_key.to_deprecated_string()
},
page="idashboard"
)
#----------------------------------------
# enrollment
elif action == 'List students who may enroll but may not have yet signed up':
ceaset = CourseEnrollmentAllowed.objects.filter(course_id=course_key)
datatable = {'header': ['StudentEmail']}
datatable['data'] = [[x.email] for x in ceaset]
datatable['title'] = action
elif action == 'Enroll multiple students':
is_shib_course = uses_shib(course)
students = request.POST.get('multiple_students', '')
auto_enroll = bool(request.POST.get('auto_enroll'))
email_students = bool(request.POST.get('email_students'))
secure = request.is_secure()
ret = _do_enroll_students(course, course_key, students, secure=secure, auto_enroll=auto_enroll, email_students=email_students, is_shib_course=is_shib_course)
datatable = ret['datatable']
elif action == 'Unenroll multiple students':
students = request.POST.get('multiple_students', '')
email_students = bool(request.POST.get('email_students'))
ret = _do_unenroll_students(course_key, students, email_students=email_students)
datatable = ret['datatable']
elif action == 'List sections available in remote gradebook':
msg2, datatable = _do_remote_gradebook(request.user, course, 'get-sections')
msg += msg2
elif action in ['List students in section in remote gradebook',
'Overload enrollment list using remote gradebook',
'Merge enrollment list with remote gradebook']:
section = request.POST.get('gradebook_section', '')
msg2, datatable = _do_remote_gradebook(request.user, course, 'get-membership', dict(section=section))
msg += msg2
if not 'List' in action:
students = ','.join([x['email'] for x in datatable['retdata']])
overload = 'Overload' in action
secure = request.is_secure()
ret = _do_enroll_students(course, course_key, students, secure=secure, overload=overload)
datatable = ret['datatable']
#----------------------------------------
# email
elif action == 'Send email':
email_to_option = request.POST.get("to_option")
email_subject = request.POST.get("subject")
html_message = request.POST.get("message")
if bulk_email_is_enabled_for_course(course_key):
try:
# Create the CourseEmail object. This is saved immediately, so that
# any transaction that has been pending up to this point will also be
# committed.
email = CourseEmail.create(
course_key.to_deprecated_string(), request.user, email_to_option, email_subject, html_message
)
# Submit the task, so that the correct InstructorTask object gets created (for monitoring purposes)
submit_bulk_course_email(request, course_key, email.id) # pylint: disable=E1101
except Exception as err: # pylint: disable=broad-except
# Catch any errors and deliver a message to the user
error_msg = "Failed to send email! ({0})".format(err)
msg += "<font color='red'>" + error_msg + "</font>"
log.exception(error_msg)
else:
# If sending the task succeeds, deliver a success message to the user.
if email_to_option == "all":
text = _(
"Your email was successfully queued for sending. "
"Please note that for large classes, it may take up to an hour "
"(or more, if other courses are simultaneously sending email) "
"to send all emails."
)
else:
text = _('Your email was successfully queued for sending.')
email_msg = '<div class="msg msg-confirm"><p class="copy">{text}</p></div>'.format(text=text)
else:
msg += "<font color='red'>Email is not enabled for this course.</font>"
elif "Show Background Email Task History" in action:
message, datatable = get_background_task_table(course_key, task_type='bulk_course_email')
msg += message
elif "Show Background Email Task History" in action:
message, datatable = get_background_task_table(course_key, task_type='bulk_course_email')
msg += message
#----------------------------------------
# psychometrics
elif action == 'Generate Histogram and IRT Plot':
problem = request.POST['Problem']
nmsg, plots = psychoanalyze.generate_plots_for_problem(problem)
msg += nmsg
track.views.server_track(request, "psychometrics-histogram-generation", {"problem": unicode(problem)}, page="idashboard")
if idash_mode == 'Psychometrics':
problems = psychoanalyze.problems_with_psychometric_data(course_key)
#----------------------------------------
# analytics
def get_analytics_result(analytics_name):
"""Return data for an Analytic piece, or None if it doesn't exist. It
logs and swallows errors.
"""
url = settings.ANALYTICS_SERVER_URL + \
u"get?aname={}&course_id={}&apikey={}".format(
analytics_name, course_key.to_deprecated_string(), settings.ANALYTICS_API_KEY
)
try:
res = requests.get(url)
except Exception: # pylint: disable=broad-except
log.exception("Error trying to access analytics at %s", url)
return None
if res.status_code == codes.OK:
# WARNING: do not use req.json because the preloaded json doesn't
# preserve the order of the original record (hence OrderedDict).
return json.loads(res.content, object_pairs_hook=OrderedDict)
else:
log.error("Error fetching %s, code: %s, msg: %s",
url, res.status_code, res.content)
return None
analytics_results = {}
if idash_mode == 'Analytics':
DASHBOARD_ANALYTICS = [
# "StudentsAttemptedProblems", # num students who tried given problem
"StudentsDailyActivity", # active students by day
"StudentsDropoffPerDay", # active students dropoff by day
# "OverallGradeDistribution", # overall point distribution for course
"StudentsActive", # num students active in time period (default = 1wk)
"StudentsEnrolled", # num students enrolled
# "StudentsPerProblemCorrect", # foreach problem, num students correct
"ProblemGradeDistribution", # foreach problem, grade distribution
]
for analytic_name in DASHBOARD_ANALYTICS:
analytics_results[analytic_name] = get_analytics_result(analytic_name)
#----------------------------------------
# Metrics
metrics_results = {}
if settings.FEATURES.get('CLASS_DASHBOARD') and idash_mode == 'Metrics':
metrics_results['section_display_name'] = dashboard_data.get_section_display_name(course_key)
metrics_results['section_has_problem'] = dashboard_data.get_array_section_has_problem(course_key)
#----------------------------------------
# offline grades?
if use_offline:
msg += "<br/><font color='orange'>{text}</font>".format(
text=_("Grades from {course_id}").format(
course_id=offline_grades_available(course_key)
)
)
# generate list of pending background tasks
if settings.FEATURES.get('ENABLE_INSTRUCTOR_BACKGROUND_TASKS'):
instructor_tasks = get_running_instructor_tasks(course_key)
else:
instructor_tasks = None
# determine if this is a studio-backed course so we can provide a link to edit this course in studio
is_studio_course = modulestore().get_modulestore_type(course_key) != ModuleStoreEnum.Type.xml
studio_url = None
if is_studio_course:
studio_url = get_cms_course_link(course)
email_editor = None
# HTML editor for email
if idash_mode == 'Email' and is_studio_course:
html_module = HtmlDescriptor(
course.system,
DictFieldData({'data': html_message}),
ScopeIds(None, None, None, course_key.make_usage_key('html', 'dummy'))
)
fragment = html_module.render('studio_view')
fragment = wrap_xblock(
'LmsRuntime', html_module, 'studio_view', fragment, None,
extra_data={"course-id": course_key.to_deprecated_string()},
usage_id_serializer=lambda usage_id: quote_slashes(usage_id.to_deprecated_string()),
request_token=request_token(request),
)
email_editor = fragment.content
# Enable instructor email only if the following conditions are met:
# 1. Feature flag is on
# 2. We have explicitly enabled email for the given course via django-admin
# 3. It is NOT an XML course
if bulk_email_is_enabled_for_course(course_key):
show_email_tab = True
# display course stats only if there is no other table to display:
course_stats = None
if not datatable:
course_stats = get_course_stats_table()
# disable buttons for large courses
disable_buttons = False
max_enrollment_for_buttons = settings.FEATURES.get("MAX_ENROLLMENT_INSTR_BUTTONS")
if max_enrollment_for_buttons is not None:
disable_buttons = enrollment_number > max_enrollment_for_buttons
#----------------------------------------
# context for rendering
context = {
'course': course,
'staff_access': True,
'admin_access': request.user.is_staff,
'instructor_access': instructor_access,
'forum_admin_access': forum_admin_access,
'datatable': datatable,
'course_stats': course_stats,
'msg': msg,
'modeflag': {idash_mode: 'selectedmode'},
'studio_url': studio_url,
'to_option': email_to_option, # email
'subject': email_subject, # email
'editor': email_editor, # email
'email_msg': email_msg, # email
'show_email_tab': show_email_tab, # email
'problems': problems, # psychometrics
'plots': plots, # psychometrics
'course_errors': modulestore().get_course_errors(course.id),
'instructor_tasks': instructor_tasks,
'offline_grade_log': offline_grades_available(course_key),
'cohorts_ajax_url': reverse('cohorts', kwargs={'course_key_string': course_key.to_deprecated_string()}),
'analytics_results': analytics_results,
'disable_buttons': disable_buttons,
'metrics_results': metrics_results,
}
context['standard_dashboard_url'] = reverse('instructor_dashboard', kwargs={'course_id': course_key.to_deprecated_string()})
return render_to_response('courseware/instructor_dashboard.html', context)
def _do_remote_gradebook(user, course, action, args=None, files=None):
'''
Perform remote gradebook action. Returns msg, datatable.
'''
rg = course.remote_gradebook
if not rg:
msg = _("No remote gradebook defined in course metadata")
return msg, {}
rgurl = settings.FEATURES.get('REMOTE_GRADEBOOK_URL', '')
if not rgurl:
msg = _("No remote gradebook url defined in settings.FEATURES")
return msg, {}
rgname = rg.get('name', '')
if not rgname:
msg = _("No gradebook name defined in course remote_gradebook metadata")
return msg, {}
if args is None:
args = {}
data = dict(submit=action, gradebook=rgname, user=user.email)
data.update(args)
try:
resp = requests.post(rgurl, data=data, verify=False, files=files)
retdict = json.loads(resp.content)
except Exception as err: # pylint: disable=broad-except
msg = _("Failed to communicate with gradebook server at {url}").format(url=rgurl) + "<br/>"
msg += _("Error: {err}").format(err=err)
msg += "<br/>resp={resp}".format(resp=resp.content)
msg += "<br/>data={data}".format(data=data)
return msg, {}
msg = '<pre>{msg}</pre>'.format(msg=retdict['msg'].replace('\n', '<br/>'))
retdata = retdict['data'] # a list of dicts
if retdata:
datatable = {'header': retdata[0].keys()}
datatable['data'] = [x.values() for x in retdata]
datatable['title'] = _('Remote gradebook response for {action}').format(action=action)
datatable['retdata'] = retdata
else:
datatable = {}
return msg, datatable
def _list_course_forum_members(course_key, rolename, datatable):
"""
Fills in datatable with forum membership information, for a given role,
so that it will be displayed on instructor dashboard.
course_ID = the CourseKey for a course
rolename = one of "Administrator", "Moderator", "Community TA"
Returns message status string to append to displayed message, if role is unknown.
"""
# make sure datatable is set up properly for display first, before checking for errors
datatable['header'] = [_('Username'), _('Full name'), _('Roles')]
datatable['title'] = _('List of Forum {name}s in course {id}').format(
name=rolename, id=course_key.to_deprecated_string()
)
datatable['data'] = []
try:
role = Role.objects.get(name=rolename, course_id=course_key)
except Role.DoesNotExist:
return '<font color="red">' + _('Error: unknown rolename "{rolename}"').format(rolename=rolename) + '</font>'
uset = role.users.all().order_by('username')
msg = 'Role = {0}'.format(rolename)
log.debug('role={0}'.format(rolename))
datatable['data'] = [[x.username, x.profile.name, ', '.join([
r.name for r in x.roles.filter(course_id=course_key).order_by('name')
])] for x in uset]
return msg
def _update_forum_role_membership(uname, course, rolename, add_or_remove):
'''
Supports adding a user to a course's forum role
uname = username string for user
course = course object
rolename = one of "Administrator", "Moderator", "Community TA"
add_or_remove = one of "add" or "remove"
Returns message status string to append to displayed message, Status is returned if user
or role is unknown, or if entry already exists when adding, or if entry doesn't exist when removing.
'''
# check that username and rolename are valid:
try:
user = User.objects.get(username=uname)
except User.DoesNotExist:
return '<font color="red">' + _('Error: unknown username "{username}"').format(username=uname) + '</font>'
try:
role = Role.objects.get(name=rolename, course_id=course.id)
except Role.DoesNotExist:
return '<font color="red">' + _('Error: unknown rolename "{rolename}"').format(rolename=rolename) + '</font>'
# check whether role already has the specified user:
alreadyexists = role.users.filter(username=uname).exists()
msg = ''
log.debug('rolename={0}'.format(rolename))
if add_or_remove == FORUM_ROLE_REMOVE:
if not alreadyexists:
msg = '<font color="red">' + _('Error: user "{username}" does not have rolename "{rolename}", cannot remove').format(username=uname, rolename=rolename) + '</font>'
else:
user.roles.remove(role)
msg = '<font color="green">' + _('Removed "{username}" from "{course_id}" forum role = "{rolename}"').format(username=user, course_id=course.id.to_deprecated_string(), rolename=rolename) + '</font>'
else:
if alreadyexists:
msg = '<font color="red">' + _('Error: user "{username}" already has rolename "{rolename}", cannot add').format(username=uname, rolename=rolename) + '</font>'
else:
if (rolename == FORUM_ROLE_ADMINISTRATOR and not has_access(user, 'staff', course)):
msg = '<font color="red">' + _('Error: user "{username}" should first be added as staff before adding as a forum administrator, cannot add').format(username=uname) + '</font>'
else:
user.roles.add(role)
msg = '<font color="green">' + _('Added "{username}" to "{course_id}" forum role = "{rolename}"').format(username=user, course_id=course.id.to_deprecated_string(), rolename=rolename) + '</font>'
return msg
def _role_members_table(role, title, course_key):
"""
Return a data table of usernames and names of users in group_name.
Arguments:
role -- a student.roles.AccessRole
title -- a descriptive title to show the user
Returns:
a dictionary with keys
'header': ['Username', 'Full name'],
'data': [[username, name] for all users]
'title': "{title} in course {course}"
"""
uset = role.users_with_role()
datatable = {'header': [_('Username'), _('Full name')]}
datatable['data'] = [[x.username, x.profile.name] for x in uset]
datatable['title'] = _('{title} in course {course_key}').format(title=title, course_key=course_key.to_deprecated_string())
return datatable
def _user_from_name_or_email(username_or_email):
"""
Return the `django.contrib.auth.User` with the supplied username or email.
If `username_or_email` contains an `@` it is treated as an email, otherwise
it is treated as the username
"""
username_or_email = strip_if_string(username_or_email)
if '@' in username_or_email:
return User.objects.get(email=username_or_email)
else:
return User.objects.get(username=username_or_email)
def add_user_to_role(request, username_or_email, role, group_title, event_name):
"""
Look up the given user by username (if no '@') or email (otherwise), and add them to group.
Arguments:
request: django request--used for tracking log
username_or_email: who to add. Decide if it's an email by presense of an '@'
group: A group name
group_title: what to call this group in messages to user--e.g. "beta-testers".
event_name: what to call this event when logging to tracking logs.
Returns:
html to insert in the message field
"""
username_or_email = strip_if_string(username_or_email)
try:
user = _user_from_name_or_email(username_or_email)
except User.DoesNotExist:
return u'<font color="red">Error: unknown username or email "{0}"</font>'.format(username_or_email)
role.add_users(user)
# Deal with historical event names
if event_name in ('staff', 'beta-tester'):
track.views.server_track(
request,
"add-or-remove-user-group",
{
"event_name": event_name,
"user": unicode(user),
"event": "add"
},
page="idashboard"
)
else:
track.views.server_track(request, "add-instructor", {"instructor": unicode(user)}, page="idashboard")
return '<font color="green">Added {0} to {1}</font>'.format(user, group_title)
def remove_user_from_role(request, username_or_email, role, group_title, event_name):
"""
Look up the given user by username (if no '@') or email (otherwise), and remove them from the supplied role.
Arguments:
request: django request--used for tracking log
username_or_email: who to remove. Decide if it's an email by presense of an '@'
role: A student.roles.AccessRole
group_title: what to call this group in messages to user--e.g. "beta-testers".
event_name: what to call this event when logging to tracking logs.
Returns:
html to insert in the message field
"""
username_or_email = strip_if_string(username_or_email)
try:
user = _user_from_name_or_email(username_or_email)
except User.DoesNotExist:
return u'<font color="red">Error: unknown username or email "{0}"</font>'.format(username_or_email)
role.remove_users(user)
# Deal with historical event names
if event_name in ('staff', 'beta-tester'):
track.views.server_track(
request,
"add-or-remove-user-group",
{
"event_name": event_name,
"user": unicode(user),
"event": "remove"
},
page="idashboard"
)
else:
track.views.server_track(request, "remove-instructor", {"instructor": unicode(user)}, page="idashboard")
return '<font color="green">Removed {0} from {1}</font>'.format(user, group_title)
class GradeTable(object):
"""
Keep track of grades, by student, for all graded assignment
components. Each student's grades are stored in a list. The
index of this list specifies the assignment component. Not
all lists have the same length, because at the start of going
through the set of grades, it is unknown what assignment
compoments exist. This is because some students may not do
all the assignment components.
The student grades are then stored in a dict, with the student
id as the key.
"""
def __init__(self):
self.components = OrderedDict()
self.grades = {}
self._current_row = {}
def _add_grade_to_row(self, component, score):
"""Creates component if needed, and assigns score
Args:
component (str): Course component being graded
score (float): Score of student on component
Returns:
None
"""
component_index = self.components.setdefault(component, len(self.components))
self._current_row[component_index] = score
@contextmanager
def add_row(self, student_id):
"""Context management for a row of grades
Uses a new dictionary to get all grades of a specified student
and closes by adding that dict to the internal table.
Args:
student_id (str): Student id that is having grades set
"""
self._current_row = {}
yield self._add_grade_to_row
self.grades[student_id] = self._current_row
def get_grade(self, student_id):
"""Retrieves padded list of grades for specified student
Args:
student_id (str): Student ID for desired grades
Returns:
list: Ordered list of grades for student
"""
row = self.grades.get(student_id, [])
ncomp = len(self.components)
return [row.get(comp, None) for comp in range(ncomp)]
def get_graded_components(self):
"""
Return a list of components that have been
discovered so far.
"""
return self.components.keys()
def get_student_grade_summary_data(request, course, get_grades=True, get_raw_scores=False, use_offline=False):
"""
Return data arrays with student identity and grades for specified course.
course = CourseDescriptor
course_key = course ID
Note: both are passed in, only because instructor_dashboard already has them already.
returns datatable = dict(header=header, data=data)
where
header = list of strings labeling the data fields
data = list (one per student) of lists of data corresponding to the fields
If get_raw_scores=True, then instead of grade summaries, the raw grades for all graded modules are returned.
"""
course_key = course.id
enrolled_students = User.objects.filter(
courseenrollment__course_id=course_key,
courseenrollment__is_active=1,
).prefetch_related("groups").order_by('username')
header = [_('ID'), _('Username'), _('Full Name'), _('edX email'), _('External email')]
datatable = {'header': header, 'students': enrolled_students}
data = []
gtab = GradeTable()
for student in enrolled_students:
datarow = [student.id, student.username, student.profile.name, student.email]
try:
datarow.append(student.externalauthmap.external_email)
except: # ExternalAuthMap.DoesNotExist
datarow.append('')
if get_grades:
gradeset = student_grades(student, request, course, keep_raw_scores=get_raw_scores, use_offline=use_offline)
log.debug('student={0}, gradeset={1}'.format(student, gradeset))
with gtab.add_row(student.id) as add_grade:
if get_raw_scores:
# TODO (ichuang) encode Score as dict instead of as list, so score[0] -> score['earned']
for score in gradeset['raw_scores']:
add_grade(score.section, getattr(score, 'earned', score[0]))
else:
for grade_item in gradeset['section_breakdown']:
add_grade(grade_item['label'], grade_item['percent'])
student.grades = gtab.get_grade(student.id)
data.append(datarow)
# if getting grades, need to do a second pass, and add grades to each datarow;
# on the first pass we don't know all the graded components
if get_grades:
for datarow in data:
# get grades for student
sgrades = gtab.get_grade(datarow[0])
datarow += sgrades
# get graded components and add to table header
assignments = gtab.get_graded_components()
header += assignments
datatable['assignments'] = assignments
datatable['data'] = data
return datatable
#-----------------------------------------------------------------------------
# Gradebook has moved to instructor.api.spoc_gradebook #
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def grade_summary(request, course_key):
"""Display the grade summary for a course."""
course = get_course_with_access(request.user, 'staff', course_key)
# For now, just a page
context = {'course': course,
'staff_access': True, }
return render_to_response('courseware/grade_summary.html', context)
#-----------------------------------------------------------------------------
# enrollment
def _do_enroll_students(course, course_key, students, secure=False, overload=False, auto_enroll=False, email_students=False, is_shib_course=False):
"""
Do the actual work of enrolling multiple students, presented as a string
of emails separated by commas or returns
`course` is course object
`course_key` id of course (a CourseKey)
`students` string of student emails separated by commas or returns (a `str`)
`overload` un-enrolls all existing students (a `boolean`)
`auto_enroll` is user input preference (a `boolean`)
`email_students` is user input preference (a `boolean`)
"""
new_students, new_students_lc = get_and_clean_student_list(students)
status = dict([x, 'unprocessed'] for x in new_students)
if overload: # delete all but staff
todelete = CourseEnrollment.objects.filter(course_id=course_key)
for ce in todelete:
if not has_access(ce.user, 'staff', course) and ce.user.email.lower() not in new_students_lc:
status[ce.user.email] = 'deleted'
ce.deactivate()
else:
status[ce.user.email] = 'is staff'
ceaset = CourseEnrollmentAllowed.objects.filter(course_id=course_key)
for cea in ceaset:
status[cea.email] = 'removed from pending enrollment list'
ceaset.delete()
if email_students:
protocol = 'https' if secure else 'http'
stripped_site_name = microsite.get_value(
'SITE_NAME',
settings.SITE_NAME
)
# TODO: Use request.build_absolute_uri rather than '{proto}://{site}{path}'.format
# and check with the Services team that this works well with microsites
registration_url = '{proto}://{site}{path}'.format(
proto=protocol,
site=stripped_site_name,
path=reverse('student.views.register_user')
)
course_url = '{proto}://{site}{path}'.format(
proto=protocol,
site=stripped_site_name,
path=reverse('course_root', kwargs={'course_id': course_key.to_deprecated_string()})
)
# We can't get the url to the course's About page if the marketing site is enabled.
course_about_url = None
if not settings.FEATURES.get('ENABLE_MKTG_SITE', False):
course_about_url = u'{proto}://{site}{path}'.format(
proto=protocol,
site=stripped_site_name,
path=reverse('about_course', kwargs={'course_id': course_key.to_deprecated_string()})
)
# Composition of email
d = {
'site_name': stripped_site_name,
'registration_url': registration_url,
'course': course,
'auto_enroll': auto_enroll,
'course_url': course_url,
'course_about_url': course_about_url,
'is_shib_course': is_shib_course
}
for student in new_students:
try:
user = User.objects.get(email=student)
except User.DoesNotExist:
#Student not signed up yet, put in pending enrollment allowed table
cea = CourseEnrollmentAllowed.objects.filter(email=student, course_id=course_key)
#If enrollmentallowed already exists, update auto_enroll flag to however it was set in UI
#Will be 0 or 1 records as there is a unique key on email + course_id
if cea:
cea[0].auto_enroll = auto_enroll
cea[0].save()
status[student] = 'user does not exist, enrollment already allowed, pending with auto enrollment ' \
+ ('on' if auto_enroll else 'off')
continue
#EnrollmentAllowed doesn't exist so create it
cea = CourseEnrollmentAllowed(email=student, course_id=course_key, auto_enroll=auto_enroll)
cea.save()
status[student] = 'user does not exist, enrollment allowed, pending with auto enrollment ' \
+ ('on' if auto_enroll else 'off')
if email_students:
# User is allowed to enroll but has not signed up yet
d['email_address'] = student
d['message'] = 'allowed_enroll'
send_mail_ret = send_mail_to_student(student, d)
status[student] += (', email sent' if send_mail_ret else '')
continue
# Student has already registered
if CourseEnrollment.is_enrolled(user, course_key):
status[student] = 'already enrolled'
continue
try:
# Not enrolled yet
CourseEnrollment.enroll(user, course_key)
status[student] = 'added'
if email_students:
# User enrolled for first time, populate dict with user specific info
d['email_address'] = student
d['full_name'] = user.profile.name
d['message'] = 'enrolled_enroll'
send_mail_ret = send_mail_to_student(student, d)
status[student] += (', email sent' if send_mail_ret else '')
except:
status[student] = 'rejected'
datatable = {'header': ['StudentEmail', 'action']}
datatable['data'] = [[x, status[x]] for x in sorted(status)]
datatable['title'] = _('Enrollment of students')
def sf(stat):
return [x for x in status if status[x] == stat]
data = dict(added=sf('added'), rejected=sf('rejected') + sf('exists'),
deleted=sf('deleted'), datatable=datatable)
return data
#Unenrollment
def _do_unenroll_students(course_key, students, email_students=False):
"""
Do the actual work of un-enrolling multiple students, presented as a string
of emails separated by commas or returns
`course_key` is id of course (a `str`)
`students` is string of student emails separated by commas or returns (a `str`)
`email_students` is user input preference (a `boolean`)
"""
old_students, __ = get_and_clean_student_list(students)
status = dict([x, 'unprocessed'] for x in old_students)
stripped_site_name = microsite.get_value(
'SITE_NAME',
settings.SITE_NAME
)
if email_students:
course = modulestore().get_course(course_key)
#Composition of email
d = {'site_name': stripped_site_name,
'course': course}
for student in old_students:
isok = False
cea = CourseEnrollmentAllowed.objects.filter(course_id=course_key, email=student)
#Will be 0 or 1 records as there is a unique key on email + course_id
if cea:
cea[0].delete()
status[student] = "un-enrolled"
isok = True
try:
user = User.objects.get(email=student)
except User.DoesNotExist:
if isok and email_students:
#User was allowed to join but had not signed up yet
d['email_address'] = student
d['message'] = 'allowed_unenroll'
send_mail_ret = send_mail_to_student(student, d)
status[student] += (', email sent' if send_mail_ret else '')
continue
#Will be 0 or 1 records as there is a unique key on user + course_id
if CourseEnrollment.is_enrolled(user, course_key):
try:
CourseEnrollment.unenroll(user, course_key)
status[student] = "un-enrolled"
if email_students:
#User was enrolled
d['email_address'] = student
d['full_name'] = user.profile.name
d['message'] = 'enrolled_unenroll'
send_mail_ret = send_mail_to_student(student, d)
status[student] += (', email sent' if send_mail_ret else '')
except Exception: # pylint: disable=broad-except
if not isok:
status[student] = "Error! Failed to un-enroll"
datatable = {'header': ['StudentEmail', 'action']}
datatable['data'] = [[x, status[x]] for x in sorted(status)]
datatable['title'] = _('Un-enrollment of students')
data = dict(datatable=datatable)
return data
def send_mail_to_student(student, param_dict):
"""
Construct the email using templates and then send it.
`student` is the student's email address (a `str`),
`param_dict` is a `dict` with keys [
`site_name`: name given to edX instance (a `str`)
`registration_url`: url for registration (a `str`)
`course_key`: id of course (a CourseKey)
`auto_enroll`: user input option (a `str`)
`course_url`: url of course (a `str`)
`email_address`: email of student (a `str`)
`full_name`: student full name (a `str`)
`message`: type of email to send and template to use (a `str`)
`is_shib_course`: (a `boolean`)
]
Returns a boolean indicating whether the email was sent successfully.
"""
# add some helpers and microconfig subsitutions
if 'course' in param_dict:
param_dict['course_name'] = param_dict['course'].display_name_with_default
param_dict['site_name'] = microsite.get_value(
'SITE_NAME',
param_dict.get('site_name', '')
)
subject = None
message = None
message_type = param_dict['message']
email_template_dict = {
'allowed_enroll': ('emails/enroll_email_allowedsubject.txt', 'emails/enroll_email_allowedmessage.txt'),
'enrolled_enroll': ('emails/enroll_email_enrolledsubject.txt', 'emails/enroll_email_enrolledmessage.txt'),
'allowed_unenroll': ('emails/unenroll_email_subject.txt', 'emails/unenroll_email_allowedmessage.txt'),
'enrolled_unenroll': ('emails/unenroll_email_subject.txt', 'emails/unenroll_email_enrolledmessage.txt'),
}
subject_template, message_template = email_template_dict.get(message_type, (None, None))
if subject_template is not None and message_template is not None:
subject = render_to_string(subject_template, param_dict)
message = render_to_string(message_template, param_dict)
if subject and message:
# Remove leading and trailing whitespace from body
message = message.strip()
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
from_address = microsite.get_value(
'email_from_address',
settings.DEFAULT_FROM_EMAIL
)
send_mail(subject, message, from_address, [student], fail_silently=False)
return True
else:
return False
def get_and_clean_student_list(students):
"""
Separate out individual student email from the comma, or space separated string.
`students` is string of student emails separated by commas or returns (a `str`)
Returns:
students: list of cleaned student emails
students_lc: list of lower case cleaned student emails
"""
students = split_by_comma_and_whitespace(students)
students = [unicode(s.strip()) for s in students]
students = [s for s in students if s != '']
students_lc = [x.lower() for x in students]
return students, students_lc
#-----------------------------------------------------------------------------
# answer distribution
def get_answers_distribution(request, course_key):
"""
Get the distribution of answers for all graded problems in the course.
Return a dict with two keys:
'header': a header row
'data': a list of rows
"""
course = get_course_with_access(request.user, 'staff', course_key)
dist = grades.answer_distributions(course.id)
d = {}
d['header'] = ['url_name', 'display name', 'answer id', 'answer', 'count']
d['data'] = [
[url_name, display_name, answer_id, a, answers[a]]
for (url_name, display_name, answer_id), answers in sorted(dist.items())
for a in answers
]
return d
#-----------------------------------------------------------------------------
def compute_course_stats(course):
"""
Compute course statistics, including number of problems, videos, html.
course is a CourseDescriptor from the xmodule system.
"""
# walk the course by using get_children() until we come to the leaves; count the
# number of different leaf types
counts = defaultdict(int)
def walk(module):
children = module.get_children()
category = module.__class__.__name__ # HtmlDescriptor, CapaDescriptor, ...
counts[category] += 1
for c in children:
walk(c)
walk(course)
stats = dict(counts) # number of each kind of module
return stats
def dump_grading_context(course):
"""
Dump information about course grading context (eg which problems are graded in what assignments)
Very useful for debugging grading_policy.json and policy.json
"""
msg = "-----------------------------------------------------------------------------\n"
msg += "Course grader:\n"
msg += '%s\n' % course.grader.__class__
graders = {}
if isinstance(course.grader, xmgraders.WeightedSubsectionsGrader):
msg += '\n'
msg += "Graded sections:\n"
for subgrader, category, weight in course.grader.sections:
msg += " subgrader=%s, type=%s, category=%s, weight=%s\n" % (subgrader.__class__, subgrader.type, category, weight)
subgrader.index = 1
graders[subgrader.type] = subgrader
msg += "-----------------------------------------------------------------------------\n"
msg += "Listing grading context for course %s\n" % course.id
gcontext = course.grading_context
msg += "graded sections:\n"
msg += '%s\n' % gcontext['graded_sections'].keys()
for (gsections, gsvals) in gcontext['graded_sections'].items():
msg += "--> Section %s:\n" % (gsections)
for sec in gsvals:
sdesc = sec['section_descriptor']
grade_format = getattr(sdesc, 'grade_format', None)
aname = ''
if grade_format in graders:
gfmt = graders[grade_format]
aname = '%s %02d' % (gfmt.short_label, gfmt.index)
gfmt.index += 1
elif sdesc.display_name in graders:
gfmt = graders[sdesc.display_name]
aname = '%s' % gfmt.short_label
notes = ''
if getattr(sdesc, 'score_by_attempt', False):
notes = ', score by attempt!'
msg += " %s (grade_format=%s, Assignment=%s%s)\n" % (s.display_name, grade_format, aname, notes)
msg += "all descriptors:\n"
msg += "length=%d\n" % len(gcontext['all_descriptors'])
msg = '<pre>%s</pre>' % msg.replace('<', '<')
return msg
def get_background_task_table(course_key, problem_url=None, student=None, task_type=None):
"""
Construct the "datatable" structure to represent background task history.
Filters the background task history to the specified course and problem.
If a student is provided, filters to only those tasks for which that student
was specified.
Returns a tuple of (msg, datatable), where the msg is a possible error message,
and the datatable is the datatable to be used for display.
"""
history_entries = get_instructor_task_history(course_key, problem_url, student, task_type)
datatable = {}
msg = ""
# first check to see if there is any history at all
# (note that we don't have to check that the arguments are valid; it
# just won't find any entries.)
if (history_entries.count()) == 0:
if problem_url is None:
msg += '<font color="red">Failed to find any background tasks for course "{course}".</font>'.format(
course=course_key.to_deprecated_string()
)
elif student is not None:
template = '<font color="red">' + _('Failed to find any background tasks for course "{course}", module "{problem}" and student "{student}".') + '</font>'
msg += template.format(course=course_key.to_deprecated_string(), problem=problem_url, student=student.username)
else:
msg += '<font color="red">' + _('Failed to find any background tasks for course "{course}" and module "{problem}".').format(
course=course_key.to_deprecated_string(), problem=problem_url
) + '</font>'
else:
datatable['header'] = ["Task Type",
"Task Id",
"Requester",
"Submitted",
"Duration (sec)",
"Task State",
"Task Status",
"Task Output"]
datatable['data'] = []
for instructor_task in history_entries:
# get duration info, if known:
duration_sec = 'unknown'
if hasattr(instructor_task, 'task_output') and instructor_task.task_output is not None:
task_output = json.loads(instructor_task.task_output)
if 'duration_ms' in task_output:
duration_sec = int(task_output['duration_ms'] / 1000.0)
# get progress status message:
success, task_message = get_task_completion_info(instructor_task)
status = "Complete" if success else "Incomplete"
# generate row for this task:
row = [
str(instructor_task.task_type),
str(instructor_task.task_id),
str(instructor_task.requester),
instructor_task.created.isoformat(' '),
duration_sec,
str(instructor_task.task_state),
status,
task_message
]
datatable['data'].append(row)
if problem_url is None:
datatable['title'] = "{course_id}".format(course_id=course_key.to_deprecated_string())
elif student is not None:
datatable['title'] = "{course_id} > {location} > {student}".format(
course_id=course_key.to_deprecated_string(),
location=problem_url,
student=student.username
)
else:
datatable['title'] = "{course_id} > {location}".format(
course_id=course_key.to_deprecated_string(), location=problem_url
)
return msg, datatable
def uses_shib(course):
"""
Used to return whether course has Shibboleth as the enrollment domain
Returns a boolean indicating if Shibboleth authentication is set for this course.
"""
return course.enrollment_domain and course.enrollment_domain.startswith(SHIBBOLETH_DOMAIN_PREFIX)<|fim▁end|> | # generate and return CSV file
return return_csv('grades {name}.csv'.format(name=aname), datatable)
|
<|file_name|>PacketPlayOutEntityHeadRotation.java<|end_file_name|><|fim▁begin|>package net.minecraft.server;
import java.io.IOException;
public class PacketPlayOutEntityHeadRotation implements Packet<PacketListenerPlayOut> {<|fim▁hole|> private byte b;
public PacketPlayOutEntityHeadRotation() {}
public PacketPlayOutEntityHeadRotation(Entity entity, byte b0) {
this.a = entity.getId();
this.b = b0;
}
public void a(PacketDataSerializer packetdataserializer) throws IOException {
this.a = packetdataserializer.g();
this.b = packetdataserializer.readByte();
}
public void b(PacketDataSerializer packetdataserializer) throws IOException {
packetdataserializer.d(this.a);
packetdataserializer.writeByte(this.b);
}
public void a(PacketListenerPlayOut packetlistenerplayout) {
packetlistenerplayout.a(this);
}
}<|fim▁end|> |
private int a; |
<|file_name|>gc.py<|end_file_name|><|fim▁begin|># Copyright 2011 Nicholas Bray
#
# 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.
from util.typedispatch import *
from . import graph as cfg<|fim▁hole|># Kills unreachable CFG nodes
class Logger(TypeDispatcher):
def __init__(self):
self.merges = []
@defaultdispatch
def default(self, node):
pass
@dispatch(cfg.MultiEntryBlock)
def visitMerge(self, node):
self.merges.append(node)
def evaluate(compiler, g):
logger = Logger()
dfs = CFGDFS(post=logger)
dfs.process(g.entryTerminal)
def live(node):
return node in dfs.processed
for merge in logger.merges:
for prev in merge._prev:
assert isinstance(prev, tuple), merge._prev
# HACK exposes the internals of merge
filtered = [prev for prev in merge._prev if live(prev[0])]
merge._prev = filtered<|fim▁end|> | from . dfs import CFGDFS
|
<|file_name|>fmlogger.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ..client import MODE_CHOICES
from ..client.tasks import ReadChannelValues, WriteChannelValue
from ..client.worker import Worker
from ..utils.command import BaseCommand
from ..values.channel import Channel
from ..values.signals import ValueChangeEvent
from optparse import OptionGroup, OptionConflictError
import logging
import sys
import time
class Command(BaseCommand):
def make_option_groups(self, parser):
groups = super(Command, self).make_option_groups(parser)
# Runtime options
runtime_group = OptionGroup(parser, 'runtime options')
runtime_group.add_option('--sleep', default=1, type='float',
help='time to sleep (s) between two probing loops')
# Channel options
channel_group = OptionGroup(parser, 'channel options')
self._append_channel_options(channel_group)
groups.append(channel_group)
# Data output options
data_group = OptionGroup(parser, 'data logging options')
data_group.add_option('--file',dest='datafile',
help="File to store data in")
groups.append(data_group)
return groups
def _append_channel_options(self, group):
# initial frequency
group.add_option('--set-freq', '-F',
help='set initial frequency (MHz)')
group.add_option('--mode', '-m', type='choice',
choices = MODE_CHOICES,
help='set device mode {mes|rds|stereo}')
group.add_option('--mes',
action='store_const', dest='mode', const='mes',
help='set measurement mode')
group.add_option('--rdsm', '--rds-mode', <|fim▁hole|> action='store_const', dest='mode', const='stereo',
help='set stereo mode')
# measurements
for descriptor in Channel.iter_descriptors():
if not descriptor.readable:
continue
longopt = '--%s' % descriptor.key
shortopt = None
if descriptor.short_key is not None:
shortopt = '-%s' % descriptor.short_key
kwargs= {
'dest': descriptor.key,
'action': 'store_true',
'help': 'enable %s measurement' % descriptor,
}
try:
group.add_option(longopt, shortopt, **kwargs)
except OptionConflictError:
group.add_option(longopt, **kwargs)
return group
def configure_logging(self):
super(Command, self).configure_logging()
datalogger_name = '%s.data' % self.get_logger_name()
datalogger = logging.getLogger(datalogger_name)
datalogger.propagate = False
datalogger.setLevel(logging.DEBUG)
data_streamhandler = logging.StreamHandler(sys.stdout)
datalogger.addHandler(data_streamhandler)
if self.options.datafile:
data_filehandler = logging.FileHandler(self.options.datafile)
datalogger.addHandler(data_filehandler)
self.datalogger = datalogger
def stop(self, signal, frame):
self.logger.info(u"stopping on signal %s..." % signal)
if hasattr(self, 'worker'):
self.worker.stop()
def execute(self):
ValueChangeEvent.connect(self.on_value_changed)
channel = self.make_channel()
self.worker.run()
mode = self.options.mode
if mode is not None:
mode_variable = channel.get_variable('mode')
mode_variable.set_command(mode)
self.worker.enqueue(WriteChannelValue, variable=mode_variable)
freq = self.options.set_freq
if freq is not None:
freq_variable = channel.get_variable('frequency')
freq_variable.set_command(freq)
self.worker.enqueue(WriteChannelValue, variable=freq_variable)
while self.worker.is_alive():
task = self.worker.enqueue(ReadChannelValues, channel=channel)
task.wait(blocking=False, timeout=2)
time.sleep(self.options.sleep)
def make_channel(self):
channel = Channel()
for variable in channel.get_variables():
enabled = getattr(self.options, variable.descriptor.key)
variable.enabled = enabled
return channel
def on_value_changed(self, sender, event):
message = self.format_event(event)
self.log_data(message)
def format_event(self, event):
descriptor = event.sender.descriptor
return '%s: %s' % (descriptor.key, descriptor.format_value(event.new_value))
def log_data(self, message):
self.datalogger.info(message)
def main():
sys.exit(Command().run())
if __name__ == '__main__':
main()<|fim▁end|> | action='store_const', dest='mode', const='rds',
help='set rds mode')
group.add_option('--stereo', |
<|file_name|>uint.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-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.
<|fim▁hole|>#![doc(primitive = "uint")]
use from_str::FromStr;
use num::FromStrRadix;
use num::strconv;
use option::Option;
pub use core::uint::{BITS, BYTES, MIN, MAX};
uint_module!(uint)<|fim▁end|> | //! Operations and constants for architecture-sized unsigned integers (`uint` type)
#![unstable] |
<|file_name|>Storage.hpp<|end_file_name|><|fim▁begin|>/* -*- Mode: c; c-basic-offset: 2 -*-
*
* Storage.cpp - Redland C++ Storage class interface
*
* Copyright (C) 2008, David Beckett http://www.dajobe.org/
*
* This package is Free Software and part of Redland http://librdf.org/
*
* It is licensed under the following three licenses as alternatives:
* 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version
* 2. GNU General Public License (GPL) V2 or any newer version
* 3. Apache License, V2.0 or any newer version
*
* You may not use this file except in compliance with at least one of
* the above three licenses.
*
* See LICENSE.html or LICENSE.txt at the top of this package for the
* complete terms and further detail along with the license texts for
* the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively.
*
*
*/
#ifndef REDLANDPP_STORAGE_HPP
#define REDLANDPP_STORAGE_HPP
#ifdef HAVE_CONFIG_H
#include <redlandpp_config.h>
#endif
#include <redland.h>
#include "redlandpp/World.hpp"
#include "redlandpp/Exception.hpp"
#include "redlandpp/Wrapper.hpp"
#include "redlandpp/Stream.hpp"
#include "redlandpp/Uri.hpp"
namespace Redland {
class Storage : public Wrapper<librdf_storage> {
public:
Storage(World* w, const std::string& sn, const std::string& n="", const std::string& opts="") throw(Exception);
Storage(World& w, const std::string& sn, const std::string& n="", const std::string& opts="") throw(Exception);
~Storage();
// public methods
const std::string name() const;
const std::string str() const;
protected:
World* world_;
private:
std::string storage_name_;
std::string name_;
std::string options_;
void init() throw(Exception);
friend std::ostream& operator<< (std::ostream& os, const Storage& p);
friend std::ostream& operator<< (std::ostream& os, const Storage* p);
};
<|fim▁hole|> MemoryStorage(World& w, const std::string n="", const std::string opts="") throw(Exception);
~MemoryStorage();
};
} // namespace Redland
#endif<|fim▁end|> |
class MemoryStorage : public Storage {
public:
MemoryStorage(World* w, const std::string n="", const std::string opts="") throw(Exception); |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|># 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 configparser
import io
import os
import subprocess
from rally.common import logging
from rally.utils import encodeutils
LOG = logging.getLogger(__name__)
def check_output(*args, **kwargs):
"""Run command with arguments and return its output.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The difference between check_output from subprocess package and this
function:
* Additional arguments:
- "msg_on_err" argument. It is a message that should be written in case
of error. Reduces a number of try...except blocks
- "debug_output" argument(Defaults to True). Print or not output to
LOG.debug
* stderr is hardcoded to stdout
* In case of error, prints failed command and output to LOG.error
* Prints output to LOG.debug<|fim▁hole|>
kwargs["stderr"] = subprocess.STDOUT
try:
output = subprocess.check_output(*args, **kwargs)
except subprocess.CalledProcessError as exc:
if msg_on_err:
LOG.error(msg_on_err)
LOG.error("Failed cmd: '%s'" % exc.cmd)
LOG.error("Error output: '%s'" % encodeutils.safe_decode(exc.output))
raise
output = encodeutils.safe_decode(output)
if output and debug_output:
LOG.debug("Subprocess output: '%s'" % output)
return output
def create_dir(dir_path):
if not os.path.isdir(dir_path):
os.makedirs(dir_path)
return dir_path
def extend_configfile(extra_options, conf_path):
conf_object = configparser.ConfigParser()
conf_object.optionxform = str
conf_object.read(conf_path)
conf_object = add_extra_options(extra_options, conf_object)
with open(conf_path, "w") as configfile:
conf_object.write(configfile)
raw_conf = io.StringIO()
conf_object.write(raw_conf)
return raw_conf.getvalue()
def add_extra_options(extra_options, conf_object):
conf_object.optionxform = str
for section in extra_options:
if section not in (conf_object.sections() + ["DEFAULT"]):
conf_object.add_section(section)
for option, value in extra_options[section].items():
conf_object.set(section, option, value)
return conf_object<|fim▁end|> |
"""
msg_on_err = kwargs.pop("msg_on_err", None)
debug_output = kwargs.pop("debug_output", True) |
<|file_name|>delete.js<|end_file_name|><|fim▁begin|><|fim▁hole|>module.exports = function(uri,opt){
return yhr('DELETE',uri,null,opt);
};<|fim▁end|> | var yhr = require('./main.js');
|
<|file_name|>constants.js<|end_file_name|><|fim▁begin|>"use strict";
var chai = require('chai'),
should = chai.should(),
expect = chai.expect,
XMLGrammers = require('../').XMLGrammers,
Parameters = require('../').Parameters;
describe('FMServerConstants', function(){
describe('XMLGrammers', function(){<|fim▁hole|> XMLGrammers.a = 1;
}).to.throw("Can't add property a, object is not extensible");
});
});
describe('Parameters', function() {
it('should be frozen', function () {
expect(function () {
Parameters.a = 1;
}).to.throw("Can't add property a, object is not extensible");
})
})
})<|fim▁end|> | it('should be frozen', function(){
expect(function(){ |
<|file_name|>saxenc.py<|end_file_name|><|fim▁begin|># This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library Lesser General Public License for more details at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# written by: Jeff Ortel ( [email protected] )
#
# sax encoding/decoding test.
#
from suds.sax.element import Element
from suds.sax.parser import Parser
def basic():
xml = "<a>Me && <b>my</b> shadow's <i>dog</i> love to 'play' and sing "la,la,la";</a>"
p = Parser()
d = p.parse(string=xml)
a = d.root()
print('A(parsed)=\n%s' % a)
assert str(a) == xml
b = Element('a')
b.setText('Me && <b>my</b> shadow\'s <i>dog</i> love to \'play\' and sing "la,la,la";')
print('B(encoded)=\n%s' % b)
assert str(b) == xml
print('A(text-decoded)=\n%s' % a.getText())
print('B(text-decoded)=\n%s' % b.getText())<|fim▁hole|> assert a.getText() == b.getText()
print('test pruning')
j = Element('A')
j.set('n', 1)
j.append(Element('B'))
print(j)
j.prune()
print(j)
def cdata():
xml = '<a><![CDATA[<b>This is my &<tag></b>]]></a>'
p = Parser()
d = p.parse(string=xml)
print(d)
a = d.root()
print(a.getText())
if __name__ == '__main__':
#basic()
cdata()<|fim▁end|> | |
<|file_name|>test_core.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# TextGridTools -- Read, write, and manipulate Praat TextGrid files
# Copyright (C) 2013-2014 Hendrik Buschmeier, Marcin Włodarczak
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, print_function
import unittest
from ..core import *
class TestTime(unittest.TestCase):
def setUp(self):
self.t1 = Time(1.0)
self.t2 = Time(1.1)
self.t3 = Time(1.01)
self.t4 = Time(1.001)
self.t5 = Time(1.00001)
def test_equals(self):
self.assertTrue(self.t1 == self.t1)
self.assertFalse(self.t1 == self.t2)
self.assertFalse(self.t1 == self.t3)
self.assertFalse(self.t1 == self.t4)
self.assertTrue(self.t1 == self.t5)
def test_not_equals(self):
self.assertFalse(self.t1 != self.t1)
self.assertTrue(self.t1 != self.t2)
self.assertTrue(self.t1 != self.t3)
self.assertTrue(self.t1 != self.t4)
self.assertFalse(self.t1 != self.t5)
def test_less(self):
self.assertFalse(self.t1 < self.t1)
self.assertTrue(self.t1 < self.t2)
self.assertTrue(self.t1 < self.t3)
self.assertTrue(self.t1 < self.t4)
self.assertFalse(self.t1 < self.t5)
def test_greater(self):
self.assertFalse(self.t1 > self.t1)
self.assertFalse(self.t1 > self.t2)
self.assertFalse(self.t1 > self.t3)
self.assertFalse(self.t1 > self.t4)
self.assertFalse(self.t1 > self.t5)
self.assertTrue(self.t2 > self.t1)
def test_greater_equal(self):
self.assertTrue(self.t1 >= self.t1)
self.assertFalse(self.t1 >= self.t2)
self.assertFalse(self.t1 >= self.t3)
self.assertFalse(self.t1 >= self.t4)
self.assertTrue(self.t1 >= self.t5)
self.assertTrue(self.t2 >= self.t1)
def test_less_equal(self):
self.assertTrue(self.t1 <= self.t1)
self.assertTrue(self.t1 <= self.t2)
self.assertTrue(self.t1 <= self.t3)
self.assertTrue(self.t1 <= self.t4)
self.assertTrue(self.t1 <= self.t5)
self.assertFalse(self.t2 <= self.t1)
class TestTier(unittest.TestCase):<|fim▁hole|> # Add to empty tier
ao1 = Annotation(0.0, 0.5, 'ao1')
t.add_annotation(ao1)
self.assertTrue(len(t) == 1)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.5)
# Append to tier leaving empty space
ao2 = Annotation(0.6, 0.75, 'ao2')
t.add_annotation(ao2)
self.assertTrue(len(t) == 2)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.75)
ao3 = Annotation(0.81, 0.9, 'ao3')
t.add_annotation(ao3)
self.assertTrue(len(t) == 3)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.9)
# Insert between existing annotations
# - leaving gaps on both sides
ao4 = Annotation(0.75, 0.77, 'ao4')
t.add_annotation(ao4)
self.assertTrue(len(t) == 4)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.9)
# - meeting preceeding annotation
ao5 = Annotation(0.77, 0.79, 'ao5')
t.add_annotation(ao5)
self.assertTrue(len(t) == 5)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.9)
# - meeting preceeding and succeeding annotation
ao6 = Annotation(0.8, 0.81, 'ao6')
t.add_annotation(ao6)
self.assertTrue(len(t) == 6)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.9)
# Insert at a place that is already occupied
# - within ao3
with self.assertRaises(ValueError):
ao7 = Annotation(0.85, 0.87, 'ao7')
t.add_annotation(ao7)
# - same boundaries as ao3
with self.assertRaises(ValueError):
ao8 = Annotation(0.81, 0.9, 'ao8')
t.add_annotation(ao8)
# - start time earlier than start time of ao3
with self.assertRaises(ValueError):
ao9 = Annotation(0.8, 0.89, 'ao9')
t.add_annotation(ao9)
# - end time later than end time of ao3
with self.assertRaises(ValueError):
ao10 = Annotation(0.82, 0.91, 'ao10')
t.add_annotation(ao10)
# - start time earlier than start time of ao3 and
# end time later than end time of ao3
with self.assertRaises(ValueError):
ao11 = Annotation(0.8, 0.91, 'ao11')
t.add_annotation(ao11)
# - Check that no annotation was added
self.assertTrue(len(t) == 6)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.9)
def test_start_end_times(self):
t = Tier(1, 2)
# Check whether specified start/end times are used
self.assertTrue(t.start_time == 1)
self.assertTrue(t.end_time == 2)
# Check whether adding an annotation within specified
# start and end times leaves them unchanged
t.add_annotation(Annotation(1.1, 1.9, 'text'))
self.assertTrue(t.start_time == 1)
self.assertTrue(t.end_time == 2)
# Expand end time by adding an annotation that ends later
t.add_annotation(Annotation(2, 3, 'text'))
self.assertTrue(t.start_time == 1)
self.assertTrue(t.end_time == 3)
# Expand start time by adding an annotation that starts ealier
t.add_annotation(Annotation(0, 1, 'text'))
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 3)
def test_queries(self):
t = Tier()
ao1 = Annotation(0, 1, 'ao1')
ao2 = Annotation(1, 2, 'ao2')
ao3 = Annotation(5, 6, 'ao3')
t.add_annotations([ao1, ao2, ao3])
# Query with start time
# - query for existing objects
ao1_retr = t.get_annotation_by_start_time(ao1.start_time)
self.assertTrue(ao1_retr == ao1)
ao2_retr = t.get_annotation_by_start_time(ao2.start_time)
self.assertTrue(ao2_retr == ao2)
ao3_retr = t.get_annotation_by_start_time(ao3.start_time)
self.assertTrue(ao3_retr == ao3)
# - query for non-existing object
aox_retr = t.get_annotation_by_start_time(0.5)
self.assertTrue(aox_retr is None)
# Query with end time
# - query for existing objects
ao1_retr = t.get_annotation_by_end_time(ao1.end_time)
self.assertTrue(ao1_retr == ao1)
ao2_retr = t.get_annotation_by_end_time(ao2.end_time)
self.assertTrue(ao2_retr == ao2)
ao3_retr = t.get_annotation_by_end_time(ao3.end_time)
self.assertTrue(ao3_retr == ao3)
# - query for non-existing object
aox_retr = t.get_annotation_by_end_time(0.5)
self.assertTrue(aox_retr is None)
# Query with time
# - query for existing objects
# - time falls within object
ao1_retr = t.get_annotations_by_time(ao1.start_time + (ao1.end_time - ao1.start_time) * 0.5)
self.assertTrue(ao1_retr[0] == ao1)
# - time equals end time of object
ao2_retr = t.get_annotations_by_time(ao2.end_time)
self.assertTrue(ao2_retr[0] == ao2)
# - time equals start time of object
ao3_retr = t.get_annotations_by_time(ao3.start_time)
self.assertTrue(ao3_retr[0] == ao3)
# - time equals start time of one object and end_time of another
ao12_retr = t.get_annotations_by_time(ao1.end_time)
self.assertTrue(len(ao12_retr) == 2)
self.assertTrue(ao12_retr[0] == ao1)
self.assertTrue(ao12_retr[1] == ao2)
# - query for non-existing object
aox_retr = t.get_annotations_by_time(3)
self.assertTrue(aox_retr == [])
# Query with text/regex
# - one match
ao1_retr = t.get_annotations_with_matching_text('ao1')
self.assertTrue(len(ao1_retr) == 1)
self.assertTrue(ao1_retr[0] == ao1)
# - mutiple matches
ao31 = Annotation(7, 8, 'ao3')
ao32 = Annotation(9, 10, 'ao3')
ao33 = Annotation(11, 12, 'ao3')
t.add_annotations([ao31, ao32, ao33])
ao3x_retr = t.get_annotations_with_matching_text('ao3')
self.assertTrue(len(ao3x_retr) == 4)
self.assertTrue(ao3x_retr[0] == ao3)
self.assertTrue(ao3x_retr[1] == ao31)
self.assertTrue(ao3x_retr[2] == ao32)
self.assertTrue(ao3x_retr[3] == ao33)
# - multiple matches, select first n
ao3xn_retr = t.get_annotations_with_matching_text('ao3', 2)
self.assertTrue(len(ao3xn_retr) == 2)
self.assertTrue(ao3xn_retr[0] == ao3)
self.assertTrue(ao3xn_retr[1] == ao31)
# - multiple matches, select last n
ao3xn_retr = t.get_annotations_with_matching_text('ao3', -2)
self.assertTrue(len(ao3xn_retr) == 2)
self.assertTrue(ao3xn_retr[0] == ao32)
self.assertTrue(ao3xn_retr[1] == ao33)
def test_get_nearest_annotation(self):
t = Tier()
ao1 = Annotation(0, 1, 'ao1')
ao2 = Annotation(1, 2, 'ao2')
ao3 = Annotation(3, 4, 'ao3')
ao4 = Annotation(5, 6, 'ao4')
t.add_annotations([ao1, ao2, ao3, ao4])
# - coincides with start time of the first interval
r = t.get_nearest_annotation(0.0, boundary='start', direction='left')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.0, boundary='end', direction='left')
self.assertTrue(r == set([]))
r = t.get_nearest_annotation(0.0, boundary='both', direction='left')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.0, boundary='start', direction='right')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.0, boundary='end', direction='right')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.0, boundary='both', direction='right')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.0, boundary='start', direction='both')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.0, boundary='end', direction='both')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.0, boundary='both', direction='both')
self.assertTrue(r == set([ao1]))
# - lies between start and end time of the first interval
r = t.get_nearest_annotation(0.4, boundary='start', direction='left')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.4, boundary='end', direction='left')
self.assertTrue(r == set([]))
r = t.get_nearest_annotation(0.4, boundary='both', direction='left')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.4, boundary='start', direction='right')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(0.4, boundary='end', direction='right')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.4, boundary='both', direction='right')
self.assertTrue(r == set([ao1, ao2]))
r = t.get_nearest_annotation(0.4, boundary='start', direction='both')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.4, boundary='end', direction='both')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.4, boundary='both', direction='both')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.5, boundary='start', direction='left')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.5, boundary='end', direction='left')
self.assertTrue(r == set([]))
r = t.get_nearest_annotation(0.5, boundary='both', direction='left')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.5, boundary='start', direction='right')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(0.5, boundary='end', direction='right')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.5, boundary='both', direction='right')
self.assertTrue(r == set([ao1, ao2]))
r = t.get_nearest_annotation(0.5, boundary='start', direction='both')
self.assertTrue(r == set([ao1, ao2]))
r = t.get_nearest_annotation(0.5, boundary='end', direction='both')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.5, boundary='both', direction='both')
self.assertTrue(r == set([ao1, ao2]))
r = t.get_nearest_annotation(0.6, boundary='start', direction='left')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.6, boundary='end', direction='left')
self.assertTrue(r == set([]))
r = t.get_nearest_annotation(0.6, boundary='both', direction='left')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.6, boundary='start', direction='right')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(0.6, boundary='end', direction='right')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.6, boundary='both', direction='right')
self.assertTrue(r == set([ao1, ao2]))
r = t.get_nearest_annotation(0.6, boundary='start', direction='both')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(0.6, boundary='end', direction='both')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(0.6, boundary='both', direction='both')
self.assertTrue(r == set([ao1, ao2]))
# - coincides with end time of one interval and coincides with start
# time of another interval
r = t.get_nearest_annotation(1.0, boundary='start', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(1.0, boundary='end', direction='left')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(1.0, boundary='both', direction='left')
self.assertTrue(r == set([ao1, ao2]))
r = t.get_nearest_annotation(1.0, boundary='start', direction='right')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(1.0, boundary='end', direction='right')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(1.0, boundary='both', direction='right')
self.assertTrue(r == set([ao1, ao2]))
r = t.get_nearest_annotation(1.0, boundary='start', direction='both')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(1.0, boundary='end', direction='both')
self.assertTrue(r == set([ao1]))
r = t.get_nearest_annotation(1.0, boundary='both', direction='both')
self.assertTrue(r == set([ao1, ao2]))
## - lies between two intervals
r = t.get_nearest_annotation(2.4, boundary='start', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(2.4, boundary='end', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(2.4, boundary='both', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(2.4, boundary='start', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(2.4, boundary='end', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(2.4, boundary='both', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(2.4, boundary='start', direction='both')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(2.4, boundary='end', direction='both')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(2.4, boundary='both', direction='both')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(2.5, boundary='start', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(2.5, boundary='end', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(2.5, boundary='both', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(2.5, boundary='start', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(2.5, boundary='end', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(2.5, boundary='both', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(2.5, boundary='start', direction='both')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(2.5, boundary='end', direction='both')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(2.5, boundary='both', direction='both')
self.assertTrue(r == set([ao3, ao2]))
r = t.get_nearest_annotation(2.6, boundary='start', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(2.6, boundary='end', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(2.6, boundary='both', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(2.6, boundary='start', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(2.6, boundary='end', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(2.6, boundary='both', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(2.6, boundary='start', direction='both')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(2.6, boundary='end', direction='both')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(2.6, boundary='both', direction='both')
self.assertTrue(r == set([ao3]))
## - coincides with start time of an isolated interval
r = t.get_nearest_annotation(3.0, boundary='start', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.0, boundary='end', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(3.0, boundary='both', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.0, boundary='start', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.0, boundary='end', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.0, boundary='both', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.0, boundary='start', direction='both')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.0, boundary='end', direction='both')
self.assertTrue(r == set([ao2, ao3]))
r = t.get_nearest_annotation(3.0, boundary='both', direction='both')
self.assertTrue(r == set([ao3]))
## - lies withing an isolated interval
r = t.get_nearest_annotation(3.6, boundary='start', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.6, boundary='end', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(3.6, boundary='both', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.6, boundary='start', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(3.6, boundary='end', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.6, boundary='both', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.6, boundary='start', direction='both')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.6, boundary='end', direction='both')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.6, boundary='both', direction='both')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.5, boundary='start', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.5, boundary='end', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(3.5, boundary='both', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.5, boundary='start', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(3.5, boundary='end', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.5, boundary='both', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.5, boundary='start', direction='both')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.5, boundary='end', direction='both')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.5, boundary='both', direction='both')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.6, boundary='start', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.6, boundary='end', direction='left')
self.assertTrue(r == set([ao2]))
r = t.get_nearest_annotation(3.6, boundary='both', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.6, boundary='start', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(3.6, boundary='end', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.6, boundary='both', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.6, boundary='start', direction='both')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.6, boundary='end', direction='both')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(3.6, boundary='both', direction='both')
self.assertTrue(r == set([ao3]))
## - coincides with end time of an isolated interval
r = t.get_nearest_annotation(4.0, boundary='start', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(4.0, boundary='end', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(4.0, boundary='both', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(4.0, boundary='start', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(4.0, boundary='end', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(4.0, boundary='both', direction='right')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(4.0, boundary='start', direction='both')
self.assertTrue(r == set([ao3, ao4]))
r = t.get_nearest_annotation(4.0, boundary='end', direction='both')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(4.0, boundary='both', direction='both')
self.assertTrue(r == set([ao3]))
#5.0, 5.4, 5.5, 5.6, 6.0
## - coincides with start time of the last interval
r = t.get_nearest_annotation(5.0, boundary='start', direction='left')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.0, boundary='end', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(5.0, boundary='both', direction='left')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.0, boundary='start', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.0, boundary='end', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.0, boundary='both', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.0, boundary='start', direction='both')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.0, boundary='end', direction='both')
self.assertTrue(r == set([ao3, ao4]))
r = t.get_nearest_annotation(5.0, boundary='both', direction='both')
self.assertTrue(r == set([ao4]))
## - lies withing an the last interval
r = t.get_nearest_annotation(5.4, boundary='start', direction='left')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.4, boundary='end', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(5.4, boundary='both', direction='left')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.4, boundary='start', direction='right')
self.assertTrue(r == set([]))
r = t.get_nearest_annotation(5.4, boundary='end', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.4, boundary='both', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.4, boundary='start', direction='both')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.4, boundary='end', direction='both')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.4, boundary='both', direction='both')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.5, boundary='start', direction='left')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.5, boundary='end', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(5.5, boundary='both', direction='left')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.5, boundary='start', direction='right')
self.assertTrue(r == set([]))
r = t.get_nearest_annotation(5.5, boundary='end', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.5, boundary='both', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.5, boundary='start', direction='both')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.5, boundary='end', direction='both')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.5, boundary='both', direction='both')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.6, boundary='start', direction='left')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.6, boundary='end', direction='left')
self.assertTrue(r == set([ao3]))
r = t.get_nearest_annotation(5.6, boundary='both', direction='left')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.6, boundary='start', direction='right')
self.assertTrue(r == set([]))
r = t.get_nearest_annotation(5.6, boundary='end', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.6, boundary='both', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.6, boundary='start', direction='both')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.6, boundary='end', direction='both')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(5.6, boundary='both', direction='both')
self.assertTrue(r == set([ao4]))
## - coincides with end time of the last interval
r = t.get_nearest_annotation(6.0, boundary='start', direction='left')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(6.0, boundary='end', direction='left')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(6.0, boundary='both', direction='left')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(6.0, boundary='start', direction='right')
self.assertTrue(r == set([]))
r = t.get_nearest_annotation(6.0, boundary='end', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(6.0, boundary='both', direction='right')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(6.0, boundary='start', direction='both')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(6.0, boundary='end', direction='both')
self.assertTrue(r == set([ao4]))
r = t.get_nearest_annotation(6.0, boundary='both', direction='both')
self.assertTrue(r == set([ao4]))
def test_get_copy_with_gaps_filled(self):
i1 = Interval(0,2, 'i1')
i2 = Interval(2,3, 'i2')
i3 = Interval(4,5, 'i3')
i4 = Interval(7,8, 'i4')
i5 = Interval(8.5,9.5, 'i5')
# - insert empty start interval
t1 = IntervalTier(0, 3, 't1')
t1.add_annotations([i2])
t1_c = t1.get_copy_with_gaps_filled()
self.assertTrue(len(t1) == 1)
self.assertTrue(len(t1_c) == 2)
# - insert emtpy end interval
t2 = IntervalTier(0, 3, 't2')
t2.add_annotations([i1])
t2_c = t2.get_copy_with_gaps_filled()
self.assertTrue(len(t2) == 1)
self.assertTrue(len(t2_c) == 2)
# - insert all over the place
t3 = IntervalTier(0, 10, 't3')
t3.add_annotations([i2, i3, i4, i5])
t3_c = t3.get_copy_with_gaps_filled()
self.assertTrue(len(t3) == 4)
self.assertTrue(len(t3_c) == 9)
# - insert into emtpy tier
t4 = IntervalTier(0, 5, 't4')
t4_c = t4.get_copy_with_gaps_filled()
self.assertTrue(len(t4) == 0)
self.assertTrue(len(t4_c) == 1)
# - do nothing
t5 = IntervalTier(0, 3, 't5')
t5.add_annotations([i1, i2])
t5_c = t5.get_copy_with_gaps_filled()
self.assertTrue(len(t5) == 2)
self.assertTrue(len(t5_c) == 2)
class TestInterval(unittest.TestCase):
def test_change_time(self):
ict = Interval(0, 1)
# Changing start and end times has an effect
ict.start_time = 0.5
self.assertTrue(ict.start_time == 0.5)
ict.end_time = 1.5
self.assertTrue(ict.end_time == 1.5)
# Correct order of start and end times is checked
with self.assertRaises(ValueError):
Interval(1,0)
with self.assertRaises(ValueError):
ict.start_time = 2.0
with self.assertRaises(ValueError):
ict.end_time = 0
def test_change_text(self):
ict = Interval(0, 1, 'text')
self.assertTrue(ict.text == 'text')
ict.text = 'text changed'
self.assertTrue(ict.text == 'text changed')
def test_duration(self):
self.id1 = Interval(0, 1)
self.assertTrue(self.id1.duration() == 1.0)
self.id2 = Interval(1, 1)
self.assertTrue(self.id2.duration() == 0)
def test_equality(self):
ie1 = Interval(0, 1, 'text')
ie2 = Interval(0, 1, 'text')
self.assertTrue(ie1 == ie2)
ie3 = Interval(1, 1, 'text')
self.assertFalse(ie1 == ie3)
ie4 = Interval(0, 2, 'text')
self.assertFalse(ie1 == ie4)
ie5 = Interval(0, 1, 'text changed')
self.assertFalse(ie1 == ie5)
def test_repr(self):
ir = Interval(0, 1, 'text')
s = repr(ir)
ir_recreated = eval(s)
self.assertTrue(ir == ir_recreated)
class TestPoint(unittest.TestCase):
def test_change_time(self):
pct = Point(0)
# Changing start and end times has an effect
pct.time = 0.5
self.assertTrue(pct.time == 0.5)
self.assertTrue(pct.start_time == 0.5)
self.assertTrue(pct.end_time == 0.5)
pct.start_time = 1
self.assertTrue(pct.time == 1)
self.assertTrue(pct.start_time == 1)
self.assertTrue(pct.end_time == 1)
pct.end_time = 1.5
self.assertTrue(pct.time == 1.5)
self.assertTrue(pct.start_time == 1.5)
self.assertTrue(pct.end_time == 1.5)
def test_change_text(self):
pct = Point(0, 'text')
self.assertTrue(pct.text == 'text')
pct.text = 'text changed'
self.assertTrue(pct.text == 'text changed')
def test_equality(self):
pe1 = Point(0, 'text')
pe2 = Point(0, 'text')
self.assertTrue(pe1 == pe2)
pe3 = Point(1, 'text')
self.assertFalse(pe1 == pe3)
pe4 = Point(0, 'text changed')
self.assertFalse(pe1 == pe4)
def test_repr(self):
pr = Point(0, 'text')
s = repr(pr)
pr_recreated = eval(s)
self.assertTrue(pr == pr_recreated)<|fim▁end|> |
def test_adding(self):
t = Tier()
|
<|file_name|>Inuvik.py<|end_file_name|><|fim▁begin|>'''tzinfo timezone information for America/Inuvik.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Inuvik(DstTzInfo):
'''America/Inuvik timezone definition. See datetime.tzinfo for details'''
zone = 'America/Inuvik'
_utc_transition_times = [
d(1,1,1,0,0,0),
d(1918,4,14,10,0,0),
d(1918,10,27,9,0,0),
d(1919,5,25,10,0,0),
d(1919,11,1,7,0,0),
d(1942,2,9,10,0,0),
d(1945,8,14,23,0,0),
d(1945,9,30,9,0,0),
d(1965,4,25,8,0,0),
d(1965,10,31,8,0,0),
d(1979,4,29,10,0,0),
d(1980,4,27,9,0,0),
d(1980,10,26,8,0,0),
d(1981,4,26,9,0,0),
d(1981,10,25,8,0,0),
d(1982,4,25,9,0,0),
d(1982,10,31,8,0,0),
d(1983,4,24,9,0,0),
d(1983,10,30,8,0,0),
d(1984,4,29,9,0,0),
d(1984,10,28,8,0,0),
d(1985,4,28,9,0,0),
d(1985,10,27,8,0,0),
d(1986,4,27,9,0,0),
d(1986,10,26,8,0,0),
d(1987,4,5,9,0,0),
d(1987,10,25,8,0,0),
d(1988,4,3,9,0,0),
d(1988,10,30,8,0,0),
d(1989,4,2,9,0,0),
d(1989,10,29,8,0,0),
d(1990,4,1,9,0,0),
d(1990,10,28,8,0,0),
d(1991,4,7,9,0,0),
d(1991,10,27,8,0,0),
d(1992,4,5,9,0,0),
d(1992,10,25,8,0,0),
d(1993,4,4,9,0,0),
d(1993,10,31,8,0,0),
d(1994,4,3,9,0,0),
d(1994,10,30,8,0,0),
d(1995,4,2,9,0,0),
d(1995,10,29,8,0,0),
d(1996,4,7,9,0,0),
d(1996,10,27,8,0,0),
d(1997,4,6,9,0,0),
d(1997,10,26,8,0,0),
d(1998,4,5,9,0,0),
d(1998,10,25,8,0,0),
d(1999,4,4,9,0,0),
d(1999,10,31,8,0,0),
d(2000,4,2,9,0,0),
d(2000,10,29,8,0,0),
d(2001,4,1,9,0,0),
d(2001,10,28,8,0,0),
d(2002,4,7,9,0,0),
d(2002,10,27,8,0,0),
d(2003,4,6,9,0,0),
d(2003,10,26,8,0,0),
d(2004,4,4,9,0,0),
d(2004,10,31,8,0,0),
d(2005,4,3,9,0,0),
d(2005,10,30,8,0,0),
d(2006,4,2,9,0,0),
d(2006,10,29,8,0,0),
d(2007,3,11,9,0,0),
d(2007,11,4,8,0,0),
d(2008,3,9,9,0,0),
d(2008,11,2,8,0,0),
d(2009,3,8,9,0,0),
d(2009,11,1,8,0,0),
d(2010,3,14,9,0,0),
d(2010,11,7,8,0,0),
d(2011,3,13,9,0,0),
d(2011,11,6,8,0,0),
d(2012,3,11,9,0,0),
d(2012,11,4,8,0,0),
d(2013,3,10,9,0,0),
d(2013,11,3,8,0,0),
d(2014,3,9,9,0,0),
d(2014,11,2,8,0,0),
d(2015,3,8,9,0,0),
d(2015,11,1,8,0,0),
d(2016,3,13,9,0,0),
d(2016,11,6,8,0,0),
d(2017,3,12,9,0,0),
d(2017,11,5,8,0,0),
d(2018,3,11,9,0,0),
d(2018,11,4,8,0,0),
d(2019,3,10,9,0,0),
d(2019,11,3,8,0,0),
d(2020,3,8,9,0,0),
d(2020,11,1,8,0,0),
d(2021,3,14,9,0,0),
d(2021,11,7,8,0,0),
d(2022,3,13,9,0,0),
d(2022,11,6,8,0,0),
d(2023,3,12,9,0,0),<|fim▁hole|>d(2025,3,9,9,0,0),
d(2025,11,2,8,0,0),
d(2026,3,8,9,0,0),
d(2026,11,1,8,0,0),
d(2027,3,14,9,0,0),
d(2027,11,7,8,0,0),
d(2028,3,12,9,0,0),
d(2028,11,5,8,0,0),
d(2029,3,11,9,0,0),
d(2029,11,4,8,0,0),
d(2030,3,10,9,0,0),
d(2030,11,3,8,0,0),
d(2031,3,9,9,0,0),
d(2031,11,2,8,0,0),
d(2032,3,14,9,0,0),
d(2032,11,7,8,0,0),
d(2033,3,13,9,0,0),
d(2033,11,6,8,0,0),
d(2034,3,12,9,0,0),
d(2034,11,5,8,0,0),
d(2035,3,11,9,0,0),
d(2035,11,4,8,0,0),
d(2036,3,9,9,0,0),
d(2036,11,2,8,0,0),
d(2037,3,8,9,0,0),
d(2037,11,1,8,0,0),
]
_transition_info = [
i(-28800,0,'PST'),
i(-25200,3600,'PDT'),
i(-28800,0,'PST'),
i(-25200,3600,'PDT'),
i(-28800,0,'PST'),
i(-25200,3600,'PWT'),
i(-25200,3600,'PPT'),
i(-28800,0,'PST'),
i(-21600,7200,'PDDT'),
i(-28800,0,'PST'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
i(-21600,3600,'MDT'),
i(-25200,0,'MST'),
]
Inuvik = Inuvik()<|fim▁end|> | d(2023,11,5,8,0,0),
d(2024,3,10,9,0,0),
d(2024,11,3,8,0,0), |
<|file_name|>image_reader.py<|end_file_name|><|fim▁begin|>from typing import Callable, Iterable, List, Optional
import os
import numpy as np
from PIL import Image, ImageFile<|fim▁hole|> pad_w: Optional[int] = None,
pad_h: Optional[int] = None,
rescale_w: bool = False,
rescale_h: bool = False,
keep_aspect_ratio: bool = False,
mode: str = 'RGB') -> Callable:
"""Get a reader of images loading them from a list of pahts.
Args:
prefix: Prefix of the paths that are listed in a image files.
pad_w: Width to which the images will be padded/cropped/resized.
pad_h: Height to with the images will be padded/corpped/resized.
rescale_w: If true, image is rescaled to have given width. It is
cropped/padded otherwise.
rescale_h: If true, image is rescaled to have given height. It is
cropped/padded otherwise.
keep_aspect_ratio: Flag whether the aspect ration should be kept during
rescaling. Can only be used if both width and height are rescaled.
mode: Scipy image loading mode, see scipy documentation for more
details.
Returns:
The reader function that takes a list of image paths (relative to
provided prefix) and returns a list of images as numpy arrays of shape
pad_h x pad_w x number of channels.
"""
if not rescale_w and not rescale_h and keep_aspect_ratio:
raise ValueError(
"It does not make sense to keep the aspect ratio while not "
"rescaling the image.")
if rescale_w != rescale_h and not keep_aspect_ratio:
raise ValueError(
"While rescaling only one side, aspect ratio must be kept, "
"was set to false.")
def load(list_files: List[str]) -> Iterable[np.ndarray]:
for list_file in list_files:
with open(list_file) as f_list:
for i, image_file in enumerate(f_list):
path = os.path.join(prefix, image_file.rstrip())
if not os.path.exists(path):
raise Exception(
("Image file '{}' no."
"{} does not exist.").format(path, i + 1))
try:
image = Image.open(path).convert(mode)
except IOError:
image = Image.new(mode, (pad_w, pad_h))
image = _rescale_or_crop(image, pad_w, pad_h,
rescale_w, rescale_h,
keep_aspect_ratio)
image_np = np.array(image)
if len(image_np.shape) == 2:
channels = 1
image_np = np.expand_dims(image_np, 2)
elif len(image_np.shape) == 3:
channels = image_np.shape[2]
else:
raise ValueError(
("Image should have either 2 (black and white) "
"or three dimensions (color channels), has {} "
"dimension.").format(len(image_np.shape)))
yield _pad(image_np, pad_w, pad_h, channels)
return load
def imagenet_reader(prefix: str,
target_width: int = 227,
target_height: int = 227) -> Callable:
"""Load and prepare image the same way as Caffe scripts."""
def load(list_files: List[str]) -> Iterable[np.ndarray]:
for list_file in list_files:
with open(list_file) as f_list:
for i, image_file in enumerate(f_list):
path = os.path.join(prefix, image_file.rstrip())
if not os.path.exists(path):
raise Exception(
"Image file '{}' no. {} does not exist."
.format(path, i + 1))
image = Image.open(path).convert('RGB')
width, height = image.size
if width == height:
_rescale_or_crop(image, target_width, target_height,
True, True, False)
elif height < width:
_rescale_or_crop(
image,
int(width * float(target_height) / height),
target_height, True, True, False)
else:
_rescale_or_crop(
image, target_width,
int(height * float(target_width) / width),
True, True, False)
cropped_image = _crop(image, target_width, target_height)
res = _pad(np.array(cropped_image),
target_width, target_height, 3)
assert res.shape == (target_width, target_height, 3)
yield res
return load
def _rescale_or_crop(image: Image.Image, pad_w: int, pad_h: int,
rescale_w: bool, rescale_h: bool,
keep_aspect_ratio: bool) -> Image.Image:
"""Rescale and/or crop the image based on the rescale configuration."""
orig_w, orig_h = image.size
if orig_w == pad_w and orig_h == pad_h:
return image
if rescale_w and rescale_h and not keep_aspect_ratio:
image.thumbnail((pad_w, pad_h))
elif rescale_w and rescale_h and keep_aspect_ratio:
ratio = min(pad_h / orig_h, pad_w / orig_h)
image.thumbnail((int(orig_w * ratio), int(orig_h * ratio)))
elif rescale_w and not rescale_h:
orig_w, orig_h = image.size
if orig_w != pad_w:
ratio = pad_w / orig_w
image.thumbnail((pad_w, int(orig_h * ratio)))
elif rescale_h and not rescale_w:
orig_w, orig_h = image.size
if orig_h != pad_h:
ratio = pad_h / orig_h
image.thumbnail((int(orig_w * ratio), pad_h))
return _crop(image, pad_w, pad_h)
def _crop(image: Image.Image, pad_w: int, pad_h: int) -> Image.Image:
orig_w, orig_h = image.size
w_shift = max(orig_w - pad_w, 0) // 2
h_shift = max(orig_h - pad_h, 0) // 2
even_w = max(orig_w - pad_w, 0) % 2
even_h = max(orig_h - pad_h, 0) % 2
return image.crop(
(w_shift, h_shift, orig_w - w_shift - even_w,
orig_h - h_shift - even_h))
def _pad(image: np.ndarray, pad_w: int, pad_h: int,
channels: int) -> np.ndarray:
img_h, img_w = image.shape[:2]
image_padded = np.zeros((pad_h, pad_w, channels))
image_padded[:img_h, :img_w, :] = image
return image_padded<|fim▁end|> | ImageFile.LOAD_TRUNCATED_IMAGES = True
def image_reader(prefix="", |
<|file_name|>server.rs<|end_file_name|><|fim▁begin|>use std::{
iter::FromIterator,
net::TcpListener,
process,
sync::mpsc,
thread,
time::Duration
};
use std::convert::Infallible;
use std::net::{IpAddr, SocketAddr};
use futures::channel::oneshot::channel;
use hyper::server::Server;
use hyper::service::make_service_fn;
use log::*;
use maplit::*;
use serde_json::{self, json, Value};
use uuid::Uuid;
use webmachine_rust::*;
use webmachine_rust::context::*;
use webmachine_rust::headers::*;
use pact_matching::models::RequestResponsePact;
use pact_mock_server::mock_server::MockServerConfig;
use pact_mock_server::tls::TlsConfigBuilder;
use crate::{SERVER_MANAGER, SERVER_OPTIONS, ServerOpts};
use crate::verify;
fn json_error(error: String) -> String {
let json_response = json!({ "error" : json!(error) });
json_response.to_string()
}
fn get_next_port(base_port: Option<u16>) -> u16 {
match base_port {
None => 0,
Some(p) => if p > 0 {
let mut port = p;
let mut listener = TcpListener::bind(("127.0.0.1", port));
while listener.is_err() && port < p + 1000 {
port += 1;
listener = TcpListener::bind(("127.0.0.1", port));
}
match listener {
Ok(listener) => listener.local_addr().unwrap().port(),
Err(_) => 0
}
} else {
0
}
}
}
fn start_provider(context: &mut WebmachineContext, options: ServerOpts) -> Result<bool, u16> {
debug!("start_provider => {}", context.request.request_path);
match context.request.body {
Some(ref body) if !body.is_empty() => {
match serde_json::from_slice(body) {
Ok(ref json) => {
let pact = RequestResponsePact::from_json(&context.request.request_path, json);
debug!("Loaded pact = {:?}", pact);
let mock_server_id = Uuid::new_v4().to_string();
let config = MockServerConfig {
cors_preflight: query_param_set(context, "cors")
};
debug!("Mock server config = {:?}", config);
let mut guard = SERVER_MANAGER.lock().unwrap();
let result = if query_param_set(context, "tls") {
debug!("Starting TLS mock server with id {}", &mock_server_id);
let key = include_str!("self-signed.key");
let cert = include_str!("self-signed.cert");
TlsConfigBuilder::new()
.key(key.as_bytes())
.cert(cert.as_bytes())
.build()
.map_err(|err| {
format!("Failed to setup TLS using self-signed certificate - {}", err)
})
.and_then(|tls_config| {
guard.start_tls_mock_server(mock_server_id.clone(), pact, get_next_port(options.base_port), &tls_config, config)
})
} else {
debug!("Starting mock server with id {}", &mock_server_id);
guard.start_mock_server(mock_server_id.clone(), pact, get_next_port(options.base_port), config)
};
match result {
Ok(mock_server) => {
debug!("mock server started on port {}", mock_server);
let mock_server_json = json!({
"id" : json!(mock_server_id.clone()),
"port" : json!(mock_server as i64),
});
let json_response = json!({ "mockServer" : mock_server_json });
context.response.body = Some(json_response.to_string().into_bytes());
context.response.add_header("Location",
vec![HeaderValue::basic(format!("/mockserver/{}", mock_server_id).as_str())]);
Ok(true)
},
Err(msg) => {
context.response.body = Some(json_error(format!("Failed to start mock server - {}", msg)).into_bytes());
Err(422)
}
}
},
Err(err) => {
log::error!("Failed to parse json body - {}", err);
context.response.body = Some(json_error(format!("Failed to parse json body - {}", err)).into_bytes());
Err(422)<|fim▁hole|> },
_ => {
log::error!("No pact json was supplied");
context.response.body = Some(json_error("No pact json was supplied".to_string()).into_bytes());
Err(422)
}
}
}
fn query_param_set(context: &mut WebmachineContext, name: &str) -> bool {
context.request.query.get(name)
.unwrap_or(&vec![]).first().unwrap_or(&String::default())
.eq("true")
}
pub fn verify_mock_server_request(context: &mut WebmachineContext) -> Result<bool, u16> {
let id = context.metadata.get("id").cloned().unwrap_or_default();
match verify::validate_id(&id, &SERVER_MANAGER) {
Ok(ms) => {
let mut map = btreemap!{ "mockServer" => ms.to_json() };
let mismatches = ms.mismatches();
if !mismatches.is_empty() {
map.insert("mismatches", json!(
Vec::from_iter(mismatches.iter().map(|m| m.to_json()))));
context.response.body = Some(json!(map).to_string().into_bytes());
Err(422)
} else {
let inner = SERVER_OPTIONS.lock().unwrap();
let options = inner.borrow();
match ms.write_pact(&options.output_path, false) {
Ok(_) => Ok(true),
Err(err) => {
map.insert("error", json!(format!("Failed to write pact to file - {}", err)));
context.response.body = Some(json!(map).to_string().into_bytes());
Err(422)
}
}
}
},
Err(_) => Err(422)
}
}
fn shutdown_resource<'a>() -> WebmachineResource<'a> {
WebmachineResource {
allowed_methods: vec!["POST"],
forbidden: callback(&|context, _| {
let options = SERVER_OPTIONS.lock().unwrap();
!context.request.has_header_value(&"Authorization".to_owned(), &format!("Bearer {}", options.borrow().server_key))
}),
process_post: callback(&|context, _| {
let shutdown_period = match context.request.body {
Some(ref body) if !body.is_empty() => {
match serde_json::from_slice::<Value>(body) {
Ok(ref json) => match json.get("period") {
Some(val) => match val.clone() {
Value::Number(n) => Ok(n.as_u64().unwrap_or(100)),
_ => Ok(100)
},
None => Ok(100)
},
Err(err) => {
error!("Failed to parse json body - {}", err);
context.response.body = Some(json_error(format!("Failed to parse json body - {}", err)).into_bytes());
Err(422)
}
}
}
_ => Ok(100)
};
match shutdown_period {
Ok(period) => {
// Need to work out how to do this as the webmachine has to have a static lifetime
// shutdown.send(()).unwrap_or_default();
thread::spawn(move || {
info!("Scheduling master server to shutdown in {}ms", period);
thread::sleep(Duration::from_millis(period));
info!("Shutting down");
process::exit(0);
});
Ok(true)
}
Err(err) => Err(err)
}
}),
..WebmachineResource::default()
}
}
fn mock_server_resource<'a>() -> WebmachineResource<'a> {
WebmachineResource {
allowed_methods: vec!["OPTIONS", "GET", "HEAD", "POST", "DELETE"],
resource_exists: callback(&|context, _| {
debug!("mock_server_resource -> resource_exists");
let paths: Vec<String> = context.request.request_path
.split('/')
.filter(|p| !p.is_empty())
.map(|p| p.to_string())
.collect();
if !paths.is_empty() && paths.len() <= 2 {
match verify::validate_id(&paths[0].clone(), &SERVER_MANAGER) {
Ok(ms) => {
context.metadata.insert("id".to_string(), ms.id.clone());
context.metadata.insert("port".to_string(), ms.port.unwrap_or_default().to_string());
if paths.len() > 1 {
context.metadata.insert("subpath".to_string(), paths[1].clone());
paths[1] == "verify"
} else {
true
}
}
Err(_) => false
}
} else {
false
}
}),
render_response: callback(&|context, _| {
debug!("mock_server_resource -> render_response");
match context.metadata.get("subpath".into()) {
None => {
let id = context.metadata.get("id".into()).unwrap().clone();
SERVER_MANAGER.lock().unwrap().find_mock_server_by_id(&id, &|ms| ms.to_json())
.map(|json| json.to_string())
}
Some(_) => {
context.response.status = 405;
None
}
}
}),
process_post: callback(&|context, _| {
debug!("mock_server_resource -> process_post");
let subpath = context.metadata.get("subpath".into()).unwrap().clone();
if subpath == "verify" {
verify_mock_server_request(context)
} else {
Err(422)
}
}),
delete_resource: callback(&|context, _| {
debug!("mock_server_resource -> delete_resource");
match context.metadata.get("subpath".into()) {
None => {
let id = context.metadata.get("id".into()).unwrap().clone();
thread::spawn(move || {
if SERVER_MANAGER.lock().unwrap().shutdown_mock_server_by_id(id) {
Ok(true)
} else {
Err(404)
}
}).join().expect("Could not spawn thread to shut down mock server")
}
Some(_) => Err(405)
}
}),
..WebmachineResource::default()
}
}
fn dispatcher() -> WebmachineDispatcher<'static> {
WebmachineDispatcher {
routes: btreemap! {
"/" => WebmachineResource {
allowed_methods: vec!["OPTIONS", "GET", "HEAD", "POST"],
resource_exists: callback(&|context, _| {
debug!("main_resource -> resource_exists");
context.request.request_path == "/"
}),
render_response: callback(&|_, _| {
debug!("main_resource -> render_response");
let mock_servers = SERVER_MANAGER.lock().unwrap().map_mock_servers(&|ms| {
ms.to_json()
});
let json_response = json!({ "mockServers" : json!(mock_servers) });
Some(json_response.to_string())
}),
process_post: callback(&|context, _| {
debug!("main_resource -> process_post");
let (tx, rx) = mpsc::channel();
let (tx2, rx2) = mpsc::channel();
if let Err(err) = tx.send(context.clone()) {
error!("Failed to send context to start new mock server - {:?}", err);
return Err(500)
}
let start_fn = move || {
let handle = thread::current();
debug!("starting mock server on thread {}", handle.name().unwrap_or("<unknown>"));
let inner = SERVER_OPTIONS.lock().unwrap();
let options = inner.borrow().clone();
let mut ctx = rx.recv().unwrap();
let result = start_provider(&mut ctx, options);
debug!("Result of starting mock server: {:?}", result.clone());
match tx2.send(ctx) {
Ok(_) => result,
Err(err) => {
error!("Failed to send result back to main resource - {:?}", err);
Err(500)
}
}
};
match thread::spawn(start_fn).join() {
Ok(res) => {
debug!("Result of thread: {:?}", res);
let ctx = rx2.recv().unwrap();
context.response = ctx.response;
res
},
Err(err) => {
error!("Failed to spawn new thread to start new mock server - {:?}", err);
Err(500)
}
}
}),
.. WebmachineResource::default()
},
"/mockserver" => mock_server_resource(),
"/shutdown" => shutdown_resource()
}
}
}
pub async fn start_server(port: u16) -> Result<(), i32> {
let addr = SocketAddr::new(IpAddr::from([0, 0, 0, 0]), port);
let (shutdown_tx, shutdown_rx) = channel::<()>();
let make_svc = make_service_fn(|_| async {
Ok::<_, Infallible>(dispatcher())
});
match Server::try_bind(&addr) {
Ok(server) => {
let server = server.serve(make_svc);
{
let inner = SERVER_OPTIONS.lock().unwrap();
let options = inner.borrow();
info!("Master server started on port {}", server.local_addr().port());
info!("Server key: '{}'", options.server_key);
}
server.with_graceful_shutdown(async { shutdown_rx.await.unwrap_or_default() }).await.map_err(|err| {
error!("Received an error starting master server: {}", err);
2
})
},
Err(err) => {
error!("could not start master server: {}", err);
Err(1)
}
}
}<|fim▁end|> | }
} |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// 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/.
<|fim▁hole|>
use ligature::{Ligature, WriteFn, QueryFn, LigatureError, Dataset};
/// The main struct used for working with the SQLite stored version of Ligature.
pub struct LigatureSQLite {
//connection:
}
impl LigatureSQLite {
fn create_or_open_file(path: String) -> LigatureSQLite {
todo!()
}
fn new_memory_store() -> LigatureSQLite {
todo!()
}
}
impl Ligature for LigatureSQLite {
fn all_datasets(&self) -> Box<dyn Iterator<Item=Result<Dataset, LigatureError>>> {
todo!()
}
fn dataset_exists(&self, dataset: &Dataset) -> Result<bool, LigatureError> {
todo!()
}
fn match_datasets_prefix(&self, prefix: &str) -> Box<dyn Iterator<Item=Result<Dataset, LigatureError>>> {
todo!()
}
fn match_datasets_range(&self, start: &str, end: &str) -> Box<dyn Iterator<Item=Result<Dataset, LigatureError>>> {
todo!()
}
fn create_dataset(&self, dataset: &Dataset) -> Result<(), LigatureError> {
todo!()
}
fn delete_dataset(&self, dataset: &Dataset) -> Result<(), LigatureError> {
todo!()
}
fn query<T>(&self, dataset: &Dataset, f: QueryFn<T>) -> Result<T, LigatureError> {
todo!()
}
fn write<T>(&self, dataset: &Dataset, f: WriteFn<T>) -> Result<T, LigatureError> {
todo!()
}
}<|fim▁end|> | //! This module is the main module for the Ligature-SQLite project.
//! It implements the traits supplied by Ligature and persists data via SQLite3.
#![deny(missing_docs)] |
<|file_name|>CrapsExperiment.java<|end_file_name|><|fim▁begin|>/****************************************************
Statistics Online Computational Resource (SOCR)
http://www.StatisticsResource.org
All SOCR programs, materials, tools and resources are developed by and freely disseminated to the entire community.
Users may revise, extend, redistribute, modify under the terms of the Lesser GNU General Public License
as published by the Open Source Initiative http://opensource.org/licenses/. All efforts should be made to develop and distribute
factually correct, useful, portable and extensible resource all available in all digital formats for free over the Internet.
SOCR resources are distributed in the hope that they will be useful, but without
any warranty; without any explicit, implicit or implied warranty for merchantability or
fitness for a particular purpose. See the GNU Lesser General Public License for
more details see http://opensource.org/licenses/lgpl-license.php.
http://www.SOCR.ucla.edu
http://wiki.stat.ucla.edu/socr
It s Online, Therefore, It Exists!
****************************************************/
package edu.ucla.stat.SOCR.experiments;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import edu.ucla.stat.SOCR.core.*;
import edu.ucla.stat.SOCR.distributions.*;
import edu.ucla.stat.SOCR.util.*;
/** The basic casino craps game */
public class CrapsExperiment extends Experiment {
//Constants
public final static int PASS = 0, DONTPASS = 1, FIELD = 2, CRAPS = 3,
CRAPS2 = 4, CRAPS3 = 5, CRAPS12 = 6, SEVEN = 7, ELEVEN = 8, BIG6 = 9,
BIG8 = 10, HARDWAY4 = 11, HARDWAY6 = 12, HARDWAY8 = 13, HARDWAY10 = 14;
//Variables
private int x, y, u, v, point1, point2, win, rolls, betType = PASS;
private double[] prob = new double[] { 251.0 / 495, 0, 244.0 / 495 };
//Objects
private JPanel toolbar = new JPanel();
private DiceBoard diceBoard = new DiceBoard(4);
private JComboBox<String> betJComboBox = new JComboBox<>();
private FiniteDistribution dist = new FiniteDistribution(-1, 1, 1, prob);
private RandomVariable profitRV = new RandomVariable(dist, "W");
private RandomVariableGraph profitGraph = new RandomVariableGraph(profitRV);
private RandomVariableTable profitTable = new RandomVariableTable(profitRV);
/** Initialize the experiment */
public CrapsExperiment() {
setName("Craps Experiment");
//Event listeners
betJComboBox.addItemListener(this);
//Bet choice
betJComboBox.addItem("Pass");
betJComboBox.addItem("Don't Pass");
betJComboBox.addItem("Field");
betJComboBox.addItem("Craps");
betJComboBox.addItem("Craps 2");
betJComboBox.addItem("Craps 3");
betJComboBox.addItem("Craps 12");
betJComboBox.addItem("Seven");
betJComboBox.addItem("Eleven");
betJComboBox.addItem("Big 6");
betJComboBox.addItem("Big 8");
betJComboBox.addItem("Hardway 4");
betJComboBox.addItem("Hardway 6");
betJComboBox.addItem("Hardway 8");
betJComboBox.addItem("Hardway 10");
//toolbars
toolbar.setLayout(new FlowLayout(FlowLayout.CENTER));
toolbar.add(betJComboBox);
addToolbar(toolbar);
//Graphs
addGraph(diceBoard);
addGraph(profitGraph);
//Table
addTable(profitTable);
reset();
}
/**
* Perform the experiment: roll the dice, and depending on the bet,
* determine whether to roll the dice a second time. Finally, deterimine the
* outcome of the bet
*/
public void doExperiment() {
super.doExperiment();
rolls = 1;
x = (int) Math.ceil(6 * Math.random());
y = (int) Math.ceil(6 * Math.random());
point1 = x + y;
point2 = 0;
switch (betType) {
case PASS:
if (point1 == 7 | point1 == 11) win = 1;
else if (point1 == 2 | point1 == 3 | point1 == 12) win = -1;
else {
while (point2 != point1 & point2 != 7) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (point2 == point1) win = 1;
else win = -1;
}
break;
case DONTPASS:
if (point1 == 7 | point1 == 11) win = -1;
else if (point1 == 2 | point1 == 3) win = 1;
else if (point1 == 12) win = 0;
else {
while (point2 != point1 & point2 != 7) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (point2 == point1) win = -1;
else win = 1;
}
break;
case FIELD:
if (point1 == 3 | point1 == 4 | point1 == 9 | point1 == 10
| point1 == 11) win = 1;
else if (point1 == 2 | point1 == 12) win = 2;
else win = -1;
break;
case CRAPS:
if (point1 == 2 | point1 == 3 | point1 == 12) win = 7;
else win = -1;
break;
case CRAPS2:
if (point1 == 2) win = 30;
else win = -1;
break;
case CRAPS3:
if (point1 == 3) win = 15;
else win = -1;
break;
case CRAPS12:
if (point1 == 12) win = 30;
else win = -1;
break;
case SEVEN:
if (point1 == 7) win = 4;
else win = -1;
break;
case ELEVEN:
if (point1 == 11) win = 15;
else win = -1;
break;
case BIG6:
if (point1 == 6) win = 1;
else if (point1 == 7) win = -1;
else {
while (point2 != 6 & point2 != 7) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (point2 == 6) win = 1;
else win = -1;
}
break;
case BIG8:
if (point1 == 8) win = 1;
else if (point1 == 7) win = -1;
else {
while (point2 != 8 & point2 != 7) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (point2 == 8) win = 1;
else win = -1;
}
break;
case HARDWAY4:
if (x == 2 & y == 2) win = 7;
else if (point1 == 7 | point1 == 4) win = -1;
else {
while (point2 != 7 & point2 != 4) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (u == 2 & v == 2) win = 7;
else win = -1;
}
break;
case HARDWAY6:
if (x == 3 & y == 3) win = 9;
else if (point1 == 7 | point1 == 6) win = -1;
else {
while (point2 != 7 & point2 != 6) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (u == 3 & v == 3) win = 9;
else win = -1;
}
break;
case HARDWAY8:
if (x == 4 & y == 4) win = 9;
else if (point1 == 7 | point1 == 8) win = -1;
else {
while (point2 != 7 & point2 != 8) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (u == 4 & v == 4) win = 9;
else win = -1;
}
break;
case HARDWAY10:
if (x == 5 & y == 5) win = 7;
else if (point1 == 7 | point1 == 10) win = -1;
else {
while (point2 != 7 & point2 != 10) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (u == 5 & v == 5) win = 7;
else win = -1;
}
break;
}
profitRV.setValue(win);
}
/**
* This method runs the the experiment one time, and add sounds depending on
* the outcome of the experiment.
*/
public void step() {
doExperiment();
update();
try {
if (win == -1) play("sounds/0.au");
else play("sounds/1.au");
} catch (Exception e) {
;
}
}
//Reset
public void reset() {
super.reset();
diceBoard.showDice(0);
profitRV.reset();
getRecordTable().append("\t(X,Y)\t(U,V)\tN\tW");
profitGraph.reset();
profitTable.reset();
}
//Update
public void update() {
super.update();
String updateText;
diceBoard.getDie(0).setValue(x);
diceBoard.getDie(1).setValue(y);
if (rolls > 1) {
diceBoard.getDie(2).setValue(u);
diceBoard.getDie(3).setValue(v);
diceBoard.showDice(4);
} else diceBoard.showDice(2);
updateText = "\t(" + x + "," + y + ")";
if (rolls > 1) updateText = updateText + "\t(" + u + "," + v + ")";
else updateText = updateText + "\t(*,*)";
updateText = updateText + "\t" + rolls + "\t" + win;
getRecordTable().append(updateText);
profitGraph.repaint();
profitTable.update();
}
public void itemStateChanged(ItemEvent event) {
if (event.getSource() == betJComboBox) {
betType = betJComboBox.getSelectedIndex();
<|fim▁hole|> switch (betType) {
case PASS:
prob = new double[3];
prob[0] = 251.0 / 495;
prob[2] = 244.0 / 495;
dist.setParameters(-1, 1, 1, prob);
break;
case DONTPASS:
prob = new double[3];
prob[0] = 244.0 / 495;
prob[1] = 1.0 / 36;
prob[2] = 949.0 / 1980;
dist.setParameters(-1, 1, 1, prob);
break;
case FIELD:
prob = new double[4];
prob[0] = 5.0 / 9;
prob[2] = 7.0 / 18;
prob[3] = 1.0 / 18;
dist.setParameters(-1, 2, 1, prob);
break;
case CRAPS:
prob = new double[9];
prob[0] = 8.0 / 9;
prob[8] = 1.0 / 9;
dist.setParameters(-1, 7, 1, prob);
break;
case CRAPS2:
prob = new double[32];
prob[0] = 35.0 / 36;
prob[31] = 1.0 / 36;
dist.setParameters(-1, 30, 1, prob);
break;
case CRAPS3:
prob = new double[17];
prob[0] = 17.0 / 18;
prob[16] = 1.0 / 18;
dist.setParameters(-1, 15, 1, prob);
break;
case CRAPS12:
prob = new double[32];
prob[0] = 35.0 / 36;
prob[31] = 1.0 / 36;
dist.setParameters(-1, 30, 1, prob);
break;
case SEVEN:
prob = new double[6];
prob[0] = 5.0 / 6;
prob[5] = 1.0 / 6;
dist.setParameters(-1, 4, 1, prob);
break;
case ELEVEN:
prob = new double[17];
prob[0] = 17.0 / 18;
prob[16] = 1.0 / 18;
dist.setParameters(-1, 15, 1, prob);
break;
case BIG6:
prob = new double[3];
prob[0] = 6.0 / 11;
prob[2] = 5.0 / 11;
dist.setParameters(-1, 1, 1, prob);
break;
case BIG8:
prob = new double[3];
prob[0] = 6.0 / 11;
prob[2] = 5.0 / 11;
dist.setParameters(-1, 1, 1, prob);
break;
case HARDWAY4:
prob = new double[9];
prob[0] = 8.0 / 9;
prob[8] = 1.0 / 9;
dist.setParameters(-1, 7, 1, prob);
break;
case HARDWAY6:
prob = new double[11];
prob[0] = 10. / 11;
prob[10] = 1.0 / 11;
dist.setParameters(-1, 9, 1, prob);
break;
case HARDWAY8:
prob = new double[11];
prob[0] = 10. / 11;
prob[10] = 1.0 / 11;
dist.setParameters(-1, 9, 1, prob);
break;
case HARDWAY10:
prob = new double[9];
prob[0] = 8.0 / 9;
prob[8] = 1.0 / 9;
dist.setParameters(-1, 7, 1, prob);
break;
}
reset();
} else super.itemStateChanged(event);
}
}<|fim▁end|> | |
<|file_name|>module_with_multiple_exports.js<|end_file_name|><|fim▁begin|>/**
* @module {Module} utils/math<|fim▁hole|> * @parent utils
*
* The module's description is the first paragraph.
*
* The body of the module's documentation.
*/
import _ from 'lodash';
/**
* @function
*
* This function's description is the first
* paragraph.
*
* This starts the body. This text comes after the signature.
*
* @param {Number} first This param's description.
* @param {Number} second This param's description.
* @return {Number} This return value's description.
*/
export function sum(first, second){ ... };
/**
* @property {{}}
*
* This function's description is the first
* paragraph.
*
* @option {Number} pi The description of pi.
*
* @option {Number} e The description of e.
*/
export var constants = {
pi: 3.14159265359,
e: 2.71828
};<|fim▁end|> | |
<|file_name|>OderEvaluateActivity.java<|end_file_name|><|fim▁begin|>package com.melvin.share.ui.activity;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.melvin.share.R;
import com.melvin.share.Utils.ShapreUtils;
import com.melvin.share.Utils.Utils;
import com.melvin.share.databinding.ActivityOrderEvaluateBinding;
import com.melvin.share.model.Evaluation;
import com.melvin.share.model.WaitPayOrderInfo;
import com.melvin.share.model.list.CommonList;
import com.melvin.share.model.serverReturn.CommonReturnModel;
import com.melvin.share.modelview.acti.OrderEvaluateViewModel;
import com.melvin.share.network.GlobalUrl;
import com.melvin.share.rx.RxActivityHelper;
import com.melvin.share.rx.RxFragmentHelper;
import com.melvin.share.rx.RxModelSubscribe;
import com.melvin.share.rx.RxSubscribe;
import com.melvin.share.ui.activity.common.BaseActivity;
import com.melvin.share.ui.activity.shopcar.ShoppingCarActivity;
import com.melvin.share.ui.fragment.productinfo.ProductEvaluateFragment;
import com.melvin.share.view.MyRecyclerView;
import com.melvin.share.view.RatingBar;
import java.util.HashMap;
import java.util.Map;
import static com.melvin.share.R.id.map;
import static com.melvin.share.R.id.ratingbar;
/**
* Author: Melvin
* <p/>
* Data: 2017/4/8
* <p/><|fim▁hole|> */
public class OderEvaluateActivity extends BaseActivity {
private ActivityOrderEvaluateBinding binding;
private Context mContext = null;
private int starCount;
private WaitPayOrderInfo.OrderBean.OrderItemResponsesBean orderItemResponsesBean;
@Override
protected void initView() {
binding = DataBindingUtil.setContentView(this, R.layout.activity_order_evaluate);
mContext = this;
initWindow();
initToolbar(binding.toolbar);
ininData();
}
private void ininData() {
binding.ratingbar.setOnRatingChangeListener(new RatingBar.OnRatingChangeListener() {
@Override
public void onRatingChange(int var1) {
starCount = var1;
}
});
orderItemResponsesBean = getIntent().getParcelableExtra("orderItemResponsesBean");
if (orderItemResponsesBean != null) {
String[] split = orderItemResponsesBean.mainPicture.split("\\|");
if (split != null && split.length >= 1) {
String url = GlobalUrl.SERVICE_URL + split[0];
Glide.with(mContext)
.load(url)
.placeholder(R.mipmap.logo)
.centerCrop()
.into(binding.image);
}
binding.name.setText(orderItemResponsesBean.productName);
}
}
public void submit(View view) {
String contents = binding.content.getText().toString();
if (TextUtils.isEmpty(contents)) {
Utils.showToast(mContext, "请评价");
}
if (starCount == 0) {
Utils.showToast(mContext, "请评分");
}
Map map = new HashMap();
map.put("orderItemId", orderItemResponsesBean.id);
map.put("startlevel", starCount);
map.put("picture", orderItemResponsesBean.mainPicture);
map.put("content", contents);
ShapreUtils.putParamCustomerId(map);
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse((new Gson().toJson(map)));
fromNetwork.insertOderItemEvaluation(jsonObject)
.compose(new RxActivityHelper<CommonReturnModel>().ioMain(OderEvaluateActivity.this, true))
.subscribe(new RxSubscribe<CommonReturnModel>(mContext, true) {
@Override
protected void myNext(CommonReturnModel commonReturnModel) {
Utils.showToast(mContext, commonReturnModel.message);
finish();
}
@Override
protected void myError(String message) {
Utils.showToast(mContext, message);
}
});
}
}<|fim▁end|> | * 描述: 订单评价页面 |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![feature(const_fn, plugin)]<|fim▁hole|>#![allow(unused_mut)]
extern crate algorithms;
#[macro_use]
extern crate expectest;
mod union_find;
mod percolation;
mod generator;
mod collinear_points;<|fim▁end|> | #![plugin(stainless)]
// for stainless |
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import os, sys
from django.core.management import execute_manager
sys.path.insert(0, os.path.abspath('./../../'))<|fim▁hole|>except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)<|fim▁end|> | try:
import settings # Assumed to be in the same directory. |
<|file_name|>resourceLimits.js<|end_file_name|><|fim▁begin|>/*
* Copyright (c) Microsoft Corporation. All rights reserved.<|fim▁hole|> *
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* The resource limits.
*
*/
class ResourceLimits {
/**
* Create a ResourceLimits.
* @member {number} [memoryInGB] The memory limit in GB of this container
* instance.
* @member {number} [cpu] The CPU limit of this container instance.
*/
constructor() {
}
/**
* Defines the metadata of ResourceLimits
*
* @returns {object} metadata of ResourceLimits
*
*/
mapper() {
return {
required: false,
serializedName: 'ResourceLimits',
type: {
name: 'Composite',
className: 'ResourceLimits',
modelProperties: {
memoryInGB: {
required: false,
serializedName: 'memoryInGB',
type: {
name: 'Number'
}
},
cpu: {
required: false,
serializedName: 'cpu',
type: {
name: 'Number'
}
}
}
}
};
}
}
module.exports = ResourceLimits;<|fim▁end|> | * Licensed under the MIT License. See License.txt in the project root for
* license information. |
<|file_name|>dvsighdl.cc<|end_file_name|><|fim▁begin|>/*
*
* Copyright (C) 2001-2010, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmpstat
*
* Author: Marco Eichelberg
*
* Purpose:
* classes: DVSignatureHandler
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/dcmpstat/dvsighdl.h"
#include "dcmtk/dcmdata/dcdeftag.h"
#include "dcmtk/dcmsign/dcsignat.h"
#include "dcmtk/dcmdata/dcobject.h"
#include "dcmtk/dcmdata/dcsequen.h"
#include "dcmtk/dcmdata/dcvrat.h"
#include "dcmtk/dcmdata/dcitem.h"
#include "dcmtk/dcmpstat/dvpscf.h"
#include "dcmtk/dcmsign/sicert.h"
#include "dcmtk/dcmsign/sitypes.h"
#include "dcmtk/dcmsign/sinullpr.h"
#include "dcmtk/dcmsign/siprivat.h"
#include "dcmtk/dcmsign/siripemd.h"
#include "dcmtk/ofstd/ofstream.h"
#ifdef WITH_OPENSSL
BEGIN_EXTERN_C
#include <openssl/x509.h>
END_EXTERN_C
/// the signature profile class we're using with DICOMscope
class DVSignatureHandlerSignatureProfile: public SiNullProfile
{
public:
/// default constructor
DVSignatureHandlerSignatureProfile(DcmAttributeTag& at)
: SiNullProfile()
, notToSign(at)
, vmNotToSign(notToSign.getVM())
{
}
/// destructor
virtual ~DVSignatureHandlerSignatureProfile() { }
/** checks whether the given tag is in the list of tags not to sign
* @param tag tag to check
* @return true if in list, false otherwise
*/
OFBool tagInList(const DcmTagKey& tag) const
{
DcmAttributeTag tempList(notToSign); // required because getTagVal() is not const
DcmTagKey tagkey;
for (unsigned long n=0; n<vmNotToSign; n++)
{
if ((EC_Normal == tempList.getTagVal(tagkey, n)) && (tag == tagkey)) return OFTrue;
}
return OFFalse;
}
/** checks whether an attribute with the given tag must not be signed
* for the current security profile.
* @param key tag key to be checked
* @return true if attribute must not be signed, false otherwise.
*/
virtual OFBool attributeForbidden(const DcmTagKey& key) const
{
return tagInList(key);
}
private:
/// list of attributes not to sign
DcmAttributeTag& notToSign;
/// number of entries in notToSign
unsigned long vmNotToSign;
};
#endif
DVSignatureHandler::DVSignatureHandler(DVConfiguration& cfg)
: htmlSR("<html><head><title>Structured Report</title></head><body>No structured report is currently active.</body></html>\n")
, htmlImage("<html><head><title>Image</title></head><body>No image is currently active.</body></html>\n")
, htmlPState("<html><head><title>Presentation State</title></head><body>No presentation state is currently active.</body></html>\n")
, htmlOverview()
, correctSignaturesSR(0)
, corruptSignaturesSR(0)
, untrustSignaturesSR(0)
, correctSignaturesImage(0)
, corruptSignaturesImage(0)
, untrustSignaturesImage(0)
, correctSignaturesPState(0)
, corruptSignaturesPState(0)
, untrustSignaturesPState(0)
#ifdef WITH_OPENSSL
, certVerifier()
#endif
, config(cfg)
{
#ifdef WITH_OPENSSL
int fileFormat = config.getTLSPEMFormat() ? X509_FILETYPE_PEM : X509_FILETYPE_ASN1;
const char *tlsCACertificateFolder = config.getTLSCACertificateFolder();
if (tlsCACertificateFolder) certVerifier.addTrustedCertificateDir(tlsCACertificateFolder, fileFormat);
#endif
updateSignatureValidationOverview();
}
DVSignatureHandler::~DVSignatureHandler()
{
}
void DVSignatureHandler::replaceString(DVPSObjectType objtype, const char *str)
{
switch (objtype)
{
case DVPSS_structuredReport:
if (str) htmlSR=str; else htmlSR.clear();
break;
case DVPSS_image:
if (str) htmlImage=str; else htmlImage.clear();
break;
case DVPSS_presentationState:
if (str) htmlPState=str; else htmlPState.clear();
break;
}
}
void DVSignatureHandler::printSignatureItemPosition(DcmStack& stack, STD_NAMESPACE ostream& os)
{
DcmObject *elem = NULL;
DcmSequenceOfItems *sq = NULL;
unsigned long sqCard=0;
const char *tagname = NULL;
unsigned long m=0;
char buf[20];
OFBool printed = OFFalse;
if (stack.card() > 2)
{
// signature is located within a sequence
for (unsigned long l=stack.card()-2; l>0; --l) // loop over all elements except the stack top and bottom
{
elem = stack.elem(l);
if (elem)
{
if ((elem->ident() == EVR_item) && sq)
{
sqCard = sq->card();
for (m=0; m<sqCard; m++)
{
if (sq->getItem(m) == elem)
{
sprintf(buf, "[%lu]", m);
os << buf;
printed = OFTrue;
}
}
}
else
{
if (printed) os << ". ";
sq = (DcmSequenceOfItems *)elem;
DcmTag currentTag(elem->getTag());
tagname = currentTag.getTagName();
if (tagname) os << tagname; else
{
sprintf(buf, "(%04x,%04x)", elem->getTag().getGroup(), elem->getTag().getElement());
os << buf;
printed = OFTrue;
}
if (elem->ident() == EVR_SQ) sq = (DcmSequenceOfItems *)elem; else sq = NULL;
}
}
}
} else {
// signature is located in the main dataset
os << "Main Dataset";
}
}
#ifdef WITH_OPENSSL
void DVSignatureHandler::updateDigitalSignatureInformation(DcmItem& dataset, DVPSObjectType objtype, OFBool /* onRead */)
#else
void DVSignatureHandler::updateDigitalSignatureInformation(DcmItem& /*dataset*/, DVPSObjectType objtype, OFBool /* onRead */)
#endif
{
OFOStringStream os;
unsigned long counter = 0;
unsigned long corrupt_counter = 0;
unsigned long untrustworthy_counter = 0;
const char *htmlHead = NULL;
const char *htmlFoot = "</body></html>\n\n";
switch (objtype)
{
case DVPSS_structuredReport:
htmlHead = "<html>\n<head><title>Structured Report</title></head><body>\n";
break;
case DVPSS_image:
htmlHead = "<html>\n<head><title>Image</title></head><body>\n";
break;
case DVPSS_presentationState:
htmlHead = "<html>\n<head><title>Presentation State</title></head><body>\n";
break;
}
os << htmlHead;
#ifdef WITH_OPENSSL
DcmStack stack;
OFString aString;
DcmAttributeTag at(DCM_DataElementsSigned);
DcmTag tag;
unsigned long numSignatures = 0;
unsigned long l=0;
Uint16 macID = 0;
DcmTagKey tagkey;
const char *tagName = NULL;
OFBool nextline;
const char *htmlEndl = "</td></tr>\n";
const char *htmlVfyOK = "<tr><td colspan=\"4\" bgcolor=\"#50ff50\">";
const char *htmlVfyCA = "<tr><td colspan=\"4\" bgcolor=\"yellow\">";
const char *htmlVfyErr = "<tr><td colspan=\"4\" bgcolor=\"#FF5050\">";
const char *htmlLine1 = "<tr><td width=\"20\" nowrap> </td><td colspan=\"2\" nowrap>";
const char *htmlLine2 = "<tr><td colspan=\"3\" nowrap> </td><td>";
const char *htmlLine3 = "<tr><td colspan=\"2\" nowrap> </td><td nowrap>";
const char *htmlLine4 = "<tr><td width=\"20\" nowrap> </td><td width=\"20\" nowrap> </td><td>";
const char *htmlNext = "</td><td>";
const char *htmlTableOK = "<table cellspacing=\"0\" bgcolor=\"#D0FFD0\">\n";
const char *htmlTableCA = "<table cellspacing=\"0\" bgcolor=\"#FFF8DC\">\n";
const char *htmlTableErr = "<table cellspacing=\"0\" bgcolor=\"#FFD0D0\">\n";
const char *htmlTableE = "</table><p>\n\n";
DcmItem *sigItem = DcmSignature::findFirstSignatureItem(dataset, stack);
OFCondition sicond = EC_Normal;
DcmSignature signer;
while (sigItem)
{
signer.attach(sigItem);
numSignatures = signer.numberOfSignatures();
for (l=0; l<numSignatures; l++)
{
if (EC_Normal == signer.selectSignature(l))
{
++counter;
sicond = signer.verifyCurrent();
SiCertificate *cert = signer.getCurrentCertificate();
if ((sicond == EC_Normal) && cert)
{
sicond = certVerifier.verifyCertificate(*cert);
}
if (sicond == EC_Normal)
os << htmlTableOK << htmlVfyOK;
else if (sicond == SI_EC_VerificationFailed_NoTrust)
os << htmlTableCA << htmlVfyCA;
else
os << htmlTableErr << htmlVfyErr;
os << "<b>Signature #" << counter << " UID=";
if (EC_Normal == signer.getCurrentSignatureUID(aString)) os << aString.c_str(); else os << "(unknown)";
os << "</b>" << htmlEndl;
os << htmlLine1 << "Location" << htmlNext;
printSignatureItemPosition(stack, os);
os << htmlEndl;
os << htmlLine1 << "MAC ID" << htmlNext;
if (EC_Normal == signer.getCurrentMacID(macID)) os << macID; else os << "(unknown)";
os << htmlEndl;
os << htmlLine1 << "MAC algorithm" << htmlNext;
if (EC_Normal == signer.getCurrentMacName(aString)) os << aString.c_str(); else os << "(unknown)";
os << htmlEndl;
os << htmlLine1 << "MAC calculation xfer syntax" << htmlNext;
if (EC_Normal == signer.getCurrentMacXferSyntaxName(aString)) os << aString.c_str(); else os << "(unknown)";
os << htmlEndl;
os << htmlLine1 << "Data elements signed" << htmlNext;
nextline = OFFalse;
if (EC_Normal == signer.getCurrentDataElementsSigned(at))
{
unsigned long atVM = at.getVM();
for (unsigned long n=0; n<atVM; n++)
{
if (EC_Normal == at.getTagVal(tagkey, n))
{
if (nextline) os << htmlLine2; else nextline=OFTrue;
os << tagkey << " ";
tag = tagkey;
tagName = tag.getTagName();
if (tagName) os << tagName;
os << htmlEndl;
}
}
} else os << "all elements" << htmlEndl;
os << htmlLine1 << "Signature date/time" << htmlNext;
if (EC_Normal == signer.getCurrentSignatureDateTime(aString)) os << aString.c_str(); else os << "(unknown)";
os << htmlEndl
<< htmlLine1 << "Certificate of signer" << htmlNext;
if ((cert == NULL)||(cert->getKeyType()==EKT_none)) os << "none" << htmlEndl; else
{
os << "X.509v" << cert->getX509Version() << htmlEndl;
cert->getCertSubjectName(aString);
os << htmlLine3 << "Subject" << htmlNext << aString.c_str() << htmlEndl;
cert->getCertIssuerName(aString);
os << htmlLine3 << "Issued by" << htmlNext << aString.c_str() << htmlEndl
<< htmlLine3 << "Serial no." << htmlNext << cert->getCertSerialNo() << htmlEndl
<< htmlLine3 << "Validity" << htmlNext << "not before ";
cert->getCertValidityNotBefore(aString);
os << aString.c_str() << ", not after ";
cert->getCertValidityNotAfter(aString);
os << aString.c_str() << htmlEndl
<< htmlLine4 << "Public key" << htmlNext;
switch (cert->getKeyType())
{
case EKT_RSA:
os << "RSA, " << cert->getCertKeyBits() << " bits" << htmlEndl;
break;
case EKT_DSA:
os << "DSA, " << cert->getCertKeyBits() << " bits" << htmlEndl;
break;
case EKT_DH:
os << "DH, " << cert->getCertKeyBits() << " bits" << htmlEndl;
break;
case EKT_none: // should never happen
os << "none" << htmlEndl;
break;
}
}
if (sicond.good())
{
os << htmlVfyOK << "<b>Verification: OK</b>" << htmlEndl;
}
else if (sicond == SI_EC_VerificationFailed_NoTrust)
{
untrustworthy_counter++;
os << htmlVfyCA << "<b>Verification: Signature is valid but certificate could not be verified: "
<< certVerifier.lastError() << "</b>" << htmlEndl ;
}
else
{
corrupt_counter++;
os << htmlVfyErr << "<b>Verification: ";
os << sicond.text() << "</b>" << htmlEndl;
}
os << htmlTableE;
}
}
signer.detach();
sigItem = DcmSignature::findNextSignatureItem(dataset, stack);
}
#endif
switch (objtype)
{
case DVPSS_structuredReport:
if (counter == 0) os << "The current structured report does not contain any digital signature." << OFendl;
corruptSignaturesSR = corrupt_counter;
untrustSignaturesSR = untrustworthy_counter;
correctSignaturesSR = counter - corrupt_counter - untrustworthy_counter;
break;
case DVPSS_image:
if (counter == 0) os << "The current image does not contain any digital signature." << OFendl;
corruptSignaturesImage = corrupt_counter;
untrustSignaturesImage = untrustworthy_counter;
correctSignaturesImage = counter - corrupt_counter - untrustworthy_counter;
break;
case DVPSS_presentationState:
if (counter == 0) os << "The current presentation state does not contain any digital signature." << OFendl;
corruptSignaturesPState = corrupt_counter;
untrustSignaturesPState = untrustworthy_counter;
correctSignaturesPState = counter - corrupt_counter - untrustworthy_counter;
break;
}
os << htmlFoot << OFStringStream_ends;
OFSTRINGSTREAM_GETSTR(os, newText)
replaceString(objtype, newText); // copies newText into OFString
OFSTRINGSTREAM_FREESTR(newText)
updateSignatureValidationOverview();
return;
}
void DVSignatureHandler::disableDigitalSignatureInformation(DVPSObjectType objtype)
{
switch (objtype)
{
case DVPSS_structuredReport:
htmlSR = "<html><head><title>Structured Report</title></head><body>The current structured report does not contain any digital signature.</body></html>\n";
corruptSignaturesSR = 0;
untrustSignaturesSR = 0;
correctSignaturesSR = 0;
break;
case DVPSS_image:
corruptSignaturesImage = 0;
untrustSignaturesImage = 0;
correctSignaturesImage = 0;
htmlImage = "<html><head><title>Image</title></head><body>The current image does not contain any digital signature.</body></html>\n";
break;
case DVPSS_presentationState:
corruptSignaturesPState = 0;
untrustSignaturesPState = 0;
correctSignaturesPState = 0;
htmlPState = "<html><head><title>Presentation State</title></head><body>The current presentation state does not contain any digital signature.</body></html>\n";
break;
}
updateSignatureValidationOverview();
}
void DVSignatureHandler::disableImageAndPState()
{
corruptSignaturesImage = 0;
untrustSignaturesImage = 0;
correctSignaturesImage = 0;
htmlImage = "<html><head><title>Image</title></head><body>No image is currently active.</body></html>\n";
corruptSignaturesPState = 0;
untrustSignaturesPState = 0;
correctSignaturesPState = 0;
htmlPState = "<html><head><title>Presentation State</title></head><body>No presentation state is currently active.</body></html>\n";
updateSignatureValidationOverview();
return;
}
DVPSSignatureStatus DVSignatureHandler::getCurrentSignatureStatus(DVPSObjectType objtype) const
{
switch (objtype)
{
case DVPSS_structuredReport:
if ((correctSignaturesSR + corruptSignaturesSR + untrustSignaturesSR) == 0) return DVPSW_unsigned;
if ((corruptSignaturesSR + untrustSignaturesSR) == 0) return DVPSW_signed_OK;
if (corruptSignaturesSR == 0) return DVPSW_signed_unknownCA;
break;
case DVPSS_image:
if ((correctSignaturesImage + corruptSignaturesImage + untrustSignaturesImage) == 0) return DVPSW_unsigned;
if ((corruptSignaturesImage + untrustSignaturesImage) == 0) return DVPSW_signed_OK;
if (corruptSignaturesImage == 0) return DVPSW_signed_unknownCA;
break;
case DVPSS_presentationState:
if ((correctSignaturesPState + corruptSignaturesPState + untrustSignaturesPState) == 0) return DVPSW_unsigned;
if ((corruptSignaturesPState + untrustSignaturesPState) == 0) return DVPSW_signed_OK;
if (corruptSignaturesPState == 0) return DVPSW_signed_unknownCA;
break;
}
return DVPSW_signed_corrupt;
}
DVPSSignatureStatus DVSignatureHandler::getCombinedImagePStateSignatureStatus() const
{
DVPSSignatureStatus statImage = getCurrentSignatureStatus(DVPSS_image);
DVPSSignatureStatus statPState = getCurrentSignatureStatus(DVPSS_presentationState);
if ((statImage == DVPSW_signed_corrupt)||(statPState == DVPSW_signed_corrupt)) return DVPSW_signed_corrupt;
if ((statImage == DVPSW_signed_unknownCA)||(statPState == DVPSW_signed_unknownCA)) return DVPSW_signed_unknownCA;
if ((statImage == DVPSW_signed_OK)&&(statPState == DVPSW_signed_OK)) return DVPSW_signed_OK;
return DVPSW_unsigned;
}
const char *DVSignatureHandler::getCurrentSignatureValidationHTML(DVPSObjectType objtype) const
{
const char *result = "";
switch (objtype)
{
case DVPSS_structuredReport:
result = htmlSR.c_str();
break;
case DVPSS_image:
result = htmlImage.c_str();
break;
case DVPSS_presentationState:
result = htmlPState.c_str();
break;
}
return result;
}
void DVSignatureHandler::updateSignatureValidationOverview()
{
const char *htmlHead = "<html>\n<head><title>Overview</title></head><body>\n";
const char *htmlFoot = "</body></html>\n\n";
const char *htmlEndl = "</td></tr>\n";
const char *htmlTitle = "<tr><td colspan=\"3\">";
const char *htmlVfyUns = "<tr><td colspan=\"3\" bgcolor=\"#A0A0A0\">";
const char *htmlVfySig = "<tr><td colspan=\"3\" bgcolor=\"#50ff50\">";
const char *htmlVfyCA = "<tr><td colspan=\"3\" bgcolor=\"yellow\">";
const char *htmlVfyErr = "<tr><td colspan=\"3\" bgcolor=\"#FF5050\">";
const char *htmlLine1 = "<tr><td width=\"20\" nowrap> </td><td nowrap>";
const char *htmlNext = "</td><td>";
const char *htmlTableUns = "<p><table cellspacing=\"0\" bgcolor=\"#E0E0E0\">\n";
const char *htmlTableSig = "<p><table cellspacing=\"0\" bgcolor=\"#FFD0D0\">\n";
const char *htmlTableCA = "<p><table cellspacing=\"0\" bgcolor=\"#FFF8DC\">\n";
const char *htmlTableErr = "<p><table cellspacing=\"0\" bgcolor=\"#FFD0D0\">\n";
const char *htmlTableE = "</table></p>\n\n";
OFOStringStream os;
DVPSSignatureStatus status;
os << htmlHead;
// Structured Report
status = getCurrentSignatureStatus(DVPSS_structuredReport);
switch (status)
{
case DVPSW_unsigned:
os << htmlTableUns;
break;
case DVPSW_signed_OK:
os << htmlTableSig;
break;
case DVPSW_signed_unknownCA:
os << htmlVfyCA;
break;
case DVPSW_signed_corrupt:
os << htmlTableErr;
break;
}
os << htmlTitle << "<b>Structured Report</b>"<< htmlEndl;
os << htmlLine1 << "Number of correct signatures" << htmlNext << correctSignaturesSR << htmlEndl;
os << htmlLine1 << "Number of corrupt signatures" << htmlNext << corruptSignaturesSR << htmlEndl;
os << htmlLine1 << "Number of untrusted signatures" << htmlNext << untrustSignaturesSR << htmlEndl;
switch (status)
{
case DVPSW_unsigned:
os << htmlVfyUns << "<b>Status: unsigned</b>" << htmlEndl;
break;
case DVPSW_signed_OK:
os << htmlVfySig << "<b>Status: signed</b>" << htmlEndl;
break;
case DVPSW_signed_unknownCA:
os << htmlVfyCA << "<b>Status: signed but untrustworthy: certificate could not be verified</b>" << htmlEndl;
break;
case DVPSW_signed_corrupt:
os << htmlVfyErr << "<b>Status: contains corrupt signatures</b>" << htmlEndl;
break;
}
os << htmlTableE;
// Image
status = getCurrentSignatureStatus(DVPSS_image);
switch (status)
{
case DVPSW_unsigned:
os << htmlTableUns;
break;
case DVPSW_signed_OK:
os << htmlTableSig;
break;
case DVPSW_signed_unknownCA:
os << htmlTableCA;
break;
case DVPSW_signed_corrupt:
os << htmlTableErr;
break;
}
os << htmlTitle << "<b>Image</b>"<< htmlEndl;
os << htmlLine1 << "Number of correct signatures" << htmlNext << correctSignaturesImage << htmlEndl;
os << htmlLine1 << "Number of corrupt signatures" << htmlNext << corruptSignaturesImage << htmlEndl;
os << htmlLine1 << "Number of untrusted signatures" << htmlNext << untrustSignaturesImage << htmlEndl;
switch (status)
{
case DVPSW_unsigned:
os << htmlVfyUns << "<b>Status: unsigned</b>" << htmlEndl;
break;
case DVPSW_signed_OK:
os << htmlVfySig << "<b>Status: signed</b>" << htmlEndl;
break;
case DVPSW_signed_unknownCA:
os << htmlVfyCA << "<b>Status: signed but untrustworthy: certificate could not be verified</b>" << htmlEndl;
break;
case DVPSW_signed_corrupt:
os << htmlVfyErr << "<b>Status: contains corrupt signatures</b>" << htmlEndl;
break;
}
os << htmlTableE;
// Presentation State
status = getCurrentSignatureStatus(DVPSS_presentationState);
switch (status)
{
case DVPSW_unsigned:
os << htmlTableUns;
break;
case DVPSW_signed_OK:
os << htmlTableSig;
break;
case DVPSW_signed_unknownCA:
os << htmlTableCA;
break;
case DVPSW_signed_corrupt:
os << htmlTableErr;
break;
}
os << htmlTitle << "<b>Presentation State</b>"<< htmlEndl;
os << htmlLine1 << "Number of correct signatures" << htmlNext << correctSignaturesPState << htmlEndl;
os << htmlLine1 << "Number of corrupt signatures" << htmlNext << corruptSignaturesPState << htmlEndl;
os << htmlLine1 << "Number of untrusted signatures" << htmlNext << untrustSignaturesPState << htmlEndl;
switch (status)
{
case DVPSW_unsigned:
os << htmlVfyUns << "<b>Status: unsigned</b>" << htmlEndl;
break;
case DVPSW_signed_OK:
os << htmlVfySig << "<b>Status: signed</b>" << htmlEndl;
break;
case DVPSW_signed_unknownCA:
os << htmlVfyCA << "<b>Status: signed but untrustworthy: certificate could not be verified</b>" << htmlEndl;
break;
case DVPSW_signed_corrupt:
os << htmlVfyErr << "<b>Status: contains corrupt signatures</b>" << htmlEndl;
break;
}
os << htmlTableE;
os << htmlFoot << OFStringStream_ends;
OFSTRINGSTREAM_GETSTR(os, newText)
htmlOverview = newText;
OFSTRINGSTREAM_FREESTR(newText)
return;
}
<|fim▁hole|>{
return htmlOverview.c_str();
}
unsigned long DVSignatureHandler::getNumberOfCorrectSignatures(DVPSObjectType objtype) const
{
unsigned long result = 0;
switch (objtype)
{
case DVPSS_structuredReport:
result = correctSignaturesSR;
break;
case DVPSS_image:
result = correctSignaturesImage;
break;
case DVPSS_presentationState:
result = correctSignaturesPState;
break;
}
return result;
}
unsigned long DVSignatureHandler::getNumberOfUntrustworthySignatures(DVPSObjectType objtype) const
{
unsigned long result = 0;
switch (objtype)
{
case DVPSS_structuredReport:
result = untrustSignaturesSR;
break;
case DVPSS_image:
result = untrustSignaturesImage;
break;
case DVPSS_presentationState:
result = untrustSignaturesPState;
break;
}
return result;
}
unsigned long DVSignatureHandler::getNumberOfCorruptSignatures(DVPSObjectType objtype) const
{
unsigned long result = 0;
switch (objtype)
{
case DVPSS_structuredReport:
result = corruptSignaturesSR;
break;
case DVPSS_image:
result = corruptSignaturesImage;
break;
case DVPSS_presentationState:
result = corruptSignaturesPState;
break;
}
return result;
}
#ifdef WITH_OPENSSL
OFBool DVSignatureHandler::attributesSigned(DcmItem& item, DcmAttributeTag& tagList) const
{
DcmStack stack;
DcmAttributeTag at(DCM_DataElementsSigned);
DcmTagKey tagkey;
DcmSignature signer;
unsigned long numSignatures;
unsigned long l;
DVSignatureHandlerSignatureProfile sigProfile(tagList);
DcmItem *sigItem = DcmSignature::findFirstSignatureItem(item, stack);
while (sigItem)
{
if (sigItem == &item)
{
// signatures on main level - check attributes signed
signer.attach(sigItem);
numSignatures = signer.numberOfSignatures();
for (l=0; l<numSignatures; l++)
{
if (EC_Normal == signer.selectSignature(l))
{
// printSignatureItemPosition(stack, os);
if (EC_Normal == signer.getCurrentDataElementsSigned(at))
{
unsigned long atVM = at.getVM();
for (unsigned long n=0; n<atVM; n++)
{
if (EC_Normal == at.getTagVal(tagkey, n))
{
if (sigProfile.tagInList(tagkey)) return OFTrue; // one of the elements in tagList is signed
}
}
} else return OFTrue; // all elements are signed
}
}
signer.detach();
}
else
{
// signatures on lower level - check whether attribute on main level is in list
unsigned long scard = stack.card();
if (scard > 1) // should always be true
{
DcmObject *obj = stack.elem(scard-2);
if (obj) // should always be true
{
if (sigProfile.tagInList(obj->getTag())) return OFTrue; // one of the elements in tagList contains a signature
}
}
}
sigItem = DcmSignature::findNextSignatureItem(item, stack);
}
return OFFalse;
}
#else
OFBool DVSignatureHandler::attributesSigned(DcmItem& /* item */, DcmAttributeTag& /* tagList */) const
{
return OFFalse;
}
#endif
#ifdef WITH_OPENSSL
OFCondition DVSignatureHandler::createSignature(
DcmItem& mainDataset,
const DcmStack& itemStack,
DcmAttributeTag& attributesNotToSignInMainDataset,
const char *userID,
const char *passwd)
{
if (userID == NULL) return EC_IllegalCall;
// get user settings
int fileformat = config.getTLSPEMFormat() ? X509_FILETYPE_PEM : X509_FILETYPE_ASN1;
const char *userDir = config.getUserCertificateFolder();
const char *userKey = config.getUserPrivateKey(userID);
if (userKey == NULL) return EC_IllegalCall;
const char *userCert = config.getUserCertificate(userID);
if (userCert == NULL) return EC_IllegalCall;
// load private key
SiPrivateKey key;
OFString filename;
if (userDir)
{
filename = userDir;
filename += PATH_SEPARATOR;
}
filename += userKey;
if (passwd) key.setPrivateKeyPasswd(passwd);
OFCondition sicond = key.loadPrivateKey(filename.c_str(), fileformat);
if (sicond != EC_Normal) return EC_IllegalCall; // unable to load private key
// load certificate
SiCertificate cert;
filename.clear();
if (userDir)
{
filename = userDir;
filename += PATH_SEPARATOR;
}
filename += userCert;
sicond = cert.loadCertificate(filename.c_str(), fileformat);
if (sicond != EC_Normal) return EC_IllegalCall; // unable to load certificate
if (! key.matchesCertificate(cert)) return EC_IllegalCall; // private key does not match certificate
DcmSignature signer;
SiRIPEMD160 mac;
SiNullProfile nullProfile;
DVSignatureHandlerSignatureProfile mainProfile(attributesNotToSignInMainDataset);
DcmObject *current;
DcmItem *currentItem;
DcmStack workStack(itemStack);
while (! workStack.empty())
{
current = workStack.pop();
if ((current->ident() != EVR_dataset) && (current->ident() != EVR_item)) return EC_IllegalCall; // wrong type on stack
currentItem = (DcmItem *)current;
signer.attach(currentItem);
if (currentItem == &mainDataset)
{
// we're creating a signature in the main dataset
// we have to establish an explicit tag list, otherwise the profile does not work!
DcmAttributeTag tagList(DCM_DataElementsSigned);
unsigned long numAttributes = currentItem->card();
for (unsigned long l=0; l<numAttributes; l++)
{
tagList.putTagVal(currentItem->getElement(l)->getTag(),l);
}
sicond = signer.createSignature(key, cert, mac, mainProfile, EXS_LittleEndianExplicit, &tagList);
if (sicond != EC_Normal) return EC_IllegalCall; // error while creating signature
}
else
{
// we're creating a signature in a sequence item
sicond = signer.createSignature(key, cert, mac, nullProfile, EXS_LittleEndianExplicit);
if (sicond != EC_Normal) return EC_IllegalCall; // error while creating signature
}
signer.detach();
}
return EC_Normal;
}
#else
OFCondition DVSignatureHandler::createSignature(
DcmItem& /* mainDataset */,
const DcmStack& /* itemStack */,
DcmAttributeTag& /* attributesNotToSignInMainDataset */,
const char * /* userID */,
const char * /* passwd */)
{
return EC_IllegalCall;
}
#endif<|fim▁end|> | const char *DVSignatureHandler::getCurrentSignatureValidationOverview() const |
<|file_name|>second.py<|end_file_name|><|fim▁begin|>"""Second module, imported as inspect_recursive.a, with no contents"""
import inspect_recursive.first as a
import sys
if sys.version_info >= (3, 7):
# For some reason 3.6 says second doesn't exist yet. I get that, it's a
# cyclic reference, but that works in 3.7.
import inspect_recursive.second as b<|fim▁hole|><|fim▁end|> |
from inspect_recursive import Foo as Bar |
<|file_name|>Step2aCorr_Gilson_etal_2012.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
'''
Based on:
Gilson, Matthieu, Tomoki Fukai, and Anthony N. Burkitt.
Spectral Analysis of Input Spike Trains by Spike-Timing-Dependent Plasticity.
PLoS Comput Biol 8, no. 7 (July 5, 2012): e1002584. doi:10.1371/journal.pcbi.1002584.
Author: Aditya Gilra, Jun 2016. (with inputs from Matthieu Gilson)
in Brian2rc3 for CAMP 2016.
'''
#import modules and functions to be used
from brian2 import * # importing brian also does:
# 'from pylab import *' which imports:
# matplot like commands into the namespace, further
# also can use np. for numpy and mpl. for matplotlib
stand_alone = True
if stand_alone: set_device('cpp_standalone', build_on_run=False)
else:
#prefs.codegen.target = 'numpy'
prefs.codegen.target = 'weave'
#prefs.codegen.target = 'cython'
import random
import time
# http://stackoverflow.com/questions/31057197/should-i-use-random-seed-or-numpy-random-seed-to-control-random-number-gener
np.random.seed(0) # set seed for reproducibility of simulations
random.seed(0) # set seed for reproducibility of simulations
# ###########################################
# Simulation parameters
# ###########################################
simdt = 0.1*ms
simtime = 100.0*second
defaultclock.dt = simdt # set Brian's sim time step
simdtraw = simdt/second # convert to value in seconds
# ###########################################
# Neuron model
# ###########################################
taudelay = 0.75*ms # synaptic delay
tauA = 1*ms # synaptic epsp tauA
tauB = 5*ms # synaptic epsp tauB
eqs_neurons='''
dA/dt=-A/tauA : 1
dB/dt=-B/tauB : 1
rho_out = (A-B)/(tauA-tauB) : Hz
'''
# ###########################################
# Network parameters: numbers
# ###########################################
Npools = 4 # Number of correlated pools
Ninp = 500 # Number of neurons per pool
nu0 = 10*Hz # spiking rate of inputs
# ###########################################
# Network parameters: synapses
# ###########################################
Q = array([[sqrt(0.4),sqrt(0.1),0.,0.],\
[0.,sqrt(0.2),sqrt(0.2),0.],\
[0.,0.,sqrt(0.1),sqrt(0.1)]])
corr = dot(transpose(Q),Q)
print "Correlation matrix between pools is\n",corr
# ###########################################<|fim▁hole|>eta = 2e-4 # learning rate (as in paper)
Apre_tau = 17*ms # STDP Apre (LTP) time constant
Apost_tau = 34*ms # STDP Apost (LTD) time constant
stdp_eqns = ''' w : 1
dApre/dt=-Apre/Apre_tau : 1 (event-driven)
dApost/dt=-Apost/Apost_tau : 1 (event-driven)
'''
Apre0 = 1.0 # incr in Apre (LTP), on pre-spikes;
# at spike coincidence, delta w = -Apre0*eta
Apost0 = 0.55 # incr in Apost (LTD) on post spike
wmax = 0.04 # max weight (hard bound)
winit = wmax/2. # initial weights are from 0 to winit
w0 = wmax/2.
pre_eqns = 'Apre+=Apre0; w+=-eta*Apost;'\
' w=clip(w,0,wmax)'
post_eqns = 'Apost+=Apost0; w += eta*Apre;'\
' w=clip(w,0,wmax)'
# ###########################################
# Initialize neuron (sub)groups
# ###########################################
# post-synaptic neuron
P=NeuronGroup(1,model=eqs_neurons,\
threshold='rand()<rho_out*dt',method='euler')
# ###########################################
# Stimuli
# ###########################################
#inputs rates for absence of correlated events such that all neurons have same firing rate F
baseline_input_rates = np.zeros(Npools*Ninp)*Hz
for i_gp in range(Npools):
baseline_input_rates[i_gp*Ninp:(i_gp+1)*Ninp] = nu0*(1.-Q[:,i_gp].sum())
print baseline_input_rates[i_gp*Ninp]
# 3 driving spike trains
Pinp0=NeuronGroup(3,model='spikerate : Hz',\
threshold='rand()<spikerate*dt')
Pinp0.spikerate = nu0
Pinps = [Pinp0[:1],Pinp0[1:2],Pinp0[2:]]
# Npools number of Ninp spike trains
Pinp1=NeuronGroup(Npools*Ninp,model='spikerate : Hz',\
threshold='rand()<spikerate*dt')
Pinp1.spikerate = baseline_input_rates
Ppools = []
for k in range(Npools):
Ppools.append(Pinp1[k*Ninp:(k+1)*Ninp])
inpconns = []
def correlate_spike_trains(PR,P,l,csqrt):
con = Synapses(PR,P,'',on_pre='spikerate+='+str(csqrt)+'/dt')
con.connect(True)
con.delay = 0.*ms
con1 = Synapses(PR,P,'',on_pre='spikerate='+str(baseline_input_rates[l*Ninp]/Hz)+'*Hz')
con1.connect(True)
con1.delay = simdt
inpconns.append((con,con1))
for k in range(3):
for l in range(Npools):
if Q[k,l]!=0.:
correlate_spike_trains(Pinps[k],Ppools[l],l,Q[k,l])
# ###########################################
# Connecting the network
# ###########################################
con = Synapses(Pinp1,P,stdp_eqns,\
on_pre='A+=w*0.05;B+=w*0.05;'+pre_eqns,on_post=post_eqns,
method='euler')
con.connect(True)
con.delay = uniform(size=(Npools*Ninp,))*1.*ms + 4.*ms
con.w = uniform(size=(Npools*Ninp,))*2*winit
# ###########################################
# Setting up monitors
# ###########################################
sm = SpikeMonitor(P)
sminp1 = SpikeMonitor(Pinp1)
# Population monitor
popm = PopulationRateMonitor(P)
popminp1 = PopulationRateMonitor(Pinp1)
# voltage monitor
sm_rho = StateMonitor(P,'rho_out',record=[0])
# weights monitor
wm = StateMonitor(con,'w',record=range(Npools*Ninp), dt=1*second)
# ###########################################
# Simulate
# ###########################################
# a simple run would not include the monitors
net = Network(collect()) # collects Brian2 objects in current context
net.add(inpconns)
print "Setup complete, running for",simtime,"at dt =",simdtraw,"s."
t1 = time.time()
net.run(simtime,report='text')
device.build(directory='output', compile=True, run=True, debug=False)
# ###########################################
# Make plots
# ###########################################
# always convert spikemon.t and spikemon.i to array-s before indexing
# spikemon.i[] indexing is extremely slow!
spiket = array(sm.t/second) # take spiketimes of all neurons
spikei = array(sm.i)
fig = figure()
cols = ['r','b','g','c']
# raster plot
subplot(231)
plot(sminp1.t/second,sminp1.i,',')
xlim([0,1])
xlabel("time (s)")
# weight evolution
subplot(232)
meanpoolw = []
for k in range(Npools):
meanpoolw.append(mean(wm.w[k*Ninp:(k+1)*Ninp,:],axis=0)/w0)
plot(wm.t/second,meanpoolw[-1],'-'+cols[k],lw=(4-k))
xlabel("time (s)")
ylabel("PCA-weight")
title('weight evolution')
# plot output firing rate sm_rho.rho_out[nrn_idx,time_idx]
subplot(234)
plot(sm_rho.t/second,sm_rho.rho_out[0]/Hz,'-')
xlim([0,simtime/second])
xlabel("")
# plot final weights wm.w[syn_idx,time_idx]
subplot(233)
plot(range(Npools*Ninp),wm.w[:,-1],'.')
for k in range(Npools):
meanpoolw_end = mean(wm.w[k*Ninp:(k+1)*Ninp,-1])
plot([k*Ninp,(k+1)*Ninp],[meanpoolw_end,meanpoolw_end],'-'+cols[k],lw=3)
xlabel("pre-neuron #")
ylabel("weight (/w0)")
title("end wts")
# plot averaged weights over last 50s (weights are sampled per second)
subplot(236)
plot(range(Npools*Ninp),mean(wm.w[:,-50:],axis=1),'.')
for k in range(Npools):
meanpoolw_end = mean(wm.w[k*Ninp:(k+1)*Ninp,-50:])
plot([k*Ninp,(k+1)*Ninp],[meanpoolw_end,meanpoolw_end],'-'+cols[k],lw=3)
xlabel("pre-neuron #")
ylabel("weight (/w0)")
title("mean (50s) end wts")
fig = figure()
# plot eigenvectors of corr = Q^T Q matrix
w,v = np.linalg.eig(corr)
subplot(131)
#plot(v)
for k in range(Npools):
plot(v[:,k],'.-'+cols[k],lw=4-k)
xlabel("pre-neuron #")
ylabel("weight (/w0)")
title('eigenvectors of corr matrix')
# weight evolution along eigenvectors of corr matrix
subplot(132)
for k in range(Npools):
plot(wm.t/second,dot(v[:,k],meanpoolw),'-'+cols[k],lw=(4-k))
xlabel('time (s)')
ylabel("weight (/w0)")
title('weights along PCs')
subplot(133)
hist(wm.w[:,-1],bins=200)
#fig.tight_layout()
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.1, hspace=0.1)
show()<|fim▁end|> | # Network parameters: synaptic plasticity
# ###########################################
|
<|file_name|>64350000.jsonp.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | jsonp({"cep":"64350000","cidade":"S\u00e3o Jo\u00e3o da Serra","uf":"PI","estado":"Piau\u00ed"}); |
<|file_name|>Str.ts<|end_file_name|><|fim▁begin|>// String validation
import schemaStore from "../SchemaStore";
import * as _ from "lodash";
import * as Utils from "../utils";
import { ConstraintOptions } from "../ConstraintOptions";
export interface StringOptions extends ConstraintOptions{
length?: number;
minLength?: number;
maxLength?: number;
toLowerCase?: boolean;
toUpperCase?: boolean;
trim?: boolean;
whitelist?: string[];
blacklist?: string[];
}
export function Str(options?: StringOptions){
if(options == null){
options = {};
}
options = Utils.makeDefault(options,{
length: null,
minLength: null,
maxLength: null,
toLowerCase: false,
toUpperCase: false,
trim: false,
whitelist: null,
blacklist: null
});
let validate = (item: any,callback,path) =>{
if(!_.isString(item)){
return callback({
errorCode: "notString",
description: `Variable is not a string!`,
path
});
}
if(options.toLowerCase){
item = item.toLowerCase();
}
if(options.toUpperCase){
item = item.toUpperCase();
}
if(options.trim){
item = item.trim()
}
if(options.whitelist != null && options.whitelist.indexOf(item) == -1){
return callback({
errorCode: "whitelistedValue",
description: `Only the following strings are allowed ${ JSON.stringify(options.whitelist) }`,
path
})
}
if(options.blacklist != null && options.blacklist.indexOf(item) != -1){
return callback({
errorCode: "blacklistedValue",
description: `The following strings are not allowed ${ JSON.stringify(options.blacklist) }`,
path
})
}
if(options.length != null && item.length != options.length){
return callback({
errorCode: "invalidLength",
description: `Only strings with the length of ${options.length} are allowed`,
path
})
}
if(options.maxLength != null && item.length > options.maxLength){
return callback({
errorCode: "tooLong",
description: `Only strings with a max. length of ${options.maxLength} are allowed`,
path
})
}
if(options.minLength != null && item.length < options.minLength){
return callback({
errorCode: "tooShort",
description: `Only strings with a min. length of ${options.maxLength} are allowed`,<|fim▁hole|>
callback(null,item);
};
let decorator = function(c,name: string){
schemaStore.addConstraint(c,name, {
validate: (item,callback,path) => {
validate(item,callback,path+"."+c.constructor.name+"."+name)
},
type: String,
options
});
};
decorator["validate"] = validate;
decorator["type"] = String;
return decorator;
}<|fim▁end|> | path
})
}
|
<|file_name|>kickstart_parser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
Pegasus utility functions for pasing a kickstart output file and return wanted information<|fim▁hole|># Copyright 2007-2010 University Of Southern California
#
# 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.
##
# Revision : $Revision: 2012 $
# Import Python modules
from xml.parsers import expat
import re
import sys
import logging
import traceback
import os
# Regular expressions used in the kickstart parser
re_parse_props = re.compile(r'(\S+)\s*=\s*([^",]+)')
re_parse_quoted_props = re.compile(r'(\S+)\s*=\s*"([^"]+)"')
logger = logging.getLogger(__name__)
class Parser:
"""
This class is used to parse a kickstart output file, and return
requested information.
"""
def __init__(self, filename):
"""
This function initializes the Parser class with the kickstart
output file that should be parsed.
"""
self._kickstart_output_file = filename
self._parsing_job_element = False
self._parsing_arguments = False
self._parsing_main_job = False
self._parsing_machine = False
self._parsing_stdout = False
self._parsing_stderr = False
self._parsing_data = False
self._parsing_cwd = False
self._parsing_final_statcall = False
self._record_number = 0
self._arguments = []
self._stdout = ""
self._stderr = ""
self._cwd = ""
self._lfn = "" # filename parsed from statcall record
self._keys = {}
self._ks_elements = {}
self._fh = None
self._open_error = False
def open(self):
"""
This function opens a kickstart output file.
"""
try:
self._fh = open(self._kickstart_output_file)
except:
# Error opening file
self._fh = None
self._open_error = True
return False
# Open succeeded
self._open_error = False
return True
def close(self):
"""
This function closes the kickstart output file.
"""
try:
self._fh.close()
except:
return False
return True
def read_record(self):
"""
This function reads an invocation record from the kickstart
output file. We also look for the struct at the end of a file
containing multiple records. It returns a string containing
the record, or None if it is not found.
"""
buffer = ""
#valid token that is parsed
token = ""
self._record_number += 1
logger.debug( "Started reading record number %d from kickstart file %s" %( self._record_number, self._kickstart_output_file))
# First, we find the beginning <invocation xmlns....
while True:
line = self._fh.readline()
if line == '':
# End of file, record not found
return None
if line.find("<invocation") != -1:
token = "<invocation"
break
if ( line.find("[cluster-task") != -1 ):
token = "[cluster-task"
break
if ( line.find("[cluster-summary") != -1 ):
token = "[cluster-summary"
break
if ( line.find("[seqexec-task") != -1 ):
#deprecated token
token = "[seqexec-task"
break
if ( line.find("[seqexec-summary") != -1 ):
#deprecated token
token = "[seqexec-summary"
break
# Found something!
#if line.find("<invocation") >= 0:
if token == "<invocation" :
# Found invocation record
start = line.find("<invocation")
buffer = line[start:]
end = buffer.find("</invocation>")
# Check if we have everything in a single line
if end >= 0:
end = end + len("</invocation>")
return buffer[:end]
#elif line.find("[seqexec-summary") >= 0:
elif ( token == "[cluster-summary" or token == "[seqexec-summary" ):
# Found line with cluster jobs summary
start = line.find(token)
buffer = line[start:]
end = buffer.find("]")
if end >= 0:
end = end + len("]")
return buffer[:end]
# clustered record should be in a single line!
logger.warning("%s: %s line is malformed... ignoring it..." % (self._kickstart_output_file, token ))
return ""
#elif line.find("[seqexec-task") >= 0:
elif ( token == "[cluster-task" or token == "[seqexec-task" ):
# Found line with task information
start = line.find( token )
buffer = line[start:]
end = buffer.find("]")
if end >= 0:
end = end + len("]")
return buffer[:end]
# task record should be in a single line!
logger.warning("%s: %s line is malformed... ignoring it..." % (self._kickstart_output_file, token))
return ""
else:
return ""
# Ok, now continue reading the file until we get a full record
buffer = [buffer]
while True:
line = self._fh.readline()
if line == '':
# End of file, record not found
return None
#buffer = buffer + line
buffer.append( line )
if line.find("</invocation>") >= 0:
break
# Now, we got it, let's make sure
end = line.find("</invocation>")
if end == -1:
return ""
#end = end + len("</invocation>")
invocation = "".join(buffer)
#print invocation
logger.debug( "Finished reading record number %d from kickstart file %s" %( self._record_number, self._kickstart_output_file))
return invocation
#return buffer[:end]
def is_invocation_record(self, buffer=''):
"""
Returns True if buffer contains an invocation record.
"""
if buffer.find("<invocation") == -1:
return False
return True
def is_task_record(self, buffer=''):
"""
Returns True if buffer contains a task record.
"""
if ( buffer.find("[seqexec-task") != -1 or buffer.find( "[cluster-task" ) != -1 ):
return True
return False
def is_clustered_record(self, buffer=''):
"""
Returns True if buffer contains a clustered record.
"""
if ( buffer.find("[seqexec-summary") != -1 or buffer.find( "[cluster-summary" ) != -1):
return True
return False
def start_element(self, name, attrs):
"""
Function called by the parser every time a new element starts
"""
# Keep track if we are parsing the main job element
if name == "mainjob":
self._parsing_main_job = True
if name == "machine":
self._parsing_machine = True
# Keep track if we are inside one of the job elements
if (name == "setup" or name == "prejob" or
name == "mainjob" or name == "postjob" or name == "cleanup"):
self._parsing_job_element = True
if name == "argument-vector" and name in self._ks_elements:
# Start parsing arguments
self._parsing_arguments = True
elif name == "cwd" and name in self._ks_elements:
# Start parsing cwd
self._parsing_cwd = True
elif name == "data":
# Start parsing data for stdout and stderr output
self._parsing_data = True
elif name == "file" and name in self._ks_elements:
if self._parsing_main_job == True :
# Special case for name inside the mainjob element (will change this later)
for my_element in self._ks_elements[name]:
if my_element in attrs:
self._keys[my_element] = attrs[my_element]
elif name == "ram" and name in self._ks_elements:
if self._parsing_machine == True:
# Special case for ram inside the machine element (will change this later)
for my_element in self._ks_elements[name]:
if my_element in attrs:
self._keys[my_element] = attrs[my_element]
elif name == "uname" and name in self._ks_elements:
if self._parsing_machine == True:
# Special case for uname inside the machine element (will change this later)
for my_element in self._ks_elements[name]:
if my_element in attrs:
self._keys[my_element] = attrs[my_element]
elif name == "statcall":
if "id" in attrs:
if attrs["id"] == "stdout" and "stdout" in self._ks_elements:
self._parsing_stdout = True
elif attrs["id"] == "stderr" and "stderr" in self._ks_elements:
self._parsing_stderr = True
elif attrs["id"] == "final" :
self._parsing_final_statcall = True
self._lfn = attrs["lfn"]
elif name == "statinfo":
if self._parsing_final_statcall is True:
statinfo = {}
for my_element in self._ks_elements[name]:
if my_element in attrs:
statinfo[my_element] = attrs[my_element]
if not self._keys.has_key( "outputs"):
self._keys[ "outputs" ] = {} #a dictionary indexed by lfn
lfn = self._lfn
if lfn is None or not statinfo:
logger.warning( "Malformed/Empty stat record for output lfn %s %s" %(lfn, statinfo))
self._keys["outputs"][lfn] = statinfo
elif name == "usage" and name in self._ks_elements:
if self._parsing_job_element:
# Special case for handling utime and stime, which need to be added
for my_element in self._ks_elements[name]:
if my_element in attrs:
if my_element in self._keys:
try:
self._keys[my_element] = self._keys[my_element] + float(attrs[my_element])
except ValueError:
logger.warning("cannot convert element %s to float!" % (my_element))
else:
try:
self._keys[my_element] = float(attrs[my_element])
except ValueError:
logger.warning("cannot convert element %s to float!" % (my_element))
else:
# For all other elements, check if we want them
if name in self._ks_elements:
for my_element in self._ks_elements[name]:
if my_element in attrs:
self._keys[my_element] = attrs[my_element]
def end_element(self, name):
"""
Function called by the parser whenever we reach the end of an element
"""
# Stop parsing argement-vector and cwd if we reached the end of those elements
if name == "argument-vector":
self._parsing_arguments = False
elif name == "cwd":
self._parsing_cwd = False
elif name == "mainjob":
self._parsing_main_job = False
elif name == "machine":
self._parsing_machine = False
elif name == "statcall":
if self._parsing_stdout == True:
self._parsing_stdout = False
if self._parsing_stderr == True:
self._parsing_stderr = False
if self._parsing_final_statcall == True:
self._parsing_final_statcall = False
elif name == "data":
self._parsing_data = False
# Now, see if we left one of the job elements
if (name == "setup" or name == "prejob" or
name == "mainjob" or name == "postjob" or name == "cleanup"):
self._parsing_job_element = False
def char_data(self, data=''):
"""
Function called by the parser whenever there's character data in an element
"""
if self._parsing_cwd == True:
self._cwd += data
if self._parsing_arguments == True:
self._arguments.append(data.strip())
if self._parsing_stdout == True and self._parsing_data == True:
self._stdout += data
if self._parsing_stderr == True and self._parsing_data == True:
self._stderr += data
def parse_invocation_record(self, buffer=''):
"""
Parses the xml record in buffer, returning the desired keys.
"""
# Initialize variables
self._parsing_arguments = False
self._parsing_main_job = False
self._parsing_machine = False
self._parsing_stdout = False
self._parsing_stderr = False
self._parsing_data = False
self._parsing_cwd = False
self._arguments = []
self._stdout = ""
self._stderr = ""
self._cwd = ""
self._keys = {}
# Check if we have an invocation record
if self.is_invocation_record(buffer) == False:
return self._keys
# Add invocation key to our response
self._keys["invocation"] = True
# Prepend XML header
buffer = '<?xml version="1.0" encoding="ISO-8859-1"?>\n' + buffer
# Create parser
self._my_parser = expat.ParserCreate()
self._my_parser.StartElementHandler = self.start_element
self._my_parser.EndElementHandler = self.end_element
self._my_parser.CharacterDataHandler = self.char_data
# Parse everything!
output = self._my_parser.Parse(buffer)
# Add cwd, arguments, stdout, and stderr to keys
if "cwd" in self._ks_elements:
self._keys["cwd"] = self._cwd
if "argument-vector" in self._ks_elements:
self._keys["argument-vector"] = " ".join(self._arguments)
if "stdout" in self._ks_elements:
self._keys["stdout"] = self._stdout
if "stderr" in self._ks_elements:
self._keys["stderr"] = self._stderr
return self._keys
def parse_clustered_record(self, buffer=''):
"""
Parses the clustered record in buffer, returning all found keys
"""
self._keys = {}
# Check if we have an invocation record
if self.is_clustered_record(buffer) == False:
return self._keys
# Add clustered key to our response
self._keys["clustered"] = True
# Parse all quoted properties
for my_key, my_val in re_parse_quoted_props.findall(buffer):
self._keys[my_key] = my_val
# And add unquoted properties as well
for my_key, my_val in re_parse_props.findall(buffer):
self._keys[my_key] = my_val
return self._keys
def parse_task_record(self, buffer=''):
"""
Parses the task record in buffer, returning all found keys
"""
self._keys = {}
# Check if we have an invocation record
if self.is_task_record(buffer) == False:
return self._keys
# Add task key to our response
self._keys["task"] = True
# Parse all quoted properties
for my_key, my_val in re_parse_quoted_props.findall(buffer):
self._keys[my_key] = my_val
# And add unquoted properties as well
for my_key, my_val in re_parse_props.findall(buffer):
self._keys[my_key] = my_val
return self._keys
def parse(self, keys_dict, tasks=True, clustered=True):
"""
This function parses the kickstart output file, looking for
the keys specified in the keys_dict variable. It returns a
list of dictionaries containing the found keys. Look at the
parse_stampede function for details about how to pass keys
using the keys_dict structure. The function will return an
empty list if no records are found or if an error happens.
"""
my_reply = []
# Place keys_dict in the _ks_elements
self._ks_elements = keys_dict
# Try to open the file
if self.open() == False:
return my_reply
logger.debug( "Started reading records from kickstart file %s" %(self._kickstart_output_file))
self._record_number = 0
# Read first record
my_buffer = self.read_record()
# Loop while we still have record to read
while my_buffer is not None:
if self.is_invocation_record(my_buffer) == True:
# We have an invocation record, parse it!
try:
my_record = self.parse_invocation_record(my_buffer)
except:
logger.warning("KICKSTART-PARSE-ERROR --> error parsing invocation record in file %s"
% (self._kickstart_output_file))
logger.warning(traceback.format_exc())
# Found error parsing this file, return empty reply
my_reply = []
# Finish the loop
break
my_reply.append(my_record)
elif self.is_clustered_record(my_buffer) == True:
# Check if we want clustered records too
if clustered:
# Clustered records are seqexec summary records for clustered jobs
# We have a clustered record, parse it!
my_reply.append(self.parse_clustered_record(my_buffer))
elif self.is_task_record(my_buffer) == True:
# Check if we want task records too
if tasks:
# We have a clustered record, parse it!
my_reply.append(self.parse_task_record(my_buffer))
else:
# We have something else, this shouldn't happen!
# Just skip it
pass
# Read next record
my_buffer = self.read_record()
# Lastly, close the file
self.close()
return my_reply
def parse_stampede(self):
"""
This function works similarly to the parse function above,
but does not require a keys_dict parameter as it uses a
built-in list of keys speficically used in the Stampede
schema.
"""
stampede_elements = {"invocation": ["hostname", "resource", "user", "hostaddr", "transformation", "derivation"],
"mainjob": ["duration", "start"],
"usage": ["utime", "stime"],
"ram": ["total"],
"uname": ["system", "release", "machine"],
"file": ["name"],
"status": ["raw"],
"regular": ["exitcode"],
"argument-vector": [],
"cwd": [],
"stdout": [],
"stderr": [],
"statinfo": ["lfn", "size", "ctime", "user" ]}
return self.parse(stampede_elements, tasks=True, clustered=True)
def parse_stdout_stderr(self):
"""
This function extracts the stdout and stderr from a kickstart output file.
It returns an array containing the output for each task in a job.
"""
stdout_stderr_elements = {"invocation": ["hostname", "resource", "derivation", "transformation"],
"file": ["name"],
"regular": ["exitcode"],
"failure": ["error"],
"argument-vector": [],
"cwd": [],
"stdout": [],
"stderr": []}
return self.parse(stdout_stderr_elements, tasks=False, clustered=False)
if __name__ == "__main__":
# Let's run a test!
print "Testing kickstart output file parsing..."
# Make sure we have an argument
if len(sys.argv) < 2:
print "For testing, please give a kickstart output filename!"
sys.exit(1)
# Create parser class
p = Parser(sys.argv[1])
# Parse file according to the Stampede schema
output = p.parse_stampede()
# Print output
for record in output:
print record<|fim▁end|> |
"""
## |
<|file_name|>galaxycash.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <galaxycash.h>
#include <chainparams.h>
#include <hash.h>
#include <memory>
#include <pow.h>
#include <uint256.h>
#include <util.h>
#include <stdint.h>
CGalaxyCashStateRef g_galaxycash;
<|fim▁hole|>CGalaxyCashDB::CGalaxyCashDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "galaxycash" / "database", nCacheSize, fMemory, fWipe)
{
}
class CGalaxyCashVM
{
public:
CGalaxyCashVM();
~CGalaxyCashVM();
};
CGalaxyCashVM::CGalaxyCashVM()
{
}
CGalaxyCashState::CGalaxyCashState() : pdb(new CGalaxyCashDB((gArgs.GetArg("-gchdbcache", 128) << 20), false, gArgs.GetBoolArg("-reindex", false)))
{
}
CGalaxyCashState::~CGalaxyCashState()
{
delete pdb;
}
void CGalaxyCashState::EvalScript()
{
}
bool CGalaxyCashConsensus::CheckSignature() const
{
return true;
}<|fim▁end|> | |
<|file_name|>JsonUser.java<|end_file_name|><|fim▁begin|>package com.at.springboot.mybatis.po;
public class JsonUser {
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.JSON_USER_ID
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
private byte[] jsonUserId;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.USER_NAME
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
private String userName;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.LAST_LOGIN_RESULT
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
private String lastLoginResult;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.LAST_LOGIN_INFO
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
private String lastLoginInfo;
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.JSON_USER_ID
* @return the value of JSON_USER.JSON_USER_ID
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
<|fim▁hole|>
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.JSON_USER_ID
* @param jsonUserId the value for JSON_USER.JSON_USER_ID
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public void setJsonUserId(byte[] jsonUserId) {
this.jsonUserId = jsonUserId;
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.USER_NAME
* @return the value of JSON_USER.USER_NAME
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public String getUserName() {
return userName;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.USER_NAME
* @param userName the value for JSON_USER.USER_NAME
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.LAST_LOGIN_RESULT
* @return the value of JSON_USER.LAST_LOGIN_RESULT
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public String getLastLoginResult() {
return lastLoginResult;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.LAST_LOGIN_RESULT
* @param lastLoginResult the value for JSON_USER.LAST_LOGIN_RESULT
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public void setLastLoginResult(String lastLoginResult) {
this.lastLoginResult = lastLoginResult == null ? null : lastLoginResult.trim();
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.LAST_LOGIN_INFO
* @return the value of JSON_USER.LAST_LOGIN_INFO
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public String getLastLoginInfo() {
return lastLoginInfo;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.LAST_LOGIN_INFO
* @param lastLoginInfo the value for JSON_USER.LAST_LOGIN_INFO
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public void setLastLoginInfo(String lastLoginInfo) {
this.lastLoginInfo = lastLoginInfo == null ? null : lastLoginInfo.trim();
}
}<|fim▁end|> | public byte[] getJsonUserId() {
return jsonUserId;
}
|
<|file_name|>api_test.py<|end_file_name|><|fim▁begin|># Copyright 2017 The TensorFlow Authors. 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.
# ==============================================================================
"""Tests for api module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import functools
import gc
import imp
import os
import re
import textwrap
import types
import numpy as np
from tensorflow.python.autograph import utils
from tensorflow.python.autograph.core import ag_ctx
from tensorflow.python.autograph.core import converter
from tensorflow.python.autograph.impl import api
from tensorflow.python.autograph.pyct import inspect_utils
from tensorflow.python.autograph.pyct import parser
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.eager import def_function
from tensorflow.python.eager import function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import test_util
from tensorflow.python.keras.engine import sequential
from tensorflow.python.keras.layers import core
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.util import function_utils
from tensorflow.python.util import tf_decorator
from tensorflow.python.util import tf_inspect
tf = utils.fake_tf()
global_n = 2
class TestResource(object):
def __init__(self):
self.x = 3
class ApiTest(test.TestCase):
@test_util.run_deprecated_v1
def test_decorator_recursive(self):
class TestClass(object):
def called_member(self, a):
if a < 0:
a = -a
return a
@api.convert(recursive=True)
def test_method(self, x, s, a):
while tf.reduce_sum(x) > s:
x //= self.called_member(a)
return x
tc = TestClass()
with self.cached_session() as sess:
x = tc.test_method(
constant_op.constant([2, 4]), constant_op.constant(1),
constant_op.constant(-2))
self.assertListEqual([0, 1], self.evaluate(x).tolist())
@test_util.run_deprecated_v1
def test_decorator_not_recursive(self):
class TestClass(object):
def called_member(self, a):
return tf.negative(a)
@api.convert(recursive=False)
def test_method(self, x, s, a):
while tf.reduce_sum(x) > s:
x //= self.called_member(a)
return x
tc = TestClass()
with self.cached_session() as sess:
x = tc.test_method(
constant_op.constant([2, 4]), constant_op.constant(1),
constant_op.constant(-2))
self.assertListEqual([0, 1], self.evaluate(x).tolist())
@test_util.run_deprecated_v1
def test_convert_then_do_not_convert(self):
class TestClass(object):
@api.do_not_convert
def called_member(self, a):
return tf.negative(a)
@api.convert(recursive=True)
def test_method(self, x, s, a):
while tf.reduce_sum(x) > s:
x //= self.called_member(a)
return x
tc = TestClass()
x = tc.test_method(
constant_op.constant((2, 4)), constant_op.constant(1),
constant_op.constant(-2))
self.assertAllEqual((0, 1), self.evaluate(x))
@test_util.run_deprecated_v1
def test_decorator_calls_decorated(self):
class TestClass(object):
@api.convert()
def called_member(self, a):
if a < 0:
a = -a
return a
@api.convert(recursive=True)
def test_method(self, x, s, a):
while tf.reduce_sum(x) > s:
x //= self.called_member(a)
return x
tc = TestClass()
with self.cached_session() as sess:
x = tc.test_method(
constant_op.constant([2, 4]), constant_op.constant(1),
constant_op.constant(-2))
self.assertListEqual([0, 1], self.evaluate(x).tolist())
def test_decorator_preserves_argspec(self):
class TestClass(object):
def test_method(self, a):
if a < 0:
a = -a
return a
test_method_converted = api.convert()(test_method)
tc = TestClass()
self.assertListEqual(
list(tf_inspect.getfullargspec(tc.test_method)),
list(tf_inspect.getfullargspec(tc.test_method_converted)))
def test_do_not_convert_argspec(self):
class TestClass(object):
def test_method(self, x, y):
z = x + y
return z
test_method_whitelisted = api.do_not_convert(test_method)
tc = TestClass()
self.assertTrue(tf_inspect.ismethod(tc.test_method_whitelisted))
# Because the wrapped function is not generated, we can't preserve its
# arg spec.
self.assertEqual((),
tuple(function_utils.fn_args(tc.test_method_whitelisted)))
def test_do_not_convert_callable_object(self):
class TestClass(object):
def __call__(self):
return 1
tc = TestClass()
self.assertEqual(1, api.do_not_convert(tc)())
@test_util.run_deprecated_v1
def test_convert_call_site_decorator(self):
class TestClass(object):
def called_member(self, a):
if a < 0:
a = -a
return a
@api.convert(recursive=True)
def test_method(self, x, s, a):
while tf.reduce_sum(x) > s:
x //= api.converted_call(self.called_member,
converter.ConversionOptions(recursive=True),
(a,), {})
return x
tc = TestClass()
x = tc.test_method(
constant_op.constant([2, 4]), constant_op.constant(1),
constant_op.constant(-2))
self.assertListEqual([0, 1], self.evaluate(x).tolist())
def test_converted_call_builtin(self):
x = api.converted_call(range, converter.ConversionOptions(recursive=True),
(3,), {})
self.assertEqual((0, 1, 2), tuple(x))
x = api.converted_call(re.compile,
converter.ConversionOptions(recursive=True),
('mnas_v4_a.*\\/.*(weights|kernel):0$',), {})
self.assertIsNotNone(x.match('mnas_v4_a/weights:0'))
def test_converted_call_function(self):
def test_fn(x):
if x < 0:
return -x
return x
x = api.converted_call(test_fn, converter.ConversionOptions(recursive=True),
(constant_op.constant(-1),), {})
self.assertEqual(1, self.evaluate(x))
@test_util.run_v1_only('b/120545219')
def test_converted_call_functools_partial(self):
def test_fn(x, y, z):
if x < 0:
return -x, -y, -z
return x, y, z
x = api.converted_call(
functools.partial(test_fn, constant_op.constant(-1), z=-3),
converter.ConversionOptions(recursive=True),
(constant_op.constant(-2),), {})
self.assertEqual((1, 2, 3), self.evaluate(x))
x = api.converted_call(
functools.partial(
functools.partial(test_fn, constant_op.constant(-1)), z=-3),
converter.ConversionOptions(recursive=True),
(constant_op.constant(-2),), {})
self.assertEqual((1, 2, 3), self.evaluate(x))
def test_converted_call_method(self):
class TestClass(object):
def __init__(self, x):
self.x = x
def test_method(self):
if self.x < 0:
return -self.x
return self.x
tc = TestClass(constant_op.constant(-1))
x = api.converted_call(tc.test_method,
converter.ConversionOptions(recursive=True), (), {})
self.assertEqual(1, self.evaluate(x))
def test_converted_call_synthetic_method(self):
class TestClass(object):
def __init__(self, x):
self.x = x
def test_function(self):
if self.x < 0:
return -self.x
return self.x
tc = TestClass(constant_op.constant(-1))
test_method = types.MethodType(test_function, tc)
x = api.converted_call(test_method,
converter.ConversionOptions(recursive=True), (), {})
self.assertEqual(1, self.evaluate(x))
def test_converted_call_method_wrapper(self):
class TestClass(object):
def foo(self):
pass
tc = TestClass()
# `method.__get__()` returns a so-called method-wrapper.
wrapper = api.converted_call(tc.foo.__get__,
converter.ConversionOptions(recursive=True),
(tc,), {})
self.assertEqual(wrapper, tc.foo)
def test_converted_call_method_as_object_attribute(self):
class AnotherClass(object):
def __init__(self):
self.another_class_attr = constant_op.constant(1)
def method(self):
if self.another_class_attr > 0:
return self.another_class_attr + 1
return self.another_class_attr + 10
class TestClass(object):
def __init__(self, another_obj_method):
self.another_obj_method = another_obj_method
obj = AnotherClass()
tc = TestClass(obj.method)
x = api.converted_call(tc.another_obj_method,
converter.ConversionOptions(recursive=True), (), {})
self.assertEqual(self.evaluate(x), 2)
def test_converted_call_method_converts_recursively(self):
class TestClass(object):
def __init__(self, x):
self.x = x
def other_method(self):
if self.x < 0:
return -self.x
return self.x
def test_method(self):
return self.other_method()
tc = TestClass(constant_op.constant(-1))
x = api.converted_call(tc.test_method,
converter.ConversionOptions(recursive=True), (), {})
self.assertEqual(1, self.evaluate(x))
def test_converted_call_method_by_class(self):
class TestClass(object):
def __init__(self, x):
self.x = x
def test_method(self):
if self.x < 0:
return -self.x
return self.x
tc = TestClass(constant_op.constant(-1))
x = api.converted_call(TestClass.test_method,
converter.ConversionOptions(recursive=True), (tc,),
{})
self.assertEqual(1, self.evaluate(x))
def test_converted_call_callable_object(self):
class TestClass(object):
def __init__(self, x):
self.x = x
def __call__(self):
if self.x < 0:
return -self.x
return self.x
tc = TestClass(constant_op.constant(-1))
x = api.converted_call(tc, converter.ConversionOptions(recursive=True), (),
{})
self.assertEqual(1, self.evaluate(x))
def test_converted_call_callable_metaclass(self):
class TestMetaclass(type):
x = constant_op.constant(-1)
def __call__(cls):
if cls.x < 0:
cls.x = -cls.x
return cls
tc = TestMetaclass('TestClass', (), {})
# This functools.partial will hide the class form the constructor
# check. Not ideal. See b/120224672.
tc = functools.partial(tc)
converted_tc = api.converted_call(
tc, converter.ConversionOptions(recursive=True), (), {})
self.assertIsInstance(converted_tc, TestMetaclass)
self.assertEqual(1, self.evaluate(converted_tc.x))
@test_util.run_deprecated_v1
def test_converted_call_constructor(self):
class TestClass(object):
def __init__(self, x):
self.x = x
def test_method(self):
if self.x < 0:
return -self.x
return self.x
tc = api.converted_call(TestClass,
converter.ConversionOptions(recursive=True),
(constant_op.constant(-1),), {})
# tc is still a TestClass - constructors are whitelisted.
# TODO(b/124016764): Support this use case.
# The error below is specific to the `if` statement not being converted.
with self.assertRaises(TypeError):
tc.test_method()
def test_converted_call_mangled_properties(self):
class TestClass(object):
def __init__(self, x):
self.__private = x
def test_method(self):
if self.__private < 0:
return self.__private
return self.__private
tc = TestClass(constant_op.constant(-1))
# The error below is specific to the `if` statement not being converted.
with self.assertRaisesRegex(NotImplementedError, 'Mangled names'):
api.converted_call(tc.test_method,
converter.ConversionOptions(recursive=True), (), {})
tc.test_method()
def test_converted_call_already_converted(self):
def f(x):
return x == 0
x = api.converted_call(f, converter.ConversionOptions(recursive=True),
(constant_op.constant(0),), {})
self.assertTrue(self.evaluate(x))
converted_f = api.to_graph(
f, experimental_optional_features=converter.Feature.ALL)
x = api.converted_call(converted_f,
converter.ConversionOptions(recursive=True),
(constant_op.constant(0),), {})
self.assertTrue(self.evaluate(x))
def test_converted_call_then_already_converted_dynamic(self):
@api.convert()
def g(x):
if x > 0:
return x
else:
return -x
def f(g, x):
return g(x)
x = api.converted_call(f, converter.ConversionOptions(recursive=True),
(g, constant_op.constant(1)), {})
self.assertEqual(self.evaluate(x), 1)
def test_converted_call_forced_when_explicitly_whitelisted(self):
@api.do_not_convert()
def f(x):
return x + 1
x = api.converted_call(
f, converter.ConversionOptions(recursive=True, user_requested=True),
(constant_op.constant(0),), {})
self.assertTrue(self.evaluate(x))
converted_f = api.to_graph(
f, experimental_optional_features=converter.Feature.ALL)
x = api.converted_call(converted_f,
converter.ConversionOptions(recursive=True), (0,),
{})
self.assertEqual(x, 1)
@test_util.run_deprecated_v1
def test_converted_call_no_user_code(self):
def f(x):
return len(x)
opts = converter.ConversionOptions(internal_convert_user_code=False)
# f should not be converted, causing len to error out.
with self.assertRaisesRegexp(Exception, 'len is not well defined'):
api.converted_call(f, opts, (constant_op.constant([0]),), {})
# len on the other hand should work fine.
x = api.converted_call(len, opts, (constant_op.constant([0]),), {})
# The constant has static shape so the result is a primitive not a Tensor.
self.assertEqual(x, 1)
def test_converted_call_no_kwargs_allowed(self):
def f(*args):
# Note: np.broadcast rejects any **kwargs, even *{}
return np.broadcast(args[:1])
opts = converter.ConversionOptions(internal_convert_user_code=False)
self.assertIsNotNone(api.converted_call(f, opts, (1, 2, 3, 4), None))
def test_converted_call_whitelisted_method(self):
opts = converter.ConversionOptions(recursive=True)
model = sequential.Sequential([core.Dense(2)])
x = api.converted_call(model.call, opts, (constant_op.constant([[0.0]]),),
{'training': True})
self.evaluate(variables.global_variables_initializer())
self.assertAllEqual([[0.0, 0.0]], self.evaluate(x))
def test_converted_call_whitelisted_method_via_owner(self):
opts = converter.ConversionOptions(recursive=True)
model = sequential.Sequential([core.Dense(2)])
x = api.converted_call(model.call, opts, (constant_op.constant([[0.0]]),),
{'training': True})
self.evaluate(variables.global_variables_initializer())
self.assertAllEqual([[0.0, 0.0]], self.evaluate(x))
def test_converted_call_numpy(self):
opts = converter.ConversionOptions(recursive=True)
x = api.converted_call(np.arange, opts, (5,), {})
self.assertAllEqual(x, list(range(5)))
def test_converted_call_tf_op_forced(self):
# TODO(mdan): Add the missing level of support to LOGICAL_EXPRESSIONS.
opts = converter.ConversionOptions(
user_requested=True, optional_features=None)
x = api.converted_call(gen_math_ops.add, opts, (1, 1), {})
self.assertAllEqual(self.evaluate(x), 2)
def test_converted_call_exec_generated_code(self):
temp_mod = imp.new_module('test_module')
dynamic_code = """
def foo(x):
return x + 1
"""
exec(textwrap.dedent(dynamic_code), temp_mod.__dict__) # pylint:disable=exec-used
opts = converter.ConversionOptions(optional_features=None)
x = api.converted_call(temp_mod.foo, opts, (1,), {})
self.assertAllEqual(x, 2)
def test_converted_call_namedtuple(self):
opts = converter.ConversionOptions(recursive=True)
x = api.converted_call(collections.namedtuple, opts,
('TestNamedtuple', ('a', 'b')), {})
self.assertTrue(inspect_utils.isnamedtuple(x))
def test_converted_call_namedtuple_via_collections(self):
opts = converter.ConversionOptions(recursive=True)
x = api.converted_call(collections.namedtuple, opts,
('TestNamedtuple', ('a', 'b')), {})
self.assertTrue(inspect_utils.isnamedtuple(x))
def test_converted_call_namedtuple_subclass_bound_method(self):
class TestClass(collections.namedtuple('TestNamedtuple', ('a', 'b'))):
def test_method(self, x):
while tf.reduce_sum(x) > self.a:
x //= self.b
return x
opts = converter.ConversionOptions(recursive=True)
obj = TestClass(5, 2)
x = api.converted_call(obj.test_method, opts,
(constant_op.constant([2, 4]),), {})
self.assertAllEqual(self.evaluate(x), [1, 2])
def test_converted_call_namedtuple_method(self):
class TestClass(collections.namedtuple('TestNamedtuple', ('a', 'b'))):
pass
opts = converter.ConversionOptions(recursive=True)
obj = TestClass(5, 2)
# _asdict is a documented method of namedtuple.
x = api.converted_call(obj._asdict, opts, (), {})
self.assertDictEqual(x, {'a': 5, 'b': 2})
def test_converted_call_namedtuple_subclass_unbound_method(self):
class TestClass(collections.namedtuple('TestNamedtuple', ('a', 'b'))):
def test_method(self, x):
while tf.reduce_sum(x) > self.a:
x //= self.b
return x
opts = converter.ConversionOptions(recursive=True)
obj = TestClass(5, 2)
x = api.converted_call(TestClass.test_method, opts,
(obj, constant_op.constant([2, 4])), {})
self.assertAllEqual(self.evaluate(x), [1, 2])
def test_converted_call_lambda(self):
opts = converter.ConversionOptions(recursive=True)
l = lambda x: x == 0
x = api.converted_call(l, opts, (constant_op.constant(0),), {})
<|fim▁hole|> def test_converted_call_defun_object_method(self):
opts = converter.ConversionOptions(recursive=True)
# pylint:disable=method-hidden
class TestClass(object):
def method(self):
return 1
def prepare(self):
self.method = function.defun(self.method)
# pylint:enable=method-hidden
tc = TestClass()
tc.prepare()
x = api.converted_call(tc.method, opts, (), {})
self.assertAllEqual(1, self.evaluate(x))
def test_converted_call_through_tf_dataset(self):
def other_fn(x):
if x > 0:
return x
return -x
def f():
return dataset_ops.Dataset.range(-3, 3).map(other_fn)
# Dataset iteration only works inside tf.
@def_function.function
def graph_fn():
opts = converter.ConversionOptions(recursive=True)
ds = api.converted_call(f, opts, (), {})
itr = iter(ds)
return next(itr), next(itr), next(itr)
self.assertAllEqual(self.evaluate(graph_fn()), (3, 2, 1))
def assertNoMemoryLeaks(self, f):
object_ids_before = {id(o) for o in gc.get_objects()}
f()
gc.collect()
objects_after = tuple(
o for o in gc.get_objects() if id(o) not in object_ids_before)
self.assertEmpty(
tuple(o for o in objects_after if isinstance(o, TestResource)))
def test_converted_call_no_leaks_via_closure(self):
def test_fn():
res = TestResource()
def f(y):
return res.x + y
opts = converter.ConversionOptions(recursive=True)
api.converted_call(f, opts, (1,), {})
self.assertNoMemoryLeaks(test_fn)
def test_converted_call_no_leaks_via_inner_function_closure(self):
def test_fn():
res = TestResource()
def f(y):
def inner_f():
return res.x + y
return inner_f
opts = converter.ConversionOptions(recursive=True)
api.converted_call(f, opts, (1,), {})()
self.assertNoMemoryLeaks(test_fn)
def test_context_tracking_direct_calls(self):
@api.do_not_convert()
def unconverted_fn():
self.assertEqual(ag_ctx.control_status_ctx().status,
ag_ctx.Status.DISABLED)
@api.convert()
def converted_fn():
self.assertEqual(ag_ctx.control_status_ctx().status,
ag_ctx.Status.ENABLED)
unconverted_fn()
self.assertEqual(ag_ctx.control_status_ctx().status,
ag_ctx.Status.ENABLED)
self.assertEqual(ag_ctx.control_status_ctx().status,
ag_ctx.Status.UNSPECIFIED)
converted_fn()
self.assertEqual(ag_ctx.control_status_ctx().status,
ag_ctx.Status.UNSPECIFIED)
@api.call_with_unspecified_conversion_status
def unspecified_fn():
self.assertEqual(ag_ctx.control_status_ctx().status,
ag_ctx.Status.UNSPECIFIED)
unspecified_fn()
def test_to_graph_basic(self):
def test_fn(x, s):
while tf.reduce_sum(x) > s:
x //= 2
return x
compiled_fn = api.to_graph(test_fn)
with tf.Graph().as_default():
x = compiled_fn(constant_op.constant((4, 8)), 4)
self.assertAllEqual(self.evaluate(x), (1, 2))
@test_util.run_deprecated_v1
def test_to_graph_with_defaults(self):
foo = 4
def test_fn(x, s=foo):
while tf.reduce_sum(x) > s:
x //= 2
return x
compiled_fn = api.to_graph(test_fn)
with self.cached_session() as sess:
x = compiled_fn(constant_op.constant([4, 8]))
self.assertListEqual([1, 2], self.evaluate(x).tolist())
def test_to_graph_with_globals(self):
def test_fn(x):
global global_n
global_n = x + global_n
return global_n
converted_fn = api.to_graph(test_fn)
prev_val = global_n
converted_fn(10)
self.assertGreater(global_n, prev_val)
def test_to_graph_with_kwargs_clashing_converted_call(self):
def called_fn(**kwargs):
return kwargs['f'] + kwargs['owner']
def test_fn():
# These arg names intentionally match converted_call's
return called_fn(f=1, owner=2)
compiled_fn = api.to_graph(test_fn)
self.assertEqual(compiled_fn(), 3)
def test_to_graph_with_kwargs_clashing_unconverted_call(self):
@api.do_not_convert
def called_fn(**kwargs):
return kwargs['f'] + kwargs['owner']
def test_fn():
# These arg names intentionally match _call_unconverted's
return called_fn(f=1, owner=2)
compiled_fn = api.to_graph(test_fn)
self.assertEqual(compiled_fn(), 3)
def test_to_graph_caching(self):
def test_fn(x):
if x > 0:
return x
else:
return -x
converted_functions = tuple(api.to_graph(test_fn) for _ in (-1, 0, 1))
# All outputs are from the same module. We can't use __module__ because
# that's reset when we instantiate the function (see conversion.py).
# TODO(mdan): Can and should we overwrite __module__ instead?
module_names = frozenset(f.ag_module for f in converted_functions)
self.assertEqual(len(module_names), 1)
self.assertNotIn('__main__', module_names)
self.assertEqual(len(frozenset(id(f) for f in converted_functions)), 3)
def test_to_graph_caching_different_options(self):
def called_fn():
pass
def test_fn():
return called_fn()
converted_recursive = api.to_graph(test_fn, recursive=True)
converted_non_recursive = api.to_graph(test_fn, recursive=False)
self.assertNotEqual(converted_recursive.ag_module,
converted_non_recursive.ag_module)
self.assertRegex(tf_inspect.getsource(converted_recursive),
'FunctionScope(.*recursive=True.*)')
self.assertRegex(tf_inspect.getsource(converted_non_recursive),
'FunctionScope(.*recursive=False.*)')
def test_to_graph_preserves_bindings(self):
y = 3
def test_fn():
return y
converted = api.to_graph(test_fn)
self.assertEqual(converted(), 3)
y = 7
self.assertEqual(converted(), 7)
def test_to_graph_source_map(self):
def test_fn(y):
return y**2
self.assertTrue(hasattr(api.to_graph(test_fn), 'ag_source_map'))
def test_to_graph_sets_conversion_context(self):
def g():
self.assertEqual(ag_ctx.control_status_ctx().status,
ag_ctx.Status.ENABLED)
return 0
# Note: the autograph=False sets the contect to Status.DISABLED. The test
# verifies that to_graph overrides that.
@def_function.function(autograph=False)
def f():
converted_g = api.to_graph(g)
converted_g()
f()
def test_to_code_basic(self):
def test_fn(x, s):
while tf.reduce_sum(x) > s:
x /= 2
return x
# Just check that the output is parseable Python code.
self.assertIsNotNone(parser.parse_str(api.to_code(test_fn)))
def test_to_code_with_wrapped_function(self):
@def_function.function
def test_fn(x, s):
while tf.reduce_sum(x) > s:
x /= 2
return x
with self.assertRaisesRegex(Exception, 'try passing.*python_function'):
api.to_code(test_fn)
def test_tf_convert_direct(self):
def f():
if tf.reduce_sum([1, 2]) > 0:
return -1
return 1
# Note: the autograph setting of tf.function has nothing to do with the
# test case. We just disable it to avoid confusion.
@def_function.function(autograph=False)
def test_fn(ctx):
return api.tf_convert(f, ctx)()
self.assertEqual(
self.evaluate(
test_fn(ag_ctx.ControlStatusCtx(status=ag_ctx.Status.ENABLED))), -1)
with self.assertRaisesRegex(TypeError, 'tf.Tensor.*bool'):
# The code in `f` is only valid with AutoGraph.
test_fn(ag_ctx.ControlStatusCtx(status=ag_ctx.Status.DISABLED))
def test_tf_convert_unspecified_not_converted_by_default(self):
def f():
self.assertEqual(ag_ctx.control_status_ctx().status,
ag_ctx.Status.UNSPECIFIED)
if tf.reduce_sum([1, 2]) > 0:
return -1
return 1
@def_function.function
def test_fn(ctx):
return api.tf_convert(f, ctx, convert_by_default=False)()
with self.assertRaisesRegex(TypeError, 'tf.Tensor.*bool'):
# The code in `f` is only valid with AutoGraph.
test_fn(ag_ctx.ControlStatusCtx(status=ag_ctx.Status.UNSPECIFIED))
def test_tf_convert_whitelisted_method(self):
model = sequential.Sequential([core.Dense(2)])
converted_call = api.tf_convert(
model.call, ag_ctx.ControlStatusCtx(status=ag_ctx.Status.ENABLED))
_, converted_target = tf_decorator.unwrap(converted_call)
self.assertIs(converted_target.__func__, model.call.__func__)
def test_tf_convert_wrapped(self):
def f():
if tf.reduce_sum([1, 2]) > 0:
return -1
return 1
@functools.wraps(f)
def wrapper(*args, **kwargs):
return wrapper.__wrapped__(*args, **kwargs)
decorated_f = tf_decorator.make_decorator(f, wrapper)
# Note: the autograph setting of tf has nothing to do with the
# test case. We just disable it to avoid confusion.
@def_function.function(autograph=False)
def test_fn(ctx):
return api.tf_convert(decorated_f, ctx)()
self.assertEqual(
self.evaluate(
test_fn(ag_ctx.ControlStatusCtx(status=ag_ctx.Status.ENABLED))), -1)
# tf_convert mutates the decorator, so we need to create a new one for
# another test.
decorated_f = tf_decorator.make_decorator(f, wrapper)
with self.assertRaisesRegex(TypeError, 'tf.Tensor.*bool'):
# The code in `f` is only valid with AutoGraph.
test_fn(ag_ctx.ControlStatusCtx(status=ag_ctx.Status.DISABLED))
def test_super_with_one_arg(self):
test_case_self = self
class TestBase(object):
def plus_three(self, x):
return x + 3
class TestSubclass(TestBase):
def plus_three(self, x):
test_case_self.fail('This should never be called.')
def one_arg(self, x):
test_base_unbound = super(TestSubclass)
test_base = test_base_unbound.__get__(self, TestSubclass)
return test_base.plus_three(x)
tc = api.converted_call(TestSubclass,
converter.ConversionOptions(recursive=True), (), {})
self.assertEqual(5, tc.one_arg(2))
def test_super_with_two_args(self):
test_case_self = self
class TestBase(object):
def plus_three(self, x):
return x + 3
class TestSubclass(TestBase):
def plus_three(self, x):
test_case_self.fail('This should never be called.')
def two_args(self, x):
return super(TestSubclass, self).plus_three(x)
tc = api.converted_call(TestSubclass,
converter.ConversionOptions(recursive=True), (), {})
self.assertEqual(5, tc.two_args(2))
if __name__ == '__main__':
os.environ['AUTOGRAPH_STRICT_CONVERSION'] = '1'
test.main()<|fim▁end|> | self.evaluate(variables.global_variables_initializer())
self.assertAllEqual(True, self.evaluate(x))
|
<|file_name|>sensei_components.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# 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 urllib
import urllib2
import json
import sys
import logging
import datetime
from datetime import datetime
import time
import re
logger = logging.getLogger("sensei_components")
#
# REST API parameter constants
#
PARAM_OFFSET = "start"
PARAM_COUNT = "rows"
PARAM_QUERY = "q"
PARAM_QUERY_PARAM = "qparam"
PARAM_SORT = "sort"
PARAM_SORT_ASC = "asc"
PARAM_SORT_DESC = "desc"
PARAM_SORT_SCORE = "relevance"
PARAM_SORT_SCORE_REVERSE = "relrev"
PARAM_SORT_DOC = "doc"
PARAM_SORT_DOC_REVERSE = "docrev"
PARAM_FETCH_STORED = "fetchstored"
PARAM_SHOW_EXPLAIN = "showexplain"
PARAM_ROUTE_PARAM = "routeparam"
PARAM_GROUP_BY = "groupby"
PARAM_MAX_PER_GROUP = "maxpergroup"
PARAM_SELECT = "select"
PARAM_SELECT_VAL = "val"
PARAM_SELECT_NOT = "not"
PARAM_SELECT_OP = "op"
PARAM_SELECT_OP_AND = "and"
PARAM_SELECT_OP_OR = "or"
PARAM_SELECT_PROP = "prop"
PARAM_FACET = "facet"
PARAM_DYNAMIC_INIT = "dyn"
PARAM_PARTITIONS = "partitions"
PARAM_FACET_EXPAND = "expand"
PARAM_FACET_MAX = "max"
PARAM_FACET_MINHIT = "minhit"
PARAM_FACET_ORDER = "order"
PARAM_FACET_ORDER_HITS = "hits"
PARAM_FACET_ORDER_VAL = "val"
PARAM_DYNAMIC_TYPE = "type"
PARAM_DYNAMIC_TYPE_STRING = "string"
PARAM_DYNAMIC_TYPE_BYTEARRAY = "bytearray"
PARAM_DYNAMIC_TYPE_BOOL = "boolean"
PARAM_DYNAMIC_TYPE_INT = "int"
PARAM_DYNAMIC_TYPE_LONG = "long"
PARAM_DYNAMIC_TYPE_DOUBLE = "double"
PARAM_DYNAMIC_VAL = "vals"
PARAM_RESULT_PARSEDQUERY = "parsedquery"
PARAM_RESULT_HIT_STORED_FIELDS = "stored"
PARAM_RESULT_HIT_STORED_FIELDS_NAME = "name"
PARAM_RESULT_HIT_STORED_FIELDS_VALUE = "val"
PARAM_RESULT_HIT_EXPLANATION = "explanation"
PARAM_RESULT_FACETS = "facets"
PARAM_RESULT_TID = "tid"
PARAM_RESULT_TOTALDOCS = "totaldocs"
PARAM_RESULT_NUMHITS = "numhits"
PARAM_RESULT_HITS = "hits"
PARAM_RESULT_HIT_UID = "uid"
PARAM_RESULT_HIT_DOCID = "docid"
PARAM_RESULT_HIT_SCORE = "score"
PARAM_RESULT_HIT_SRC_DATA = "srcdata"
PARAM_RESULT_TIME = "time"
PARAM_RESULT_SELECT_LIST = "select_list"
PARAM_SYSINFO_NUMDOCS = "numdocs"
PARAM_SYSINFO_LASTMODIFIED = "lastmodified"
PARAM_SYSINFO_VERSION = "version"
PARAM_SYSINFO_FACETS = "facets"
PARAM_SYSINFO_FACETS_NAME = "name"
PARAM_SYSINFO_FACETS_RUNTIME = "runtime"
PARAM_SYSINFO_FACETS_PROPS = "props"
PARAM_SYSINFO_CLUSTERINFO = "clusterinfo"
PARAM_SYSINFO_CLUSTERINFO_ID = "id"
PARAM_SYSINFO_CLUSTERINFO_PARTITIONS = "partitions"
PARAM_SYSINFO_CLUSTERINFO_NODELINK = "nodelink"
PARAM_SYSINFO_CLUSTERINFO_ADMINLINK = "adminlink"
PARAM_RESULT_HITS_EXPL_VALUE = "value"
PARAM_RESULT_HITS_EXPL_DESC = "description"
PARAM_RESULT_HITS_EXPL_DETAILS = "details"
PARAM_RESULT_FACET_INFO_VALUE = "value"
PARAM_RESULT_FACET_INFO_COUNT = "count"
PARAM_RESULT_FACET_INFO_SELECTED = "selected"
#
# JSON API parameter constants
#
JSON_PARAM_COLUMNS = "columns"
JSON_PARAM_EXPLAIN = "explain"
JSON_PARAM_FACETS = "facets"
JSON_PARAM_FACET_INIT = "facetInit"
JSON_PARAM_FETCH_STORED = "fetchStored"
JSON_PARAM_FETCH_TERM_VECTORS = "fetchTermVectors"
JSON_PARAM_FILTER = "filter"
JSON_PARAM_FROM = "from"
JSON_PARAM_GROUPBY = "groupBy"
JSON_PARAM_PARTITIONS = "partitions"
JSON_PARAM_QUERY = "query"
JSON_PARAM_QUERY_STRING = "query_string"
JSON_PARAM_ROUTEPARAM = "routeParam"
JSON_PARAM_SELECTIONS = "selections"
JSON_PARAM_SIZE = "size"
JSON_PARAM_SORT = "sort"
JSON_PARAM_TOP = "top"
JSON_PARAM_VALUES = "values"
JSON_PARAM_EXCLUDES = "excludes"
JSON_PARAM_OPERATOR = "operator"
JSON_PARAM_NO_OPTIMIZE = "_noOptimize"
# Group by related column names
GROUP_VALUE = "groupvalue"
GROUP_HITS = "grouphits"
# Default constants
DEFAULT_REQUEST_OFFSET = 0
DEFAULT_REQUEST_COUNT = 10
DEFAULT_REQUEST_MAX_PER_GROUP = 10
DEFAULT_FACET_MINHIT = 1
DEFAULT_FACET_MAXHIT = 10
DEFAULT_FACET_ORDER = PARAM_FACET_ORDER_HITS
#
# Utilities for result display
#
def print_line(keys, max_lens, char='-', sep_char='+'):
sys.stdout.write(sep_char)
for key in keys:
sys.stdout.write(char * (max_lens[key] + 2) + sep_char)
sys.stdout.write('\n')
def print_header(keys, max_lens, char='-', sep_char='+'):
print_line(keys, max_lens, char=char, sep_char=sep_char)
sys.stdout.write('|')
for key in keys:
sys.stdout.write(' %s%s |' % (key, ' ' * (max_lens[key] - len(key))))
sys.stdout.write('\n')
print_line(keys, max_lens, char=char, sep_char=sep_char)
def print_footer(keys, max_lens, char='-', sep_char='+'):
print_line(keys, max_lens, char=char, sep_char=sep_char)
def safe_str(obj):
"""Return the byte string representation of obj."""
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode("unicode_escape")
class SenseiClientError(Exception):
"""Exception raised for all errors related to Sensei client."""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class SenseiFacet:
def __init__(self,expand=False,minHits=1,maxCounts=10,orderBy=PARAM_FACET_ORDER_HITS):
self.expand = expand
self.minHits = minHits
self.maxCounts = maxCounts
self.orderBy = orderBy
class SenseiSelections:
def __init__(self, type):
self.type = type;
self.selection = {}
def get_type(self):
return self.type
def get_selection(self):
return self.selection
class SenseiQuery:
def __init__(self, type):
self.type = type
self.query = {}
def get_type(self):
return self.type
def get_query(self):
return self.query
class SenseiQueryMatchAll(SenseiQuery):
def __init__(self):
SenseiQuery.__init__(self, "match_all")
self.query={"match_all":{"boost":1.0}}
def set_boost(self, boost):
target = (self.query)["match_all"]
target["boost"]=boost
class SenseiQueryIDs(SenseiQuery):
def __init__(self, values, excludes):
SenseiQuery.__init__(self, "ids")
self.query={"ids" : {"values" : [], "excludes":[], "boost":1.0}}
if isinstance(values, list) and isinstance(excludes, list):
self.query = {"ids" : {"values" : values, "excludes":excludes, "boost":1.0}}
def add_values(self, values):
if self.query.has_key("ids"):
values_excludes = self.query["ids"]
if values_excludes.has_key("values"):
orig_values = values_excludes["values"]
orig_set = set(orig_values)
for new_value in values:
if new_value not in orig_set:
orig_values.append(new_value)
def add_excludes(self, excludes):
if self.query.has_key("ids"):
values_excludes = self.query["ids"]
if values_excludes.has_key("excludes"):
orig_excludes = values_excludes["excludes"]
orig_set = set(orig_excludes)
for new_value in excludes:
if new_value not in orig_set:
orig_excludes.append(new_value)
def set_boost(self, boost):
target = (self.query)["ids"]
target["boost"]=boost
class SenseiQueryString(SenseiQuery):
def __init__(self, query):
SenseiQuery.__init__(self, "query_string")
self.query={"query_string":{"query":query,
"default_field":"contents",
"default_operator":"OR",
"allow_leading_wildcard":True,
"lowercase_expanded_terms":True,
"enable_position_increments":True,
"fuzzy_prefix_length":0,
"fuzzy_min_sim":0.5,
"phrase_slop":0,
"boost":1.0,
"auto_generate_phrase_queries":False,
"fields":[],
"use_dis_max":True,
"tie_breaker":0
}}
def set_field(self, field):
self.query["query_string"]["default_field"]=field
def set_operator(self, operator):
self.query["query_string"]["default_operator"]=operator
def set_allow_leading_wildcard(self, allow_leading_wildcard):
self.query["query_string"]["allow_leading_wildcard"]=allow_leading_wildcard
def set_lowercase_expanded_terms(self, lowercase_expanded_terms):
self.query["query_string"]["lowercase_expanded_terms"]=lowercase_expanded_terms
def set_enable_position_increments(self, enable_position_increments):
self.query["query_string"]["enable_position_increments"]=enable_position_increments
def set_fuzzy_prefix_length(self, fuzzy_prefix_length):
self.query["query_string"]["fuzzy_prefix_length"]=fuzzy_prefix_length
def set_fuzzy_min_sim(self, fuzzy_min_sim):
self.query["query_string"]["fuzzy_min_sim"]=fuzzy_min_sim
def set_phrase_slop(self, phrase_slop):
self.query["query_string"]["phrase_slop"]=phrase_slop
def set_boost(self, boost):
self.query["query_string"]["boost"]=boost
def set_auto_generate_phrase_queries(self, auto_generate_phrase_queries):
self.query["query_string"]["auto_generate_phrase_queries"]=auto_generate_phrase_queries
def set_fields(self, fields):
if isinstance(fields, list):
self.query["query_string"]["fields"]=fields
def set_use_dis_max(self, use_dis_max):
self.query["query_string"]["use_dis_max"]=use_dis_max
def set_tie_breaker(self, tie_breaker):
self.query["query_string"]["tie_breaker"]=tie_breaker
class SenseiQueryText(SenseiQuery):
def __init__(self, message, operator, type):
SenseiQuery.__init__(self, "text")
self.query={"text":{"message":message, "operator":operator, "type":type}}
class SenseiQueryTerm(SenseiQuery):
def __init__(self, column, value):
SenseiQuery.__init__(self, "term")
self.query={"term":{column:{"value":value, "boost":1.0}}}
def set_boost(self, boost):
target = (self.query)["term"]
for column, desc in target.iterms():
desc["boost"]=boost
class SenseiFilter:
def __init__(self, type):
self.type = type
self.filter = {}
def get_type(self):
return self.type
def get_filter(self):
return self.filter
class SenseiFilterIDs(SenseiFilter):
def __init__(self, values, excludes):
SenseiFilter.__init__(self, "ids")
self.filter={"ids" : {"values" : [], "excludes":[]}}
if isinstance(values, list) and isinstance(excludes, list):
self.filter = {"ids" : {"values" : values, "excludes":excludes}}
def add_values(self, values):
if self.filter.has_key("ids"):
values_excludes = self.filter["ids"]
if values_excludes.has_key("values"):
orig_values = values_excludes["values"]
orig_set = set(orig_values)
for new_value in values:
if new_value not in orig_set:
orig_values.append(new_value)
def add_excludes(self, excludes):
if self.filter.has_key("ids"):
values_excludes = self.filter["ids"]
if values_excludes.has_key("excludes"):
orig_excludes = values_excludes["excludes"]
orig_set = set(orig_excludes)
for new_value in excludes:
if new_value not in orig_set:
orig_excludes.append(new_value)
class SenseiFilterBool(SenseiFilter):
def __init__(self, must_filter=None, must_not_filter=None, should_filter=None):
SenseiFilter.__init__(self, "bool");
self.filter = {"bool":{"must":{}, "must_not":{}, "should":{}}}
if must_filter is not None and isinstance(must_filter, SenseiFilter):
target = (self.filter)["bool"]
target["must"]=must_filter
if must_not_filter is not None and isinstance(must_not_filter, SenseiFilter):
target = (self.filter)["bool"]
target["must_not"]=must_not_filter
if should_filter is not None and isinstance(should_filter, SenseiFilter):
target = (self.filter)["bool"]
target["should"]=should_filter
class SenseiFilterAND(SenseiFilter):
def __init__(self, filter_list):
SenseiFilter.__init__(self, "and")
self.filter={"and":[]}
old_filter_list = (self.filter)["and"]
if isinstance(filter_list, list):
for new_filter in filter_list:
if isinstance(new_filter, SenseiFilter):
old_filter_list.append(new_filter.get_filter())
class SenseiFilterOR(SenseiFilter):
def __init__(self, filter_list):
SenseiFilter.__init__(self, "or")
self.filter={"or":[]}
old_filter_list = (self.filter)["or"]
if isinstance(filter_list, list):
for new_filter in filter_list:
if isinstance(new_filter, SenseiFilter):
old_filter_list.append(new_filter.get_filter())
class SenseiFilterTerm(SenseiFilter):
def __init__(self, column, value, noOptimize=False):
SenseiFilter.__init__(self, "term")
self.filter={"term":{column:{"value": value, "_noOptimize":noOptimize}}}
class SenseiFilterTerms(SenseiFilter):
def __init__(self, column, values=None, excludes=None, operator="or", noOptimize=False):
SenseiFilter.__init__(self, "terms")
self.filter={"terms":{}}
if values is not None and isinstance(values, list):
if excludes is not None and isinstance(excludes, list):
# complicated mode
self.filter={"terms":{column:{"values":values, "excludes":excludes, "operator":operator, "_noOptimize":noOptimize}}}
else:
self.filter={"terms":{column:values}}
class SenseiFilterRange(SenseiFilter):
def __init__(self, column, from_val, to_val):
SenseiFilter.__init__(self, "range")
self.filter={"range":{column:{"from":from_val, "to":to_val, "_noOptimize":False}}}
def set_No_optimization(self, type, date_format=None):
range = (self.filter)["range"]
for key, value in range.items():
if value is not None:
value["_type"] = type
value["_noOptimize"] = True
if type == "date" and date_format is not None:
value["_date_format"]=date_format
class SenseiFilterQuery(SenseiFilter):
def __init__(self, query):
SenseiFilter.__init__(self, "query")
self.filter={"query":{}}
if isinstance(query, SenseiQuery):
self.filter={"query": query.get_query()}
class SenseiFilterSelection(SenseiFilter):
def __init__(self, selection):
SenseiFilter.__init__(self, "selection")
self.filter = {"selection":{}}
if isinstance(selection, SenseiSelections):
self.filter={"selection":selection.get_selection()}
class SenseiSelection:
def __init__(self, field, operation=PARAM_SELECT_OP_OR):
self.field = field
self.operation = operation
self.type = None
self.values = []
self.excludes = []
self.properties = {}
def __str__(self):
return ("Selection:%s:%s:%s:%s" %
(self.field, self.operation,
','.join(self.values), ','.join(self.excludes)))
def _get_type(self, value):
if isinstance(value, basestring) and RANGE_REGEX.match(value):
return SELECTION_TYPE_RANGE
else:
return SELECTION_TYPE_SIMPLE
def addSelection(self, value, isNot=False):
val_type = self._get_type(value)<|fim▁hole|> elif self.type != val_type:
raise SenseiClientError("Value (%s) type mismatch for facet %s: "
% (value, self.field))
if isNot:
self.excludes.append(safe_str(value))
else:
self.values.append(safe_str(value))
def removeSelection(self, value, isNot=False):
if isNot:
self.excludes.remove(safe_str(value))
else:
self.values.remove(safe_str(value))
def addProperty(self, name, value):
self.properties[name] = value
def removeProperty(self, name):
del self.properties[name]
def getValues(self):
return self.values
def setValues(self, values):
self.values = []
if len(values) > 0:
for value in values:
self.addSelection(value)
def getExcludes(self):
return self.excludes
def setExcludes(self, excludes):
self.excludes = []
if len(excludes) > 0:
for value in excludes:
self.addSelection(value, True)
def getType(self):
return self.type
def setType(self, val_type):
self.type = val_type
def getSelectNotParam(self):
return "%s.%s.%s" % (PARAM_SELECT, self.field, PARAM_SELECT_NOT)
def getSelectNotParamValues(self):
return ",".join(self.excludes)
def getSelectOpParam(self):
return "%s.%s.%s" % (PARAM_SELECT, self.field, PARAM_SELECT_OP)
def getSelectValParam(self):
return "%s.%s.%s" % (PARAM_SELECT, self.field, PARAM_SELECT_VAL)
def getSelectValParamValues(self):
return ",".join(self.values)
def getSelectPropParam(self):
return "%s.%s.%s" % (PARAM_SELECT, self.field, PARAM_SELECT_PROP)
def getSelectPropParamValues(self):
return ",".join(key + ":" + self.properties.get(key)
for key in self.properties.keys())
class SenseiSort:
def __init__(self, field, reverse=False):
self.field = field
self.dir = None
if not (field == PARAM_SORT_SCORE or
field == PARAM_SORT_SCORE_REVERSE or
field == PARAM_SORT_DOC or
field == PARAM_SORT_DOC_REVERSE):
if reverse:
self.dir = PARAM_SORT_DESC
else:
self.dir = PARAM_SORT_ASC
def __str__(self):
return self.build_sort_field()
def build_sort_field(self):
if self.dir:
return self.field + ":" + self.dir
else:
return self.field
def build_sort_spec(self):
if self.dir:
return {self.field: self.dir}
elif self.field == PARAM_SORT_SCORE:
return "_score"
else:
return self.field
class SenseiFacetInitParams:
"""FacetHandler initialization parameters."""
def __init__(self):
self.bool_map = {}
self.int_map = {}
self.long_map = {}
self.string_map = {}
self.byte_map = {}
self.double_map = {}
# Getters for param names for different types
def get_bool_param_names(self):
return self.bool_map.keys()
def get_int_param_names(self):
return self.int_map.keys()
def get_long_param_names(self):
return self.long_map.keys()
def get_string_param_names(self):
return self.string_map.keys()
def get_byte_param_names(self):
return self.byte_map.keys()
def get_double_param_names(self):
return self.double_map.keys()
# Add param name, values
def put_bool_param(self, key, value):
if isinstance(value, list):
self.bool_map[key] = value
else:
self.bool_map[key] = [value]
def put_int_param(self, key, value):
if isinstance(value, list):
self.int_map[key] = value
else:
self.int_map[key] = [value]
def put_long_param(self, key, value):
if isinstance(value, list):
self.long_map[key] = value
else:
self.long_map[key] = [value]
def put_string_param(self, key, value):
if isinstance(value, list):
self.string_map[key] = value
else:
self.string_map[key] = [value]
def put_byte_param(self, key, value):
if isinstance(value, list):
self.byte_map[key] = value
else:
self.byte_map[key] = [value]
def put_double_param(self, key, value):
if isinstance(value, list):
self.double_map[key] = value
else:
self.double_map[key] = [value]
# Getters of param value(s) based on param names
def get_bool_param(self, key):
return self.bool_map.get(key)
def get_int_param(self, key):
return self.int_map.get(key)
def get_long_param(self, key):
return self.long_map.get(key)
def get_string_param(self, key):
return self.string_map.get(key)
def get_byte_param(self, key):
return self.byte_map.get(key)
def get_double_param(self, key):
return self.double_map.get(key)
class SenseiFacetInfo:
def __init__(self, name, runtime=False, props={}):
self.name = name
self.runtime = runtime
self.props = props
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
def get_runtime(self):
return self.runtime
def set_runtime(self, runtime):
self.runtime = runtime
def get_props(self):
return self.props
def set_props(self, props):
self.props = props
class SenseiNodeInfo:
def __init__(self, id, partitions, node_link, admin_link):
self.id = id
self.partitions = partitions
self.node_link = node_link
self.admin_link = admin_link
def get_id(self):
return self.id
def get_partitions(self):
return self.partitions
def get_node_link(self):
return self.node_link
def get_admin_link(self):
return self.admin_link
class SenseiSystemInfo:
def __init__(self, json_data):
logger.debug("json_data = %s" % json_data)
self.num_docs = int(json_data.get(PARAM_SYSINFO_NUMDOCS))
self.last_modified = long(json_data.get(PARAM_SYSINFO_LASTMODIFIED))
self.version = json_data.get(PARAM_SYSINFO_VERSION)
self.facet_infos = []
for facet in json_data.get(PARAM_SYSINFO_FACETS):
facet_info = SenseiFacetInfo(facet.get(PARAM_SYSINFO_FACETS_NAME),
facet.get(PARAM_SYSINFO_FACETS_RUNTIME),
facet.get(PARAM_SYSINFO_FACETS_PROPS))
self.facet_infos.append(facet_info)
# TODO: get cluster_info
self.cluster_info = None
def display(self):
"""Display sysinfo."""
keys = ["facet_name", "facet_type", "runtime", "column", "column_type", "depends"]
max_lens = None
# XXX add existing flags
def get_max_lens(columns):
max_lens = {}
for column in columns:
max_lens[column] = len(column)
for facet_info in self.facet_infos:
props = facet_info.get_props()
tmp_len = len(facet_info.get_name())
if tmp_len > max_lens["facet_name"]:
max_lens["facet_name"] = tmp_len
tmp_len = len(props.get("type"))
if tmp_len > max_lens["facet_type"]:
max_lens["facet_type"] = tmp_len
# runtime can only contain "true" or "false", so len("runtime")
# is big enough
tmp_len = len(props.get("column"))
if tmp_len > max_lens["column"]:
max_lens["column"] = tmp_len
tmp_len = len(props.get("column_type"))
if tmp_len > max_lens["column_type"]:
max_lens["column_type"] = tmp_len
tmp_len = len(props.get("depends"))
if tmp_len > max_lens["depends"]:
max_lens["depends"] = tmp_len
return max_lens
max_lens = get_max_lens(keys)
print_header(keys, max_lens)
for facet_info in self.facet_infos:
props = facet_info.get_props()
sys.stdout.write('|')
val = facet_info.get_name()
sys.stdout.write(' %s%s |' % (val, ' ' * (max_lens["facet_name"] - len(val))))
val = props.get("type")
sys.stdout.write(' %s%s |' % (val, ' ' * (max_lens["facet_type"] - len(val))))
val = facet_info.get_runtime() and "true" or "false"
sys.stdout.write(' %s%s |' % (val, ' ' * (max_lens["runtime"] - len(val))))
val = props.get("column")
sys.stdout.write(' %s%s |' % (val, ' ' * (max_lens["column"] - len(val))))
val = props.get("column_type")
sys.stdout.write(' %s%s |' % (val, ' ' * (max_lens["column_type"] - len(val))))
val = props.get("depends")
sys.stdout.write(' %s%s |' % (val, ' ' * (max_lens["depends"] - len(val))))
sys.stdout.write('\n')
print_footer(keys, max_lens)
def get_num_docs(self):
return self.num_docs
def set_num_docs(self, num_docs):
self.num_docs = num_docs
def get_last_modified(self):
return self.last_modified
def set_last_modified(self, last_modified):
self.last_modified = last_modified
def get_facet_infos(self):
return self.facet_infos
def set_facet_infos(self, facet_infos):
self.facet_infos = facet_infos
def get_version(self):
return self.version
def set_version(self, version):
self.version = version
def get_cluster_info(self):
return self.cluster_info
def set_cluster_info(self, cluster_info):
self.cluster_info = cluster_info
class SenseiRequest:
def __init__(self,
bql_req=None,
offset=DEFAULT_REQUEST_OFFSET,
count=DEFAULT_REQUEST_COUNT,
max_per_group=DEFAULT_REQUEST_MAX_PER_GROUP,
facet_map=None):
self.qParam = {}
self.explain = False
self.route_param = None
self.prepare_time = 0 # Statement prepare time in milliseconds
self.stmt_type = "unknown"
if bql_req != None:
assert(facet_map)
time1 = datetime.now() # XXX need to move to SenseiClient
# ok, msg = bql_req.merge_selections()
# if not ok:
# raise SenseiClientError(msg)
self.stmt_type = bql_req.get_stmt_type()
if self.stmt_type == "desc":
self.index = bql_req.get_index()
else:
self.query = bql_req.get_query()
self.offset = bql_req.get_offset() or offset
self.count = bql_req.get_count() or count
self.columns = bql_req.get_columns()
self.sorts = bql_req.get_sorts()
self.selections = bql_req.get_selections()
self.filter = bql_req.get_filter()
self.query_pred = bql_req.get_query_pred()
self.facets = bql_req.get_facets()
# PARAM_RESULT_HIT_STORED_FIELDS is a reserved column name. If this
# column is selected, turn on fetch_stored flag automatically.
if (PARAM_RESULT_HIT_STORED_FIELDS in self.columns or
bql_req.get_fetching_stored()):
self.fetch_stored = True
else:
self.fetch_stored = False
self.groupby = bql_req.get_groupby()
self.max_per_group = bql_req.get_max_per_group() or max_per_group
self.facet_init_param_map = bql_req.get_facet_init_param_map()
delta = datetime.now() - time1
self.prepare_time = delta.seconds * 1000 + delta.microseconds / 1000
logger.debug("Prepare time: %sms" % self.prepare_time)
else:
self.query = None
self.offset = offset
self.count = count
self.columns = []
self.sorts = None
self.selections = []
self.filter = {}
self.query_pred = {}
self.facets = {}
self.fetch_stored = False
self.groupby = None
self.max_per_group = max_per_group
self.facet_init_param_map = {}
def set_offset(self, offset):
self.offset = offset
def set_count(self, count):
self.count = count
def set_query(self, query):
self.query = query
def set_explain(self, explain):
self.explain = explain
def set_fetch_stored(self, fetch_stored):
self.fetch_stored = fetch_stored
def set_route_param(self, route_param):
self.route_param = route_param
def set_sorts(self, sorts):
self.sorts = sorts
def append_sort(self, sort):
if isinstance(sort, SenseiSort):
if self.sorts is None:
self.sorts = []
self.sorts.append(sort)
else:
self.sorts.append(sort)
def set_filter(self, filter):
self.filter = filter
def set_selections(self, selections):
self.selections = selections
def append_term_selection(self, column, value):
if self.selections is None:
self.selections = []
term_selection = {"term": {column : {"value" : value}}}
self.selections.append(term_selection)
def append_terms_selection(self, column, values, excludes, operator):
if self.selections is None:
self.selections = []
terms_selection = {"terms": {column : {"value" : value}}}
self.selections.append(term_selection)
def append_range_selection(self, column, from_str="*", to_str="*", include_lower=True, include_upper=True):
if self.selections is None:
self.selections = []
range_selection = {"range":{column:{"to":to_str, "from":from_str, "include_lower":include_lower, "include_upper":include_upper}}}
self.selections.append(range_selection)
def append_path_selection(self, column, value, strict=False, depth=1):
if self.selections is None:
self.selections = []
path_selection = {"path": {column : {"value":value, "strict":strict, "depth":depth}}}
self.selections.append(path_selection)
def set_facets(self, facets):
self.facets = facets
def set_groupby(self, groupby):
self.groupby = groupby
def set_max_per_group(self, max_per_group):
self.max_per_group = max_per_group
def set_facet_init_param_map(self, facet_init_param_map):
self.facet_init_param_map = facet_init_param_map
def get_columns(self):
return self.columns
class SenseiHit:
def __init__(self):
self.docid = None
self.uid = None
self.srcData = {}
self.score = None
self.explanation = None
self.stored = None
def load(self, jsonHit):
self.docid = jsonHit.get(PARAM_RESULT_HIT_DOCID)
self.uid = jsonHit.get(PARAM_RESULT_HIT_UID)
self.score = jsonHit.get(PARAM_RESULT_HIT_SCORE)
srcStr = jsonHit.get(PARAM_RESULT_HIT_SRC_DATA)
self.explanation = jsonHit.get(PARAM_RESULT_HIT_EXPLANATION)
self.stored = jsonHit.get(PARAM_RESULT_HIT_STORED_FIELDS)
if srcStr:
self.srcData = json.loads(srcStr)
else:
self.srcData = None
class SenseiResultFacet:
value = None
count = None
selected = None
def load(self,json):
self.value=json.get(PARAM_RESULT_FACET_INFO_VALUE)
self.count=json.get(PARAM_RESULT_FACET_INFO_COUNT)
self.selected=json.get(PARAM_RESULT_FACET_INFO_SELECTED,False)
class SenseiResult:
"""Sensei search results for a query."""
def __init__(self, json_data):
logger.debug("json_data = %s" % json_data)
self.jsonMap = json_data
self.parsedQuery = json_data.get(PARAM_RESULT_PARSEDQUERY)
self.totalDocs = json_data.get(PARAM_RESULT_TOTALDOCS, 0)
self.time = json_data.get(PARAM_RESULT_TIME, 0)
self.total_time = 0
self.numHits = json_data.get(PARAM_RESULT_NUMHITS, 0)
self.hits = json_data.get(PARAM_RESULT_HITS)
self.error = json_data.get("error")
map = json_data.get(PARAM_RESULT_FACETS)
self.facetMap = {}
if map:
for k, v in map.items():
facetList = []
for facet in v:
facetObj = SenseiResultFacet()
facetObj.load(facet)
facetList.append(facetObj)
self.facetMap[k]=facetList
def display(self, columns=['*'], max_col_width=40):
"""Print the results in SQL SELECT result format."""
keys = []
max_lens = None
has_group_hits = False
def get_max_lens(columns):
max_lens = {}
has_group_hits = False
for col in columns:
max_lens[col] = len(col)
for hit in self.hits:
group_hits = [hit]
if hit.has_key(GROUP_HITS):
group_hits = hit.get(GROUP_HITS)
has_group_hits = True
for group_hit in group_hits:
for col in columns:
if group_hit.has_key(col):
v = group_hit.get(col)
else:
v = '<Not Found>'
if isinstance(v, list):
v = ','.join([safe_str(item) for item in v])
elif isinstance(v, (int, long, float)):
v = str(v)
value_len = len(v)
if value_len > max_lens[col]:
max_lens[col] = min(value_len, max_col_width)
return max_lens, has_group_hits
if not self.hits:
print "No hit is found."
return
elif not columns:
print "No column is selected."
return
if len(columns) == 1 and columns[0] == '*':
keys = self.hits[0].keys()
if GROUP_HITS in keys:
keys.remove(GROUP_HITS)
if GROUP_VALUE in keys:
keys.remove(GROUP_VALUE)
if PARAM_RESULT_HIT_SRC_DATA in keys:
keys.remove(PARAM_RESULT_HIT_SRC_DATA)
else:
keys = columns
max_lens, has_group_hits = get_max_lens(keys)
print_header(keys, max_lens,
has_group_hits and '=' or '-',
has_group_hits and '=' or '+')
# Print the results
for hit in self.hits:
group_hits = [hit]
if hit.has_key(GROUP_HITS):
group_hits = hit.get(GROUP_HITS)
for group_hit in group_hits:
sys.stdout.write('|')
for key in keys:
if group_hit.has_key(key):
v = group_hit.get(key)
else:
v = '<Not Found>'
if isinstance(v, list):
v = ','.join([safe_str(item) for item in v])
elif isinstance(v, (int, float, long)):
v = str(v)
else:
# The value may contain unicode characters
v = safe_str(v)
if len(v) > max_col_width:
v = v[:max_col_width]
sys.stdout.write(' %s%s |' % (v, ' ' * (max_lens[key] - len(v))))
sys.stdout.write('\n')
if has_group_hits:
print_line(keys, max_lens)
print_footer(keys, max_lens,
has_group_hits and '=' or '-',
has_group_hits and '=' or '+')
sys.stdout.write('%s %s%s in set, %s hit%s, %s total doc%s (server: %sms, total: %sms)\n' %
(len(self.hits),
has_group_hits and 'group' or 'row',
len(self.hits) > 1 and 's' or '',
self.numHits,
self.numHits > 1 and 's' or '',
self.totalDocs,
self.totalDocs > 1 and 's' or '',
self.time,
self.total_time
))
# Print facet information
for facet, values in self.jsonMap.get(PARAM_RESULT_FACETS).iteritems():
max_val_len = len(facet)
max_count_len = 1
for val in values:
max_val_len = max(max_val_len, min(max_col_width, len(val.get('value'))))
max_count_len = max(max_count_len, len(str(val.get('count'))))
total_len = max_val_len + 2 + max_count_len + 3
sys.stdout.write('+' + '-' * total_len + '+\n')
sys.stdout.write('| ' + facet + ' ' * (total_len - len(facet) - 1) + '|\n')
sys.stdout.write('+' + '-' * total_len + '+\n')
for val in values:
sys.stdout.write('| %s%s (%s)%s |\n' %
(val.get('value'),
' ' * (max_val_len - len(val.get('value'))),
val.get('count'),
' ' * (max_count_len - len(str(val.get('count'))))))
sys.stdout.write('+' + '-' * total_len + '+\n')<|fim▁end|> | if not self.type:
self.type = val_type |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.