file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
models.py | #!/usr/bin/env python
# encoding: utf-8
"""
models.py
Created by Darcy Liu on 2012-03-03.
Copyright (c) 2012 Close To U. All rights reserved.
"""
from django.db import models
from django.contrib.auth.models import User
# class Setting(models.Model):
# sid = models.AutoField(primary_key=True)
# option = models.CharField(unique=True,max_length=128,verbose_name='Option')
# value = models.CharField(max_length=256,verbose_name='Value')
class | (models.Model):
key = models.AutoField(primary_key=True)
name = models.CharField(max_length=256,verbose_name='name')
slug = models.CharField(unique=True,max_length=128,verbose_name='slug')
meta = models.TextField(blank=True, verbose_name='meta')
description = models.TextField(blank=True, verbose_name='description')
author = models.ForeignKey(User,verbose_name='author')
created = models.DateTimeField(auto_now_add=True,verbose_name='created')
updated = models.DateTimeField(auto_now=True,verbose_name='updated')
def __unicode__(self):
result = self.name
return unicode(result)
class Page(models.Model):
key = models.AutoField(primary_key=True)
name = models.CharField(max_length=256,verbose_name='name')
slug = models.CharField(max_length=128,verbose_name='slug')
#type=//insite standlone
Mode_Choices = (
('0', 'insite'),
('1', 'standlone'),
)
mode = models.CharField(verbose_name='format',max_length=1,default=0,choices=Mode_Choices)
#content-type
mime = models.CharField(max_length=64,default='text/html;charset=utf-8',verbose_name='mime')
#format
Format_Choices = (
('0', 'txt'),
('1', 'html'),
('2', 'markdown'),
('3', 'textile'),
)
format = models.CharField(verbose_name='format',max_length=1,default=0,choices=Format_Choices)
text = models.TextField(blank=True, verbose_name='content')
script = models.TextField(blank=True, verbose_name='script')
style = models.TextField(blank=True, verbose_name='style')
text_html = models.TextField(blank=True, verbose_name='html')
minisite = models.ForeignKey(Minisite,verbose_name='minisite')
author = models.ForeignKey(User,verbose_name='author')
created = models.DateTimeField(auto_now_add=True,verbose_name='created')
updated = models.DateTimeField(auto_now=True,verbose_name='updated')
def __unicode__(self):
result = self.name
return unicode(result)
class Meta:
unique_together = (('slug', 'minisite'),) | Minisite | identifier_name |
models.py | #!/usr/bin/env python
# encoding: utf-8
"""
models.py
Created by Darcy Liu on 2012-03-03.
Copyright (c) 2012 Close To U. All rights reserved.
"""
from django.db import models
from django.contrib.auth.models import User
# class Setting(models.Model):
# sid = models.AutoField(primary_key=True)
# option = models.CharField(unique=True,max_length=128,verbose_name='Option')
# value = models.CharField(max_length=256,verbose_name='Value')
class Minisite(models.Model):
key = models.AutoField(primary_key=True) | slug = models.CharField(unique=True,max_length=128,verbose_name='slug')
meta = models.TextField(blank=True, verbose_name='meta')
description = models.TextField(blank=True, verbose_name='description')
author = models.ForeignKey(User,verbose_name='author')
created = models.DateTimeField(auto_now_add=True,verbose_name='created')
updated = models.DateTimeField(auto_now=True,verbose_name='updated')
def __unicode__(self):
result = self.name
return unicode(result)
class Page(models.Model):
key = models.AutoField(primary_key=True)
name = models.CharField(max_length=256,verbose_name='name')
slug = models.CharField(max_length=128,verbose_name='slug')
#type=//insite standlone
Mode_Choices = (
('0', 'insite'),
('1', 'standlone'),
)
mode = models.CharField(verbose_name='format',max_length=1,default=0,choices=Mode_Choices)
#content-type
mime = models.CharField(max_length=64,default='text/html;charset=utf-8',verbose_name='mime')
#format
Format_Choices = (
('0', 'txt'),
('1', 'html'),
('2', 'markdown'),
('3', 'textile'),
)
format = models.CharField(verbose_name='format',max_length=1,default=0,choices=Format_Choices)
text = models.TextField(blank=True, verbose_name='content')
script = models.TextField(blank=True, verbose_name='script')
style = models.TextField(blank=True, verbose_name='style')
text_html = models.TextField(blank=True, verbose_name='html')
minisite = models.ForeignKey(Minisite,verbose_name='minisite')
author = models.ForeignKey(User,verbose_name='author')
created = models.DateTimeField(auto_now_add=True,verbose_name='created')
updated = models.DateTimeField(auto_now=True,verbose_name='updated')
def __unicode__(self):
result = self.name
return unicode(result)
class Meta:
unique_together = (('slug', 'minisite'),) | name = models.CharField(max_length=256,verbose_name='name') | random_line_split |
models.py | #!/usr/bin/env python
# encoding: utf-8
"""
models.py
Created by Darcy Liu on 2012-03-03.
Copyright (c) 2012 Close To U. All rights reserved.
"""
from django.db import models
from django.contrib.auth.models import User
# class Setting(models.Model):
# sid = models.AutoField(primary_key=True)
# option = models.CharField(unique=True,max_length=128,verbose_name='Option')
# value = models.CharField(max_length=256,verbose_name='Value')
class Minisite(models.Model):
key = models.AutoField(primary_key=True)
name = models.CharField(max_length=256,verbose_name='name')
slug = models.CharField(unique=True,max_length=128,verbose_name='slug')
meta = models.TextField(blank=True, verbose_name='meta')
description = models.TextField(blank=True, verbose_name='description')
author = models.ForeignKey(User,verbose_name='author')
created = models.DateTimeField(auto_now_add=True,verbose_name='created')
updated = models.DateTimeField(auto_now=True,verbose_name='updated')
def __unicode__(self):
result = self.name
return unicode(result)
class Page(models.Model):
key = models.AutoField(primary_key=True)
name = models.CharField(max_length=256,verbose_name='name')
slug = models.CharField(max_length=128,verbose_name='slug')
#type=//insite standlone
Mode_Choices = (
('0', 'insite'),
('1', 'standlone'),
)
mode = models.CharField(verbose_name='format',max_length=1,default=0,choices=Mode_Choices)
#content-type
mime = models.CharField(max_length=64,default='text/html;charset=utf-8',verbose_name='mime')
#format
Format_Choices = (
('0', 'txt'),
('1', 'html'),
('2', 'markdown'),
('3', 'textile'),
)
format = models.CharField(verbose_name='format',max_length=1,default=0,choices=Format_Choices)
text = models.TextField(blank=True, verbose_name='content')
script = models.TextField(blank=True, verbose_name='script')
style = models.TextField(blank=True, verbose_name='style')
text_html = models.TextField(blank=True, verbose_name='html')
minisite = models.ForeignKey(Minisite,verbose_name='minisite')
author = models.ForeignKey(User,verbose_name='author')
created = models.DateTimeField(auto_now_add=True,verbose_name='created')
updated = models.DateTimeField(auto_now=True,verbose_name='updated')
def __unicode__(self):
|
class Meta:
unique_together = (('slug', 'minisite'),) | result = self.name
return unicode(result) | identifier_body |
inherited.rs | use super::callee::DeferredCallResolution;
use super::MaybeInProgressTables;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::{self, Span};
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::{self, ObligationCause, TraitEngine, TraitEngineExt};
use std::cell::RefCell;
use std::ops::Deref;
/// Closures defined within the function. For example:
///
/// fn foo() {
/// bar(move|| { ... })
/// }
///
/// Here, the function `foo()` and the closure passed to
/// `bar()` will each have their own `FnCtxt`, but they will
/// share the inherited fields.
pub struct Inherited<'a, 'tcx> {
pub(super) infcx: InferCtxt<'a, 'tcx>,
pub(super) typeck_results: super::MaybeInProgressTables<'a, 'tcx>,
pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
// Some additional `Sized` obligations badly affect type inference. | RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
// When we process a call like `c()` where `c` is a closure type,
// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
// `FnOnce` closure. In that case, we defer full resolution of the
// call until upvar inference can kick in and make the
// decision. We keep these deferred resolutions grouped by the
// def-id of the closure, so that once we decide, we can easily go
// back and process them.
pub(super) deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
pub(super) deferred_generator_interiors:
RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
/// Reports whether this is in a const context.
pub(super) constness: hir::Constness,
pub(super) body_id: Option<hir::BodyId>,
}
impl<'a, 'tcx> Deref for Inherited<'a, 'tcx> {
type Target = InferCtxt<'a, 'tcx>;
fn deref(&self) -> &Self::Target {
&self.infcx
}
}
/// Helper type of a temporary returned by `Inherited::build(...)`.
/// Necessary because we can't write the following bound:
/// `F: for<'b, 'tcx> where 'tcx FnOnce(Inherited<'b, 'tcx>)`.
pub struct InheritedBuilder<'tcx> {
infcx: infer::InferCtxtBuilder<'tcx>,
def_id: LocalDefId,
}
impl Inherited<'_, 'tcx> {
pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;
InheritedBuilder {
infcx: tcx.infer_ctxt().with_fresh_in_progress_typeck_results(hir_owner),
def_id,
}
}
}
impl<'tcx> InheritedBuilder<'tcx> {
pub fn enter<F, R>(&mut self, f: F) -> R
where
F: for<'a> FnOnce(Inherited<'a, 'tcx>) -> R,
{
let def_id = self.def_id;
self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
}
}
impl Inherited<'a, 'tcx> {
pub(super) fn new(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness_for_typeck())
}
pub(super) fn with_constness(
infcx: InferCtxt<'a, 'tcx>,
def_id: LocalDefId,
constness: hir::Constness,
) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
let body_id = tcx.hir().maybe_body_owned_by(item_id);
Inherited {
typeck_results: MaybeInProgressTables {
maybe_typeck_results: infcx.in_progress_typeck_results,
},
infcx,
fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
locals: RefCell::new(Default::default()),
deferred_sized_obligations: RefCell::new(Vec::new()),
deferred_call_resolutions: RefCell::new(Default::default()),
deferred_cast_checks: RefCell::new(Vec::new()),
deferred_generator_interiors: RefCell::new(Vec::new()),
constness,
body_id,
}
}
pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
debug!("register_predicate({:?})", obligation);
if obligation.has_escaping_bound_vars() {
span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
}
self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
}
pub(super) fn register_predicates<I>(&self, obligations: I)
where
I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
{
for obligation in obligations {
self.register_predicate(obligation);
}
}
pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
self.register_predicates(infer_ok.obligations);
infer_ok.value
}
pub(super) fn normalize_associated_types_in<T>(
&self,
span: Span,
body_id: hir::HirId,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
self.normalize_associated_types_in_with_cause(
ObligationCause::misc(span, body_id),
param_env,
value,
)
}
pub(super) fn normalize_associated_types_in_with_cause<T>(
&self,
cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
let ok = self.partially_normalize_associated_types_in(cause, param_env, value);
debug!(?ok);
self.register_infer_ok_obligations(ok)
}
} | // These obligations are added in a later stage of typeck.
pub(super) deferred_sized_obligations: | random_line_split |
inherited.rs | use super::callee::DeferredCallResolution;
use super::MaybeInProgressTables;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::{self, Span};
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::{self, ObligationCause, TraitEngine, TraitEngineExt};
use std::cell::RefCell;
use std::ops::Deref;
/// Closures defined within the function. For example:
///
/// fn foo() {
/// bar(move|| { ... })
/// }
///
/// Here, the function `foo()` and the closure passed to
/// `bar()` will each have their own `FnCtxt`, but they will
/// share the inherited fields.
pub struct Inherited<'a, 'tcx> {
pub(super) infcx: InferCtxt<'a, 'tcx>,
pub(super) typeck_results: super::MaybeInProgressTables<'a, 'tcx>,
pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
// Some additional `Sized` obligations badly affect type inference.
// These obligations are added in a later stage of typeck.
pub(super) deferred_sized_obligations:
RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
// When we process a call like `c()` where `c` is a closure type,
// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
// `FnOnce` closure. In that case, we defer full resolution of the
// call until upvar inference can kick in and make the
// decision. We keep these deferred resolutions grouped by the
// def-id of the closure, so that once we decide, we can easily go
// back and process them.
pub(super) deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
pub(super) deferred_generator_interiors:
RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
/// Reports whether this is in a const context.
pub(super) constness: hir::Constness,
pub(super) body_id: Option<hir::BodyId>,
}
impl<'a, 'tcx> Deref for Inherited<'a, 'tcx> {
type Target = InferCtxt<'a, 'tcx>;
fn deref(&self) -> &Self::Target {
&self.infcx
}
}
/// Helper type of a temporary returned by `Inherited::build(...)`.
/// Necessary because we can't write the following bound:
/// `F: for<'b, 'tcx> where 'tcx FnOnce(Inherited<'b, 'tcx>)`.
pub struct InheritedBuilder<'tcx> {
infcx: infer::InferCtxtBuilder<'tcx>,
def_id: LocalDefId,
}
impl Inherited<'_, 'tcx> {
pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;
InheritedBuilder {
infcx: tcx.infer_ctxt().with_fresh_in_progress_typeck_results(hir_owner),
def_id,
}
}
}
impl<'tcx> InheritedBuilder<'tcx> {
pub fn enter<F, R>(&mut self, f: F) -> R
where
F: for<'a> FnOnce(Inherited<'a, 'tcx>) -> R,
{
let def_id = self.def_id;
self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
}
}
impl Inherited<'a, 'tcx> {
pub(super) fn new(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness_for_typeck())
}
pub(super) fn with_constness(
infcx: InferCtxt<'a, 'tcx>,
def_id: LocalDefId,
constness: hir::Constness,
) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
let body_id = tcx.hir().maybe_body_owned_by(item_id);
Inherited {
typeck_results: MaybeInProgressTables {
maybe_typeck_results: infcx.in_progress_typeck_results,
},
infcx,
fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
locals: RefCell::new(Default::default()),
deferred_sized_obligations: RefCell::new(Vec::new()),
deferred_call_resolutions: RefCell::new(Default::default()),
deferred_cast_checks: RefCell::new(Vec::new()),
deferred_generator_interiors: RefCell::new(Vec::new()),
constness,
body_id,
}
}
pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) |
pub(super) fn register_predicates<I>(&self, obligations: I)
where
I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
{
for obligation in obligations {
self.register_predicate(obligation);
}
}
pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
self.register_predicates(infer_ok.obligations);
infer_ok.value
}
pub(super) fn normalize_associated_types_in<T>(
&self,
span: Span,
body_id: hir::HirId,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
self.normalize_associated_types_in_with_cause(
ObligationCause::misc(span, body_id),
param_env,
value,
)
}
pub(super) fn normalize_associated_types_in_with_cause<T>(
&self,
cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
let ok = self.partially_normalize_associated_types_in(cause, param_env, value);
debug!(?ok);
self.register_infer_ok_obligations(ok)
}
}
| {
debug!("register_predicate({:?})", obligation);
if obligation.has_escaping_bound_vars() {
span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
}
self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
} | identifier_body |
inherited.rs | use super::callee::DeferredCallResolution;
use super::MaybeInProgressTables;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::{self, Span};
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::{self, ObligationCause, TraitEngine, TraitEngineExt};
use std::cell::RefCell;
use std::ops::Deref;
/// Closures defined within the function. For example:
///
/// fn foo() {
/// bar(move|| { ... })
/// }
///
/// Here, the function `foo()` and the closure passed to
/// `bar()` will each have their own `FnCtxt`, but they will
/// share the inherited fields.
pub struct Inherited<'a, 'tcx> {
pub(super) infcx: InferCtxt<'a, 'tcx>,
pub(super) typeck_results: super::MaybeInProgressTables<'a, 'tcx>,
pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
// Some additional `Sized` obligations badly affect type inference.
// These obligations are added in a later stage of typeck.
pub(super) deferred_sized_obligations:
RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
// When we process a call like `c()` where `c` is a closure type,
// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
// `FnOnce` closure. In that case, we defer full resolution of the
// call until upvar inference can kick in and make the
// decision. We keep these deferred resolutions grouped by the
// def-id of the closure, so that once we decide, we can easily go
// back and process them.
pub(super) deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
pub(super) deferred_generator_interiors:
RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
/// Reports whether this is in a const context.
pub(super) constness: hir::Constness,
pub(super) body_id: Option<hir::BodyId>,
}
impl<'a, 'tcx> Deref for Inherited<'a, 'tcx> {
type Target = InferCtxt<'a, 'tcx>;
fn | (&self) -> &Self::Target {
&self.infcx
}
}
/// Helper type of a temporary returned by `Inherited::build(...)`.
/// Necessary because we can't write the following bound:
/// `F: for<'b, 'tcx> where 'tcx FnOnce(Inherited<'b, 'tcx>)`.
pub struct InheritedBuilder<'tcx> {
infcx: infer::InferCtxtBuilder<'tcx>,
def_id: LocalDefId,
}
impl Inherited<'_, 'tcx> {
pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;
InheritedBuilder {
infcx: tcx.infer_ctxt().with_fresh_in_progress_typeck_results(hir_owner),
def_id,
}
}
}
impl<'tcx> InheritedBuilder<'tcx> {
pub fn enter<F, R>(&mut self, f: F) -> R
where
F: for<'a> FnOnce(Inherited<'a, 'tcx>) -> R,
{
let def_id = self.def_id;
self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
}
}
impl Inherited<'a, 'tcx> {
pub(super) fn new(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness_for_typeck())
}
pub(super) fn with_constness(
infcx: InferCtxt<'a, 'tcx>,
def_id: LocalDefId,
constness: hir::Constness,
) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
let body_id = tcx.hir().maybe_body_owned_by(item_id);
Inherited {
typeck_results: MaybeInProgressTables {
maybe_typeck_results: infcx.in_progress_typeck_results,
},
infcx,
fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
locals: RefCell::new(Default::default()),
deferred_sized_obligations: RefCell::new(Vec::new()),
deferred_call_resolutions: RefCell::new(Default::default()),
deferred_cast_checks: RefCell::new(Vec::new()),
deferred_generator_interiors: RefCell::new(Vec::new()),
constness,
body_id,
}
}
pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
debug!("register_predicate({:?})", obligation);
if obligation.has_escaping_bound_vars() {
span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
}
self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
}
pub(super) fn register_predicates<I>(&self, obligations: I)
where
I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
{
for obligation in obligations {
self.register_predicate(obligation);
}
}
pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
self.register_predicates(infer_ok.obligations);
infer_ok.value
}
pub(super) fn normalize_associated_types_in<T>(
&self,
span: Span,
body_id: hir::HirId,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
self.normalize_associated_types_in_with_cause(
ObligationCause::misc(span, body_id),
param_env,
value,
)
}
pub(super) fn normalize_associated_types_in_with_cause<T>(
&self,
cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
let ok = self.partially_normalize_associated_types_in(cause, param_env, value);
debug!(?ok);
self.register_infer_ok_obligations(ok)
}
}
| deref | identifier_name |
inherited.rs | use super::callee::DeferredCallResolution;
use super::MaybeInProgressTables;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::{self, Span};
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::{self, ObligationCause, TraitEngine, TraitEngineExt};
use std::cell::RefCell;
use std::ops::Deref;
/// Closures defined within the function. For example:
///
/// fn foo() {
/// bar(move|| { ... })
/// }
///
/// Here, the function `foo()` and the closure passed to
/// `bar()` will each have their own `FnCtxt`, but they will
/// share the inherited fields.
pub struct Inherited<'a, 'tcx> {
pub(super) infcx: InferCtxt<'a, 'tcx>,
pub(super) typeck_results: super::MaybeInProgressTables<'a, 'tcx>,
pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
// Some additional `Sized` obligations badly affect type inference.
// These obligations are added in a later stage of typeck.
pub(super) deferred_sized_obligations:
RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
// When we process a call like `c()` where `c` is a closure type,
// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
// `FnOnce` closure. In that case, we defer full resolution of the
// call until upvar inference can kick in and make the
// decision. We keep these deferred resolutions grouped by the
// def-id of the closure, so that once we decide, we can easily go
// back and process them.
pub(super) deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
pub(super) deferred_generator_interiors:
RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
/// Reports whether this is in a const context.
pub(super) constness: hir::Constness,
pub(super) body_id: Option<hir::BodyId>,
}
impl<'a, 'tcx> Deref for Inherited<'a, 'tcx> {
type Target = InferCtxt<'a, 'tcx>;
fn deref(&self) -> &Self::Target {
&self.infcx
}
}
/// Helper type of a temporary returned by `Inherited::build(...)`.
/// Necessary because we can't write the following bound:
/// `F: for<'b, 'tcx> where 'tcx FnOnce(Inherited<'b, 'tcx>)`.
pub struct InheritedBuilder<'tcx> {
infcx: infer::InferCtxtBuilder<'tcx>,
def_id: LocalDefId,
}
impl Inherited<'_, 'tcx> {
pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;
InheritedBuilder {
infcx: tcx.infer_ctxt().with_fresh_in_progress_typeck_results(hir_owner),
def_id,
}
}
}
impl<'tcx> InheritedBuilder<'tcx> {
pub fn enter<F, R>(&mut self, f: F) -> R
where
F: for<'a> FnOnce(Inherited<'a, 'tcx>) -> R,
{
let def_id = self.def_id;
self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
}
}
impl Inherited<'a, 'tcx> {
pub(super) fn new(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness_for_typeck())
}
pub(super) fn with_constness(
infcx: InferCtxt<'a, 'tcx>,
def_id: LocalDefId,
constness: hir::Constness,
) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
let body_id = tcx.hir().maybe_body_owned_by(item_id);
Inherited {
typeck_results: MaybeInProgressTables {
maybe_typeck_results: infcx.in_progress_typeck_results,
},
infcx,
fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
locals: RefCell::new(Default::default()),
deferred_sized_obligations: RefCell::new(Vec::new()),
deferred_call_resolutions: RefCell::new(Default::default()),
deferred_cast_checks: RefCell::new(Vec::new()),
deferred_generator_interiors: RefCell::new(Vec::new()),
constness,
body_id,
}
}
pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
debug!("register_predicate({:?})", obligation);
if obligation.has_escaping_bound_vars() |
self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
}
pub(super) fn register_predicates<I>(&self, obligations: I)
where
I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
{
for obligation in obligations {
self.register_predicate(obligation);
}
}
pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
self.register_predicates(infer_ok.obligations);
infer_ok.value
}
pub(super) fn normalize_associated_types_in<T>(
&self,
span: Span,
body_id: hir::HirId,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
self.normalize_associated_types_in_with_cause(
ObligationCause::misc(span, body_id),
param_env,
value,
)
}
pub(super) fn normalize_associated_types_in_with_cause<T>(
&self,
cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
let ok = self.partially_normalize_associated_types_in(cause, param_env, value);
debug!(?ok);
self.register_infer_ok_obligations(ok)
}
}
| {
span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
} | conditional_block |
global.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writing
//! code that works in workers as well as window scopes.
use dom::bindings::conversions::native_from_reflector_jsmanaged;
use dom::bindings::js::{JS, JSRef, Root, Unrooted};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers};
use dom::window::{self, WindowHelpers};
use devtools_traits::DevtoolsControlChan;
use script_task::{ScriptChan, ScriptPort, ScriptMsg, ScriptTask};
use msg::constellation_msg::{PipelineId, WorkerId};
use net_traits::ResourceTask;
use js::{JSCLASS_IS_GLOBAL, JSCLASS_IS_DOMJSCLASS};
use js::glue::{GetGlobalForObjectCrossCompartment};
use js::jsapi::{JSContext, JSObject};
use js::jsapi::{JS_GetClass};
use url::Url;
/// A freely-copyable reference to a rooted global object.
#[derive(Copy)]
pub enum GlobalRef<'a> {
/// A reference to a `Window` object.
Window(JSRef<'a, window::Window>),
/// A reference to a `WorkerGlobalScope` object.
Worker(JSRef<'a, WorkerGlobalScope>),
}
/// A stack-based rooted reference to a global object.
pub enum GlobalRoot {
/// A root for a `Window` object.
Window(Root<window::Window>),
/// A root for a `WorkerGlobalScope` object.
Worker(Root<WorkerGlobalScope>),
}
/// A traced reference to a global object, for use in fields of traced Rust
/// structures.
#[jstraceable]
#[must_root]
pub enum GlobalField {
/// A field for a `Window` object.
Window(JS<window::Window>),
/// A field for a `WorkerGlobalScope` object.
Worker(JS<WorkerGlobalScope>),
}
/// An unrooted reference to a global object.
#[must_root]
pub enum GlobalUnrooted {
/// An unrooted reference to a `Window` object.
Window(Unrooted<window::Window>),
/// An unrooted reference to a `WorkerGlobalScope` object.
Worker(Unrooted<WorkerGlobalScope>),
}
impl<'a> GlobalRef<'a> {
/// Get the `JSContext` for the `JSRuntime` associated with the thread
/// this global object is on.
pub fn get_cx(&self) -> *mut JSContext {
match *self {
GlobalRef::Window(ref window) => window.get_cx(),
GlobalRef::Worker(ref worker) => worker.get_cx(),
}
}
/// Extract a `Window`, causing task failure if the global object is not
/// a `Window`.
pub fn as_window<'b>(&'b self) -> JSRef<'b, window::Window> {
match *self {
GlobalRef::Window(window) => window,
GlobalRef::Worker(_) => panic!("expected a Window scope"),
}
}
/// Get the `PipelineId` for this global scope.
pub fn pipeline(&self) -> PipelineId {
match *self {
GlobalRef::Window(window) => window.pipeline(),
GlobalRef::Worker(worker) => worker.pipeline(),
}
}
/// Get `DevtoolsControlChan` to send messages to Devtools
/// task when available.
pub fn devtools_chan(&self) -> Option<DevtoolsControlChan> {
match *self {
GlobalRef::Window(window) => window.devtools_chan(),
GlobalRef::Worker(worker) => worker.devtools_chan(),
}
}
/// Get the `ResourceTask` for this global scope.
pub fn resource_task(&self) -> ResourceTask {
match *self {
GlobalRef::Window(ref window) => window.resource_task().clone(),
GlobalRef::Worker(ref worker) => worker.resource_task().clone(),
}
}
/// Get next worker id.
pub fn get_next_worker_id(&self) -> WorkerId {
match *self {
GlobalRef::Window(ref window) => window.get_next_worker_id(),
GlobalRef::Worker(ref worker) => worker.get_next_worker_id()
}
}
/// Get the URL for this global scope.
pub fn get_url(&self) -> Url {
match *self {
GlobalRef::Window(ref window) => window.get_url(),
GlobalRef::Worker(ref worker) => worker.get_url().clone(),
}
}
/// `ScriptChan` used to send messages to the event loop of this global's
/// thread.
pub fn script_chan(&self) -> Box<ScriptChan+Send> {
match *self {
GlobalRef::Window(ref window) => window.script_chan(),
GlobalRef::Worker(ref worker) => worker.script_chan(),
}
}
/// Create a new sender/receiver pair that can be used to implement an on-demand
/// event loop. Used for implementing web APIs that require blocking semantics
/// without resorting to nested event loops.
pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) {
match *self {
GlobalRef::Window(ref window) => window.new_script_pair(),
GlobalRef::Worker(ref worker) => worker.new_script_pair(),
}
}
/// Process a single event as if it were the next event in the task queue for
/// this global.
pub fn process_event(&self, msg: ScriptMsg) {
match *self {
GlobalRef::Window(_) => ScriptTask::process_event(msg),
GlobalRef::Worker(ref worker) => worker.process_event(msg),
}
}
}
impl<'a> Reflectable for GlobalRef<'a> {
fn reflector<'b>(&'b self) -> &'b Reflector {
match *self {
GlobalRef::Window(ref window) => window.reflector(),
GlobalRef::Worker(ref worker) => worker.reflector(),
}
}
}
impl GlobalRoot {
/// Obtain a safe reference to the global object that cannot outlive the
/// lifetime of this root.
pub fn r<'c>(&'c self) -> GlobalRef<'c> {
match *self {
GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()),
GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()),
}
}
}
impl GlobalField {
/// Create a new `GlobalField` from a rooted reference.
pub fn from_rooted(global: &GlobalRef) -> GlobalField {
match *global {
GlobalRef::Window(window) => GlobalField::Window(JS::from_rooted(window)),
GlobalRef::Worker(worker) => GlobalField::Worker(JS::from_rooted(worker)),
}
}
/// Create a stack-bounded root for this reference.
pub fn | (&self) -> GlobalRoot {
match *self {
GlobalField::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalField::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
impl GlobalUnrooted {
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
GlobalUnrooted::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalUnrooted::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
/// Returns the global object of the realm that the given JS object was created in.
#[allow(unrooted_must_root)]
pub fn global_object_for_js_object(obj: *mut JSObject) -> GlobalUnrooted {
unsafe {
let global = GetGlobalForObjectCrossCompartment(obj);
let clasp = JS_GetClass(global);
assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0);
match native_from_reflector_jsmanaged(global) {
Ok(window) => return GlobalUnrooted::Window(window),
Err(_) => (),
}
match native_from_reflector_jsmanaged(global) {
Ok(worker) => return GlobalUnrooted::Worker(worker),
Err(_) => (),
}
panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope")
}
}
| root | identifier_name |
global.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writing
//! code that works in workers as well as window scopes.
use dom::bindings::conversions::native_from_reflector_jsmanaged;
use dom::bindings::js::{JS, JSRef, Root, Unrooted};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers};
use dom::window::{self, WindowHelpers};
use devtools_traits::DevtoolsControlChan;
use script_task::{ScriptChan, ScriptPort, ScriptMsg, ScriptTask};
use msg::constellation_msg::{PipelineId, WorkerId};
use net_traits::ResourceTask;
use js::{JSCLASS_IS_GLOBAL, JSCLASS_IS_DOMJSCLASS};
use js::glue::{GetGlobalForObjectCrossCompartment};
use js::jsapi::{JSContext, JSObject};
use js::jsapi::{JS_GetClass};
use url::Url;
/// A freely-copyable reference to a rooted global object.
#[derive(Copy)]
pub enum GlobalRef<'a> {
/// A reference to a `Window` object.
Window(JSRef<'a, window::Window>),
/// A reference to a `WorkerGlobalScope` object.
Worker(JSRef<'a, WorkerGlobalScope>),
}
/// A stack-based rooted reference to a global object.
pub enum GlobalRoot {
/// A root for a `Window` object.
Window(Root<window::Window>),
/// A root for a `WorkerGlobalScope` object.
Worker(Root<WorkerGlobalScope>),
}
/// A traced reference to a global object, for use in fields of traced Rust
/// structures.
#[jstraceable]
#[must_root]
pub enum GlobalField {
/// A field for a `Window` object.
Window(JS<window::Window>),
/// A field for a `WorkerGlobalScope` object.
Worker(JS<WorkerGlobalScope>),
}
/// An unrooted reference to a global object.
#[must_root]
pub enum GlobalUnrooted {
/// An unrooted reference to a `Window` object.
Window(Unrooted<window::Window>),
/// An unrooted reference to a `WorkerGlobalScope` object.
Worker(Unrooted<WorkerGlobalScope>),
}
impl<'a> GlobalRef<'a> {
/// Get the `JSContext` for the `JSRuntime` associated with the thread
/// this global object is on.
pub fn get_cx(&self) -> *mut JSContext {
match *self {
GlobalRef::Window(ref window) => window.get_cx(),
GlobalRef::Worker(ref worker) => worker.get_cx(),
}
}
/// Extract a `Window`, causing task failure if the global object is not
/// a `Window`.
pub fn as_window<'b>(&'b self) -> JSRef<'b, window::Window> {
match *self {
GlobalRef::Window(window) => window,
GlobalRef::Worker(_) => panic!("expected a Window scope"),
}
}
/// Get the `PipelineId` for this global scope.
pub fn pipeline(&self) -> PipelineId {
match *self {
GlobalRef::Window(window) => window.pipeline(),
GlobalRef::Worker(worker) => worker.pipeline(),
}
}
/// Get `DevtoolsControlChan` to send messages to Devtools
/// task when available.
pub fn devtools_chan(&self) -> Option<DevtoolsControlChan> {
match *self {
GlobalRef::Window(window) => window.devtools_chan(),
GlobalRef::Worker(worker) => worker.devtools_chan(),
}
}
/// Get the `ResourceTask` for this global scope.
pub fn resource_task(&self) -> ResourceTask {
match *self {
GlobalRef::Window(ref window) => window.resource_task().clone(),
GlobalRef::Worker(ref worker) => worker.resource_task().clone(),
}
}
/// Get next worker id.
pub fn get_next_worker_id(&self) -> WorkerId {
match *self {
GlobalRef::Window(ref window) => window.get_next_worker_id(),
GlobalRef::Worker(ref worker) => worker.get_next_worker_id()
}
}
/// Get the URL for this global scope.
pub fn get_url(&self) -> Url {
match *self {
GlobalRef::Window(ref window) => window.get_url(),
GlobalRef::Worker(ref worker) => worker.get_url().clone(),
}
}
/// `ScriptChan` used to send messages to the event loop of this global's
/// thread.
pub fn script_chan(&self) -> Box<ScriptChan+Send> {
match *self {
GlobalRef::Window(ref window) => window.script_chan(),
GlobalRef::Worker(ref worker) => worker.script_chan(),
}
}
| match *self {
GlobalRef::Window(ref window) => window.new_script_pair(),
GlobalRef::Worker(ref worker) => worker.new_script_pair(),
}
}
/// Process a single event as if it were the next event in the task queue for
/// this global.
pub fn process_event(&self, msg: ScriptMsg) {
match *self {
GlobalRef::Window(_) => ScriptTask::process_event(msg),
GlobalRef::Worker(ref worker) => worker.process_event(msg),
}
}
}
impl<'a> Reflectable for GlobalRef<'a> {
fn reflector<'b>(&'b self) -> &'b Reflector {
match *self {
GlobalRef::Window(ref window) => window.reflector(),
GlobalRef::Worker(ref worker) => worker.reflector(),
}
}
}
impl GlobalRoot {
/// Obtain a safe reference to the global object that cannot outlive the
/// lifetime of this root.
pub fn r<'c>(&'c self) -> GlobalRef<'c> {
match *self {
GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()),
GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()),
}
}
}
impl GlobalField {
/// Create a new `GlobalField` from a rooted reference.
pub fn from_rooted(global: &GlobalRef) -> GlobalField {
match *global {
GlobalRef::Window(window) => GlobalField::Window(JS::from_rooted(window)),
GlobalRef::Worker(worker) => GlobalField::Worker(JS::from_rooted(worker)),
}
}
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
GlobalField::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalField::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
impl GlobalUnrooted {
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
GlobalUnrooted::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalUnrooted::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
/// Returns the global object of the realm that the given JS object was created in.
#[allow(unrooted_must_root)]
pub fn global_object_for_js_object(obj: *mut JSObject) -> GlobalUnrooted {
unsafe {
let global = GetGlobalForObjectCrossCompartment(obj);
let clasp = JS_GetClass(global);
assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0);
match native_from_reflector_jsmanaged(global) {
Ok(window) => return GlobalUnrooted::Window(window),
Err(_) => (),
}
match native_from_reflector_jsmanaged(global) {
Ok(worker) => return GlobalUnrooted::Worker(worker),
Err(_) => (),
}
panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope")
}
} | /// Create a new sender/receiver pair that can be used to implement an on-demand
/// event loop. Used for implementing web APIs that require blocking semantics
/// without resorting to nested event loops.
pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) { | random_line_split |
global.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writing
//! code that works in workers as well as window scopes.
use dom::bindings::conversions::native_from_reflector_jsmanaged;
use dom::bindings::js::{JS, JSRef, Root, Unrooted};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers};
use dom::window::{self, WindowHelpers};
use devtools_traits::DevtoolsControlChan;
use script_task::{ScriptChan, ScriptPort, ScriptMsg, ScriptTask};
use msg::constellation_msg::{PipelineId, WorkerId};
use net_traits::ResourceTask;
use js::{JSCLASS_IS_GLOBAL, JSCLASS_IS_DOMJSCLASS};
use js::glue::{GetGlobalForObjectCrossCompartment};
use js::jsapi::{JSContext, JSObject};
use js::jsapi::{JS_GetClass};
use url::Url;
/// A freely-copyable reference to a rooted global object.
#[derive(Copy)]
pub enum GlobalRef<'a> {
/// A reference to a `Window` object.
Window(JSRef<'a, window::Window>),
/// A reference to a `WorkerGlobalScope` object.
Worker(JSRef<'a, WorkerGlobalScope>),
}
/// A stack-based rooted reference to a global object.
pub enum GlobalRoot {
/// A root for a `Window` object.
Window(Root<window::Window>),
/// A root for a `WorkerGlobalScope` object.
Worker(Root<WorkerGlobalScope>),
}
/// A traced reference to a global object, for use in fields of traced Rust
/// structures.
#[jstraceable]
#[must_root]
pub enum GlobalField {
/// A field for a `Window` object.
Window(JS<window::Window>),
/// A field for a `WorkerGlobalScope` object.
Worker(JS<WorkerGlobalScope>),
}
/// An unrooted reference to a global object.
#[must_root]
pub enum GlobalUnrooted {
/// An unrooted reference to a `Window` object.
Window(Unrooted<window::Window>),
/// An unrooted reference to a `WorkerGlobalScope` object.
Worker(Unrooted<WorkerGlobalScope>),
}
impl<'a> GlobalRef<'a> {
/// Get the `JSContext` for the `JSRuntime` associated with the thread
/// this global object is on.
pub fn get_cx(&self) -> *mut JSContext {
match *self {
GlobalRef::Window(ref window) => window.get_cx(),
GlobalRef::Worker(ref worker) => worker.get_cx(),
}
}
/// Extract a `Window`, causing task failure if the global object is not
/// a `Window`.
pub fn as_window<'b>(&'b self) -> JSRef<'b, window::Window> {
match *self {
GlobalRef::Window(window) => window,
GlobalRef::Worker(_) => panic!("expected a Window scope"),
}
}
/// Get the `PipelineId` for this global scope.
pub fn pipeline(&self) -> PipelineId {
match *self {
GlobalRef::Window(window) => window.pipeline(),
GlobalRef::Worker(worker) => worker.pipeline(),
}
}
/// Get `DevtoolsControlChan` to send messages to Devtools
/// task when available.
pub fn devtools_chan(&self) -> Option<DevtoolsControlChan> {
match *self {
GlobalRef::Window(window) => window.devtools_chan(),
GlobalRef::Worker(worker) => worker.devtools_chan(),
}
}
/// Get the `ResourceTask` for this global scope.
pub fn resource_task(&self) -> ResourceTask {
match *self {
GlobalRef::Window(ref window) => window.resource_task().clone(),
GlobalRef::Worker(ref worker) => worker.resource_task().clone(),
}
}
/// Get next worker id.
pub fn get_next_worker_id(&self) -> WorkerId {
match *self {
GlobalRef::Window(ref window) => window.get_next_worker_id(),
GlobalRef::Worker(ref worker) => worker.get_next_worker_id()
}
}
/// Get the URL for this global scope.
pub fn get_url(&self) -> Url {
match *self {
GlobalRef::Window(ref window) => window.get_url(),
GlobalRef::Worker(ref worker) => worker.get_url().clone(),
}
}
/// `ScriptChan` used to send messages to the event loop of this global's
/// thread.
pub fn script_chan(&self) -> Box<ScriptChan+Send> {
match *self {
GlobalRef::Window(ref window) => window.script_chan(),
GlobalRef::Worker(ref worker) => worker.script_chan(),
}
}
/// Create a new sender/receiver pair that can be used to implement an on-demand
/// event loop. Used for implementing web APIs that require blocking semantics
/// without resorting to nested event loops.
pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) |
/// Process a single event as if it were the next event in the task queue for
/// this global.
pub fn process_event(&self, msg: ScriptMsg) {
match *self {
GlobalRef::Window(_) => ScriptTask::process_event(msg),
GlobalRef::Worker(ref worker) => worker.process_event(msg),
}
}
}
impl<'a> Reflectable for GlobalRef<'a> {
fn reflector<'b>(&'b self) -> &'b Reflector {
match *self {
GlobalRef::Window(ref window) => window.reflector(),
GlobalRef::Worker(ref worker) => worker.reflector(),
}
}
}
impl GlobalRoot {
/// Obtain a safe reference to the global object that cannot outlive the
/// lifetime of this root.
pub fn r<'c>(&'c self) -> GlobalRef<'c> {
match *self {
GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()),
GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()),
}
}
}
impl GlobalField {
/// Create a new `GlobalField` from a rooted reference.
pub fn from_rooted(global: &GlobalRef) -> GlobalField {
match *global {
GlobalRef::Window(window) => GlobalField::Window(JS::from_rooted(window)),
GlobalRef::Worker(worker) => GlobalField::Worker(JS::from_rooted(worker)),
}
}
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
GlobalField::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalField::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
impl GlobalUnrooted {
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
GlobalUnrooted::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalUnrooted::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
/// Returns the global object of the realm that the given JS object was created in.
#[allow(unrooted_must_root)]
pub fn global_object_for_js_object(obj: *mut JSObject) -> GlobalUnrooted {
unsafe {
let global = GetGlobalForObjectCrossCompartment(obj);
let clasp = JS_GetClass(global);
assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0);
match native_from_reflector_jsmanaged(global) {
Ok(window) => return GlobalUnrooted::Window(window),
Err(_) => (),
}
match native_from_reflector_jsmanaged(global) {
Ok(worker) => return GlobalUnrooted::Worker(worker),
Err(_) => (),
}
panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope")
}
}
| {
match *self {
GlobalRef::Window(ref window) => window.new_script_pair(),
GlobalRef::Worker(ref worker) => worker.new_script_pair(),
}
} | identifier_body |
ngb-calendar-islamic-umalqura.ts | import {NgbCalendarIslamicCivil} from './ngb-calendar-islamic-civil';
import {NgbDate} from '../ngb-date';
import {Injectable} from '@angular/core';
/**
* Umalqura calendar is one type of Hijri calendars used in islamic countries.
* This Calendar is used by Saudi Arabia for administrative purpose.
* Unlike tabular calendars, the algorithm involves astronomical calculation, but it's still deterministic.
* http://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types
*/
const GREGORIAN_FIRST_DATE = new Date(1882, 10, 12);
const GREGORIAN_LAST_DATE = new Date(2174, 10, 25);
const HIJRI_BEGIN = 1300;
const HIJRI_END = 1600;
const ONE_DAY = 1000 * 60 * 60 * 24;
const MONTH_LENGTH = [
// 1300-1304
'101010101010', '110101010100', '111011001001', '011011010100', '011011101010',
// 1305-1309
'001101101100', '101010101101', '010101010101', '011010101001', '011110010010',
// 1310-1314
'101110101001', '010111010100', '101011011010', '010101011100', '110100101101',
// 1315-1319
'011010010101', '011101001010', '101101010100', '101101101010', '010110101101',
// 1320-1324
'010010101110', '101001001111', '010100010111', '011010001011', '011010100101',
// 1325-1329
'101011010101', '001011010110', '100101011011', '010010011101', '101001001101',
// 1330-1334
'110100100110', '110110010101', '010110101100', '100110110110', '001010111010',
// 1335-1339
'101001011011', '010100101011', '101010010101', '011011001010', '101011101001',
// 1340-1344
'001011110100', '100101110110', '001010110110', '100101010110', '101011001010',
// 1345-1349
'101110100100', '101111010010', '010111011001', '001011011100', '100101101101',
// 1350-1354
'010101001101', '101010100101', '101101010010', '101110100101', '010110110100',
// 1355-1359
'100110110110', '010101010111', '001010010111', '010101001011', '011010100011',
// 1360-1364
'011101010010', '101101100101', '010101101010', '101010101011', '010100101011',
// 1365-1369
'110010010101', '110101001010', '110110100101', '010111001010', '101011010110',
// 1370-1374
'100101010111', '010010101011', '100101001011', '101010100101', '101101010010',
// 1375-1379
'101101101010', '010101110101', '001001110110', '100010110111', '010001011011',
// 1380-1384
'010101010101', '010110101001', '010110110100', '100111011010', '010011011101',
// 1385-1389
'001001101110', '100100110110', '101010101010', '110101010100', '110110110010',
// 1390-1394
'010111010101', '001011011010', '100101011011', '010010101011', '101001010101',
// 1395-1399
'101101001001', '101101100100', '101101110001', '010110110100', '101010110101',
// 1400-1404
'101001010101', '110100100101', '111010010010', '111011001001', '011011010100',
// 1405-1409
'101011101001', '100101101011', '010010101011', '101010010011', '110101001001',
// 1410-1414
'110110100100', '110110110010', '101010111001', '010010111010', '101001011011',
// 1415-1419
'010100101011', '101010010101', '101100101010', '101101010101', '010101011100',
// 1420-1424
'010010111101', '001000111101', '100100011101', '101010010101', '101101001010',
// 1425-1429
'101101011010', '010101101101', '001010110110', '100100111011', '010010011011',
// 1430-1434
'011001010101', '011010101001', '011101010100', '101101101010', '010101101100',
// 1435-1439
'101010101101', '010101010101', '101100101001', '101110010010', '101110101001',
// 1440-1444
'010111010100', '101011011010', '010101011010', '101010101011', '010110010101',
// 1445-1449
'011101001001', '011101100100', '101110101010', '010110110101', '001010110110',
// 1450-1454
'101001010110', '111001001101', '101100100101', '101101010010', '101101101010',
// 1455-1459
'010110101101', '001010101110', '100100101111', '010010010111', '011001001011',
// 1460-1464
'011010100101', '011010101100', '101011010110', '010101011101', '010010011101',
// 1465-1469
'101001001101', '110100010110', '110110010101', '010110101010', '010110110101',
// 1470-1474
'001011011010', '100101011011', '010010101101', '010110010101', '011011001010',
// 1475-1479
'011011100100', '101011101010', '010011110101', '001010110110', '100101010110',
// 1480-1484
'101010101010', '101101010100', '101111010010', '010111011001', '001011101010',
// 1485-1489
'100101101101', '010010101101', '101010010101', '101101001010', '101110100101',
// 1490-1494
'010110110010', '100110110101', '010011010110', '101010010111', '010101000111',
// 1495-1499
'011010010011', '011101001001', '101101010101', '010101101010', '101001101011',
// 1500-1504
'010100101011', '101010001011', '110101000110', '110110100011', '010111001010',
// 1505-1509
'101011010110', '010011011011', '001001101011', '100101001011', '101010100101',
// 1510-1514
'101101010010', '101101101001', '010101110101', '000101110110', '100010110111',
// 1515-1519
'001001011011', '010100101011', '010101100101', '010110110100', '100111011010',
// 1520-1524
'010011101101', '000101101101', '100010110110', '101010100110', '110101010010',
// 1525-1529
'110110101001', '010111010100', '101011011010', '100101011011', '010010101011',
// 1530-1534
'011001010011', '011100101001', '011101100010', '101110101001', '010110110010',
// 1535-1539
'101010110101', '010101010101', '101100100101', '110110010010', '111011001001',
// 1540-1544
'011011010010', '101011101001', '010101101011', '010010101011', '101001010101',
// 1545-1549
'110100101001', '110101010100', '110110101010', '100110110101', '010010111010',
// 1550-1554
'101000111011', '010010011011', '101001001101', '101010101010', '101011010101',
// 1555-1559
'001011011010', '100101011101', '010001011110', '101000101110', '110010011010',
// 1560-1564
'110101010101', '011010110010', '011010111001', '010010111010', '101001011101',
// 1565-1569
'010100101101', '101010010101', '101101010010', '101110101000', '101110110100',
// 1570-1574
'010110111001', '001011011010', '100101011010', '101101001010', '110110100100',
// 1575-1579
'111011010001', '011011101000', '101101101010', '010101101101', '010100110101',
// 1580-1584
'011010010101', '110101001010', '110110101000', '110111010100', '011011011010',
// 1585-1589
'010101011011', '001010011101', '011000101011', '101100010101', '101101001010',
// 1590-1594
'101110010101', '010110101010', '101010101110', '100100101110', '110010001111',
// 1595-1599
'010100100111', '011010010101', '011010101010', '101011010110', '010101011101',
// 1600
'001010011101'
];
function getDaysDiff(date1: Date, date2: Date): number {
const diff = Math.abs(date1.getTime() - date2.getTime());
return Math.round(diff / ONE_DAY);
}
@Injectable()
export class | extends NgbCalendarIslamicCivil {
/**
* Returns the equivalent islamic(Umalqura) date value for a give input Gregorian date.
* `gdate` is s JS Date to be converted to Hijri.
*/
fromGregorian(gDate: Date): NgbDate {
let hDay = 1, hMonth = 0, hYear = 1300;
let daysDiff = getDaysDiff(gDate, GREGORIAN_FIRST_DATE);
if (gDate.getTime() - GREGORIAN_FIRST_DATE.getTime() >= 0 && gDate.getTime() - GREGORIAN_LAST_DATE.getTime() <= 0) {
let year = 1300;
for (let i = 0; i < MONTH_LENGTH.length; i++, year++) {
for (let j = 0; j < 12; j++) {
let numOfDays = +MONTH_LENGTH[i][j] + 29;
if (daysDiff <= numOfDays) {
hDay = daysDiff + 1;
if (hDay > numOfDays) {
hDay = 1;
j++;
}
if (j > 11) {
j = 0;
year++;
}
hMonth = j;
hYear = year;
return new NgbDate(hYear, hMonth + 1, hDay);
}
daysDiff = daysDiff - numOfDays;
}
}
} else {
return super.fromGregorian(gDate);
}
}
/**
* Converts the current Hijri date to Gregorian.
*/
toGregorian(hDate: NgbDate): Date {
const hYear = hDate.year;
const hMonth = hDate.month - 1;
const hDay = hDate.day;
let gDate = new Date(GREGORIAN_FIRST_DATE);
let dayDiff = hDay - 1;
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) {
for (let y = 0; y < hYear - HIJRI_BEGIN; y++) {
for (let m = 0; m < 12; m++) {
dayDiff += +MONTH_LENGTH[y][m] + 29;
}
}
for (let m = 0; m < hMonth; m++) {
dayDiff += +MONTH_LENGTH[hYear - HIJRI_BEGIN][m] + 29;
}
gDate.setDate(GREGORIAN_FIRST_DATE.getDate() + dayDiff);
} else {
gDate = super.toGregorian(hDate);
}
return gDate;
}
/**
* Returns the number of days in a specific Hijri hMonth.
* `hMonth` is 1 for Muharram, 2 for Safar, etc.
* `hYear` is any Hijri hYear.
*/
getDaysPerMonth(hMonth: number, hYear: number): number {
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) {
const pos = hYear - HIJRI_BEGIN;
return +MONTH_LENGTH[pos][hMonth - 1] + 29;
}
return super.getDaysPerMonth(hMonth, hYear);
}
}
| NgbCalendarIslamicUmalqura | identifier_name |
ngb-calendar-islamic-umalqura.ts | import {NgbCalendarIslamicCivil} from './ngb-calendar-islamic-civil';
import {NgbDate} from '../ngb-date';
import {Injectable} from '@angular/core';
/**
* Umalqura calendar is one type of Hijri calendars used in islamic countries.
* This Calendar is used by Saudi Arabia for administrative purpose.
* Unlike tabular calendars, the algorithm involves astronomical calculation, but it's still deterministic.
* http://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types
*/
const GREGORIAN_FIRST_DATE = new Date(1882, 10, 12);
const GREGORIAN_LAST_DATE = new Date(2174, 10, 25);
const HIJRI_BEGIN = 1300;
const HIJRI_END = 1600;
const ONE_DAY = 1000 * 60 * 60 * 24;
const MONTH_LENGTH = [
// 1300-1304
'101010101010', '110101010100', '111011001001', '011011010100', '011011101010',
// 1305-1309
'001101101100', '101010101101', '010101010101', '011010101001', '011110010010',
// 1310-1314
'101110101001', '010111010100', '101011011010', '010101011100', '110100101101',
// 1315-1319
'011010010101', '011101001010', '101101010100', '101101101010', '010110101101',
// 1320-1324
'010010101110', '101001001111', '010100010111', '011010001011', '011010100101',
// 1325-1329
'101011010101', '001011010110', '100101011011', '010010011101', '101001001101',
// 1330-1334
'110100100110', '110110010101', '010110101100', '100110110110', '001010111010',
// 1335-1339
'101001011011', '010100101011', '101010010101', '011011001010', '101011101001',
// 1340-1344
'001011110100', '100101110110', '001010110110', '100101010110', '101011001010',
// 1345-1349
'101110100100', '101111010010', '010111011001', '001011011100', '100101101101',
// 1350-1354
'010101001101', '101010100101', '101101010010', '101110100101', '010110110100',
// 1355-1359
'100110110110', '010101010111', '001010010111', '010101001011', '011010100011',
// 1360-1364
'011101010010', '101101100101', '010101101010', '101010101011', '010100101011',
// 1365-1369
'110010010101', '110101001010', '110110100101', '010111001010', '101011010110',
// 1370-1374
'100101010111', '010010101011', '100101001011', '101010100101', '101101010010',
// 1375-1379
'101101101010', '010101110101', '001001110110', '100010110111', '010001011011',
// 1380-1384
'010101010101', '010110101001', '010110110100', '100111011010', '010011011101',
// 1385-1389
'001001101110', '100100110110', '101010101010', '110101010100', '110110110010',
// 1390-1394
'010111010101', '001011011010', '100101011011', '010010101011', '101001010101',
// 1395-1399
'101101001001', '101101100100', '101101110001', '010110110100', '101010110101',
// 1400-1404
'101001010101', '110100100101', '111010010010', '111011001001', '011011010100',
// 1405-1409
'101011101001', '100101101011', '010010101011', '101010010011', '110101001001',
// 1410-1414
'110110100100', '110110110010', '101010111001', '010010111010', '101001011011',
// 1415-1419
'010100101011', '101010010101', '101100101010', '101101010101', '010101011100',
// 1420-1424
'010010111101', '001000111101', '100100011101', '101010010101', '101101001010',
// 1425-1429
'101101011010', '010101101101', '001010110110', '100100111011', '010010011011',
// 1430-1434
'011001010101', '011010101001', '011101010100', '101101101010', '010101101100',
// 1435-1439
'101010101101', '010101010101', '101100101001', '101110010010', '101110101001',
// 1440-1444
'010111010100', '101011011010', '010101011010', '101010101011', '010110010101',
// 1445-1449
'011101001001', '011101100100', '101110101010', '010110110101', '001010110110',
// 1450-1454
'101001010110', '111001001101', '101100100101', '101101010010', '101101101010',
// 1455-1459
'010110101101', '001010101110', '100100101111', '010010010111', '011001001011',
// 1460-1464
'011010100101', '011010101100', '101011010110', '010101011101', '010010011101',
// 1465-1469
'101001001101', '110100010110', '110110010101', '010110101010', '010110110101',
// 1470-1474
'001011011010', '100101011011', '010010101101', '010110010101', '011011001010',
// 1475-1479
'011011100100', '101011101010', '010011110101', '001010110110', '100101010110',
// 1480-1484
'101010101010', '101101010100', '101111010010', '010111011001', '001011101010',
// 1485-1489
'100101101101', '010010101101', '101010010101', '101101001010', '101110100101',
// 1490-1494
'010110110010', '100110110101', '010011010110', '101010010111', '010101000111',
// 1495-1499
'011010010011', '011101001001', '101101010101', '010101101010', '101001101011',
// 1500-1504
'010100101011', '101010001011', '110101000110', '110110100011', '010111001010',
// 1505-1509
'101011010110', '010011011011', '001001101011', '100101001011', '101010100101',
// 1510-1514
'101101010010', '101101101001', '010101110101', '000101110110', '100010110111',
// 1515-1519
'001001011011', '010100101011', '010101100101', '010110110100', '100111011010',
// 1520-1524
'010011101101', '000101101101', '100010110110', '101010100110', '110101010010',
// 1525-1529
'110110101001', '010111010100', '101011011010', '100101011011', '010010101011',
// 1530-1534
'011001010011', '011100101001', '011101100010', '101110101001', '010110110010',
// 1535-1539
'101010110101', '010101010101', '101100100101', '110110010010', '111011001001',
// 1540-1544
'011011010010', '101011101001', '010101101011', '010010101011', '101001010101',
// 1545-1549
'110100101001', '110101010100', '110110101010', '100110110101', '010010111010',
// 1550-1554
'101000111011', '010010011011', '101001001101', '101010101010', '101011010101',
// 1555-1559
'001011011010', '100101011101', '010001011110', '101000101110', '110010011010',
// 1560-1564
'110101010101', '011010110010', '011010111001', '010010111010', '101001011101',
// 1565-1569
'010100101101', '101010010101', '101101010010', '101110101000', '101110110100',
// 1570-1574
'010110111001', '001011011010', '100101011010', '101101001010', '110110100100',
// 1575-1579
'111011010001', '011011101000', '101101101010', '010101101101', '010100110101',
// 1580-1584
'011010010101', '110101001010', '110110101000', '110111010100', '011011011010',
// 1585-1589
'010101011011', '001010011101', '011000101011', '101100010101', '101101001010',
// 1590-1594
'101110010101', '010110101010', '101010101110', '100100101110', '110010001111',
// 1595-1599
'010100100111', '011010010101', '011010101010', '101011010110', '010101011101',
// 1600
'001010011101'
];
function getDaysDiff(date1: Date, date2: Date): number {
const diff = Math.abs(date1.getTime() - date2.getTime());
return Math.round(diff / ONE_DAY);
}
@Injectable()
export class NgbCalendarIslamicUmalqura extends NgbCalendarIslamicCivil {
/**
* Returns the equivalent islamic(Umalqura) date value for a give input Gregorian date.
* `gdate` is s JS Date to be converted to Hijri.
*/
fromGregorian(gDate: Date): NgbDate {
let hDay = 1, hMonth = 0, hYear = 1300;
let daysDiff = getDaysDiff(gDate, GREGORIAN_FIRST_DATE);
if (gDate.getTime() - GREGORIAN_FIRST_DATE.getTime() >= 0 && gDate.getTime() - GREGORIAN_LAST_DATE.getTime() <= 0) {
let year = 1300;
for (let i = 0; i < MONTH_LENGTH.length; i++, year++) {
for (let j = 0; j < 12; j++) {
let numOfDays = +MONTH_LENGTH[i][j] + 29;
if (daysDiff <= numOfDays) {
hDay = daysDiff + 1;
if (hDay > numOfDays) {
hDay = 1;
j++;
}
if (j > 11) {
j = 0;
year++;
}
hMonth = j;
hYear = year;
return new NgbDate(hYear, hMonth + 1, hDay);
}
daysDiff = daysDiff - numOfDays;
}
}
} else {
return super.fromGregorian(gDate);
}
}
/**
* Converts the current Hijri date to Gregorian.
*/
toGregorian(hDate: NgbDate): Date {
const hYear = hDate.year;
const hMonth = hDate.month - 1;
const hDay = hDate.day;
let gDate = new Date(GREGORIAN_FIRST_DATE);
let dayDiff = hDay - 1;
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) {
for (let y = 0; y < hYear - HIJRI_BEGIN; y++) {
for (let m = 0; m < 12; m++) {
dayDiff += +MONTH_LENGTH[y][m] + 29;
}
}
for (let m = 0; m < hMonth; m++) {
dayDiff += +MONTH_LENGTH[hYear - HIJRI_BEGIN][m] + 29;
}
gDate.setDate(GREGORIAN_FIRST_DATE.getDate() + dayDiff);
} else {
gDate = super.toGregorian(hDate);
}
return gDate;
}
/**
* Returns the number of days in a specific Hijri hMonth.
* `hMonth` is 1 for Muharram, 2 for Safar, etc.
* `hYear` is any Hijri hYear.
*/
getDaysPerMonth(hMonth: number, hYear: number): number {
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) |
return super.getDaysPerMonth(hMonth, hYear);
}
}
| {
const pos = hYear - HIJRI_BEGIN;
return +MONTH_LENGTH[pos][hMonth - 1] + 29;
} | conditional_block |
ngb-calendar-islamic-umalqura.ts | import {NgbCalendarIslamicCivil} from './ngb-calendar-islamic-civil';
import {NgbDate} from '../ngb-date';
import {Injectable} from '@angular/core';
/**
* Umalqura calendar is one type of Hijri calendars used in islamic countries.
* This Calendar is used by Saudi Arabia for administrative purpose.
* Unlike tabular calendars, the algorithm involves astronomical calculation, but it's still deterministic.
* http://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types
*/
const GREGORIAN_FIRST_DATE = new Date(1882, 10, 12);
const GREGORIAN_LAST_DATE = new Date(2174, 10, 25);
const HIJRI_BEGIN = 1300;
const HIJRI_END = 1600;
const ONE_DAY = 1000 * 60 * 60 * 24;
const MONTH_LENGTH = [
// 1300-1304
'101010101010', '110101010100', '111011001001', '011011010100', '011011101010', | // 1305-1309
'001101101100', '101010101101', '010101010101', '011010101001', '011110010010',
// 1310-1314
'101110101001', '010111010100', '101011011010', '010101011100', '110100101101',
// 1315-1319
'011010010101', '011101001010', '101101010100', '101101101010', '010110101101',
// 1320-1324
'010010101110', '101001001111', '010100010111', '011010001011', '011010100101',
// 1325-1329
'101011010101', '001011010110', '100101011011', '010010011101', '101001001101',
// 1330-1334
'110100100110', '110110010101', '010110101100', '100110110110', '001010111010',
// 1335-1339
'101001011011', '010100101011', '101010010101', '011011001010', '101011101001',
// 1340-1344
'001011110100', '100101110110', '001010110110', '100101010110', '101011001010',
// 1345-1349
'101110100100', '101111010010', '010111011001', '001011011100', '100101101101',
// 1350-1354
'010101001101', '101010100101', '101101010010', '101110100101', '010110110100',
// 1355-1359
'100110110110', '010101010111', '001010010111', '010101001011', '011010100011',
// 1360-1364
'011101010010', '101101100101', '010101101010', '101010101011', '010100101011',
// 1365-1369
'110010010101', '110101001010', '110110100101', '010111001010', '101011010110',
// 1370-1374
'100101010111', '010010101011', '100101001011', '101010100101', '101101010010',
// 1375-1379
'101101101010', '010101110101', '001001110110', '100010110111', '010001011011',
// 1380-1384
'010101010101', '010110101001', '010110110100', '100111011010', '010011011101',
// 1385-1389
'001001101110', '100100110110', '101010101010', '110101010100', '110110110010',
// 1390-1394
'010111010101', '001011011010', '100101011011', '010010101011', '101001010101',
// 1395-1399
'101101001001', '101101100100', '101101110001', '010110110100', '101010110101',
// 1400-1404
'101001010101', '110100100101', '111010010010', '111011001001', '011011010100',
// 1405-1409
'101011101001', '100101101011', '010010101011', '101010010011', '110101001001',
// 1410-1414
'110110100100', '110110110010', '101010111001', '010010111010', '101001011011',
// 1415-1419
'010100101011', '101010010101', '101100101010', '101101010101', '010101011100',
// 1420-1424
'010010111101', '001000111101', '100100011101', '101010010101', '101101001010',
// 1425-1429
'101101011010', '010101101101', '001010110110', '100100111011', '010010011011',
// 1430-1434
'011001010101', '011010101001', '011101010100', '101101101010', '010101101100',
// 1435-1439
'101010101101', '010101010101', '101100101001', '101110010010', '101110101001',
// 1440-1444
'010111010100', '101011011010', '010101011010', '101010101011', '010110010101',
// 1445-1449
'011101001001', '011101100100', '101110101010', '010110110101', '001010110110',
// 1450-1454
'101001010110', '111001001101', '101100100101', '101101010010', '101101101010',
// 1455-1459
'010110101101', '001010101110', '100100101111', '010010010111', '011001001011',
// 1460-1464
'011010100101', '011010101100', '101011010110', '010101011101', '010010011101',
// 1465-1469
'101001001101', '110100010110', '110110010101', '010110101010', '010110110101',
// 1470-1474
'001011011010', '100101011011', '010010101101', '010110010101', '011011001010',
// 1475-1479
'011011100100', '101011101010', '010011110101', '001010110110', '100101010110',
// 1480-1484
'101010101010', '101101010100', '101111010010', '010111011001', '001011101010',
// 1485-1489
'100101101101', '010010101101', '101010010101', '101101001010', '101110100101',
// 1490-1494
'010110110010', '100110110101', '010011010110', '101010010111', '010101000111',
// 1495-1499
'011010010011', '011101001001', '101101010101', '010101101010', '101001101011',
// 1500-1504
'010100101011', '101010001011', '110101000110', '110110100011', '010111001010',
// 1505-1509
'101011010110', '010011011011', '001001101011', '100101001011', '101010100101',
// 1510-1514
'101101010010', '101101101001', '010101110101', '000101110110', '100010110111',
// 1515-1519
'001001011011', '010100101011', '010101100101', '010110110100', '100111011010',
// 1520-1524
'010011101101', '000101101101', '100010110110', '101010100110', '110101010010',
// 1525-1529
'110110101001', '010111010100', '101011011010', '100101011011', '010010101011',
// 1530-1534
'011001010011', '011100101001', '011101100010', '101110101001', '010110110010',
// 1535-1539
'101010110101', '010101010101', '101100100101', '110110010010', '111011001001',
// 1540-1544
'011011010010', '101011101001', '010101101011', '010010101011', '101001010101',
// 1545-1549
'110100101001', '110101010100', '110110101010', '100110110101', '010010111010',
// 1550-1554
'101000111011', '010010011011', '101001001101', '101010101010', '101011010101',
// 1555-1559
'001011011010', '100101011101', '010001011110', '101000101110', '110010011010',
// 1560-1564
'110101010101', '011010110010', '011010111001', '010010111010', '101001011101',
// 1565-1569
'010100101101', '101010010101', '101101010010', '101110101000', '101110110100',
// 1570-1574
'010110111001', '001011011010', '100101011010', '101101001010', '110110100100',
// 1575-1579
'111011010001', '011011101000', '101101101010', '010101101101', '010100110101',
// 1580-1584
'011010010101', '110101001010', '110110101000', '110111010100', '011011011010',
// 1585-1589
'010101011011', '001010011101', '011000101011', '101100010101', '101101001010',
// 1590-1594
'101110010101', '010110101010', '101010101110', '100100101110', '110010001111',
// 1595-1599
'010100100111', '011010010101', '011010101010', '101011010110', '010101011101',
// 1600
'001010011101'
];
function getDaysDiff(date1: Date, date2: Date): number {
const diff = Math.abs(date1.getTime() - date2.getTime());
return Math.round(diff / ONE_DAY);
}
@Injectable()
export class NgbCalendarIslamicUmalqura extends NgbCalendarIslamicCivil {
/**
* Returns the equivalent islamic(Umalqura) date value for a give input Gregorian date.
* `gdate` is s JS Date to be converted to Hijri.
*/
fromGregorian(gDate: Date): NgbDate {
let hDay = 1, hMonth = 0, hYear = 1300;
let daysDiff = getDaysDiff(gDate, GREGORIAN_FIRST_DATE);
if (gDate.getTime() - GREGORIAN_FIRST_DATE.getTime() >= 0 && gDate.getTime() - GREGORIAN_LAST_DATE.getTime() <= 0) {
let year = 1300;
for (let i = 0; i < MONTH_LENGTH.length; i++, year++) {
for (let j = 0; j < 12; j++) {
let numOfDays = +MONTH_LENGTH[i][j] + 29;
if (daysDiff <= numOfDays) {
hDay = daysDiff + 1;
if (hDay > numOfDays) {
hDay = 1;
j++;
}
if (j > 11) {
j = 0;
year++;
}
hMonth = j;
hYear = year;
return new NgbDate(hYear, hMonth + 1, hDay);
}
daysDiff = daysDiff - numOfDays;
}
}
} else {
return super.fromGregorian(gDate);
}
}
/**
* Converts the current Hijri date to Gregorian.
*/
toGregorian(hDate: NgbDate): Date {
const hYear = hDate.year;
const hMonth = hDate.month - 1;
const hDay = hDate.day;
let gDate = new Date(GREGORIAN_FIRST_DATE);
let dayDiff = hDay - 1;
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) {
for (let y = 0; y < hYear - HIJRI_BEGIN; y++) {
for (let m = 0; m < 12; m++) {
dayDiff += +MONTH_LENGTH[y][m] + 29;
}
}
for (let m = 0; m < hMonth; m++) {
dayDiff += +MONTH_LENGTH[hYear - HIJRI_BEGIN][m] + 29;
}
gDate.setDate(GREGORIAN_FIRST_DATE.getDate() + dayDiff);
} else {
gDate = super.toGregorian(hDate);
}
return gDate;
}
/**
* Returns the number of days in a specific Hijri hMonth.
* `hMonth` is 1 for Muharram, 2 for Safar, etc.
* `hYear` is any Hijri hYear.
*/
getDaysPerMonth(hMonth: number, hYear: number): number {
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) {
const pos = hYear - HIJRI_BEGIN;
return +MONTH_LENGTH[pos][hMonth - 1] + 29;
}
return super.getDaysPerMonth(hMonth, hYear);
}
} | random_line_split | |
ngb-calendar-islamic-umalqura.ts | import {NgbCalendarIslamicCivil} from './ngb-calendar-islamic-civil';
import {NgbDate} from '../ngb-date';
import {Injectable} from '@angular/core';
/**
* Umalqura calendar is one type of Hijri calendars used in islamic countries.
* This Calendar is used by Saudi Arabia for administrative purpose.
* Unlike tabular calendars, the algorithm involves astronomical calculation, but it's still deterministic.
* http://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types
*/
const GREGORIAN_FIRST_DATE = new Date(1882, 10, 12);
const GREGORIAN_LAST_DATE = new Date(2174, 10, 25);
const HIJRI_BEGIN = 1300;
const HIJRI_END = 1600;
const ONE_DAY = 1000 * 60 * 60 * 24;
const MONTH_LENGTH = [
// 1300-1304
'101010101010', '110101010100', '111011001001', '011011010100', '011011101010',
// 1305-1309
'001101101100', '101010101101', '010101010101', '011010101001', '011110010010',
// 1310-1314
'101110101001', '010111010100', '101011011010', '010101011100', '110100101101',
// 1315-1319
'011010010101', '011101001010', '101101010100', '101101101010', '010110101101',
// 1320-1324
'010010101110', '101001001111', '010100010111', '011010001011', '011010100101',
// 1325-1329
'101011010101', '001011010110', '100101011011', '010010011101', '101001001101',
// 1330-1334
'110100100110', '110110010101', '010110101100', '100110110110', '001010111010',
// 1335-1339
'101001011011', '010100101011', '101010010101', '011011001010', '101011101001',
// 1340-1344
'001011110100', '100101110110', '001010110110', '100101010110', '101011001010',
// 1345-1349
'101110100100', '101111010010', '010111011001', '001011011100', '100101101101',
// 1350-1354
'010101001101', '101010100101', '101101010010', '101110100101', '010110110100',
// 1355-1359
'100110110110', '010101010111', '001010010111', '010101001011', '011010100011',
// 1360-1364
'011101010010', '101101100101', '010101101010', '101010101011', '010100101011',
// 1365-1369
'110010010101', '110101001010', '110110100101', '010111001010', '101011010110',
// 1370-1374
'100101010111', '010010101011', '100101001011', '101010100101', '101101010010',
// 1375-1379
'101101101010', '010101110101', '001001110110', '100010110111', '010001011011',
// 1380-1384
'010101010101', '010110101001', '010110110100', '100111011010', '010011011101',
// 1385-1389
'001001101110', '100100110110', '101010101010', '110101010100', '110110110010',
// 1390-1394
'010111010101', '001011011010', '100101011011', '010010101011', '101001010101',
// 1395-1399
'101101001001', '101101100100', '101101110001', '010110110100', '101010110101',
// 1400-1404
'101001010101', '110100100101', '111010010010', '111011001001', '011011010100',
// 1405-1409
'101011101001', '100101101011', '010010101011', '101010010011', '110101001001',
// 1410-1414
'110110100100', '110110110010', '101010111001', '010010111010', '101001011011',
// 1415-1419
'010100101011', '101010010101', '101100101010', '101101010101', '010101011100',
// 1420-1424
'010010111101', '001000111101', '100100011101', '101010010101', '101101001010',
// 1425-1429
'101101011010', '010101101101', '001010110110', '100100111011', '010010011011',
// 1430-1434
'011001010101', '011010101001', '011101010100', '101101101010', '010101101100',
// 1435-1439
'101010101101', '010101010101', '101100101001', '101110010010', '101110101001',
// 1440-1444
'010111010100', '101011011010', '010101011010', '101010101011', '010110010101',
// 1445-1449
'011101001001', '011101100100', '101110101010', '010110110101', '001010110110',
// 1450-1454
'101001010110', '111001001101', '101100100101', '101101010010', '101101101010',
// 1455-1459
'010110101101', '001010101110', '100100101111', '010010010111', '011001001011',
// 1460-1464
'011010100101', '011010101100', '101011010110', '010101011101', '010010011101',
// 1465-1469
'101001001101', '110100010110', '110110010101', '010110101010', '010110110101',
// 1470-1474
'001011011010', '100101011011', '010010101101', '010110010101', '011011001010',
// 1475-1479
'011011100100', '101011101010', '010011110101', '001010110110', '100101010110',
// 1480-1484
'101010101010', '101101010100', '101111010010', '010111011001', '001011101010',
// 1485-1489
'100101101101', '010010101101', '101010010101', '101101001010', '101110100101',
// 1490-1494
'010110110010', '100110110101', '010011010110', '101010010111', '010101000111',
// 1495-1499
'011010010011', '011101001001', '101101010101', '010101101010', '101001101011',
// 1500-1504
'010100101011', '101010001011', '110101000110', '110110100011', '010111001010',
// 1505-1509
'101011010110', '010011011011', '001001101011', '100101001011', '101010100101',
// 1510-1514
'101101010010', '101101101001', '010101110101', '000101110110', '100010110111',
// 1515-1519
'001001011011', '010100101011', '010101100101', '010110110100', '100111011010',
// 1520-1524
'010011101101', '000101101101', '100010110110', '101010100110', '110101010010',
// 1525-1529
'110110101001', '010111010100', '101011011010', '100101011011', '010010101011',
// 1530-1534
'011001010011', '011100101001', '011101100010', '101110101001', '010110110010',
// 1535-1539
'101010110101', '010101010101', '101100100101', '110110010010', '111011001001',
// 1540-1544
'011011010010', '101011101001', '010101101011', '010010101011', '101001010101',
// 1545-1549
'110100101001', '110101010100', '110110101010', '100110110101', '010010111010',
// 1550-1554
'101000111011', '010010011011', '101001001101', '101010101010', '101011010101',
// 1555-1559
'001011011010', '100101011101', '010001011110', '101000101110', '110010011010',
// 1560-1564
'110101010101', '011010110010', '011010111001', '010010111010', '101001011101',
// 1565-1569
'010100101101', '101010010101', '101101010010', '101110101000', '101110110100',
// 1570-1574
'010110111001', '001011011010', '100101011010', '101101001010', '110110100100',
// 1575-1579
'111011010001', '011011101000', '101101101010', '010101101101', '010100110101',
// 1580-1584
'011010010101', '110101001010', '110110101000', '110111010100', '011011011010',
// 1585-1589
'010101011011', '001010011101', '011000101011', '101100010101', '101101001010',
// 1590-1594
'101110010101', '010110101010', '101010101110', '100100101110', '110010001111',
// 1595-1599
'010100100111', '011010010101', '011010101010', '101011010110', '010101011101',
// 1600
'001010011101'
];
function getDaysDiff(date1: Date, date2: Date): number {
const diff = Math.abs(date1.getTime() - date2.getTime());
return Math.round(diff / ONE_DAY);
}
@Injectable()
export class NgbCalendarIslamicUmalqura extends NgbCalendarIslamicCivil {
/**
* Returns the equivalent islamic(Umalqura) date value for a give input Gregorian date.
* `gdate` is s JS Date to be converted to Hijri.
*/
fromGregorian(gDate: Date): NgbDate |
/**
* Converts the current Hijri date to Gregorian.
*/
toGregorian(hDate: NgbDate): Date {
const hYear = hDate.year;
const hMonth = hDate.month - 1;
const hDay = hDate.day;
let gDate = new Date(GREGORIAN_FIRST_DATE);
let dayDiff = hDay - 1;
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) {
for (let y = 0; y < hYear - HIJRI_BEGIN; y++) {
for (let m = 0; m < 12; m++) {
dayDiff += +MONTH_LENGTH[y][m] + 29;
}
}
for (let m = 0; m < hMonth; m++) {
dayDiff += +MONTH_LENGTH[hYear - HIJRI_BEGIN][m] + 29;
}
gDate.setDate(GREGORIAN_FIRST_DATE.getDate() + dayDiff);
} else {
gDate = super.toGregorian(hDate);
}
return gDate;
}
/**
* Returns the number of days in a specific Hijri hMonth.
* `hMonth` is 1 for Muharram, 2 for Safar, etc.
* `hYear` is any Hijri hYear.
*/
getDaysPerMonth(hMonth: number, hYear: number): number {
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) {
const pos = hYear - HIJRI_BEGIN;
return +MONTH_LENGTH[pos][hMonth - 1] + 29;
}
return super.getDaysPerMonth(hMonth, hYear);
}
}
| {
let hDay = 1, hMonth = 0, hYear = 1300;
let daysDiff = getDaysDiff(gDate, GREGORIAN_FIRST_DATE);
if (gDate.getTime() - GREGORIAN_FIRST_DATE.getTime() >= 0 && gDate.getTime() - GREGORIAN_LAST_DATE.getTime() <= 0) {
let year = 1300;
for (let i = 0; i < MONTH_LENGTH.length; i++, year++) {
for (let j = 0; j < 12; j++) {
let numOfDays = +MONTH_LENGTH[i][j] + 29;
if (daysDiff <= numOfDays) {
hDay = daysDiff + 1;
if (hDay > numOfDays) {
hDay = 1;
j++;
}
if (j > 11) {
j = 0;
year++;
}
hMonth = j;
hYear = year;
return new NgbDate(hYear, hMonth + 1, hDay);
}
daysDiff = daysDiff - numOfDays;
}
}
} else {
return super.fromGregorian(gDate);
}
} | identifier_body |
Fn.js | // The MIT License (MIT)
// Copyright (c) 2016 – 2019 David Hofmann <the.urban.drone@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import { typeOf } from '../core/typeof';
import { Type } from '../adt';
import { Show } from '../generics/Show';
import { Eq } from '../generics/Eq';
/*
* @module monoid
*/
/**
* The Fn monoid. Fn can be used to combine multiple functions
* @class module:monoid.Fn
* @extends module:generics/Show
* @extends module:generics/Eq
* @static
* @version 3.0.0
*
* @example
* const {Fn} = require('futils').monoid;
*
* Fn((a) => a); // -> Fn(a -> a)
*
* Fn((a) => a).value; // -> (a -> a)
* Fn((a) => a).run(1); // -> 1
*/
export const Fn = Type('Fn', ['value']).deriving(Show, Eq);
/**
* Lifts a value into a Fn. Returns the empty Fn for values which are no
* functions
* @method of
* @static
* @memberof module:monoid.Fn
* @param {any} a The value to lift
* @return {Fn} A new Fn
*
* @example
* const {Fn} = require('futils').monoid;
*
* Fn.of((a) => a * 2); // -> Fn(a -> a * 2)
* Fn.of(null); // -> Fn(a -> a)
* Fn.of({}); // -> Fn(a -> a)
*/
Fn.of = a => (typeof a === 'function' ? Fn(a) : Fn(x => x));
/**
* Monoid implementation for Fn. Returns a Fn of the id function (a -> a)
* @method empty
* @static
* @memberof module:monoid.Fn
* @return {Fn} The empty Fn
*
* @example
* const {Fn} = require('futils').monoid;
*
* Fn.empty(); // -> Fn(a -> a)
*/
Fn.empty = () => Fn(a => a);
/**
* Concatenates a Fn with another using function composition
* @method concat
* @memberof module:monoid.Fn
* @instance
* @param {Fn} a The Fn instance to concatenate with
* @return {Fn} A new Fn
*
* @example
* const {Fn} = require('futils').monoid;
*
* const fn = Fn((a) => a * 2);
*
* fn.concat(Fn((a) => a * 3)); // -> Fn(a -> a * 2 * 3)
*/
Fn.fn.concat = function(a) {
if (Fn.is(a)) {
| throw `Fn::concat cannot append ${typeOf(a)} to ${typeOf(this)}`;
};
// Polyfill `.run()`, too. This often makes for better readability
Fn.fn.run = function(a) {
return this.value(a);
};
| return Fn(x => a.value(this.value(x)));
}
| conditional_block |
Fn.js | // The MIT License (MIT)
// Copyright (c) 2016 – 2019 David Hofmann <the.urban.drone@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import { typeOf } from '../core/typeof';
import { Type } from '../adt';
import { Show } from '../generics/Show';
import { Eq } from '../generics/Eq';
/*
* @module monoid
*/
/**
* The Fn monoid. Fn can be used to combine multiple functions
* @class module:monoid.Fn
* @extends module:generics/Show
* @extends module:generics/Eq
* @static
* @version 3.0.0
*
* @example
* const {Fn} = require('futils').monoid;
*
* Fn((a) => a); // -> Fn(a -> a)
*
* Fn((a) => a).value; // -> (a -> a)
* Fn((a) => a).run(1); // -> 1
*/
export const Fn = Type('Fn', ['value']).deriving(Show, Eq);
/**
* Lifts a value into a Fn. Returns the empty Fn for values which are no
* functions
* @method of
* @static
* @memberof module:monoid.Fn
* @param {any} a The value to lift
* @return {Fn} A new Fn
*
* @example
* const {Fn} = require('futils').monoid;
*
* Fn.of((a) => a * 2); // -> Fn(a -> a * 2)
* Fn.of(null); // -> Fn(a -> a)
* Fn.of({}); // -> Fn(a -> a)
*/
Fn.of = a => (typeof a === 'function' ? Fn(a) : Fn(x => x));
/**
* Monoid implementation for Fn. Returns a Fn of the id function (a -> a)
* @method empty
* @static
* @memberof module:monoid.Fn
* @return {Fn} The empty Fn
*
* @example
* const {Fn} = require('futils').monoid;
*
* Fn.empty(); // -> Fn(a -> a)
*/
Fn.empty = () => Fn(a => a);
/**
* Concatenates a Fn with another using function composition
* @method concat
* @memberof module:monoid.Fn
* @instance
* @param {Fn} a The Fn instance to concatenate with
* @return {Fn} A new Fn | * const {Fn} = require('futils').monoid;
*
* const fn = Fn((a) => a * 2);
*
* fn.concat(Fn((a) => a * 3)); // -> Fn(a -> a * 2 * 3)
*/
Fn.fn.concat = function(a) {
if (Fn.is(a)) {
return Fn(x => a.value(this.value(x)));
}
throw `Fn::concat cannot append ${typeOf(a)} to ${typeOf(this)}`;
};
// Polyfill `.run()`, too. This often makes for better readability
Fn.fn.run = function(a) {
return this.value(a);
}; | *
* @example | random_line_split |
virtualMachineExtensionImage.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
var models = require('./index');
var util = require('util');
/**
* @class
* Initializes a new instance of the VirtualMachineExtensionImage class.
* @constructor
* Describes a Virtual Machine Extension Image.
* @member {string} operatingSystem the operating system this extension
* supports.
*
* @member {string} computeRole the type of role (IaaS or PaaS) this extension
* supports.
*
* @member {string} handlerSchema the schema defined by publisher, where
* extension consumers should provide settings in a matching schema.
*
* @member {boolean} [vmScaleSetEnabled] whether the extension can be used on
* xRP VMScaleSets.By default existing extensions are usable on scalesets,
* but there might be cases where a publisher wants to explicitly indicate
* the extension is only enabled for CRP VMs but not VMSS.
*
* @member {boolean} [supportsMultipleExtensions] whether the handler can
* support multiple extensions.
*
*/
function VirtualMachineExtensionImage() |
util.inherits(VirtualMachineExtensionImage, models['Resource']);
/**
* Defines the metadata of VirtualMachineExtensionImage
*
* @returns {object} metadata of VirtualMachineExtensionImage
*
*/
VirtualMachineExtensionImage.prototype.mapper = function () {
return {
required: false,
serializedName: 'VirtualMachineExtensionImage',
type: {
name: 'Composite',
className: 'VirtualMachineExtensionImage',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
location: {
required: true,
serializedName: 'location',
type: {
name: 'String'
}
},
tags: {
required: false,
serializedName: 'tags',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
operatingSystem: {
required: true,
serializedName: 'properties.operatingSystem',
type: {
name: 'String'
}
},
computeRole: {
required: true,
serializedName: 'properties.computeRole',
type: {
name: 'String'
}
},
handlerSchema: {
required: true,
serializedName: 'properties.handlerSchema',
type: {
name: 'String'
}
},
vmScaleSetEnabled: {
required: false,
serializedName: 'properties.vmScaleSetEnabled',
type: {
name: 'Boolean'
}
},
supportsMultipleExtensions: {
required: false,
serializedName: 'properties.supportsMultipleExtensions',
type: {
name: 'Boolean'
}
}
}
}
};
};
module.exports = VirtualMachineExtensionImage;
| {
VirtualMachineExtensionImage['super_'].call(this);
} | identifier_body |
virtualMachineExtensionImage.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
var models = require('./index');
var util = require('util');
/**
* @class
* Initializes a new instance of the VirtualMachineExtensionImage class.
* @constructor
* Describes a Virtual Machine Extension Image.
* @member {string} operatingSystem the operating system this extension
* supports.
*
* @member {string} computeRole the type of role (IaaS or PaaS) this extension
* supports.
*
* @member {string} handlerSchema the schema defined by publisher, where
* extension consumers should provide settings in a matching schema.
*
* @member {boolean} [vmScaleSetEnabled] whether the extension can be used on
* xRP VMScaleSets.By default existing extensions are usable on scalesets,
* but there might be cases where a publisher wants to explicitly indicate
* the extension is only enabled for CRP VMs but not VMSS.
*
* @member {boolean} [supportsMultipleExtensions] whether the handler can
* support multiple extensions.
*
*/
function | () {
VirtualMachineExtensionImage['super_'].call(this);
}
util.inherits(VirtualMachineExtensionImage, models['Resource']);
/**
* Defines the metadata of VirtualMachineExtensionImage
*
* @returns {object} metadata of VirtualMachineExtensionImage
*
*/
VirtualMachineExtensionImage.prototype.mapper = function () {
return {
required: false,
serializedName: 'VirtualMachineExtensionImage',
type: {
name: 'Composite',
className: 'VirtualMachineExtensionImage',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
location: {
required: true,
serializedName: 'location',
type: {
name: 'String'
}
},
tags: {
required: false,
serializedName: 'tags',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
operatingSystem: {
required: true,
serializedName: 'properties.operatingSystem',
type: {
name: 'String'
}
},
computeRole: {
required: true,
serializedName: 'properties.computeRole',
type: {
name: 'String'
}
},
handlerSchema: {
required: true,
serializedName: 'properties.handlerSchema',
type: {
name: 'String'
}
},
vmScaleSetEnabled: {
required: false,
serializedName: 'properties.vmScaleSetEnabled',
type: {
name: 'Boolean'
}
},
supportsMultipleExtensions: {
required: false,
serializedName: 'properties.supportsMultipleExtensions',
type: {
name: 'Boolean'
}
}
}
}
};
};
module.exports = VirtualMachineExtensionImage;
| VirtualMachineExtensionImage | identifier_name |
virtualMachineExtensionImage.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
var models = require('./index');
var util = require('util');
/**
* @class
* Initializes a new instance of the VirtualMachineExtensionImage class.
* @constructor
* Describes a Virtual Machine Extension Image.
* @member {string} operatingSystem the operating system this extension
* supports.
*
* @member {string} computeRole the type of role (IaaS or PaaS) this extension
* supports.
*
* @member {string} handlerSchema the schema defined by publisher, where
* extension consumers should provide settings in a matching schema.
*
* @member {boolean} [vmScaleSetEnabled] whether the extension can be used on
* xRP VMScaleSets.By default existing extensions are usable on scalesets,
* but there might be cases where a publisher wants to explicitly indicate
* the extension is only enabled for CRP VMs but not VMSS.
*
* @member {boolean} [supportsMultipleExtensions] whether the handler can
* support multiple extensions.
*
*/
function VirtualMachineExtensionImage() {
VirtualMachineExtensionImage['super_'].call(this);
}
util.inherits(VirtualMachineExtensionImage, models['Resource']);
/**
* Defines the metadata of VirtualMachineExtensionImage
*
* @returns {object} metadata of VirtualMachineExtensionImage
*
*/
VirtualMachineExtensionImage.prototype.mapper = function () {
return {
required: false,
serializedName: 'VirtualMachineExtensionImage',
type: {
name: 'Composite',
className: 'VirtualMachineExtensionImage',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
location: {
required: true,
serializedName: 'location',
type: {
name: 'String'
}
},
tags: {
required: false,
serializedName: 'tags',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
operatingSystem: {
required: true,
serializedName: 'properties.operatingSystem',
type: {
name: 'String'
}
},
computeRole: {
required: true,
serializedName: 'properties.computeRole',
type: {
name: 'String'
}
},
handlerSchema: {
required: true,
serializedName: 'properties.handlerSchema',
type: { | required: false,
serializedName: 'properties.vmScaleSetEnabled',
type: {
name: 'Boolean'
}
},
supportsMultipleExtensions: {
required: false,
serializedName: 'properties.supportsMultipleExtensions',
type: {
name: 'Boolean'
}
}
}
}
};
};
module.exports = VirtualMachineExtensionImage; | name: 'String'
}
},
vmScaleSetEnabled: { | random_line_split |
parse.js | 'use strict';
exports.__esModule = true;
const moduleRequire = require('./module-require').default;
const extname = require('path').extname;
const fs = require('fs');
const log = require('debug')('eslint-plugin-import:parse');
function getBabelEslintVisitorKeys(parserPath) {
if (parserPath.endsWith('index.js')) {
const hypotheticalLocation = parserPath.replace('index.js', 'visitor-keys.js');
if (fs.existsSync(hypotheticalLocation)) {
const keys = moduleRequire(hypotheticalLocation);
return keys.default || keys;
}
}
return null;
}
function keysFromParser(parserPath, parserInstance, parsedResult) {
// Exposed by @typescript-eslint/parser and @babel/eslint-parser
if (parsedResult && parsedResult.visitorKeys) {
return parsedResult.visitorKeys;
}
if (/.*espree.*/.test(parserPath)) {
return parserInstance.VisitorKeys;
}
if (/.*babel-eslint.*/.test(parserPath)) {
return getBabelEslintVisitorKeys(parserPath);
}
return null;
}
exports.default = function parse(path, content, context) {
if (context == null) throw new Error('need context to parse properly');
let parserOptions = context.parserOptions;
const parserPath = getParserPath(path, context);
if (!parserPath) throw new Error('parserPath is required!');
// hack: espree blows up with frozen options
parserOptions = Object.assign({}, parserOptions);
parserOptions.ecmaFeatures = Object.assign({}, parserOptions.ecmaFeatures);
// always include comments and tokens (for doc parsing)
parserOptions.comment = true;
parserOptions.attachComment = true; // keeping this for backward-compat with older parsers
parserOptions.tokens = true;
// attach node locations
parserOptions.loc = true;
parserOptions.range = true;
// provide the `filePath` like eslint itself does, in `parserOptions`
// https://github.com/eslint/eslint/blob/3ec436ee/lib/linter.js#L637
parserOptions.filePath = path;
// @typescript-eslint/parser will parse the entire project with typechecking if you provide
// "project" or "projects" in parserOptions. Removing these options means the parser will
// only parse one file in isolate mode, which is much, much faster.
// https://github.com/import-js/eslint-plugin-import/issues/1408#issuecomment-509298962
delete parserOptions.project;
delete parserOptions.projects;
// require the parser relative to the main module (i.e., ESLint)
const parser = moduleRequire(parserPath);
if (typeof parser.parseForESLint === 'function') {
let ast;
try {
const parserRaw = parser.parseForESLint(content, parserOptions);
ast = parserRaw.ast;
return {
ast,
visitorKeys: keysFromParser(parserPath, parser, parserRaw),
};
} catch (e) {
console.warn();
console.warn('Error while parsing ' + parserOptions.filePath);
console.warn('Line ' + e.lineNumber + ', column ' + e.column + ': ' + e.message);
}
if (!ast || typeof ast !== 'object') {
console.warn(
'`parseForESLint` from parser `' +
parserPath +
'` is invalid and will just be ignored'
);
} else |
}
const keys = keysFromParser(parserPath, parser, undefined);
return {
ast: parser.parse(content, parserOptions),
visitorKeys: keys,
};
};
function getParserPath(path, context) {
const parsers = context.settings['import/parsers'];
if (parsers != null) {
const extension = extname(path);
for (const parserPath in parsers) {
if (parsers[parserPath].indexOf(extension) > -1) {
// use this alternate parser
log('using alt parser:', parserPath);
return parserPath;
}
}
}
// default to use ESLint parser
return context.parserPath;
}
| {
return {
ast,
visitorKeys: keysFromParser(parserPath, parser, undefined),
};
} | conditional_block |
parse.js | 'use strict';
exports.__esModule = true;
const moduleRequire = require('./module-require').default;
const extname = require('path').extname;
const fs = require('fs');
const log = require('debug')('eslint-plugin-import:parse');
function getBabelEslintVisitorKeys(parserPath) {
if (parserPath.endsWith('index.js')) {
const hypotheticalLocation = parserPath.replace('index.js', 'visitor-keys.js');
if (fs.existsSync(hypotheticalLocation)) {
const keys = moduleRequire(hypotheticalLocation);
return keys.default || keys;
}
}
return null;
}
function keysFromParser(parserPath, parserInstance, parsedResult) {
// Exposed by @typescript-eslint/parser and @babel/eslint-parser
if (parsedResult && parsedResult.visitorKeys) {
return parsedResult.visitorKeys;
}
if (/.*espree.*/.test(parserPath)) {
return parserInstance.VisitorKeys;
}
if (/.*babel-eslint.*/.test(parserPath)) {
return getBabelEslintVisitorKeys(parserPath);
}
return null;
}
exports.default = function parse(path, content, context) {
if (context == null) throw new Error('need context to parse properly');
let parserOptions = context.parserOptions;
const parserPath = getParserPath(path, context);
if (!parserPath) throw new Error('parserPath is required!');
// hack: espree blows up with frozen options
parserOptions = Object.assign({}, parserOptions);
parserOptions.ecmaFeatures = Object.assign({}, parserOptions.ecmaFeatures);
// always include comments and tokens (for doc parsing)
parserOptions.comment = true;
parserOptions.attachComment = true; // keeping this for backward-compat with older parsers
parserOptions.tokens = true;
// attach node locations
parserOptions.loc = true;
parserOptions.range = true;
// provide the `filePath` like eslint itself does, in `parserOptions`
// https://github.com/eslint/eslint/blob/3ec436ee/lib/linter.js#L637
parserOptions.filePath = path;
// @typescript-eslint/parser will parse the entire project with typechecking if you provide
// "project" or "projects" in parserOptions. Removing these options means the parser will
// only parse one file in isolate mode, which is much, much faster.
// https://github.com/import-js/eslint-plugin-import/issues/1408#issuecomment-509298962
delete parserOptions.project;
delete parserOptions.projects;
// require the parser relative to the main module (i.e., ESLint)
const parser = moduleRequire(parserPath);
if (typeof parser.parseForESLint === 'function') {
let ast;
try {
const parserRaw = parser.parseForESLint(content, parserOptions);
ast = parserRaw.ast;
return {
ast,
visitorKeys: keysFromParser(parserPath, parser, parserRaw),
};
} catch (e) {
console.warn();
console.warn('Error while parsing ' + parserOptions.filePath);
console.warn('Line ' + e.lineNumber + ', column ' + e.column + ': ' + e.message);
}
if (!ast || typeof ast !== 'object') {
console.warn(
'`parseForESLint` from parser `' +
parserPath +
'` is invalid and will just be ignored'
);
} else {
return {
ast,
visitorKeys: keysFromParser(parserPath, parser, undefined),
};
}
}
const keys = keysFromParser(parserPath, parser, undefined);
return {
ast: parser.parse(content, parserOptions),
visitorKeys: keys,
};
};
function getParserPath(path, context) { | if (parsers != null) {
const extension = extname(path);
for (const parserPath in parsers) {
if (parsers[parserPath].indexOf(extension) > -1) {
// use this alternate parser
log('using alt parser:', parserPath);
return parserPath;
}
}
}
// default to use ESLint parser
return context.parserPath;
} | const parsers = context.settings['import/parsers']; | random_line_split |
parse.js | 'use strict';
exports.__esModule = true;
const moduleRequire = require('./module-require').default;
const extname = require('path').extname;
const fs = require('fs');
const log = require('debug')('eslint-plugin-import:parse');
function getBabelEslintVisitorKeys(parserPath) {
if (parserPath.endsWith('index.js')) {
const hypotheticalLocation = parserPath.replace('index.js', 'visitor-keys.js');
if (fs.existsSync(hypotheticalLocation)) {
const keys = moduleRequire(hypotheticalLocation);
return keys.default || keys;
}
}
return null;
}
function keysFromParser(parserPath, parserInstance, parsedResult) {
// Exposed by @typescript-eslint/parser and @babel/eslint-parser
if (parsedResult && parsedResult.visitorKeys) {
return parsedResult.visitorKeys;
}
if (/.*espree.*/.test(parserPath)) {
return parserInstance.VisitorKeys;
}
if (/.*babel-eslint.*/.test(parserPath)) {
return getBabelEslintVisitorKeys(parserPath);
}
return null;
}
exports.default = function parse(path, content, context) {
if (context == null) throw new Error('need context to parse properly');
let parserOptions = context.parserOptions;
const parserPath = getParserPath(path, context);
if (!parserPath) throw new Error('parserPath is required!');
// hack: espree blows up with frozen options
parserOptions = Object.assign({}, parserOptions);
parserOptions.ecmaFeatures = Object.assign({}, parserOptions.ecmaFeatures);
// always include comments and tokens (for doc parsing)
parserOptions.comment = true;
parserOptions.attachComment = true; // keeping this for backward-compat with older parsers
parserOptions.tokens = true;
// attach node locations
parserOptions.loc = true;
parserOptions.range = true;
// provide the `filePath` like eslint itself does, in `parserOptions`
// https://github.com/eslint/eslint/blob/3ec436ee/lib/linter.js#L637
parserOptions.filePath = path;
// @typescript-eslint/parser will parse the entire project with typechecking if you provide
// "project" or "projects" in parserOptions. Removing these options means the parser will
// only parse one file in isolate mode, which is much, much faster.
// https://github.com/import-js/eslint-plugin-import/issues/1408#issuecomment-509298962
delete parserOptions.project;
delete parserOptions.projects;
// require the parser relative to the main module (i.e., ESLint)
const parser = moduleRequire(parserPath);
if (typeof parser.parseForESLint === 'function') {
let ast;
try {
const parserRaw = parser.parseForESLint(content, parserOptions);
ast = parserRaw.ast;
return {
ast,
visitorKeys: keysFromParser(parserPath, parser, parserRaw),
};
} catch (e) {
console.warn();
console.warn('Error while parsing ' + parserOptions.filePath);
console.warn('Line ' + e.lineNumber + ', column ' + e.column + ': ' + e.message);
}
if (!ast || typeof ast !== 'object') {
console.warn(
'`parseForESLint` from parser `' +
parserPath +
'` is invalid and will just be ignored'
);
} else {
return {
ast,
visitorKeys: keysFromParser(parserPath, parser, undefined),
};
}
}
const keys = keysFromParser(parserPath, parser, undefined);
return {
ast: parser.parse(content, parserOptions),
visitorKeys: keys,
};
};
function getParserPath(path, context) | {
const parsers = context.settings['import/parsers'];
if (parsers != null) {
const extension = extname(path);
for (const parserPath in parsers) {
if (parsers[parserPath].indexOf(extension) > -1) {
// use this alternate parser
log('using alt parser:', parserPath);
return parserPath;
}
}
}
// default to use ESLint parser
return context.parserPath;
} | identifier_body | |
parse.js | 'use strict';
exports.__esModule = true;
const moduleRequire = require('./module-require').default;
const extname = require('path').extname;
const fs = require('fs');
const log = require('debug')('eslint-plugin-import:parse');
function | (parserPath) {
if (parserPath.endsWith('index.js')) {
const hypotheticalLocation = parserPath.replace('index.js', 'visitor-keys.js');
if (fs.existsSync(hypotheticalLocation)) {
const keys = moduleRequire(hypotheticalLocation);
return keys.default || keys;
}
}
return null;
}
function keysFromParser(parserPath, parserInstance, parsedResult) {
// Exposed by @typescript-eslint/parser and @babel/eslint-parser
if (parsedResult && parsedResult.visitorKeys) {
return parsedResult.visitorKeys;
}
if (/.*espree.*/.test(parserPath)) {
return parserInstance.VisitorKeys;
}
if (/.*babel-eslint.*/.test(parserPath)) {
return getBabelEslintVisitorKeys(parserPath);
}
return null;
}
exports.default = function parse(path, content, context) {
if (context == null) throw new Error('need context to parse properly');
let parserOptions = context.parserOptions;
const parserPath = getParserPath(path, context);
if (!parserPath) throw new Error('parserPath is required!');
// hack: espree blows up with frozen options
parserOptions = Object.assign({}, parserOptions);
parserOptions.ecmaFeatures = Object.assign({}, parserOptions.ecmaFeatures);
// always include comments and tokens (for doc parsing)
parserOptions.comment = true;
parserOptions.attachComment = true; // keeping this for backward-compat with older parsers
parserOptions.tokens = true;
// attach node locations
parserOptions.loc = true;
parserOptions.range = true;
// provide the `filePath` like eslint itself does, in `parserOptions`
// https://github.com/eslint/eslint/blob/3ec436ee/lib/linter.js#L637
parserOptions.filePath = path;
// @typescript-eslint/parser will parse the entire project with typechecking if you provide
// "project" or "projects" in parserOptions. Removing these options means the parser will
// only parse one file in isolate mode, which is much, much faster.
// https://github.com/import-js/eslint-plugin-import/issues/1408#issuecomment-509298962
delete parserOptions.project;
delete parserOptions.projects;
// require the parser relative to the main module (i.e., ESLint)
const parser = moduleRequire(parserPath);
if (typeof parser.parseForESLint === 'function') {
let ast;
try {
const parserRaw = parser.parseForESLint(content, parserOptions);
ast = parserRaw.ast;
return {
ast,
visitorKeys: keysFromParser(parserPath, parser, parserRaw),
};
} catch (e) {
console.warn();
console.warn('Error while parsing ' + parserOptions.filePath);
console.warn('Line ' + e.lineNumber + ', column ' + e.column + ': ' + e.message);
}
if (!ast || typeof ast !== 'object') {
console.warn(
'`parseForESLint` from parser `' +
parserPath +
'` is invalid and will just be ignored'
);
} else {
return {
ast,
visitorKeys: keysFromParser(parserPath, parser, undefined),
};
}
}
const keys = keysFromParser(parserPath, parser, undefined);
return {
ast: parser.parse(content, parserOptions),
visitorKeys: keys,
};
};
function getParserPath(path, context) {
const parsers = context.settings['import/parsers'];
if (parsers != null) {
const extension = extname(path);
for (const parserPath in parsers) {
if (parsers[parserPath].indexOf(extension) > -1) {
// use this alternate parser
log('using alt parser:', parserPath);
return parserPath;
}
}
}
// default to use ESLint parser
return context.parserPath;
}
| getBabelEslintVisitorKeys | identifier_name |
jquery.dateobj.js | /*
* Copyright © 2015-2019 the contributors (see Contributors.md).
*
* This file is part of Knora.
*
* Knora 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.
*
* Knora 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 Knora. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Lukas Rosenthaler <lukas.rosenthaler@unibas.ch>
* @package jqplugins
*
* This plugin creates an edit-form for the properties of a resource
*
* <pre>
* <em>Title:</em><div class="propedit" data-propname="title" />
* <em>Autor:</em><div class="propedit" data-propname="author" />
* </pre>
*
* <pre>
* <script type="text/javascript">
* $('div.propedit').propedit(resdata, propdata);
* </script>
* </pre>
*/
(function( $ ){
'use strict';
var spin_up = new Image();
spin_up.src = SITE_URL + '/app/icons/up.png';
var spin_down = new Image();
spin_down.src = SITE_URL + '/app/icons/down.png';
/*
var spin_up2 = new Image();
spin_up2.src = SITE_URL + '/app/icons/spin-up2.png';
var spin_down2 = new Image();
spin_down2.src = SITE_URL + '/app/icons/spin-down2.png';
var spin_up3 = new Image();
spin_up3.src = SITE_URL + '/app/icons/spin-up3.png';
var spin_down3 = new Image();
spin_down3.src = SITE_URL + '/app/icons/spin-down3.png';
*/
// TODO: temporary fix due to async loading problem of strings, https://github.com/dhlab-basel/Knora/issues/92
var cal_strings = {
"_day_su" : "Sun",
"_day_mo" : "Mon",
"_day_tu" : "Tue",
"_day_we" : "Wed",
"_day_th" : "Thu",
"_day_fr" : "Fri",
"_day_sa" : "Sat",
"_mon_jan_short" : "Jan",
"_mon_feb_short" : "Feb",
"_mon_mar_short" : "Mar",
"_mon_apr_short" : "Apr",
"_mon_may_short" : "May",
"_mon_jun_short" : "Jun",
"_mon_jul_short" : "Jul",
"_mon_aug_short" : "Aug",
"_mon_sep_short" : "Sep",
"_mon_oct_short" : "Oct",
"_mon_nov_short" : "Nov",
"_mon_dec_short" : "Dec",
"_mon_jan_long" : "January",
"_mon_feb_long" : "February",
"_mon_mar_long" : "March",
"_mon_apr_long" : "April",
"_mon_may_long" : "May",
"_mon_jun_long" : "June",
"_mon_jul_long" : "July",
"_mon_aug_long" : "August",
"_mon_sep_long" : "September",
"_mon_oct_long" : "October",
"_mon_nov_long" : "November",
"_mon_dec_long" : "December",
"_not_stated" : "Not stated",
"_change_year" : "Change Year",
"_change_decade" : "Change decade",
"_change_century" : "Change century",
"_period" : "Period"
};
var weekday = [cal_strings._day_su, cal_strings._day_mo, cal_strings._day_tu, cal_strings._day_we, cal_strings._day_th, cal_strings._day_fr, cal_strings._day_sa];
var months = {
GREGORIAN: ['ZERO', cal_strings._mon_jan_short, cal_strings._mon_feb_short, cal_strings._mon_mar_short, cal_strings._mon_apr_short, cal_strings._mon_may_short, cal_strings._mon_jun_short, cal_strings._mon_jul_short, cal_strings._mon_aug_short, cal_strings._mon_sep_short, cal_strings._mon_oct_short, cal_strings._mon_nov_short, cal_strings._mon_dec_short],
JULIAN: ['ZERO', cal_strings._mon_jan_short, cal_strings._mon_feb_short, cal_strings._mon_mar_short, cal_strings._mon_apr_short, cal_strings._mon_may_short, cal_strings._mon_jun_short, cal_strings._mon_jul_short, cal_strings._mon_aug_short, cal_strings._mon_sep_short, cal_strings._mon_oct_short, cal_strings._mon_nov_short, cal_strings._mon_dec_short],
JEWISH: ['ZERO', 'Tishri', 'Heshvan', 'Kislev', 'Tevet', 'Shevat', 'AdarI', 'AdarII', 'Nisan', 'Iyyar', 'Sivan', 'Tammuz', 'Av', 'Elul'],
FRENCH: ['ZERO', 'Vendemiaire', 'Brumaire', 'Frimaire', 'Nivose', 'Pluviose', 'Ventose', 'Germinal', 'Floreal', 'Prairial', 'Messidor', 'Thermidor', 'Fructidor', 'Extra']
};
var months_long = {
GREGORIAN: ['ZERO', cal_strings._mon_jan_long, cal_strings._mon_feb_long, cal_strings._mon_mar_long, cal_strings._mon_apr_long, cal_strings._mon_may_long, cal_strings._mon_jun_long, cal_strings._mon_jul_long, cal_strings._mon_aug_long, cal_strings._mon_sep_long, cal_strings._mon_oct_long, cal_strings._mon_nov_long, cal_strings._mon_dec_long],
JULIAN: ['ZERO', cal_strings._mon_jan_long, cal_strings._mon_feb_long, cal_strings._mon_mar_long, cal_strings._mon_mapr_long, cal_strings._mon_may_long, cal_strings._mon_jun_long, cal_strings._mon_jul_long, cal_strings._mon_aug_long, cal_strings._mon_sep_long, cal_strings._mon_oct_long, cal_strings._mon_nov_long, cal_strings._mon_dec_long],
JEWISH: ['ZERO', 'Tishri', 'Heshvan', 'Kislev', 'Tevet', 'Shevat', 'AdarI', 'AdarII', 'Nisan', 'Iyyar', 'Sivan', 'Tammuz', 'Av', 'Elul'],
FRENCH: ['ZERO', 'Vendemiaire', 'Brumaire', 'Frimaire', 'Nivose', 'Pluviose', 'Ventose', 'Germinal', 'Floreal', 'Prairial', 'Messidor', 'Thermidor', 'Fructidor', 'Extra']
};
var precision = {
DAY: 'Day',
MONTH: 'Month',
YEAR: 'Year'
};
var day_popoup_is_open = false;
var open_daysel_popup = function(daysel, month, year, era, current_cal, precision) {
// console.log("open_daysel_popup: year is " + year.toString() + ", era is " + era.toString());
if (era === "BCE" || era === "BC") {
year = -year;
}
var p = daysel.offset(); // relative to browser window
var tmpcss = {
position: 'fixed',
left: p.left + daysel.width(),
top: p.top,
'z-index': 2 /* :( i don't like black magic numbers or const */
};
if (day_popoup_is_open) {
return;
}
var __daysel = $('<div>').addClass('daysel').css(tmpcss);
$('<div>').css({'text-align': 'center', 'font-style': 'italic', 'font-weight': 'bold', 'font-size': 'large'}).text(months_long[current_cal][month]).appendTo(__daysel);
var daytab = $('<table>').appendTo(__daysel);
var line = $('<tr>').appendTo(daytab);
for (var i = 0; i < 7; i++) {
$('<th>').text(weekday[i]).appendTo(line);
}
var data2 = SALSAH.daycnt(current_cal, year, month);
var i, cnt, td_ele;
line = $('<tr>').appendTo(daytab);
for (cnt = 0; cnt < data2.weekday_first; cnt++) {
$('<td>').text(' ').appendTo(line);
}
for (i = 1; i <= data2.days; i++) {
if ((cnt % 7) == 0) {
line = $('<tr>').appendTo(daytab);
}
td_ele = $('<td>').text(i).data('day', i).on('click', function(e) {
e.stopPropagation();
daysel.val($(this).data('day'));
__daysel.remove();
$(document).off('click.daysel');
day_popoup_is_open = false;
}).appendTo(line);
if ((i == daysel.val()) && (precision == 'DAY')) {
td_ele.addClass('highlight');
}
cnt++;
}
line = $('<tr>').appendTo(daytab);
td_ele = $('<td>', {colspan: 7}).text(cal_strings._not_stated).on('click', function(e) {
e.stopPropagation();
daysel.val('-');
__daysel.remove();
$(document).off('click.daysel');
day_popoup_is_open = false;
}).appendTo(line);
if ((daysel.val() == '-') || (precision != 'DAY')) {
td_ele.addClass('highlight');
}
$(document).on('click.daysel', function() {
__daysel.remove();
$(document).off('click.daysel');
day_popoup_is_open = false;
});
day_popoup_is_open = true;
return __daysel;
}
var create_date_entry = function (ele, jdc, current_cal, precision, no_day, no_month) {
var postdata = {
func: 'jdc2date',
jdc: jdc,
cal: current_cal
};
var tmparr;
var day, month, year, era;
switch (current_cal) {
case 'GREGORIAN':
case 'gregorian': {
tmparr = SALSAH.jd_to_gregorian(jdc);
year = tmparr[0];
month = tmparr[1];
day = tmparr[2];
break;
}
case 'JULIAN':
case 'julian': {
tmparr = SALSAH.jd_to_julian(jdc);
year = tmparr[0];
month = tmparr[1];
day = tmparr[2];
break;
}
case 'JEWISH':
case 'jewish': {
tmparr = SALSAH.jd_to_hebrew(jdc);
year = tmparr[0];
month = tmparr[1];
day = tmparr[2];
break;
}
case 'FRENCH':
case 'french': {
//list($m, $d, $y) = explode('/', jdtofrench($jdc));
break;
}
}
if (year < 0) {
era = "BCE";
} else {
era = "CE";
}
year = Math.abs(year);
// console.log("year is " + year.toString() + ", era is " + era.toString());
var daysel, monthsel, yearsel, erasel;
var dayval;
//
// selection for day
//
if (precision != 'DAY') {
dayval = '-';
}
else {
dayval = day > 0 ? day : '-';
}
var dayselattr = {type: 'text', size: 1, maxlength: 1, readonly: true};
if (precision == 'YEAR') {
dayselattr.disabled = true;
}
daysel = $('<input>').attr(dayselattr).addClass('propedit').addClass('daysel').on('click.dayselin', function(e){
e.stopPropagation();
ele.append(open_daysel_popup(daysel, monthsel.val(), yearsel.val(), erasel.val(), current_cal, precision));
}).val(dayval).appendTo(ele);
if ((no_day !== undefined) && no_day) {
daysel.css('display', 'none');
}
//
// pulldown for month
//
monthsel = $('<select>', {'class': 'propedit monthsel'}).change(function(event) {
//
// month changed...
//
month = event.target.value;
if (month == 0) {
daysel.val('-').attr({disabled: 'disabled'});
}
else {
var actual_day = daysel.val(); // save current day for use below...
daysel.empty();
daysel.removeAttr('disabled');
if (precision != 'DAY') {
$('<option>').attr({selected: 'selected'}).append('-').appendTo(daysel);
}
else {
$('<option>').append('-').appendTo(daysel);
}
var data2 = SALSAH.daycnt(current_cal, year, month);
if (actual_day > data2.days) actual_day = data2.days;
for (var i = 1; i <= data2.days; i++) {
var attributes = {Class: 'propedit'};
if ((precision == 'DAY') && (i == actual_day)) {
attributes.selected = 'selected';
}
attributes.value = i;
$('<option>', attributes).append(i).appendTo(daysel);
}
}
});
var monthattr = {'class': 'propedit monthsel', value: 0};
if (precision != 'MONTH') {
monthattr.selected = 'selected';
}
$('<option>', monthattr).append('-').appendTo(monthsel);
for (var i = 1; i <= SALSAH.calendars[current_cal].n_months; i++) {
var attributes = {Class: 'propedit monthsel'};
if ((i == month) && ((precision == 'MONTH') || (precision == 'DAY'))) {
attributes.selected = 'selected';
}
attributes.value = i;
$('<option>', attributes).append(months[current_cal][i]).appendTo(monthsel);
}
ele.append(monthsel);
//
// textfield for year
//
yearsel = $('<input>', {type: 'text', 'class': 'propedit yearsel', value: year, size: '4', maxlength: '4'}).appendTo(ele);
ele.append($('<span>').attr({title: cal_strings._change_year})
.append($('<img>', {src: spin_up.src}).css({'vertical-align': 'middle', cursor: 'pointer'}).attr({title: 'click: +1\nshift+click: +10\nshift+alt+click: +100'}).click(function(event){
if (event.shiftKey && event.altKey){
yearsel.val(parseInt(yearsel.val()) + 100);
}
else if (event.shiftKey) {
yearsel.val(parseInt(yearsel.val()) + 10);
}
else {
yearsel.val(parseInt(yearsel.val()) + 1);
}
}))
.append($('<img>', {src: spin_down.src}).css({'vertical-align': 'middle', cursor: 'pointer'}).attr({title: 'click: -1\nshift+click: -10\nshift+alt+click: -100'}).click(function(event){
if (event.shiftKey && event.altKey){
yearsel.val(parseInt(yearsel.val()) - 100);
}
else if (event.shiftKey) {
yearsel.val(parseInt(yearsel.val()) - 10);
}
else {
yearsel.val(parseInt(yearsel.val()) - 1);
}
}))
);
erasel = $('<select>', {'class': 'propedit erasel'});
var ceOption = $('<option>').append('CE');
var bceOption = $('<option>').append('BCE');
if (era === "BCE") {
bceOption.attr({selected: 'selected'});
} else {
ceOption.attr({selected: 'selected'});
}
ceOption.appendTo(erasel);
bceOption.appendTo(erasel);
ele.append(erasel);
};
var parse_datestr = function(datestr, calendar, era, periodpart) {
var d = {};
var dd;
var d_arr = datestr.split('-');
var year_sign = 1;
if (era === "BC" || era === "BCE") {
year_sign = -1;
}
if (d_arr.length == 3) {
d.precision = 'DAY';
d.jdc = SALSAH.date_to_jdc(d_arr[2], d_arr[1], d_arr[0] * year_sign, calendar, periodpart);
}
else if (d_arr.length == 2) {
d.precision = 'MONTH';
d.jdc = SALSAH.date_to_jdc(0, d_arr[1], d_arr[0] * year_sign, calendar, periodpart);
}
else if (d_arr.length == 1) {
d.precision = 'YEAR';
d.jdc = SALSAH.date_to_jdc(0, 0, d_arr[0] * year_sign, calendar, periodpart);
}
else {
alert('ERROR: Invalid datestr: ' + datestr);
}
dd = SALSAH.jdc_to_date(d.jdc, calendar);
d.year = dd.year;
d.month = dd.month;
d.day = dd.day;
d.weekday = dd.weekday;
d.calendar = calendar;
// console.log("in parse_datestr: datestr is " + datestr.toString() + ", era is " + era + ", and d is " + JSON.stringify(d));
return d;
};
/**
* Dateobject:
* - <i>name</i>.dateval1 (YYYY-MM-DD)
* - <i>name</i>.dateval2 (YYYY-MM-DD)
* - <i>name</i>.calendar ("GREGORIAN", "JULIAN", "JEWISH", "FRENCH")
*/
var methods = {
init: function (dateobj) {
var $that = this;
var d1;
var d2;
var d1_abs_year, d2_abs_year;
var d1_era, d2_era;
var d1_year_str, d2_year_str; | d1_era = "BCE";
} else {
d1_era = "CE";
}
if (d2.year < 0) {
d2_era = "BCE";
} else {
d2_era = "CE";
}
d1_abs_year = Math.abs(d1.year);
d2_abs_year = Math.abs(d2.year);
d1_year_str = d1_abs_year + ' ' + d1_era;
d2_year_str = d2_abs_year + ' ' + d2_era;
var datestr = '';
if (d1.precision == d2.precision) {
//
// same precisions for start- and end-date
//
switch (d1.precision) {
case 'DAY': {
if ((d1.year == d2.year) && (d1.month == d2.month) && (d1.day == d2.day)) {
datestr = weekday[d1.weekday] + ' ' + d1.day + '. ' + months[dateobj.calendar][d1.month] + ' ' + d1_year_str;
}
else {
datestr = weekday[d1.weekday] + ' ' + d1.day + '. ' + months[dateobj.calendar][d1.month] + ' ' + d1_year_str + ' - ' + weekday[d2.weekday] + ' ' + d2.day + '. ' + months[dateobj.calendar][d2.month] + ' ' + d2_year_str;
}
break;
}
case 'MONTH': {
if ((d1.year == d2.year) && (d1.month == d2.month)) {
datestr = months[dateobj.calendar][d1.month] + ' ' + d1_year_str;
}
else {
datestr = months[dateobj.calendar][d1.month] + ' ' + d1.year + ' - ' + months[dateobj.calendar][d2.month] + ' ' + d2_year_str;
}
break;
}
case 'YEAR': {
if (d1.year == d2.year) {
datestr = d1_year_str;
}
else {
datestr = d1.year + ' - ' + d2_year_str;
}
break;
}
} // switch(precision1)
}
else {
//
// different precisions for start- and end-date
//
switch (d1.precision) {
case 'DAY': {
datestr = weekday[d1.weekday] + ' ' + d1.day + '. ' + months[dateobj.calendar][d1.month] + ' ' + d1_year_str;
break;
}
case 'MONTH': {
datestr = months[dateobj.calendar][d1.month] + ' ' + d1_year_str;
break;
}
case 'YEAR': {
datestr = d1_year_str;
break;
}
} // switch(propinfo.values[value_index].precision1)
datestr += ' - ';
switch (d2.precision) {
case 'DAY': {
datestr += weekday[d2.weekday] + ' ' + d2.day + '. ' + months[dateobj.calendar][d2.month] + ' ' + d2_year_str;
break;
}
case 'MONTH': {
datestr += months[dateobj.calendar][d2.month] + ' ' + d2_year_str;
break;
}
case 'YEAR': {
datestr += d2_year_str;
break;
}
} // switch(precision2)
}
datestr += ' (' + SALSAH.calendars[d1.calendar].name + ')';
return this.each(function() {
$(this).append(datestr);
});
},
/*
* defvals: {
* current_cal: 'GREGORIAN' | 'JULIAN',
* date1: {
* day: <int>,
* month: <int>,
* year: <int>
* }
* date2: {
* day: <int>,
* month: <int>,
* year: <int>
* }
* no_calsel: true | false,
* no_day: true | false
* }
*/
edit: function(dateobj, defvals) {
var period = false;
var d1 = {};
var d2 = {};
if (dateobj === undefined) {
var jsdateobj = new Date();
if (defvals === undefined) {
d1.calendar = 'GREGORIAN';
d1.day = jsdateobj.getDate();
d1.month = jsdateobj.getMonth() + 1;
d1.year = jsdateobj.getFullYear();
d1.precision = 'DAY';
d2 = $.extend({}, d1);
}
else {
d1.calendar = (defvals.current_cal === undefined) ? 'GREGORIAN' : defvals.current_cal;
if (defvals.date1 === undefined) {
d1.day = jsdateobj.getDate();
d1.month = jsdateobj.getMonth() + 1;
d1.year = jsdateobj.getFullYear();
}
else {
d1.day = defvals.date1.day === undefined ? jsdateobj.getDate() : defvals.date1.day;
d1.month = defvals.date1.month === undefined ? jsdateobj.getMonth() + 1 : defvals.date1.month;
d1.year = defvals.date1.year === undefined ? jsdateobj.getFullYear() : defvals.date1.year;
}
if (defvals.date2 === undefined) {
d2 = $.extend({}, d1);
}
else {
d2.day = defvals.date2.day === undefined ? jsdateobj.getDate() : defvals.date2.day;
d2.month = defvals.date2.month === undefined ? jsdateobj.getMonth() + 1 : defvals.date2.month;
d2.year = defvals.date2.year === undefined ? jsdateobj.getFullYear() : defvals.date2.year;
d2.calendar = d1.calendar;
}
d1.precision = defvals.dateprecision1 === undefined ? 'DAY' : defvals.dateprecision1;
d2.precision = defvals.dateprecision2 === undefined ? 'DAY' : defvals.dateprecision2;
}
d1.jdc = SALSAH.date_to_jdc(d1.day, d1.month, d1.year, d1.calendar, 'START');
d2.jdc = SALSAH.date_to_jdc(d2.day, d2.month, d2.year, d2.calendar, 'END');
}
else {
var current_cal = dateobj.calendar;
if (dateobj.dateprecision1 !== undefined) {
alert('OLD DATE FORMAT!!!')
d1.jdc = dateobj.dateval1;
d2.jdc = dateobj.dateval2;
var date1 = SALSAH.jdc_to_date(dateval1, current_cal);
var date2 = SALSAH.jdc_to_date(dateval2, current_cal);
var dateprecision1 = dateobj.dateprecision1;
var dateprecision2 = dateobj.dateprecision2;
}
else {
d1 = parse_datestr(dateobj.dateval1, dateobj.calendar, dateobj.era1, 'START');
d2 = parse_datestr(dateobj.dateval2, dateobj.calendar, dateobj.era2, 'END');
}
}
var datecontainer1 = $('<span>').appendTo(this);
var datecontainer2 = $('<span>').appendTo(this);
if (d1.precision == d2.precision) {
switch (d1.precision) {
case 'DAY': {
if ((d1.day != d2.day) || (d1.month != d2.month) || (d1.year != d2.year)) period = true;
break;
}
case 'MONTH': {
if ((d1.month != d2.month) || (d1.year != d2.year)) period = true;
break;
}
case 'YEAR': {
if (d1.year != d2.year) period = true;
break;
}
default: {
period = true;
}
}
}
else {
period = true; // different date precisions imply a period!
}
var no_day = false;
if ((defvals !== undefined) && (defvals.no_day !== undefined)) no_day = defvals.no_day
create_date_entry(datecontainer1, d1.jdc, d1.calendar, d1.precision, no_day);
if (period) {
datecontainer2.append(' – ');
create_date_entry(datecontainer2, d2.jdc, d2.calendar, d2.precision, no_day);
}
//
// period...
//
var periodattr = {
'class': 'propedit periodsel',
type: 'checkbox'
};
if (period) periodattr.checked = 'checked';
this.append(' ' + cal_strings._period + ':');
var periodsel = $('<input>', periodattr).click(function(event) {
if (event.target.checked) {
datecontainer2.append(' - ');
create_date_entry(datecontainer2, d2.jdc, d2.calendar, d2.precision);
period = true;
}
else {
datecontainer2.empty();
period = false;
}
}).appendTo(this);
this.append(' ');
//
// calendar selection
//
var calsel = $('<select>', {'class': 'propedit calsel'}).change(function(event) {
//
// calendar selection changed...
//
//
// first dave the actual date into a calendar independant JDC
//
var day1 = datecontainer1.find('.daysel').val();
var month1 = datecontainer1.find('.monthsel').val();
var year1 = datecontainer1.find('.yearsel').val();
if ((day1 == '-') && (month1 == 0)) {
d1.precision = 'YEAR';
day1 = 0;
}
else if (day1 == '-') {
d1.precision = 'MONTH';
day1 = 0;
}
else {
d1.precision = 'DAY';
}
d1.jdc = SALSAH.date_to_jdc(day1, month1, year1, d1.calendar, 'START');
if (period) {
var day2 = datecontainer2.find('.daysel').val();
var month2 = datecontainer2.find('.monthsel').val();
var year2 = datecontainer2.find('.yearsel').val();
if ((day2 == '-') && (month2 == 0)) {
d2.precision = 'YEAR';
day2 = 0;
}
else if (day2 == '-') {
d2.precision = 'MONTH';
day2 = 0;
}
else {
d2.precision = 'DAY';
}
d2.jdc = SALSAH.date_to_jdc(day2, month2, year2, d2.calendar, 'END');
}
d1.calendar = event.target.value; // get new calendar value
d2.calendar = event.target.value; // get new calendar value
datecontainer1.empty();
create_date_entry(datecontainer1, d1.jdc, d1.calendar, d1.precision);
if (period) {
datecontainer2.empty();
datecontainer2.append(' - ');
create_date_entry(datecontainer2, d2.jdc, d2.calendar, d2.precision);
}
}).appendTo(this);
for (var i in SALSAH.calendars) {
if (i == 'FRENCH') continue; // no french revolutionary at the moment!
if (i == 'JEWISH') continue; // no hebrew at the moment!
var attributes = {Class: 'propedit'};
if (i == d1.calendar) {
attributes.selected = 'selected';
}
attributes.value = i;
$('<option>', attributes).append(SALSAH.calendars[i].name).appendTo(calsel); // !!!!!!!!!!!!!!!!!!!!!!!!!!
}
if ((defvals !== undefined) && (defvals.no_calsel !== undefined) && defvals.no_calsel) {
calsel.css('display', 'none');
}
return $(this);
},
value: function() {
var dateobj = {};
var datecontainer1 = $(this.children('span').get(0));
var datecontainer2 = $(this.children('span').get(1));
var period = this.find('.periodsel').prop('checked'); // attr() -> prop()
dateobj.calendar = this.find('.calsel').val();
dateobj.dateval1 = '';
var year1 = datecontainer1.find('.yearsel').val();
if (isNaN(year1) || (year1 == 0)) {
alert('Date with invalid year! Assumed year 1');
year1 = 1;
}
dateobj.dateval1 += year1;
var month1 = datecontainer1.find('.monthsel').val();
if (month1 > 0) {
dateobj.dateval1 += '-' + month1;
var day1 = datecontainer1.find('.daysel').val();
if ((day1 != '-') && (day1 > 0)) {
dateobj.dateval1 += '-' + day1;
}
}
dateobj.era1 = datecontainer1.find('.erasel').val();
if (period) {
dateobj.dateval2 = '';
var year2 = datecontainer2.find('.yearsel').val();
if (isNaN(year2) || (year2 == 0)) {
alert('Period with invalid year! Assumed year ' + year1);
year2 = year1;
}
dateobj.dateval2 += year2;
var month2 = datecontainer2.find('.monthsel').val();
if (month2 > 0) {
dateobj.dateval2 += '-' + month2;
var day2 = datecontainer2.find('.daysel').val();
if ((day2 != '-') && (day2 > 0)) {
dateobj.dateval2 += '-' + day2;
}
}
dateobj.era2 = datecontainer2.find('.erasel').val();
}
// console.log("in function value: dateobj is " + JSON.stringify(dateobj));
return dateobj;
},
}
$.fn.dateobj = function(method) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
throw 'Method ' + method + ' does not exist on jQuery.tooltip';
}
};
})( jQuery ); |
d1 = parse_datestr(dateobj.dateval1, dateobj.calendar, dateobj.era1, 'START');
d2 = parse_datestr(dateobj.dateval2, dateobj.calendar, dateobj.era2, 'END');
if (d1.year < 0) { | random_line_split |
attr.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutNullableHeap};
use dom::bindings::js::{LayoutJS, Root, RootedReference};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{AttributeMutation, Element};
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use std::borrow::ToOwned;
use std::cell::Ref;
use std::mem;
use std::ops::Deref;
use string_cache::{Atom, Namespace};
use util::str::{DOMString, parse_unsigned_integer, split_html_space_chars, str_join};
#[derive(JSTraceable, PartialEq, Clone, HeapSizeOf)]
pub enum AttrValue {
String(DOMString),
TokenList(DOMString, Vec<Atom>),
UInt(DOMString, u32),
Atom(Atom),
}
impl AttrValue {
pub fn from_serialized_tokenlist(tokens: DOMString) -> AttrValue {
let atoms =
split_html_space_chars(&tokens)
.map(Atom::from_slice)
.fold(vec![], |mut acc, atom| {
if !acc.contains(&atom) { acc.push(atom) }
acc
});
AttrValue::TokenList(tokens, atoms)
}
pub fn from_atomic_tokens(atoms: Vec<Atom>) -> AttrValue {
let tokens = str_join(&atoms, "\x20");
AttrValue::TokenList(tokens, atoms)
}
// https://html.spec.whatwg.org/multipage/#reflecting-content-attributes-in-idl-attributes:idl-unsigned-long
pub fn from_u32(string: DOMString, default: u32) -> AttrValue {
let result = parse_unsigned_integer(string.chars()).unwrap_or(default);
let result = if result > 2147483647 {
default
} else {
result
};
AttrValue::UInt(string, result)
}
// https://html.spec.whatwg.org/multipage/#limited-to-only-non-negative-numbers-greater-than-zero
pub fn from_limited_u32(string: DOMString, default: u32) -> AttrValue {
let result = parse_unsigned_integer(string.chars()).unwrap_or(default);
let result = if result == 0 || result > 2147483647 {
default
} else {
result
};
AttrValue::UInt(string, result)
}
pub fn from_atomic(string: DOMString) -> AttrValue {
let value = Atom::from_slice(&string);
AttrValue::Atom(value)
}
pub fn as_tokens(&self) -> &[Atom] {
match *self {
AttrValue::TokenList(_, ref tokens) => tokens,
_ => panic!("Tokens not found"),
}
}
pub fn as_atom(&self) -> &Atom {
match *self {
AttrValue::Atom(ref value) => value,
_ => panic!("Atom not found"),
}
}
/// Return the AttrValue as its integer representation, if any.
/// This corresponds to attribute values returned as `AttrValue::UInt(_)`
/// by `VirtualMethods::parse_plain_attribute()`.
pub fn as_uint(&self) -> u32 {
if let AttrValue::UInt(_, value) = *self {
value
} else {
panic!("Uint not found");
}
}
}
impl Deref for AttrValue {
type Target = str;
fn deref(&self) -> &str {
match *self {
AttrValue::String(ref value) |
AttrValue::TokenList(ref value, _) |
AttrValue::UInt(ref value, _) => &value,
AttrValue::Atom(ref value) => &value,
}
}
}
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
reflector_: Reflector,
local_name: Atom,
value: DOMRefCell<AttrValue>,
name: Atom,
namespace: Namespace,
prefix: Option<Atom>,
/// the element that owns this attribute.
owner: MutNullableHeap<JS<Element>>,
}
impl Attr {
fn new_inherited(local_name: Atom, value: AttrValue, name: Atom, namespace: Namespace,
prefix: Option<Atom>, owner: Option<&Element>) -> Attr {
Attr {
reflector_: Reflector::new(),
local_name: local_name,
value: DOMRefCell::new(value),
name: name,
namespace: namespace,
prefix: prefix,
owner: MutNullableHeap::new(owner.map(JS::from_ref)),
}
}
pub fn new(window: &Window, local_name: Atom, value: AttrValue,
name: Atom, namespace: Namespace,
prefix: Option<Atom>, owner: Option<&Element>) -> Root<Attr> {
reflect_dom_object(
box Attr::new_inherited(local_name, value, name, namespace, prefix, owner),
GlobalRef::Window(window),
AttrBinding::Wrap)
}
#[inline]
pub fn name(&self) -> &Atom {
&self.name
}
#[inline]
pub fn namespace(&self) -> &Namespace { | #[inline]
pub fn prefix(&self) -> &Option<Atom> {
&self.prefix
}
}
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
(**self.local_name()).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
(**self.value()).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn SetValue(&self, value: DOMString) {
match self.owner() {
None => *self.value.borrow_mut() = AttrValue::String(value),
Some(owner) => {
let value = owner.r().parse_attribute(&self.namespace, self.local_name(), value);
self.set_value(value, owner.r());
}
}
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn TextContent(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn SetTextContent(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn NodeValue(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn SetNodeValue(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString {
(*self.name).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
let Namespace(ref atom) = self.namespace;
match &**atom {
"" => None,
url => Some(url.to_owned()),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
self.prefix().as_ref().map(|p| (**p).to_owned())
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> {
self.owner()
}
// https://dom.spec.whatwg.org/#dom-attr-specified
fn Specified(&self) -> bool {
true // Always returns true
}
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
assert!(Some(owner) == self.owner().r());
mem::swap(&mut *self.value.borrow_mut(), &mut value);
if self.namespace == ns!("") {
vtable_for(NodeCast::from_ref(owner)).attribute_mutated(
self, AttributeMutation::Set(Some(&value)));
}
}
pub fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &Atom {
&self.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
let ref ns = self.namespace;
match (self.owner().r(), owner) {
(None, Some(new)) => {
// Already in the list of attributes of new owner.
assert!(new.get_attribute(&ns, &self.local_name) == Some(Root::from_ref(self)))
}
(Some(old), None) => {
// Already gone from the list of attributes of old owner.
assert!(old.get_attribute(&ns, &self.local_name).is_none())
}
(old, new) => assert!(old == new)
}
self.owner.set(owner.map(JS::from_ref))
}
pub fn owner(&self) -> Option<Root<Element>> {
self.owner.get().map(Root::from_rooted)
}
pub fn summarize(&self) -> AttrInfo {
let Namespace(ref ns) = self.namespace;
AttrInfo {
namespace: (**ns).to_owned(),
name: self.Name(),
value: self.Value(),
}
}
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout {
unsafe fn value_forever(&self) -> &'static AttrValue;
unsafe fn value_ref_forever(&self) -> &'static str;
unsafe fn value_atom_forever(&self) -> Option<Atom>;
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>;
unsafe fn local_name_atom_forever(&self) -> Atom;
unsafe fn value_for_layout(&self) -> &AttrValue;
}
#[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> {
#[inline]
unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction.
mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout())
}
#[inline]
unsafe fn value_ref_forever(&self) -> &'static str {
&**self.value_forever()
}
#[inline]
unsafe fn value_atom_forever(&self) -> Option<Atom> {
let value = (*self.unsafe_get()).value.borrow_for_layout();
match *value {
AttrValue::Atom(ref val) => Some(val.clone()),
_ => None,
}
}
#[inline]
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> {
// This transmute is used to cheat the lifetime restriction.
match *self.value_forever() {
AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None,
}
}
#[inline]
unsafe fn local_name_atom_forever(&self) -> Atom {
(*self.unsafe_get()).local_name.clone()
}
#[inline]
unsafe fn value_for_layout(&self) -> &AttrValue {
(*self.unsafe_get()).value.borrow_for_layout()
}
} | &self.namespace
}
| random_line_split |
attr.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutNullableHeap};
use dom::bindings::js::{LayoutJS, Root, RootedReference};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{AttributeMutation, Element};
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use std::borrow::ToOwned;
use std::cell::Ref;
use std::mem;
use std::ops::Deref;
use string_cache::{Atom, Namespace};
use util::str::{DOMString, parse_unsigned_integer, split_html_space_chars, str_join};
#[derive(JSTraceable, PartialEq, Clone, HeapSizeOf)]
pub enum AttrValue {
String(DOMString),
TokenList(DOMString, Vec<Atom>),
UInt(DOMString, u32),
Atom(Atom),
}
impl AttrValue {
pub fn from_serialized_tokenlist(tokens: DOMString) -> AttrValue {
let atoms =
split_html_space_chars(&tokens)
.map(Atom::from_slice)
.fold(vec![], |mut acc, atom| {
if !acc.contains(&atom) { acc.push(atom) }
acc
});
AttrValue::TokenList(tokens, atoms)
}
pub fn from_atomic_tokens(atoms: Vec<Atom>) -> AttrValue {
let tokens = str_join(&atoms, "\x20");
AttrValue::TokenList(tokens, atoms)
}
// https://html.spec.whatwg.org/multipage/#reflecting-content-attributes-in-idl-attributes:idl-unsigned-long
pub fn from_u32(string: DOMString, default: u32) -> AttrValue {
let result = parse_unsigned_integer(string.chars()).unwrap_or(default);
let result = if result > 2147483647 {
default
} else {
result
};
AttrValue::UInt(string, result)
}
// https://html.spec.whatwg.org/multipage/#limited-to-only-non-negative-numbers-greater-than-zero
pub fn from_limited_u32(string: DOMString, default: u32) -> AttrValue {
let result = parse_unsigned_integer(string.chars()).unwrap_or(default);
let result = if result == 0 || result > 2147483647 {
default
} else {
result
};
AttrValue::UInt(string, result)
}
pub fn from_atomic(string: DOMString) -> AttrValue {
let value = Atom::from_slice(&string);
AttrValue::Atom(value)
}
pub fn as_tokens(&self) -> &[Atom] {
match *self {
AttrValue::TokenList(_, ref tokens) => tokens,
_ => panic!("Tokens not found"),
}
}
pub fn as_atom(&self) -> &Atom {
match *self {
AttrValue::Atom(ref value) => value,
_ => panic!("Atom not found"),
}
}
/// Return the AttrValue as its integer representation, if any.
/// This corresponds to attribute values returned as `AttrValue::UInt(_)`
/// by `VirtualMethods::parse_plain_attribute()`.
pub fn as_uint(&self) -> u32 {
if let AttrValue::UInt(_, value) = *self {
value
} else {
panic!("Uint not found");
}
}
}
impl Deref for AttrValue {
type Target = str;
fn deref(&self) -> &str {
match *self {
AttrValue::String(ref value) |
AttrValue::TokenList(ref value, _) |
AttrValue::UInt(ref value, _) => &value,
AttrValue::Atom(ref value) => &value,
}
}
}
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
reflector_: Reflector,
local_name: Atom,
value: DOMRefCell<AttrValue>,
name: Atom,
namespace: Namespace,
prefix: Option<Atom>,
/// the element that owns this attribute.
owner: MutNullableHeap<JS<Element>>,
}
impl Attr {
fn new_inherited(local_name: Atom, value: AttrValue, name: Atom, namespace: Namespace,
prefix: Option<Atom>, owner: Option<&Element>) -> Attr {
Attr {
reflector_: Reflector::new(),
local_name: local_name,
value: DOMRefCell::new(value),
name: name,
namespace: namespace,
prefix: prefix,
owner: MutNullableHeap::new(owner.map(JS::from_ref)),
}
}
pub fn new(window: &Window, local_name: Atom, value: AttrValue,
name: Atom, namespace: Namespace,
prefix: Option<Atom>, owner: Option<&Element>) -> Root<Attr> {
reflect_dom_object(
box Attr::new_inherited(local_name, value, name, namespace, prefix, owner),
GlobalRef::Window(window),
AttrBinding::Wrap)
}
#[inline]
pub fn name(&self) -> &Atom {
&self.name
}
#[inline]
pub fn namespace(&self) -> &Namespace {
&self.namespace
}
#[inline]
pub fn prefix(&self) -> &Option<Atom> {
&self.prefix
}
}
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
(**self.local_name()).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
(**self.value()).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn SetValue(&self, value: DOMString) {
match self.owner() {
None => *self.value.borrow_mut() = AttrValue::String(value),
Some(owner) => {
let value = owner.r().parse_attribute(&self.namespace, self.local_name(), value);
self.set_value(value, owner.r());
}
}
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn TextContent(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn SetTextContent(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn NodeValue(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn SetNodeValue(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString {
(*self.name).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
let Namespace(ref atom) = self.namespace;
match &**atom {
"" => None,
url => Some(url.to_owned()),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
self.prefix().as_ref().map(|p| (**p).to_owned())
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> {
self.owner()
}
// https://dom.spec.whatwg.org/#dom-attr-specified
fn Specified(&self) -> bool {
true // Always returns true
}
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
assert!(Some(owner) == self.owner().r());
mem::swap(&mut *self.value.borrow_mut(), &mut value);
if self.namespace == ns!("") {
vtable_for(NodeCast::from_ref(owner)).attribute_mutated(
self, AttributeMutation::Set(Some(&value)));
}
}
pub fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &Atom {
&self.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
let ref ns = self.namespace;
match (self.owner().r(), owner) {
(None, Some(new)) => {
// Already in the list of attributes of new owner.
assert!(new.get_attribute(&ns, &self.local_name) == Some(Root::from_ref(self)))
}
(Some(old), None) => {
// Already gone from the list of attributes of old owner.
assert!(old.get_attribute(&ns, &self.local_name).is_none())
}
(old, new) => assert!(old == new)
}
self.owner.set(owner.map(JS::from_ref))
}
pub fn owner(&self) -> Option<Root<Element>> {
self.owner.get().map(Root::from_rooted)
}
pub fn summarize(&self) -> AttrInfo {
let Namespace(ref ns) = self.namespace;
AttrInfo {
namespace: (**ns).to_owned(),
name: self.Name(),
value: self.Value(),
}
}
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout {
unsafe fn value_forever(&self) -> &'static AttrValue;
unsafe fn value_ref_forever(&self) -> &'static str;
unsafe fn value_atom_forever(&self) -> Option<Atom>;
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>;
unsafe fn local_name_atom_forever(&self) -> Atom;
unsafe fn value_for_layout(&self) -> &AttrValue;
}
#[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> {
#[inline]
unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction.
mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout())
}
#[inline]
unsafe fn value_ref_forever(&self) -> &'static str {
&**self.value_forever()
}
#[inline]
unsafe fn value_atom_forever(&self) -> Option<Atom> {
let value = (*self.unsafe_get()).value.borrow_for_layout();
match *value {
AttrValue::Atom(ref val) => Some(val.clone()),
_ => None,
}
}
#[inline]
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> |
#[inline]
unsafe fn local_name_atom_forever(&self) -> Atom {
(*self.unsafe_get()).local_name.clone()
}
#[inline]
unsafe fn value_for_layout(&self) -> &AttrValue {
(*self.unsafe_get()).value.borrow_for_layout()
}
}
| {
// This transmute is used to cheat the lifetime restriction.
match *self.value_forever() {
AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None,
}
} | identifier_body |
attr.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutNullableHeap};
use dom::bindings::js::{LayoutJS, Root, RootedReference};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{AttributeMutation, Element};
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use std::borrow::ToOwned;
use std::cell::Ref;
use std::mem;
use std::ops::Deref;
use string_cache::{Atom, Namespace};
use util::str::{DOMString, parse_unsigned_integer, split_html_space_chars, str_join};
#[derive(JSTraceable, PartialEq, Clone, HeapSizeOf)]
pub enum AttrValue {
String(DOMString),
TokenList(DOMString, Vec<Atom>),
UInt(DOMString, u32),
Atom(Atom),
}
impl AttrValue {
pub fn from_serialized_tokenlist(tokens: DOMString) -> AttrValue {
let atoms =
split_html_space_chars(&tokens)
.map(Atom::from_slice)
.fold(vec![], |mut acc, atom| {
if !acc.contains(&atom) { acc.push(atom) }
acc
});
AttrValue::TokenList(tokens, atoms)
}
pub fn from_atomic_tokens(atoms: Vec<Atom>) -> AttrValue {
let tokens = str_join(&atoms, "\x20");
AttrValue::TokenList(tokens, atoms)
}
// https://html.spec.whatwg.org/multipage/#reflecting-content-attributes-in-idl-attributes:idl-unsigned-long
pub fn | (string: DOMString, default: u32) -> AttrValue {
let result = parse_unsigned_integer(string.chars()).unwrap_or(default);
let result = if result > 2147483647 {
default
} else {
result
};
AttrValue::UInt(string, result)
}
// https://html.spec.whatwg.org/multipage/#limited-to-only-non-negative-numbers-greater-than-zero
pub fn from_limited_u32(string: DOMString, default: u32) -> AttrValue {
let result = parse_unsigned_integer(string.chars()).unwrap_or(default);
let result = if result == 0 || result > 2147483647 {
default
} else {
result
};
AttrValue::UInt(string, result)
}
pub fn from_atomic(string: DOMString) -> AttrValue {
let value = Atom::from_slice(&string);
AttrValue::Atom(value)
}
pub fn as_tokens(&self) -> &[Atom] {
match *self {
AttrValue::TokenList(_, ref tokens) => tokens,
_ => panic!("Tokens not found"),
}
}
pub fn as_atom(&self) -> &Atom {
match *self {
AttrValue::Atom(ref value) => value,
_ => panic!("Atom not found"),
}
}
/// Return the AttrValue as its integer representation, if any.
/// This corresponds to attribute values returned as `AttrValue::UInt(_)`
/// by `VirtualMethods::parse_plain_attribute()`.
pub fn as_uint(&self) -> u32 {
if let AttrValue::UInt(_, value) = *self {
value
} else {
panic!("Uint not found");
}
}
}
impl Deref for AttrValue {
type Target = str;
fn deref(&self) -> &str {
match *self {
AttrValue::String(ref value) |
AttrValue::TokenList(ref value, _) |
AttrValue::UInt(ref value, _) => &value,
AttrValue::Atom(ref value) => &value,
}
}
}
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
reflector_: Reflector,
local_name: Atom,
value: DOMRefCell<AttrValue>,
name: Atom,
namespace: Namespace,
prefix: Option<Atom>,
/// the element that owns this attribute.
owner: MutNullableHeap<JS<Element>>,
}
impl Attr {
fn new_inherited(local_name: Atom, value: AttrValue, name: Atom, namespace: Namespace,
prefix: Option<Atom>, owner: Option<&Element>) -> Attr {
Attr {
reflector_: Reflector::new(),
local_name: local_name,
value: DOMRefCell::new(value),
name: name,
namespace: namespace,
prefix: prefix,
owner: MutNullableHeap::new(owner.map(JS::from_ref)),
}
}
pub fn new(window: &Window, local_name: Atom, value: AttrValue,
name: Atom, namespace: Namespace,
prefix: Option<Atom>, owner: Option<&Element>) -> Root<Attr> {
reflect_dom_object(
box Attr::new_inherited(local_name, value, name, namespace, prefix, owner),
GlobalRef::Window(window),
AttrBinding::Wrap)
}
#[inline]
pub fn name(&self) -> &Atom {
&self.name
}
#[inline]
pub fn namespace(&self) -> &Namespace {
&self.namespace
}
#[inline]
pub fn prefix(&self) -> &Option<Atom> {
&self.prefix
}
}
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
(**self.local_name()).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
(**self.value()).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn SetValue(&self, value: DOMString) {
match self.owner() {
None => *self.value.borrow_mut() = AttrValue::String(value),
Some(owner) => {
let value = owner.r().parse_attribute(&self.namespace, self.local_name(), value);
self.set_value(value, owner.r());
}
}
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn TextContent(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn SetTextContent(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn NodeValue(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn SetNodeValue(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString {
(*self.name).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
let Namespace(ref atom) = self.namespace;
match &**atom {
"" => None,
url => Some(url.to_owned()),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
self.prefix().as_ref().map(|p| (**p).to_owned())
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> {
self.owner()
}
// https://dom.spec.whatwg.org/#dom-attr-specified
fn Specified(&self) -> bool {
true // Always returns true
}
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
assert!(Some(owner) == self.owner().r());
mem::swap(&mut *self.value.borrow_mut(), &mut value);
if self.namespace == ns!("") {
vtable_for(NodeCast::from_ref(owner)).attribute_mutated(
self, AttributeMutation::Set(Some(&value)));
}
}
pub fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &Atom {
&self.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
let ref ns = self.namespace;
match (self.owner().r(), owner) {
(None, Some(new)) => {
// Already in the list of attributes of new owner.
assert!(new.get_attribute(&ns, &self.local_name) == Some(Root::from_ref(self)))
}
(Some(old), None) => {
// Already gone from the list of attributes of old owner.
assert!(old.get_attribute(&ns, &self.local_name).is_none())
}
(old, new) => assert!(old == new)
}
self.owner.set(owner.map(JS::from_ref))
}
pub fn owner(&self) -> Option<Root<Element>> {
self.owner.get().map(Root::from_rooted)
}
pub fn summarize(&self) -> AttrInfo {
let Namespace(ref ns) = self.namespace;
AttrInfo {
namespace: (**ns).to_owned(),
name: self.Name(),
value: self.Value(),
}
}
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout {
unsafe fn value_forever(&self) -> &'static AttrValue;
unsafe fn value_ref_forever(&self) -> &'static str;
unsafe fn value_atom_forever(&self) -> Option<Atom>;
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>;
unsafe fn local_name_atom_forever(&self) -> Atom;
unsafe fn value_for_layout(&self) -> &AttrValue;
}
#[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> {
#[inline]
unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction.
mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout())
}
#[inline]
unsafe fn value_ref_forever(&self) -> &'static str {
&**self.value_forever()
}
#[inline]
unsafe fn value_atom_forever(&self) -> Option<Atom> {
let value = (*self.unsafe_get()).value.borrow_for_layout();
match *value {
AttrValue::Atom(ref val) => Some(val.clone()),
_ => None,
}
}
#[inline]
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> {
// This transmute is used to cheat the lifetime restriction.
match *self.value_forever() {
AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None,
}
}
#[inline]
unsafe fn local_name_atom_forever(&self) -> Atom {
(*self.unsafe_get()).local_name.clone()
}
#[inline]
unsafe fn value_for_layout(&self) -> &AttrValue {
(*self.unsafe_get()).value.borrow_for_layout()
}
}
| from_u32 | identifier_name |
simple-lexical-scope.rs | // Copyright 2013-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.
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print x
// gdb-check:$1 = false
// gdb-command:continue
// gdb-command:print x
// gdb-check:$2 = false
// gdb-command:continue
// gdb-command:print x
// gdb-check:$3 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$4 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$5 = 10.5
// gdb-command:continue
// gdb-command:print x
// gdb-check:$6 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$7 = false
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print x
// lldbg-check:[...]$0 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$1 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$2 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$3 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$4 = 10.5
// lldbr-check:(f64) x = 10.5
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$5 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$6 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
fn main() {
let x = false;
zzz(); // #break
sentinel();
{
zzz(); // #break
sentinel();
let x = 10;
zzz(); // #break
sentinel();
{
zzz(); // #break
sentinel();
let x = 10.5f64;
zzz(); // #break
sentinel();
}
zzz(); // #break
sentinel();
}
zzz(); // #break
sentinel();
}
fn | () {()}
fn sentinel() {()}
| zzz | identifier_name |
simple-lexical-scope.rs | // Copyright 2013-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.
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print x
// gdb-check:$1 = false
// gdb-command:continue
// gdb-command:print x
// gdb-check:$2 = false
// gdb-command:continue
// gdb-command:print x
// gdb-check:$3 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$4 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$5 = 10.5
// gdb-command:continue
// gdb-command:print x
// gdb-check:$6 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$7 = false
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print x
// lldbg-check:[...]$0 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$1 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$2 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$3 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$4 = 10.5
// lldbr-check:(f64) x = 10.5
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$5 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$6 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
fn main() {
let x = false;
zzz(); // #break
sentinel();
{
zzz(); // #break
sentinel();
let x = 10;
|
{
zzz(); // #break
sentinel();
let x = 10.5f64;
zzz(); // #break
sentinel();
}
zzz(); // #break
sentinel();
}
zzz(); // #break
sentinel();
}
fn zzz() {()}
fn sentinel() {()} | zzz(); // #break
sentinel(); | random_line_split |
simple-lexical-scope.rs | // Copyright 2013-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.
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print x
// gdb-check:$1 = false
// gdb-command:continue
// gdb-command:print x
// gdb-check:$2 = false
// gdb-command:continue
// gdb-command:print x
// gdb-check:$3 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$4 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$5 = 10.5
// gdb-command:continue
// gdb-command:print x
// gdb-check:$6 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$7 = false
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print x
// lldbg-check:[...]$0 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$1 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$2 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$3 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$4 = 10.5
// lldbr-check:(f64) x = 10.5
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$5 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$6 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
fn main() {
let x = false;
zzz(); // #break
sentinel();
{
zzz(); // #break
sentinel();
let x = 10;
zzz(); // #break
sentinel();
{
zzz(); // #break
sentinel();
let x = 10.5f64;
zzz(); // #break
sentinel();
}
zzz(); // #break
sentinel();
}
zzz(); // #break
sentinel();
}
fn zzz() |
fn sentinel() {()}
| {()} | identifier_body |
LyricItemContainer.tsx | import * as React from 'react';
import { observer } from 'mobx-react';
interface LyricItemContainerProps {
timeline: number;
text: string;
translation: string | object;
index: number;
}
@observer
export default class LyricItemContainer extends React.Component<LyricItemContainerProps> {
constructor(props: LyricItemContainerProps) |
render() {
const { text, translation, index } = this.props;
return (
<li
className={ 'muse-lyric__item' }
data-lyric-item-id={ index }
>
<span className={ 'muse-lyric__text' }>{ text }</span>
{(() => {
if (translation) {
return (
<span className={ 'muse-lyric__translation' }>
{ translation }
</span>
);
} // inject translation if exists
})()}
</li>
);
}
}
| {
super(props);
} | identifier_body |
LyricItemContainer.tsx | import * as React from 'react';
import { observer } from 'mobx-react';
interface LyricItemContainerProps {
timeline: number;
text: string;
translation: string | object;
index: number;
}
@observer
export default class LyricItemContainer extends React.Component<LyricItemContainerProps> {
| constructor(props: LyricItemContainerProps) {
super(props);
}
render() {
const { text, translation, index } = this.props;
return (
<li
className={ 'muse-lyric__item' }
data-lyric-item-id={ index }
>
<span className={ 'muse-lyric__text' }>{ text }</span>
{(() => {
if (translation) {
return (
<span className={ 'muse-lyric__translation' }>
{ translation }
</span>
);
} // inject translation if exists
})()}
</li>
);
}
} | random_line_split | |
LyricItemContainer.tsx | import * as React from 'react';
import { observer } from 'mobx-react';
interface LyricItemContainerProps {
timeline: number;
text: string;
translation: string | object;
index: number;
}
@observer
export default class LyricItemContainer extends React.Component<LyricItemContainerProps> {
| (props: LyricItemContainerProps) {
super(props);
}
render() {
const { text, translation, index } = this.props;
return (
<li
className={ 'muse-lyric__item' }
data-lyric-item-id={ index }
>
<span className={ 'muse-lyric__text' }>{ text }</span>
{(() => {
if (translation) {
return (
<span className={ 'muse-lyric__translation' }>
{ translation }
</span>
);
} // inject translation if exists
})()}
</li>
);
}
}
| constructor | identifier_name |
LyricItemContainer.tsx | import * as React from 'react';
import { observer } from 'mobx-react';
interface LyricItemContainerProps {
timeline: number;
text: string;
translation: string | object;
index: number;
}
@observer
export default class LyricItemContainer extends React.Component<LyricItemContainerProps> {
constructor(props: LyricItemContainerProps) {
super(props);
}
render() {
const { text, translation, index } = this.props;
return (
<li
className={ 'muse-lyric__item' }
data-lyric-item-id={ index }
>
<span className={ 'muse-lyric__text' }>{ text }</span>
{(() => {
if (translation) |
})()}
</li>
);
}
}
| {
return (
<span className={ 'muse-lyric__translation' }>
{ translation }
</span>
);
} // inject translation if exists
| conditional_block |
issue-40001-plugin.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(box_syntax, plugin, plugin_registrar, rustc_private)]
#![crate_type = "dylib"]
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
extern crate syntax;
use rustc_plugin::Registry;
use syntax::attr;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::symbol::Symbol;
use rustc::hir;
use rustc::hir::intravisit;
use rustc::hir::map as hir_map;
use hir::Node;
use rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext};
use rustc::ty;
use syntax::{ast, source_map};
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_late_lint_pass(box MissingWhitelistedAttrPass);
reg.register_attribute("whitelisted_attr".to_string(), Whitelisted);
}
declare_lint!(MISSING_WHITELISTED_ATTR, Deny,
"Checks for missing `whitelisted_attr` attribute");
struct MissingWhitelistedAttrPass;
impl LintPass for MissingWhitelistedAttrPass {
fn get_lints(&self) -> LintArray {
lint_array!(MISSING_WHITELISTED_ATTR)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingWhitelistedAttrPass {
fn check_fn(&mut self,
cx: &LateContext<'a, 'tcx>,
_: intravisit::FnKind<'tcx>,
_: &'tcx hir::FnDecl,
_: &'tcx hir::Body,
span: source_map::Span,
id: ast::NodeId) {
let item = match cx.tcx.hir().get(id) {
Node::Item(item) => item,
_ => cx.tcx.hir().expect_item(cx.tcx.hir().get_parent(id)),
};
if !attr::contains_name(&item.attrs, "whitelisted_attr") |
}
}
| {
cx.span_lint(MISSING_WHITELISTED_ATTR, span,
"Missing 'whitelisted_attr' attribute");
} | conditional_block |
issue-40001-plugin.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(box_syntax, plugin, plugin_registrar, rustc_private)]
#![crate_type = "dylib"]
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
extern crate syntax;
use rustc_plugin::Registry;
use syntax::attr;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::symbol::Symbol;
use rustc::hir;
use rustc::hir::intravisit;
use rustc::hir::map as hir_map;
use hir::Node;
use rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext};
use rustc::ty;
use syntax::{ast, source_map};
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_late_lint_pass(box MissingWhitelistedAttrPass);
reg.register_attribute("whitelisted_attr".to_string(), Whitelisted);
}
declare_lint!(MISSING_WHITELISTED_ATTR, Deny,
"Checks for missing `whitelisted_attr` attribute");
struct MissingWhitelistedAttrPass;
impl LintPass for MissingWhitelistedAttrPass {
fn get_lints(&self) -> LintArray {
lint_array!(MISSING_WHITELISTED_ATTR)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingWhitelistedAttrPass {
fn | (&mut self,
cx: &LateContext<'a, 'tcx>,
_: intravisit::FnKind<'tcx>,
_: &'tcx hir::FnDecl,
_: &'tcx hir::Body,
span: source_map::Span,
id: ast::NodeId) {
let item = match cx.tcx.hir().get(id) {
Node::Item(item) => item,
_ => cx.tcx.hir().expect_item(cx.tcx.hir().get_parent(id)),
};
if !attr::contains_name(&item.attrs, "whitelisted_attr") {
cx.span_lint(MISSING_WHITELISTED_ATTR, span,
"Missing 'whitelisted_attr' attribute");
}
}
}
| check_fn | identifier_name |
issue-40001-plugin.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(box_syntax, plugin, plugin_registrar, rustc_private)]
#![crate_type = "dylib"]
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
extern crate syntax;
use rustc_plugin::Registry;
use syntax::attr;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::symbol::Symbol;
use rustc::hir;
use rustc::hir::intravisit;
use rustc::hir::map as hir_map;
use hir::Node;
use rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext};
use rustc::ty;
use syntax::{ast, source_map};
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) |
declare_lint!(MISSING_WHITELISTED_ATTR, Deny,
"Checks for missing `whitelisted_attr` attribute");
struct MissingWhitelistedAttrPass;
impl LintPass for MissingWhitelistedAttrPass {
fn get_lints(&self) -> LintArray {
lint_array!(MISSING_WHITELISTED_ATTR)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingWhitelistedAttrPass {
fn check_fn(&mut self,
cx: &LateContext<'a, 'tcx>,
_: intravisit::FnKind<'tcx>,
_: &'tcx hir::FnDecl,
_: &'tcx hir::Body,
span: source_map::Span,
id: ast::NodeId) {
let item = match cx.tcx.hir().get(id) {
Node::Item(item) => item,
_ => cx.tcx.hir().expect_item(cx.tcx.hir().get_parent(id)),
};
if !attr::contains_name(&item.attrs, "whitelisted_attr") {
cx.span_lint(MISSING_WHITELISTED_ATTR, span,
"Missing 'whitelisted_attr' attribute");
}
}
}
| {
reg.register_late_lint_pass(box MissingWhitelistedAttrPass);
reg.register_attribute("whitelisted_attr".to_string(), Whitelisted);
} | identifier_body |
issue-40001-plugin.rs | // Copyright 2016 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 | // except according to those terms.
#![feature(box_syntax, plugin, plugin_registrar, rustc_private)]
#![crate_type = "dylib"]
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
extern crate syntax;
use rustc_plugin::Registry;
use syntax::attr;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::symbol::Symbol;
use rustc::hir;
use rustc::hir::intravisit;
use rustc::hir::map as hir_map;
use hir::Node;
use rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext};
use rustc::ty;
use syntax::{ast, source_map};
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_late_lint_pass(box MissingWhitelistedAttrPass);
reg.register_attribute("whitelisted_attr".to_string(), Whitelisted);
}
declare_lint!(MISSING_WHITELISTED_ATTR, Deny,
"Checks for missing `whitelisted_attr` attribute");
struct MissingWhitelistedAttrPass;
impl LintPass for MissingWhitelistedAttrPass {
fn get_lints(&self) -> LintArray {
lint_array!(MISSING_WHITELISTED_ATTR)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingWhitelistedAttrPass {
fn check_fn(&mut self,
cx: &LateContext<'a, 'tcx>,
_: intravisit::FnKind<'tcx>,
_: &'tcx hir::FnDecl,
_: &'tcx hir::Body,
span: source_map::Span,
id: ast::NodeId) {
let item = match cx.tcx.hir().get(id) {
Node::Item(item) => item,
_ => cx.tcx.hir().expect_item(cx.tcx.hir().get_parent(id)),
};
if !attr::contains_name(&item.attrs, "whitelisted_attr") {
cx.span_lint(MISSING_WHITELISTED_ATTR, span,
"Missing 'whitelisted_attr' attribute");
}
}
} | // option. This file may not be copied, modified, or distributed | random_line_split |
cms_plugins.py | # coding: utf-8
import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class GalleryForm(ModelForm):
|
class GalleryItemInline(admin.TabularInline):
model = GalleryItem
class GalleryPlugin(CMSPluginBase):
model = Gallery
form = GalleryForm
name = _("Gallery")
render_template = "gallery.html"
inlines = [
GalleryItemInline,
]
def render(self, context, instance, placeholder):
context.update({'instance': instance})
return context
plugin_pool.register_plugin(GalleryPlugin)
| class Meta:
model = Gallery
def clean_domid(self):
data = self.cleaned_data['domid']
if not re.match(r'^[a-zA-Z_]\w*$', data):
raise ValidationError(
_("The name must be a single word beginning with a letter"))
return data | identifier_body |
cms_plugins.py | # coding: utf-8
import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
| data = self.cleaned_data['domid']
if not re.match(r'^[a-zA-Z_]\w*$', data):
raise ValidationError(
_("The name must be a single word beginning with a letter"))
return data
class GalleryItemInline(admin.TabularInline):
model = GalleryItem
class GalleryPlugin(CMSPluginBase):
model = Gallery
form = GalleryForm
name = _("Gallery")
render_template = "gallery.html"
inlines = [
GalleryItemInline,
]
def render(self, context, instance, placeholder):
context.update({'instance': instance})
return context
plugin_pool.register_plugin(GalleryPlugin) | class GalleryForm(ModelForm):
class Meta:
model = Gallery
def clean_domid(self): | random_line_split |
cms_plugins.py | # coding: utf-8
import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class GalleryForm(ModelForm):
class Meta:
model = Gallery
def clean_domid(self):
data = self.cleaned_data['domid']
if not re.match(r'^[a-zA-Z_]\w*$', data):
|
return data
class GalleryItemInline(admin.TabularInline):
model = GalleryItem
class GalleryPlugin(CMSPluginBase):
model = Gallery
form = GalleryForm
name = _("Gallery")
render_template = "gallery.html"
inlines = [
GalleryItemInline,
]
def render(self, context, instance, placeholder):
context.update({'instance': instance})
return context
plugin_pool.register_plugin(GalleryPlugin)
| raise ValidationError(
_("The name must be a single word beginning with a letter")) | conditional_block |
cms_plugins.py | # coding: utf-8
import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class GalleryForm(ModelForm):
class Meta:
model = Gallery
def clean_domid(self):
data = self.cleaned_data['domid']
if not re.match(r'^[a-zA-Z_]\w*$', data):
raise ValidationError(
_("The name must be a single word beginning with a letter"))
return data
class GalleryItemInline(admin.TabularInline):
model = GalleryItem
class | (CMSPluginBase):
model = Gallery
form = GalleryForm
name = _("Gallery")
render_template = "gallery.html"
inlines = [
GalleryItemInline,
]
def render(self, context, instance, placeholder):
context.update({'instance': instance})
return context
plugin_pool.register_plugin(GalleryPlugin)
| GalleryPlugin | identifier_name |
test_model.py | #!/usr/bin/python3
# -*- encoding: utf-8 -*-
import unittest
from model import *
from example_data import expenses, payments, participations, persons, events
kasse = Gruppenkasse.create_new()
kasse.fill_with(expenses, payments, participations)
class TestGruppenkasse(unittest.TestCase):
def setUp(self):
...
def test_persons(self):
|
def test_events(self):
print(kasse.person_dict)
event_names = list(map(lambda p: p.name, kasse.events))
for name in event_names:
self.assertTrue(name in events, msg=name)
for name in events:
self.assertTrue(name in event_names, msg=name)
def test_event(self):
for event in kasse.events:
...#print(event)
def test_person(self):
for person in kasse.persons:
print(person, "\t{:5.2f}".format(person.balance / 100))
def test_payments(self):
print(kasse.payments)
if __name__ == '__main__':
unittest.main()
| person_names = list(map(lambda p: p.name, kasse.persons))
for name in person_names:
self.assertTrue(name in persons, msg=name) | identifier_body |
test_model.py | #!/usr/bin/python3
# -*- encoding: utf-8 -*-
import unittest
from model import *
from example_data import expenses, payments, participations, persons, events
kasse = Gruppenkasse.create_new()
kasse.fill_with(expenses, payments, participations)
class TestGruppenkasse(unittest.TestCase):
def setUp(self):
...
def test_persons(self):
person_names = list(map(lambda p: p.name, kasse.persons))
for name in person_names:
self.assertTrue(name in persons, msg=name)
def test_events(self):
print(kasse.person_dict)
event_names = list(map(lambda p: p.name, kasse.events))
for name in event_names:
self.assertTrue(name in events, msg=name)
for name in events:
self.assertTrue(name in event_names, msg=name)
def test_event(self):
for event in kasse.events:
...#print(event)
def test_person(self):
for person in kasse.persons:
print(person, "\t{:5.2f}".format(person.balance / 100))
def test_payments(self):
print(kasse.payments)
if __name__ == '__main__':
| unittest.main() | conditional_block | |
test_model.py | #!/usr/bin/python3
# -*- encoding: utf-8 -*-
import unittest
from model import *
from example_data import expenses, payments, participations, persons, events
kasse = Gruppenkasse.create_new()
kasse.fill_with(expenses, payments, participations)
class TestGruppenkasse(unittest.TestCase):
def setUp(self):
...
def test_persons(self):
person_names = list(map(lambda p: p.name, kasse.persons))
for name in person_names:
self.assertTrue(name in persons, msg=name)
def | (self):
print(kasse.person_dict)
event_names = list(map(lambda p: p.name, kasse.events))
for name in event_names:
self.assertTrue(name in events, msg=name)
for name in events:
self.assertTrue(name in event_names, msg=name)
def test_event(self):
for event in kasse.events:
...#print(event)
def test_person(self):
for person in kasse.persons:
print(person, "\t{:5.2f}".format(person.balance / 100))
def test_payments(self):
print(kasse.payments)
if __name__ == '__main__':
unittest.main()
| test_events | identifier_name |
test_model.py | #!/usr/bin/python3
# -*- encoding: utf-8 -*-
import unittest
from model import *
from example_data import expenses, payments, participations, persons, events
kasse = Gruppenkasse.create_new()
kasse.fill_with(expenses, payments, participations)
class TestGruppenkasse(unittest.TestCase):
def setUp(self):
...
def test_persons(self):
person_names = list(map(lambda p: p.name, kasse.persons))
for name in person_names:
self.assertTrue(name in persons, msg=name)
def test_events(self):
print(kasse.person_dict)
event_names = list(map(lambda p: p.name, kasse.events))
for name in event_names:
self.assertTrue(name in events, msg=name)
for name in events:
self.assertTrue(name in event_names, msg=name)
def test_event(self):
for event in kasse.events:
...#print(event) | def test_person(self):
for person in kasse.persons:
print(person, "\t{:5.2f}".format(person.balance / 100))
def test_payments(self):
print(kasse.payments)
if __name__ == '__main__':
unittest.main() | random_line_split | |
logcat-helper.ts | import byline = require("byline");
import { DeviceAndroidDebugBridge } from "./device-android-debug-bridge";
import { ChildProcess } from "child_process";
import * as semver from "semver";
interface IDeviceLoggingData {
loggingProcess: ChildProcess;
lineStream: any;
keepSingleProcess: boolean;
}
export class LogcatHelper implements Mobile.ILogcatHelper {
private mapDevicesLoggingData: IDictionary<IDeviceLoggingData>;
constructor(private $deviceLogProvider: Mobile.IDeviceLogProvider,
private $devicePlatformsConstants: Mobile.IDevicePlatformsConstants,
private $logger: ILogger,
private $injector: IInjector,
private $processService: IProcessService,
private $devicesService: Mobile.IDevicesService) {
this.mapDevicesLoggingData = Object.create(null);
}
public async start(options: Mobile.ILogcatStartOptions): Promise<void> {
const deviceIdentifier = options.deviceIdentifier;
if (deviceIdentifier && !this.mapDevicesLoggingData[deviceIdentifier]) |
}
private async getLogcatStream(deviceIdentifier: string, pid?: string) {
const device = await this.$devicesService.getDevice(deviceIdentifier);
const minAndroidWithLogcatPidSupport = "7.0.0";
const isLogcatPidSupported = semver.gte(semver.coerce(device.deviceInfo.version), minAndroidWithLogcatPidSupport);
const adb: Mobile.IDeviceAndroidDebugBridge = this.$injector.resolve(DeviceAndroidDebugBridge, { identifier: deviceIdentifier });
const logcatCommand = ["logcat"];
if (pid && isLogcatPidSupported) {
logcatCommand.push(`--pid=${pid}`);
}
const logcatStream = await adb.executeCommand(logcatCommand, { returnChildProcess: true });
return logcatStream;
}
public async dump(deviceIdentifier: string): Promise<void> {
const adb: Mobile.IDeviceAndroidDebugBridge = this.$injector.resolve(DeviceAndroidDebugBridge, { identifier: deviceIdentifier });
const logcatDumpStream = await adb.executeCommand(["logcat", "-d"], { returnChildProcess: true });
const lineStream = byline(logcatDumpStream.stdout);
lineStream.on('data', (line: NodeBuffer) => {
const lineText = line.toString();
this.$logger.trace(lineText);
});
logcatDumpStream.on("close", (code: number) => {
logcatDumpStream.removeAllListeners();
lineStream.removeAllListeners();
});
this.$processService.attachToProcessExitSignals(this, logcatDumpStream.kill);
}
/**
* Stops the logcat process for the specified device if keepSingleProcess is not passed on start
*/
public stop(deviceIdentifier: string): void {
if (this.mapDevicesLoggingData[deviceIdentifier] && !this.mapDevicesLoggingData[deviceIdentifier].keepSingleProcess) {
this.mapDevicesLoggingData[deviceIdentifier].loggingProcess.removeAllListeners();
this.mapDevicesLoggingData[deviceIdentifier].loggingProcess.kill("SIGINT");
this.mapDevicesLoggingData[deviceIdentifier].lineStream.removeAllListeners();
delete this.mapDevicesLoggingData[deviceIdentifier];
}
}
}
$injector.register("logcatHelper", LogcatHelper);
| {
this.mapDevicesLoggingData[deviceIdentifier] = {
loggingProcess: null,
lineStream: null,
keepSingleProcess: options.keepSingleProcess
};
const logcatStream = await this.getLogcatStream(deviceIdentifier, options.pid);
const lineStream = byline(logcatStream.stdout);
this.mapDevicesLoggingData[deviceIdentifier].loggingProcess = logcatStream;
this.mapDevicesLoggingData[deviceIdentifier].lineStream = lineStream;
logcatStream.stderr.on("data", (data: NodeBuffer) => {
this.$logger.trace("ADB logcat stderr: " + data.toString());
});
logcatStream.on("close", (code: number) => {
try {
this.stop(deviceIdentifier);
if (code !== 0) {
this.$logger.trace("ADB process exited with code " + code.toString());
}
} catch (err) {
// Ignore the error, the process is dead.
}
});
lineStream.on('data', (line: NodeBuffer) => {
const lineText = line.toString();
this.$deviceLogProvider.logData(lineText, this.$devicePlatformsConstants.Android, deviceIdentifier);
});
this.$processService.attachToProcessExitSignals(this, logcatStream.kill);
} | conditional_block |
logcat-helper.ts | import byline = require("byline");
import { DeviceAndroidDebugBridge } from "./device-android-debug-bridge";
import { ChildProcess } from "child_process";
import * as semver from "semver";
interface IDeviceLoggingData {
loggingProcess: ChildProcess;
lineStream: any;
keepSingleProcess: boolean;
}
export class | implements Mobile.ILogcatHelper {
private mapDevicesLoggingData: IDictionary<IDeviceLoggingData>;
constructor(private $deviceLogProvider: Mobile.IDeviceLogProvider,
private $devicePlatformsConstants: Mobile.IDevicePlatformsConstants,
private $logger: ILogger,
private $injector: IInjector,
private $processService: IProcessService,
private $devicesService: Mobile.IDevicesService) {
this.mapDevicesLoggingData = Object.create(null);
}
public async start(options: Mobile.ILogcatStartOptions): Promise<void> {
const deviceIdentifier = options.deviceIdentifier;
if (deviceIdentifier && !this.mapDevicesLoggingData[deviceIdentifier]) {
this.mapDevicesLoggingData[deviceIdentifier] = {
loggingProcess: null,
lineStream: null,
keepSingleProcess: options.keepSingleProcess
};
const logcatStream = await this.getLogcatStream(deviceIdentifier, options.pid);
const lineStream = byline(logcatStream.stdout);
this.mapDevicesLoggingData[deviceIdentifier].loggingProcess = logcatStream;
this.mapDevicesLoggingData[deviceIdentifier].lineStream = lineStream;
logcatStream.stderr.on("data", (data: NodeBuffer) => {
this.$logger.trace("ADB logcat stderr: " + data.toString());
});
logcatStream.on("close", (code: number) => {
try {
this.stop(deviceIdentifier);
if (code !== 0) {
this.$logger.trace("ADB process exited with code " + code.toString());
}
} catch (err) {
// Ignore the error, the process is dead.
}
});
lineStream.on('data', (line: NodeBuffer) => {
const lineText = line.toString();
this.$deviceLogProvider.logData(lineText, this.$devicePlatformsConstants.Android, deviceIdentifier);
});
this.$processService.attachToProcessExitSignals(this, logcatStream.kill);
}
}
private async getLogcatStream(deviceIdentifier: string, pid?: string) {
const device = await this.$devicesService.getDevice(deviceIdentifier);
const minAndroidWithLogcatPidSupport = "7.0.0";
const isLogcatPidSupported = semver.gte(semver.coerce(device.deviceInfo.version), minAndroidWithLogcatPidSupport);
const adb: Mobile.IDeviceAndroidDebugBridge = this.$injector.resolve(DeviceAndroidDebugBridge, { identifier: deviceIdentifier });
const logcatCommand = ["logcat"];
if (pid && isLogcatPidSupported) {
logcatCommand.push(`--pid=${pid}`);
}
const logcatStream = await adb.executeCommand(logcatCommand, { returnChildProcess: true });
return logcatStream;
}
public async dump(deviceIdentifier: string): Promise<void> {
const adb: Mobile.IDeviceAndroidDebugBridge = this.$injector.resolve(DeviceAndroidDebugBridge, { identifier: deviceIdentifier });
const logcatDumpStream = await adb.executeCommand(["logcat", "-d"], { returnChildProcess: true });
const lineStream = byline(logcatDumpStream.stdout);
lineStream.on('data', (line: NodeBuffer) => {
const lineText = line.toString();
this.$logger.trace(lineText);
});
logcatDumpStream.on("close", (code: number) => {
logcatDumpStream.removeAllListeners();
lineStream.removeAllListeners();
});
this.$processService.attachToProcessExitSignals(this, logcatDumpStream.kill);
}
/**
* Stops the logcat process for the specified device if keepSingleProcess is not passed on start
*/
public stop(deviceIdentifier: string): void {
if (this.mapDevicesLoggingData[deviceIdentifier] && !this.mapDevicesLoggingData[deviceIdentifier].keepSingleProcess) {
this.mapDevicesLoggingData[deviceIdentifier].loggingProcess.removeAllListeners();
this.mapDevicesLoggingData[deviceIdentifier].loggingProcess.kill("SIGINT");
this.mapDevicesLoggingData[deviceIdentifier].lineStream.removeAllListeners();
delete this.mapDevicesLoggingData[deviceIdentifier];
}
}
}
$injector.register("logcatHelper", LogcatHelper);
| LogcatHelper | identifier_name |
logcat-helper.ts | import byline = require("byline");
import { DeviceAndroidDebugBridge } from "./device-android-debug-bridge";
import { ChildProcess } from "child_process";
import * as semver from "semver";
interface IDeviceLoggingData {
loggingProcess: ChildProcess;
lineStream: any;
keepSingleProcess: boolean;
}
| export class LogcatHelper implements Mobile.ILogcatHelper {
private mapDevicesLoggingData: IDictionary<IDeviceLoggingData>;
constructor(private $deviceLogProvider: Mobile.IDeviceLogProvider,
private $devicePlatformsConstants: Mobile.IDevicePlatformsConstants,
private $logger: ILogger,
private $injector: IInjector,
private $processService: IProcessService,
private $devicesService: Mobile.IDevicesService) {
this.mapDevicesLoggingData = Object.create(null);
}
public async start(options: Mobile.ILogcatStartOptions): Promise<void> {
const deviceIdentifier = options.deviceIdentifier;
if (deviceIdentifier && !this.mapDevicesLoggingData[deviceIdentifier]) {
this.mapDevicesLoggingData[deviceIdentifier] = {
loggingProcess: null,
lineStream: null,
keepSingleProcess: options.keepSingleProcess
};
const logcatStream = await this.getLogcatStream(deviceIdentifier, options.pid);
const lineStream = byline(logcatStream.stdout);
this.mapDevicesLoggingData[deviceIdentifier].loggingProcess = logcatStream;
this.mapDevicesLoggingData[deviceIdentifier].lineStream = lineStream;
logcatStream.stderr.on("data", (data: NodeBuffer) => {
this.$logger.trace("ADB logcat stderr: " + data.toString());
});
logcatStream.on("close", (code: number) => {
try {
this.stop(deviceIdentifier);
if (code !== 0) {
this.$logger.trace("ADB process exited with code " + code.toString());
}
} catch (err) {
// Ignore the error, the process is dead.
}
});
lineStream.on('data', (line: NodeBuffer) => {
const lineText = line.toString();
this.$deviceLogProvider.logData(lineText, this.$devicePlatformsConstants.Android, deviceIdentifier);
});
this.$processService.attachToProcessExitSignals(this, logcatStream.kill);
}
}
private async getLogcatStream(deviceIdentifier: string, pid?: string) {
const device = await this.$devicesService.getDevice(deviceIdentifier);
const minAndroidWithLogcatPidSupport = "7.0.0";
const isLogcatPidSupported = semver.gte(semver.coerce(device.deviceInfo.version), minAndroidWithLogcatPidSupport);
const adb: Mobile.IDeviceAndroidDebugBridge = this.$injector.resolve(DeviceAndroidDebugBridge, { identifier: deviceIdentifier });
const logcatCommand = ["logcat"];
if (pid && isLogcatPidSupported) {
logcatCommand.push(`--pid=${pid}`);
}
const logcatStream = await adb.executeCommand(logcatCommand, { returnChildProcess: true });
return logcatStream;
}
public async dump(deviceIdentifier: string): Promise<void> {
const adb: Mobile.IDeviceAndroidDebugBridge = this.$injector.resolve(DeviceAndroidDebugBridge, { identifier: deviceIdentifier });
const logcatDumpStream = await adb.executeCommand(["logcat", "-d"], { returnChildProcess: true });
const lineStream = byline(logcatDumpStream.stdout);
lineStream.on('data', (line: NodeBuffer) => {
const lineText = line.toString();
this.$logger.trace(lineText);
});
logcatDumpStream.on("close", (code: number) => {
logcatDumpStream.removeAllListeners();
lineStream.removeAllListeners();
});
this.$processService.attachToProcessExitSignals(this, logcatDumpStream.kill);
}
/**
* Stops the logcat process for the specified device if keepSingleProcess is not passed on start
*/
public stop(deviceIdentifier: string): void {
if (this.mapDevicesLoggingData[deviceIdentifier] && !this.mapDevicesLoggingData[deviceIdentifier].keepSingleProcess) {
this.mapDevicesLoggingData[deviceIdentifier].loggingProcess.removeAllListeners();
this.mapDevicesLoggingData[deviceIdentifier].loggingProcess.kill("SIGINT");
this.mapDevicesLoggingData[deviceIdentifier].lineStream.removeAllListeners();
delete this.mapDevicesLoggingData[deviceIdentifier];
}
}
}
$injector.register("logcatHelper", LogcatHelper); | random_line_split | |
logcat-helper.ts | import byline = require("byline");
import { DeviceAndroidDebugBridge } from "./device-android-debug-bridge";
import { ChildProcess } from "child_process";
import * as semver from "semver";
interface IDeviceLoggingData {
loggingProcess: ChildProcess;
lineStream: any;
keepSingleProcess: boolean;
}
export class LogcatHelper implements Mobile.ILogcatHelper {
private mapDevicesLoggingData: IDictionary<IDeviceLoggingData>;
constructor(private $deviceLogProvider: Mobile.IDeviceLogProvider,
private $devicePlatformsConstants: Mobile.IDevicePlatformsConstants,
private $logger: ILogger,
private $injector: IInjector,
private $processService: IProcessService,
private $devicesService: Mobile.IDevicesService) {
this.mapDevicesLoggingData = Object.create(null);
}
public async start(options: Mobile.ILogcatStartOptions): Promise<void> |
private async getLogcatStream(deviceIdentifier: string, pid?: string) {
const device = await this.$devicesService.getDevice(deviceIdentifier);
const minAndroidWithLogcatPidSupport = "7.0.0";
const isLogcatPidSupported = semver.gte(semver.coerce(device.deviceInfo.version), minAndroidWithLogcatPidSupport);
const adb: Mobile.IDeviceAndroidDebugBridge = this.$injector.resolve(DeviceAndroidDebugBridge, { identifier: deviceIdentifier });
const logcatCommand = ["logcat"];
if (pid && isLogcatPidSupported) {
logcatCommand.push(`--pid=${pid}`);
}
const logcatStream = await adb.executeCommand(logcatCommand, { returnChildProcess: true });
return logcatStream;
}
public async dump(deviceIdentifier: string): Promise<void> {
const adb: Mobile.IDeviceAndroidDebugBridge = this.$injector.resolve(DeviceAndroidDebugBridge, { identifier: deviceIdentifier });
const logcatDumpStream = await adb.executeCommand(["logcat", "-d"], { returnChildProcess: true });
const lineStream = byline(logcatDumpStream.stdout);
lineStream.on('data', (line: NodeBuffer) => {
const lineText = line.toString();
this.$logger.trace(lineText);
});
logcatDumpStream.on("close", (code: number) => {
logcatDumpStream.removeAllListeners();
lineStream.removeAllListeners();
});
this.$processService.attachToProcessExitSignals(this, logcatDumpStream.kill);
}
/**
* Stops the logcat process for the specified device if keepSingleProcess is not passed on start
*/
public stop(deviceIdentifier: string): void {
if (this.mapDevicesLoggingData[deviceIdentifier] && !this.mapDevicesLoggingData[deviceIdentifier].keepSingleProcess) {
this.mapDevicesLoggingData[deviceIdentifier].loggingProcess.removeAllListeners();
this.mapDevicesLoggingData[deviceIdentifier].loggingProcess.kill("SIGINT");
this.mapDevicesLoggingData[deviceIdentifier].lineStream.removeAllListeners();
delete this.mapDevicesLoggingData[deviceIdentifier];
}
}
}
$injector.register("logcatHelper", LogcatHelper);
| {
const deviceIdentifier = options.deviceIdentifier;
if (deviceIdentifier && !this.mapDevicesLoggingData[deviceIdentifier]) {
this.mapDevicesLoggingData[deviceIdentifier] = {
loggingProcess: null,
lineStream: null,
keepSingleProcess: options.keepSingleProcess
};
const logcatStream = await this.getLogcatStream(deviceIdentifier, options.pid);
const lineStream = byline(logcatStream.stdout);
this.mapDevicesLoggingData[deviceIdentifier].loggingProcess = logcatStream;
this.mapDevicesLoggingData[deviceIdentifier].lineStream = lineStream;
logcatStream.stderr.on("data", (data: NodeBuffer) => {
this.$logger.trace("ADB logcat stderr: " + data.toString());
});
logcatStream.on("close", (code: number) => {
try {
this.stop(deviceIdentifier);
if (code !== 0) {
this.$logger.trace("ADB process exited with code " + code.toString());
}
} catch (err) {
// Ignore the error, the process is dead.
}
});
lineStream.on('data', (line: NodeBuffer) => {
const lineText = line.toString();
this.$deviceLogProvider.logData(lineText, this.$devicePlatformsConstants.Android, deviceIdentifier);
});
this.$processService.attachToProcessExitSignals(this, logcatStream.kill);
}
} | identifier_body |
update.py | # Copyright (c) 2013 Calin Crisan
# This file is part of motionEye.
#
# motionEye 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/>.
import logging
# versions
def get_version():
import motioneye
return motioneye.VERSION
def get_all_versions():
return []
def compare_versions(version1, version2):
version1 = [int(n) for n in version1.split('.')]
version2 = [int(n) for n in version2.split('.')] | length = min(len1, len2)
for i in xrange(length):
p1 = version1[i]
p2 = version2[i]
if p1 < p2:
return -1
elif p1 > p2:
return 1
if len1 < len2:
return -1
elif len1 > len2:
return 1
else:
return 0
def perform_update(version):
logging.error('updating is not implemented')
return False |
len1 = len(version1)
len2 = len(version2) | random_line_split |
update.py |
# Copyright (c) 2013 Calin Crisan
# This file is part of motionEye.
#
# motionEye 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/>.
import logging
# versions
def get_version():
import motioneye
return motioneye.VERSION
def get_all_versions():
return []
def compare_versions(version1, version2):
version1 = [int(n) for n in version1.split('.')]
version2 = [int(n) for n in version2.split('.')]
len1 = len(version1)
len2 = len(version2)
length = min(len1, len2)
for i in xrange(length):
p1 = version1[i]
p2 = version2[i]
if p1 < p2:
return -1
elif p1 > p2:
return 1
if len1 < len2:
return -1
elif len1 > len2:
return 1
else:
return 0
def | (version):
logging.error('updating is not implemented')
return False
| perform_update | identifier_name |
update.py |
# Copyright (c) 2013 Calin Crisan
# This file is part of motionEye.
#
# motionEye 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/>.
import logging
# versions
def get_version():
import motioneye
return motioneye.VERSION
def get_all_versions():
return []
def compare_versions(version1, version2):
version1 = [int(n) for n in version1.split('.')]
version2 = [int(n) for n in version2.split('.')]
len1 = len(version1)
len2 = len(version2)
length = min(len1, len2)
for i in xrange(length):
p1 = version1[i]
p2 = version2[i]
if p1 < p2:
return -1
elif p1 > p2:
return 1
if len1 < len2:
return -1
elif len1 > len2:
return 1
else:
return 0
def perform_update(version):
| logging.error('updating is not implemented')
return False | identifier_body | |
update.py |
# Copyright (c) 2013 Calin Crisan
# This file is part of motionEye.
#
# motionEye 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/>.
import logging
# versions
def get_version():
import motioneye
return motioneye.VERSION
def get_all_versions():
return []
def compare_versions(version1, version2):
version1 = [int(n) for n in version1.split('.')]
version2 = [int(n) for n in version2.split('.')]
len1 = len(version1)
len2 = len(version2)
length = min(len1, len2)
for i in xrange(length):
p1 = version1[i]
p2 = version2[i]
if p1 < p2:
return -1
elif p1 > p2:
return 1
if len1 < len2:
|
elif len1 > len2:
return 1
else:
return 0
def perform_update(version):
logging.error('updating is not implemented')
return False
| return -1 | conditional_block |
main.rs | extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate curl;
extern crate inflections;
mod parser;
mod types;
mod writer;
use std::env;
use std::collections::HashMap;
use curl::easy::Easy;
fn main() |
fn download(url: &str) -> String {
let mut buf = Vec::new();
{
let mut easy = Easy::new();
easy.url(url).unwrap();
let mut transfer = easy.transfer();
transfer.write_function(|data| {
buf.extend(data);
Ok(data.len())
}).unwrap();
transfer.perform().unwrap();
}
String::from_utf8(buf).unwrap()
}
| {
let mut args = env::args();
let name = args.next().unwrap();
let (version, path) = match (args.next(), args.next()) {
(Some(v), Some(f)) => (v,f),
_ => {
println!("Usage: {} [qemu-version] [export-path]", name);
::std::process::exit(1);
}
};
let schema = download(&format!("https://raw.githubusercontent.com/qemu/qemu/{}/qapi-schema.json", version));
let events = download(&format!("https://raw.githubusercontent.com/qemu/qemu/{}/qapi/event.json", version));
let res = parser::parse(&schema).unwrap();
println!("{:?}", res);
let mut types = HashMap::new();
types::to_types(res, &mut types);
println!("\n\n\n");
println!("{:?}", types);
let res = parser::parse(&events).unwrap();
let sections = types::to_sections(res, &mut types);
println!("\n\n\n");
println!("{:?}", sections);
writer::write(path, sections, types).unwrap();
} | identifier_body |
main.rs | extern crate serde;
extern crate serde_json;
#[macro_use] | extern crate serde_derive;
extern crate curl;
extern crate inflections;
mod parser;
mod types;
mod writer;
use std::env;
use std::collections::HashMap;
use curl::easy::Easy;
fn main() {
let mut args = env::args();
let name = args.next().unwrap();
let (version, path) = match (args.next(), args.next()) {
(Some(v), Some(f)) => (v,f),
_ => {
println!("Usage: {} [qemu-version] [export-path]", name);
::std::process::exit(1);
}
};
let schema = download(&format!("https://raw.githubusercontent.com/qemu/qemu/{}/qapi-schema.json", version));
let events = download(&format!("https://raw.githubusercontent.com/qemu/qemu/{}/qapi/event.json", version));
let res = parser::parse(&schema).unwrap();
println!("{:?}", res);
let mut types = HashMap::new();
types::to_types(res, &mut types);
println!("\n\n\n");
println!("{:?}", types);
let res = parser::parse(&events).unwrap();
let sections = types::to_sections(res, &mut types);
println!("\n\n\n");
println!("{:?}", sections);
writer::write(path, sections, types).unwrap();
}
fn download(url: &str) -> String {
let mut buf = Vec::new();
{
let mut easy = Easy::new();
easy.url(url).unwrap();
let mut transfer = easy.transfer();
transfer.write_function(|data| {
buf.extend(data);
Ok(data.len())
}).unwrap();
transfer.perform().unwrap();
}
String::from_utf8(buf).unwrap()
} | random_line_split | |
main.rs | extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate curl;
extern crate inflections;
mod parser;
mod types;
mod writer;
use std::env;
use std::collections::HashMap;
use curl::easy::Easy;
fn | () {
let mut args = env::args();
let name = args.next().unwrap();
let (version, path) = match (args.next(), args.next()) {
(Some(v), Some(f)) => (v,f),
_ => {
println!("Usage: {} [qemu-version] [export-path]", name);
::std::process::exit(1);
}
};
let schema = download(&format!("https://raw.githubusercontent.com/qemu/qemu/{}/qapi-schema.json", version));
let events = download(&format!("https://raw.githubusercontent.com/qemu/qemu/{}/qapi/event.json", version));
let res = parser::parse(&schema).unwrap();
println!("{:?}", res);
let mut types = HashMap::new();
types::to_types(res, &mut types);
println!("\n\n\n");
println!("{:?}", types);
let res = parser::parse(&events).unwrap();
let sections = types::to_sections(res, &mut types);
println!("\n\n\n");
println!("{:?}", sections);
writer::write(path, sections, types).unwrap();
}
fn download(url: &str) -> String {
let mut buf = Vec::new();
{
let mut easy = Easy::new();
easy.url(url).unwrap();
let mut transfer = easy.transfer();
transfer.write_function(|data| {
buf.extend(data);
Ok(data.len())
}).unwrap();
transfer.perform().unwrap();
}
String::from_utf8(buf).unwrap()
}
| main | identifier_name |
core.js | var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Support: IE9
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "@VERSION",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler and self cleanup method
completed = function() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
// Support: Safari <= 5.1 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if ( obj.constructor &&
!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: JSON.parse,
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
trim: function( text ) {
return text == null ? "" : core_trim.call( text );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : core_indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: Date.now,
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function | ( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
| isArraylike | identifier_name |
core.js | var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Support: IE9
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "@VERSION",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler and self cleanup method
completed = function() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
// Support: Safari <= 5.1 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if ( obj.constructor &&
!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: JSON.parse,
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
trim: function( text ) {
return text == null ? "" : core_trim.call( text );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : core_indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0, | if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: Date.now,
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document); | length = elems.length,
bulk = key == null;
// Sets many values | random_line_split |
core.js | var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Support: IE9
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "@VERSION",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler and self cleanup method
completed = function() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
// Support: Safari <= 5.1 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if ( obj.constructor &&
!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: JSON.parse,
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
trim: function( text ) {
return text == null ? "" : core_trim.call( text );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : core_indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: Date.now,
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) |
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
| {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
} | identifier_body |
core.js | var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Support: IE9
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "@VERSION",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler and self cleanup method
completed = function() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else |
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
// Support: Safari <= 5.1 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if ( obj.constructor &&
!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: JSON.parse,
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
trim: function( text ) {
return text == null ? "" : core_trim.call( text );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : core_indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: Date.now,
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
| {
return this.constructor( context ).find( selector );
} | conditional_block |
toUniqueStringsArray.test.js | import toUniqueStringsArray from "../toUniqueStringsArray";
describe("toUniqueStringsArray", () => {
it("sane defaults", () => {
expect(toUniqueStringsArray()).toEqual([]); | });
it("handles a single string", () => {
expect(toUniqueStringsArray("red")).toEqual(["red"]);
});
it("handles comma separated string", () => {
expect(toUniqueStringsArray("red, blue, red, green, blue")).toEqual([
"red",
"blue",
"green",
]);
});
it("handles array of strings", () => {
expect(toUniqueStringsArray(["red", "blue", "red", "green", "blue"])).toEqual([
"red",
"blue",
"green",
]);
});
}); | expect(toUniqueStringsArray(null)).toEqual([]);
expect(toUniqueStringsArray({})).toEqual([]);
expect(toUniqueStringsArray("")).toEqual([]);
expect(toUniqueStringsArray([])).toEqual([]); | random_line_split |
GeometryBatchAnalysisSpec.js | import {SpatialAnalystService} from '../../../src/mapboxgl/services/SpatialAnalystService';
import {GeometryBufferAnalystParameters} from '../../../src/common/iServer/GeometryBufferAnalystParameters';
import {GeometryOverlayAnalystParameters} from '../../../src/common/iServer/GeometryOverlayAnalystParameters';
import {BufferSetting} from '../../../src/common/iServer/BufferSetting';
import {BufferDistance} from '../../../src/common/iServer/BufferDistance';
import {BufferEndType} from '../../../src/common/REST';
import {OverlayOperationType} from '../../../src/common/REST';
import { FetchRequest } from '../../../src/common/util/FetchRequest';
var serviceUrl = GlobeParameter.spatialAnalystURL;
describe('mapboxgl_SpatialAnalystService_geometryBatchAnalysis', () => {
var originalTimeout;
var serviceResult;
beforeEach(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;
serviceResult = null;
});
afterEach(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
it('geometryBatchAnalysis', (done) => {
//缓冲区分析参数
var bufferLine = {
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [[117, 40.50], [118, 40]]
}
};
var geoBufferAnalystParams = {
analystName: "buffer",
param: new GeometryBufferAnalystParameters({
sourceGeometry: bufferLine,
sourceGeometrySRID: 4326,
bufferSetting: new BufferSetting({
endType: BufferEndType.ROUND,
leftDistance: new BufferDistance({value: 0.05}),
rightDistance: new BufferDistance({value: 0.05}),
semicircleLineSegment: 10
})
})
};
//叠加分析参数
var sourceGeometry = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [[[116, 39.75],
[116, 39.15],
[117, 39.15],
[117, 39.85],
[116, 39.85]]]
}
};
var operateGeometry = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [[[116.25, 40.5],
[116.25, 38.5],
[116.75, 38.5],
[116.75, 40.5],
[116.25, 40.5]]]
}
};
var OverlayBatchAnalystParameters = {
analystName: "overlay",
param: new GeometryOverlayAnalystParameters({
sourceGeometry: sourceGeometry,
operateGeometry: operateGeometry,
operation: OverlayOperationType.CLIP
})
};
//批量分析参数
var parameters = [geoBufferAnalystParams, OverlayBatchAnalystParameters];
//批量分析
spyOn(FetchRequest, 'commit').and.callFake((method, testUrl, params, options) => {
expect(method).toBe("POST");
expect(testUrl).toBe(serviceUrl + "/geometry/batchanalyst?returnContent=true&ignoreAnalystParam=true");
var paramsObj = JSON.parse(params.replace(/'/g, "\""));
expect(paramsObj[0].analystName).toBe("buffer");
expect(paramsObj[0].param.analystParameter.endType).toBe("ROUND");
expect(paramsObj[0].param.analystParameter.leftDistance.value).toEqual(0.05);
expect(paramsObj[1].analystName).toBe("overlay");
expect(paramsObj[1].param.operation).toBe("CLIP");
expect(options).not.toBeNull();
return Promise.resolve(new Response(JSON.stringify(geometryBatchAnalystEscapedJson)));
});
new SpatialAnalystService(serviceUrl).geometrybatchAnalysis(parameters, function (result) {
serviceResult = result;
expect(serviceResult).not.toBeNull();
expect(serviceResult.type).toBe("processCompleted");
expect(serviceResult.result.succeed).toEqual(true);
expect(serviceResult.result.length).toEqual(1);
for (var i = 0; i < serviceResult.result.length; i++) {
expect(serviceResult.result[ | i].resultGeometry).not.toBeNull();
expect(serviceResult.result[i].resultGeometry.geometry).not.toBeNull();
expect(serviceResult.result[i].resultGeometry.geometry.coordinates.length).toBeGreaterThan(0);
expect(serviceResult.result[i].resultGeometry.geometry.type).toBe("MultiPolygon");
expect(serviceResult.result[i].resultGeometry.type).toBe("Feature");
expect(serviceResult.result[i].succeed).toBe(true);
}
done();
});
});
}); | conditional_block | |
GeometryBatchAnalysisSpec.js | import {SpatialAnalystService} from '../../../src/mapboxgl/services/SpatialAnalystService';
import {GeometryBufferAnalystParameters} from '../../../src/common/iServer/GeometryBufferAnalystParameters';
import {GeometryOverlayAnalystParameters} from '../../../src/common/iServer/GeometryOverlayAnalystParameters';
import {BufferSetting} from '../../../src/common/iServer/BufferSetting';
import {BufferDistance} from '../../../src/common/iServer/BufferDistance';
import {BufferEndType} from '../../../src/common/REST';
import {OverlayOperationType} from '../../../src/common/REST';
import { FetchRequest } from '../../../src/common/util/FetchRequest';
var serviceUrl = GlobeParameter.spatialAnalystURL;
describe('mapboxgl_SpatialAnalystService_geometryBatchAnalysis', () => {
var originalTimeout;
var serviceResult;
beforeEach(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;
serviceResult = null;
});
afterEach(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
it('geometryBatchAnalysis', (done) => {
//缓冲区分析参数
var bufferLine = {
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [[117, 40.50], [118, 40]]
}
};
var geoBufferAnalystParams = {
analystName: "buffer",
param: new GeometryBufferAnalystParameters({
sourceGeometry: bufferLine,
sourceGeometrySRID: 4326,
bufferSetting: new BufferSetting({
endType: BufferEndType.ROUND,
leftDistance: new BufferDistance({value: 0.05}),
rightDistance: new BufferDistance({value: 0.05}),
semicircleLineSegment: 10
})
}) | var sourceGeometry = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [[[116, 39.75],
[116, 39.15],
[117, 39.15],
[117, 39.85],
[116, 39.85]]]
}
};
var operateGeometry = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [[[116.25, 40.5],
[116.25, 38.5],
[116.75, 38.5],
[116.75, 40.5],
[116.25, 40.5]]]
}
};
var OverlayBatchAnalystParameters = {
analystName: "overlay",
param: new GeometryOverlayAnalystParameters({
sourceGeometry: sourceGeometry,
operateGeometry: operateGeometry,
operation: OverlayOperationType.CLIP
})
};
//批量分析参数
var parameters = [geoBufferAnalystParams, OverlayBatchAnalystParameters];
//批量分析
spyOn(FetchRequest, 'commit').and.callFake((method, testUrl, params, options) => {
expect(method).toBe("POST");
expect(testUrl).toBe(serviceUrl + "/geometry/batchanalyst?returnContent=true&ignoreAnalystParam=true");
var paramsObj = JSON.parse(params.replace(/'/g, "\""));
expect(paramsObj[0].analystName).toBe("buffer");
expect(paramsObj[0].param.analystParameter.endType).toBe("ROUND");
expect(paramsObj[0].param.analystParameter.leftDistance.value).toEqual(0.05);
expect(paramsObj[1].analystName).toBe("overlay");
expect(paramsObj[1].param.operation).toBe("CLIP");
expect(options).not.toBeNull();
return Promise.resolve(new Response(JSON.stringify(geometryBatchAnalystEscapedJson)));
});
new SpatialAnalystService(serviceUrl).geometrybatchAnalysis(parameters, function (result) {
serviceResult = result;
expect(serviceResult).not.toBeNull();
expect(serviceResult.type).toBe("processCompleted");
expect(serviceResult.result.succeed).toEqual(true);
expect(serviceResult.result.length).toEqual(1);
for (var i = 0; i < serviceResult.result.length; i++) {
expect(serviceResult.result[i].resultGeometry).not.toBeNull();
expect(serviceResult.result[i].resultGeometry.geometry).not.toBeNull();
expect(serviceResult.result[i].resultGeometry.geometry.coordinates.length).toBeGreaterThan(0);
expect(serviceResult.result[i].resultGeometry.geometry.type).toBe("MultiPolygon");
expect(serviceResult.result[i].resultGeometry.type).toBe("Feature");
expect(serviceResult.result[i].succeed).toBe(true);
}
done();
});
});
}); | };
//叠加分析参数 | random_line_split |
MonitorRFDischargesScanSynthAmp.py | # This loop monitors the rf Discharges for a particular amplitude, then repeats for other amplitudes
# n
from DAQ.Environment import *
def scanRF(LowestAmp, HighestAmp, step, numScans):
# setup
AmpList = []
fileSystem = Environs.FileSystem
file = \
fileSystem.GetDataDirectory(\
fileSystem.Paths["scanMasterDataPath"])\
+ fileSystem.GenerateNextDataFileName()
print("Saving as " + file + "_" + "MeasuredRF1Amp" + "*.zip")
print("")
# start looping
r = range(int(10*LowestAmp), int(10*HighestAmp), int(10*step))
for i in range(len(r)):
|
print "List of Measured Amplitudes =" + str(AmpList).strip('[]')
def run_script():
print "Use scanRF(LowestAmp, HighestAmp, step, numScans)"
| print "hc:rf1 Amplitude -> " + str(float(r[i])/10)
hc.SetGreenSynthAmp(float(r[i])/10)
# hc.GreenSynthOnAmplitude = double(r[i]/10)
hc.EnableGreenSynth( False )
hc.EnableGreenSynth( True )
hc.UpdateRFPowerMonitor()
rfAmpMeasured = hc.RF1PowerCentre
hc.StepTarget(2)
System.Threading.Thread.Sleep(500)
sm.AcquireAndWait(numScans)
scanPath = file + "_" + str(i) + "_" + str(rfAmpMeasured) + ".zip"
sm.SaveData(scanPath)
AmpList.append(str(rfAmpMeasured)) | conditional_block |
MonitorRFDischargesScanSynthAmp.py | # This loop monitors the rf Discharges for a particular amplitude, then repeats for other amplitudes
# n
from DAQ.Environment import *
def scanRF(LowestAmp, HighestAmp, step, numScans):
# setup
|
def run_script():
print "Use scanRF(LowestAmp, HighestAmp, step, numScans)"
| AmpList = []
fileSystem = Environs.FileSystem
file = \
fileSystem.GetDataDirectory(\
fileSystem.Paths["scanMasterDataPath"])\
+ fileSystem.GenerateNextDataFileName()
print("Saving as " + file + "_" + "MeasuredRF1Amp" + "*.zip")
print("")
# start looping
r = range(int(10*LowestAmp), int(10*HighestAmp), int(10*step))
for i in range(len(r)):
print "hc:rf1 Amplitude -> " + str(float(r[i])/10)
hc.SetGreenSynthAmp(float(r[i])/10)
# hc.GreenSynthOnAmplitude = double(r[i]/10)
hc.EnableGreenSynth( False )
hc.EnableGreenSynth( True )
hc.UpdateRFPowerMonitor()
rfAmpMeasured = hc.RF1PowerCentre
hc.StepTarget(2)
System.Threading.Thread.Sleep(500)
sm.AcquireAndWait(numScans)
scanPath = file + "_" + str(i) + "_" + str(rfAmpMeasured) + ".zip"
sm.SaveData(scanPath)
AmpList.append(str(rfAmpMeasured))
print "List of Measured Amplitudes =" + str(AmpList).strip('[]') | identifier_body |
MonitorRFDischargesScanSynthAmp.py | # This loop monitors the rf Discharges for a particular amplitude, then repeats for other amplitudes
# n
from DAQ.Environment import *
def scanRF(LowestAmp, HighestAmp, step, numScans):
# setup
AmpList = []
fileSystem = Environs.FileSystem
file = \
fileSystem.GetDataDirectory(\
fileSystem.Paths["scanMasterDataPath"])\
+ fileSystem.GenerateNextDataFileName()
print("Saving as " + file + "_" + "MeasuredRF1Amp" + "*.zip")
print("")
# start looping
r = range(int(10*LowestAmp), int(10*HighestAmp), int(10*step))
for i in range(len(r)):
print "hc:rf1 Amplitude -> " + str(float(r[i])/10)
hc.SetGreenSynthAmp(float(r[i])/10)
# hc.GreenSynthOnAmplitude = double(r[i]/10)
hc.EnableGreenSynth( False )
hc.EnableGreenSynth( True )
hc.UpdateRFPowerMonitor()
rfAmpMeasured = hc.RF1PowerCentre
hc.StepTarget(2)
System.Threading.Thread.Sleep(500) | scanPath = file + "_" + str(i) + "_" + str(rfAmpMeasured) + ".zip"
sm.SaveData(scanPath)
AmpList.append(str(rfAmpMeasured))
print "List of Measured Amplitudes =" + str(AmpList).strip('[]')
def run_script():
print "Use scanRF(LowestAmp, HighestAmp, step, numScans)" | sm.AcquireAndWait(numScans) | random_line_split |
MonitorRFDischargesScanSynthAmp.py | # This loop monitors the rf Discharges for a particular amplitude, then repeats for other amplitudes
# n
from DAQ.Environment import *
def | (LowestAmp, HighestAmp, step, numScans):
# setup
AmpList = []
fileSystem = Environs.FileSystem
file = \
fileSystem.GetDataDirectory(\
fileSystem.Paths["scanMasterDataPath"])\
+ fileSystem.GenerateNextDataFileName()
print("Saving as " + file + "_" + "MeasuredRF1Amp" + "*.zip")
print("")
# start looping
r = range(int(10*LowestAmp), int(10*HighestAmp), int(10*step))
for i in range(len(r)):
print "hc:rf1 Amplitude -> " + str(float(r[i])/10)
hc.SetGreenSynthAmp(float(r[i])/10)
# hc.GreenSynthOnAmplitude = double(r[i]/10)
hc.EnableGreenSynth( False )
hc.EnableGreenSynth( True )
hc.UpdateRFPowerMonitor()
rfAmpMeasured = hc.RF1PowerCentre
hc.StepTarget(2)
System.Threading.Thread.Sleep(500)
sm.AcquireAndWait(numScans)
scanPath = file + "_" + str(i) + "_" + str(rfAmpMeasured) + ".zip"
sm.SaveData(scanPath)
AmpList.append(str(rfAmpMeasured))
print "List of Measured Amplitudes =" + str(AmpList).strip('[]')
def run_script():
print "Use scanRF(LowestAmp, HighestAmp, step, numScans)"
| scanRF | identifier_name |
aim_server.py | #!/usr/bin/env python
from threaded_ssh import ThreadedClients
from ServerConfig import Aim
from ServerConfig import TellStore
from ServerConfig import General
from ServerConfig import Storage
from ServerConfig import Kudu
def hostToIp(host):
return General.infinibandIp[host]
def semicolonReduce(x, y):
return x + ';' + y
def startAimServers(observers = []):
Aim.rsyncBuild()
numChunks = (len(Storage.servers) + len(Storage.servers1)) * Aim.numRTAClients * 16
chunkSize = ((TellStore.scanMemory // numChunks) // 8) * 8
serverExec = ""
if Storage.storage == Kudu:
serverExec = "aim_kudu -P {0} -s {1}".format((len(Storage.servers) + len(Storage.servers1)) * 2, Storage.master)
elif Storage.storage == TellStore:
serverExec = 'aim_server -M {0} -m {1} -c "{2}" -s "{3}" --processing-threads {4}'.format(numChunks, chunkSize, TellStore.getCommitManagerAddress(), TellStore.getServerList(), Aim.serverthreads)
cmd = '{0}/watch/aim-benchmark/{3} -f {1} -b {2}'.format(Aim.builddir, Aim.schemaFile, Aim.batchSize, serverExec)
client0 = ThreadedClients(Aim.sepservers0 + Aim.rtaservers0, "numactl -m 0 -N 0 {0}".format(cmd), root=True)
client1 = ThreadedClients(Aim.sepservers1 + Aim.rtaservers1, "numactl -m 1 -N 1 {0} -p 8715 -u 8716".format(cmd), root=True)
client0.start()
client1.start()
return [client0, client1]
if __name__ == '__main__':
| clients = startAimServers()
for c in clients:
c.join() | conditional_block | |
aim_server.py | #!/usr/bin/env python
from threaded_ssh import ThreadedClients
from ServerConfig import Aim
from ServerConfig import TellStore
from ServerConfig import General
from ServerConfig import Storage
from ServerConfig import Kudu
def hostToIp(host):
return General.infinibandIp[host]
def semicolonReduce(x, y):
return x + ';' + y
def startAimServers(observers = []):
Aim.rsyncBuild()
numChunks = (len(Storage.servers) + len(Storage.servers1)) * Aim.numRTAClients * 16
chunkSize = ((TellStore.scanMemory // numChunks) // 8) * 8
| serverExec = "aim_kudu -P {0} -s {1}".format((len(Storage.servers) + len(Storage.servers1)) * 2, Storage.master)
elif Storage.storage == TellStore:
serverExec = 'aim_server -M {0} -m {1} -c "{2}" -s "{3}" --processing-threads {4}'.format(numChunks, chunkSize, TellStore.getCommitManagerAddress(), TellStore.getServerList(), Aim.serverthreads)
cmd = '{0}/watch/aim-benchmark/{3} -f {1} -b {2}'.format(Aim.builddir, Aim.schemaFile, Aim.batchSize, serverExec)
client0 = ThreadedClients(Aim.sepservers0 + Aim.rtaservers0, "numactl -m 0 -N 0 {0}".format(cmd), root=True)
client1 = ThreadedClients(Aim.sepservers1 + Aim.rtaservers1, "numactl -m 1 -N 1 {0} -p 8715 -u 8716".format(cmd), root=True)
client0.start()
client1.start()
return [client0, client1]
if __name__ == '__main__':
clients = startAimServers()
for c in clients:
c.join() | serverExec = ""
if Storage.storage == Kudu: | random_line_split |
aim_server.py | #!/usr/bin/env python
from threaded_ssh import ThreadedClients
from ServerConfig import Aim
from ServerConfig import TellStore
from ServerConfig import General
from ServerConfig import Storage
from ServerConfig import Kudu
def hostToIp(host):
return General.infinibandIp[host]
def semicolonReduce(x, y):
return x + ';' + y
def | (observers = []):
Aim.rsyncBuild()
numChunks = (len(Storage.servers) + len(Storage.servers1)) * Aim.numRTAClients * 16
chunkSize = ((TellStore.scanMemory // numChunks) // 8) * 8
serverExec = ""
if Storage.storage == Kudu:
serverExec = "aim_kudu -P {0} -s {1}".format((len(Storage.servers) + len(Storage.servers1)) * 2, Storage.master)
elif Storage.storage == TellStore:
serverExec = 'aim_server -M {0} -m {1} -c "{2}" -s "{3}" --processing-threads {4}'.format(numChunks, chunkSize, TellStore.getCommitManagerAddress(), TellStore.getServerList(), Aim.serverthreads)
cmd = '{0}/watch/aim-benchmark/{3} -f {1} -b {2}'.format(Aim.builddir, Aim.schemaFile, Aim.batchSize, serverExec)
client0 = ThreadedClients(Aim.sepservers0 + Aim.rtaservers0, "numactl -m 0 -N 0 {0}".format(cmd), root=True)
client1 = ThreadedClients(Aim.sepservers1 + Aim.rtaservers1, "numactl -m 1 -N 1 {0} -p 8715 -u 8716".format(cmd), root=True)
client0.start()
client1.start()
return [client0, client1]
if __name__ == '__main__':
clients = startAimServers()
for c in clients:
c.join()
| startAimServers | identifier_name |
aim_server.py | #!/usr/bin/env python
from threaded_ssh import ThreadedClients
from ServerConfig import Aim
from ServerConfig import TellStore
from ServerConfig import General
from ServerConfig import Storage
from ServerConfig import Kudu
def hostToIp(host):
return General.infinibandIp[host]
def semicolonReduce(x, y):
|
def startAimServers(observers = []):
Aim.rsyncBuild()
numChunks = (len(Storage.servers) + len(Storage.servers1)) * Aim.numRTAClients * 16
chunkSize = ((TellStore.scanMemory // numChunks) // 8) * 8
serverExec = ""
if Storage.storage == Kudu:
serverExec = "aim_kudu -P {0} -s {1}".format((len(Storage.servers) + len(Storage.servers1)) * 2, Storage.master)
elif Storage.storage == TellStore:
serverExec = 'aim_server -M {0} -m {1} -c "{2}" -s "{3}" --processing-threads {4}'.format(numChunks, chunkSize, TellStore.getCommitManagerAddress(), TellStore.getServerList(), Aim.serverthreads)
cmd = '{0}/watch/aim-benchmark/{3} -f {1} -b {2}'.format(Aim.builddir, Aim.schemaFile, Aim.batchSize, serverExec)
client0 = ThreadedClients(Aim.sepservers0 + Aim.rtaservers0, "numactl -m 0 -N 0 {0}".format(cmd), root=True)
client1 = ThreadedClients(Aim.sepservers1 + Aim.rtaservers1, "numactl -m 1 -N 1 {0} -p 8715 -u 8716".format(cmd), root=True)
client0.start()
client1.start()
return [client0, client1]
if __name__ == '__main__':
clients = startAimServers()
for c in clients:
c.join()
| return x + ';' + y | identifier_body |
stop_guard.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Stop guard mod
use std::sync::Arc;
use std::sync::atomic::*;
/// Stop guard that will set a stop flag on drop
pub struct StopGuard {
flag: Arc<AtomicBool>,
}
impl StopGuard {
/// Create a stop guard
pub fn new() -> StopGuard {
StopGuard {
flag: Arc::new(AtomicBool::new(false))
}
}
/// Share stop guard between the threads
pub fn share(&self) -> Arc<AtomicBool> {
self.flag.clone()
}
}
impl Drop for StopGuard {
fn drop(&mut self) |
}
| {
self.flag.store(true, Ordering::Relaxed)
} | identifier_body |
stop_guard.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Stop guard mod
use std::sync::Arc;
use std::sync::atomic::*;
/// Stop guard that will set a stop flag on drop
pub struct | {
flag: Arc<AtomicBool>,
}
impl StopGuard {
/// Create a stop guard
pub fn new() -> StopGuard {
StopGuard {
flag: Arc::new(AtomicBool::new(false))
}
}
/// Share stop guard between the threads
pub fn share(&self) -> Arc<AtomicBool> {
self.flag.clone()
}
}
impl Drop for StopGuard {
fn drop(&mut self) {
self.flag.store(true, Ordering::Relaxed)
}
}
| StopGuard | identifier_name |
stop_guard.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Stop guard mod |
use std::sync::Arc;
use std::sync::atomic::*;
/// Stop guard that will set a stop flag on drop
pub struct StopGuard {
flag: Arc<AtomicBool>,
}
impl StopGuard {
/// Create a stop guard
pub fn new() -> StopGuard {
StopGuard {
flag: Arc::new(AtomicBool::new(false))
}
}
/// Share stop guard between the threads
pub fn share(&self) -> Arc<AtomicBool> {
self.flag.clone()
}
}
impl Drop for StopGuard {
fn drop(&mut self) {
self.flag.store(true, Ordering::Relaxed)
}
} | random_line_split | |
fs.js | // Parts of this source are modified from npm and lerna:
// npm: https://github.com/npm/npm/blob/master/LICENSE
// lerna: https://github.com/lerna/lerna/blob/master/LICENSE
// @flow
import fs from 'fs';
import path from 'path';
import _cmdShim from 'cmd-shim';
import _readCmdShim from 'read-cmd-shim';
import promisify from 'typeable-promisify';
import makeDir from 'make-dir';
import _rimraf from 'rimraf';
export function readFile(filePath: string): Promise<string> {
return promisify(cb => fs.readFile(filePath, cb));
}
export function writeFile(
filePath: string,
fileContents: string
): Promise<string> {
return promisify(cb => fs.writeFile(filePath, fileContents, cb));
}
export function mkdirp(filePath: string): Promise<void> {
return makeDir(filePath);
}
export function rimraf(filePath: string): Promise<void> {
return promisify(cb => _rimraf(filePath, cb));
}
export function stat(filePath: string) {
return promisify(cb => fs.stat(filePath, cb));
}
export function lstat(filePath: string) {
return promisify(cb => fs.lstat(filePath, cb));
}
function unlink(filePath: string) {
return promisify(cb => fs.unlink(filePath, cb));
}
export function realpath(filePath: string) {
return promisify(cb => fs.realpath(filePath, cb));
}
function _symlink(src: string, dest: string, type: string) {
return promisify(cb => fs.symlink(src, dest, type, cb));
}
function stripExtension(filePath: string) {
return path.join(
path.dirname(filePath),
path.basename(filePath, path.extname(filePath))
);
}
async function cmdShim(src: string, dest: string) {
// If not a symlink we default to the actual src file
// https://github.com/npm/npm/blob/d081cc6c8d73f2aa698aab36605377c95e916224/lib/utils/gently-rm.js#L273
let relativeShimTarget = await readlink(src);
let currentShimTarget = relativeShimTarget
? path.resolve(path.dirname(src), relativeShimTarget)
: src;
await promisify(cb => _cmdShim(currentShimTarget, stripExtension(dest), cb));
}
async function createSymbolicLink(src, dest, type) {
try {
await lstat(dest);
await rimraf(dest);
} catch (err) {
if (err.code === 'EPERM') throw err;
}
await _symlink(src, dest, type);
}
async function createPosixSymlink(origin, dest, type) {
if (type === 'exec') {
type = 'file';
}
let src = path.relative(path.dirname(dest), origin);
return await createSymbolicLink(src, dest, type);
}
async function createWindowsSymlink(src, dest, type) {
if (type === 'exec') {
return await cmdShim(src, dest);
} else {
return await createSymbolicLink(src, dest, type);
}
}
export async function symlink(
src: string,
dest: string,
type: 'exec' | 'junction'
) {
if (dest.includes(path.sep)) {
await mkdirp(path.dirname(dest));
}
if (process.platform === 'win32') {
return await createWindowsSymlink(src, dest, type);
} else {
return await createPosixSymlink(src, dest, type);
}
}
export async function readdir(dir: string) {
return promisify(cb => fs.readdir(dir, cb));
}
// Return an empty array if a directory doesnt exist (but still throw if errof if dir is a file)
export async function readdirSafe(dir: string) {
return stat(dir)
.catch(err => Promise.resolve([]))
.then(statsOrArray => {
if (statsOrArray instanceof Array) return statsOrArray;
if (!statsOrArray.isDirectory())
throw new Error(dir + ' is not a directory');
return readdir(dir);
});
}
function readCmdShim(filePath: string) {
return promisify(cb => _readCmdShim(filePath, cb));
}
function _readlink(filePath: string) {
return promisify(cb => fs.readlink(filePath, cb));
}
// Copied from:
// https://github.com/npm/npm/blob/d081cc6c8d73f2aa698aab36605377c95e916224/lib/utils/gently-rm.js#L280-L297
export async function readlink(filePath: string) {
let stat = await lstat(filePath);
let result = null;
if (stat.isSymbolicLink()) {
result = await _readlink(filePath);
} else {
try {
result = await readCmdShim(filePath);
} catch (err) {
| (err.code !== 'ENOTASHIM' && err.code !== 'EISDIR') {
throw err;
}
}
}
return result;
}
export async function dirExists(dir: string) {
try {
let _stat = await stat(dir);
return _stat.isDirectory();
} catch (err) {
return false;
}
}
export async function symlinkExists(filePath: string) {
try {
let stat = await lstat(filePath);
return stat.isSymbolicLink();
} catch (err) {
return false;
}
}
| if | identifier_name |
fs.js | // Parts of this source are modified from npm and lerna:
// npm: https://github.com/npm/npm/blob/master/LICENSE
// lerna: https://github.com/lerna/lerna/blob/master/LICENSE
// @flow
import fs from 'fs';
import path from 'path';
import _cmdShim from 'cmd-shim';
import _readCmdShim from 'read-cmd-shim';
import promisify from 'typeable-promisify';
import makeDir from 'make-dir';
import _rimraf from 'rimraf';
export function readFile(filePath: string): Promise<string> {
return promisify(cb => fs.readFile(filePath, cb));
}
export function writeFile(
filePath: string,
fileContents: string
): Promise<string> {
return promisify(cb => fs.writeFile(filePath, fileContents, cb));
}
export function mkdirp(filePath: string): Promise<void> {
return makeDir(filePath);
}
export function rimraf(filePath: string): Promise<void> {
return promisify(cb => _rimraf(filePath, cb));
}
export function stat(filePath: string) {
return promisify(cb => fs.stat(filePath, cb));
}
export function lstat(filePath: string) {
return promisify(cb => fs.lstat(filePath, cb));
}
function unlink(filePath: string) {
return promisify(cb => fs.unlink(filePath, cb));
}
export function realpath(filePath: string) {
return promisify(cb => fs.realpath(filePath, cb));
}
function _symlink(src: string, dest: string, type: string) {
return promisify(cb => fs.symlink(src, dest, type, cb));
}
function stripExtension(filePath: string) {
return path.join(
path.dirname(filePath),
path.basename(filePath, path.extname(filePath))
);
}
async function cmdShim(src: string, dest: string) {
// If not a symlink we default to the actual src file
// https://github.com/npm/npm/blob/d081cc6c8d73f2aa698aab36605377c95e916224/lib/utils/gently-rm.js#L273
let relativeShimTarget = await readlink(src);
let currentShimTarget = relativeShimTarget
? path.resolve(path.dirname(src), relativeShimTarget)
: src;
await promisify(cb => _cmdShim(currentShimTarget, stripExtension(dest), cb));
}
async function createSymbolicLink(src, dest, type) {
try {
await lstat(dest);
await rimraf(dest);
} catch (err) {
if (err.code === 'EPERM') throw err;
}
await _symlink(src, dest, type);
}
async function createPosixSymlink(origin, dest, type) {
if (type === 'exec') {
type = 'file';
}
let src = path.relative(path.dirname(dest), origin);
return await createSymbolicLink(src, dest, type);
}
async function createWindowsSymlink(src, dest, type) {
if (type === 'exec') {
return await cmdShim(src, dest);
} else {
return await createSymbolicLink(src, dest, type);
}
}
export async function symlink(
src: string,
dest: string,
type: 'exec' | 'junction'
) {
if (dest.includes(path.sep)) {
await mkdirp(path.dirname(dest)); | }
if (process.platform === 'win32') {
return await createWindowsSymlink(src, dest, type);
} else {
return await createPosixSymlink(src, dest, type);
}
}
export async function readdir(dir: string) {
return promisify(cb => fs.readdir(dir, cb));
}
// Return an empty array if a directory doesnt exist (but still throw if errof if dir is a file)
export async function readdirSafe(dir: string) {
return stat(dir)
.catch(err => Promise.resolve([]))
.then(statsOrArray => {
if (statsOrArray instanceof Array) return statsOrArray;
if (!statsOrArray.isDirectory())
throw new Error(dir + ' is not a directory');
return readdir(dir);
});
}
function readCmdShim(filePath: string) {
return promisify(cb => _readCmdShim(filePath, cb));
}
function _readlink(filePath: string) {
return promisify(cb => fs.readlink(filePath, cb));
}
// Copied from:
// https://github.com/npm/npm/blob/d081cc6c8d73f2aa698aab36605377c95e916224/lib/utils/gently-rm.js#L280-L297
export async function readlink(filePath: string) {
let stat = await lstat(filePath);
let result = null;
if (stat.isSymbolicLink()) {
result = await _readlink(filePath);
} else {
try {
result = await readCmdShim(filePath);
} catch (err) {
if (err.code !== 'ENOTASHIM' && err.code !== 'EISDIR') {
throw err;
}
}
}
return result;
}
export async function dirExists(dir: string) {
try {
let _stat = await stat(dir);
return _stat.isDirectory();
} catch (err) {
return false;
}
}
export async function symlinkExists(filePath: string) {
try {
let stat = await lstat(filePath);
return stat.isSymbolicLink();
} catch (err) {
return false;
}
} | random_line_split | |
fs.js | // Parts of this source are modified from npm and lerna:
// npm: https://github.com/npm/npm/blob/master/LICENSE
// lerna: https://github.com/lerna/lerna/blob/master/LICENSE
// @flow
import fs from 'fs';
import path from 'path';
import _cmdShim from 'cmd-shim';
import _readCmdShim from 'read-cmd-shim';
import promisify from 'typeable-promisify';
import makeDir from 'make-dir';
import _rimraf from 'rimraf';
export function readFile(filePath: string): Promise<string> {
return promisify(cb => fs.readFile(filePath, cb));
}
export function writeFile(
filePath: string,
fileContents: string
): Promise<string> {
return promisify(cb => fs.writeFile(filePath, fileContents, cb));
}
export function mkdirp(filePath: string): Promise<void> {
return makeDir(filePath);
}
export function rimraf(filePath: string): Promise<void> {
return promisify(cb => _rimraf(filePath, cb));
}
export function stat(filePath: string) {
return promisify(cb => fs.stat(filePath, cb));
}
export function lstat(filePath: string) {
return promisify(cb => fs.lstat(filePath, cb));
}
function unlink(filePath: string) {
return promisify(cb => fs.unlink(filePath, cb));
}
export function realpath(filePath: string) {
return promisify(cb => fs.realpath(filePath, cb));
}
function _symlink(src: string, dest: string, type: string) {
return promisify(cb => fs.symlink(src, dest, type, cb));
}
function stripExtension(filePath: string) {
return path.join(
path.dirname(filePath),
path.basename(filePath, path.extname(filePath))
);
}
async function cmdShim(src: string, dest: string) {
// If not a symlink we default to the actual src file
// https://github.com/npm/npm/blob/d081cc6c8d73f2aa698aab36605377c95e916224/lib/utils/gently-rm.js#L273
let relativeShimTarget = await readlink(src);
let currentShimTarget = relativeShimTarget
? path.resolve(path.dirname(src), relativeShimTarget)
: src;
await promisify(cb => _cmdShim(currentShimTarget, stripExtension(dest), cb));
}
async function createSymbolicLink(src, dest, type) {
try {
await lstat(dest);
await rimraf(dest);
} catch (err) {
if (err.code === 'EPERM') throw err;
}
await _symlink(src, dest, type);
}
async function createPosixSymlink(origin, dest, type) {
if (type === 'exec') {
type = 'file';
}
let src = path.relative(path.dirname(dest), origin);
return await createSymbolicLink(src, dest, type);
}
async function createWindowsSymlink(src, dest, type) {
if (type === 'exec') {
return await cmdShim(src, dest);
} else {
return await createSymbolicLink(src, dest, type);
}
}
export async function symlink(
src: string,
dest: string,
type: 'exec' | 'junction'
) {
if (dest.includes(path.sep)) {
await mkdirp(path.dirname(dest));
}
if (process.platform === 'win32') {
return await createWindowsSymlink(src, dest, type);
} else {
return await createPosixSymlink(src, dest, type);
}
}
export async function readdir(dir: string) {
return promisify(cb => fs.readdir(dir, cb));
}
// Return an empty array if a directory doesnt exist (but still throw if errof if dir is a file)
export async function readdirSafe(dir: string) {
return stat(dir)
.catch(err => Promise.resolve([]))
.then(statsOrArray => {
if (statsOrArray instanceof Array) return statsOrArray;
if (!statsOrArray.isDirectory())
throw new Error(dir + ' is not a directory');
return readdir(dir);
});
}
function readCmdShim(filePath: string) {
return promisify(cb => _readCmdShim(filePath, cb));
}
function _readlink(filePath: string) {
return promisify(cb => fs.readlink(filePath, cb));
}
// Copied from:
// https://github.com/npm/npm/blob/d081cc6c8d73f2aa698aab36605377c95e916224/lib/utils/gently-rm.js#L280-L297
export async function readlink(filePath: string) {
let stat = await lstat(filePath);
let result = null;
if (stat.isSymbolicLink()) {
result = await _readlink(filePath);
} else {
try {
result = await readCmdShim(filePath);
} catch (err) {
if (err.code !== 'ENOTASHIM' && err.code !== 'EISDIR') |
}
}
return result;
}
export async function dirExists(dir: string) {
try {
let _stat = await stat(dir);
return _stat.isDirectory();
} catch (err) {
return false;
}
}
export async function symlinkExists(filePath: string) {
try {
let stat = await lstat(filePath);
return stat.isSymbolicLink();
} catch (err) {
return false;
}
}
| {
throw err;
} | identifier_body |
security_group_rules_client.py | # Copyright 2012 OpenStack Foundation
# 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.
from oslo_serialization import jsonutils as json
from tempest.lib.api_schema.response.compute.v2_1 import \
security_groups as schema
from tempest.lib.common import rest_client
class SecurityGroupRulesClient(rest_client.RestClient):
def | (self, **kwargs):
"""Create a new security group rule.
Available params: see http://developer.openstack.org/
api-ref-compute-v2.1.html#createSecGroupRule
"""
post_body = json.dumps({'security_group_rule': kwargs})
url = 'os-security-group-rules'
resp, body = self.post(url, post_body)
body = json.loads(body)
self.validate_response(schema.create_security_group_rule, resp, body)
return rest_client.ResponseBody(resp, body)
def delete_security_group_rule(self, group_rule_id):
"""Deletes the provided Security Group rule."""
resp, body = self.delete('os-security-group-rules/%s' %
group_rule_id)
self.validate_response(schema.delete_security_group_rule, resp, body)
return rest_client.ResponseBody(resp, body)
| create_security_group_rule | identifier_name |
security_group_rules_client.py | # Copyright 2012 OpenStack Foundation
# 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.
from oslo_serialization import jsonutils as json
from tempest.lib.api_schema.response.compute.v2_1 import \
security_groups as schema
from tempest.lib.common import rest_client
class SecurityGroupRulesClient(rest_client.RestClient):
| def create_security_group_rule(self, **kwargs):
"""Create a new security group rule.
Available params: see http://developer.openstack.org/
api-ref-compute-v2.1.html#createSecGroupRule
"""
post_body = json.dumps({'security_group_rule': kwargs})
url = 'os-security-group-rules'
resp, body = self.post(url, post_body)
body = json.loads(body)
self.validate_response(schema.create_security_group_rule, resp, body)
return rest_client.ResponseBody(resp, body)
def delete_security_group_rule(self, group_rule_id):
"""Deletes the provided Security Group rule."""
resp, body = self.delete('os-security-group-rules/%s' %
group_rule_id)
self.validate_response(schema.delete_security_group_rule, resp, body)
return rest_client.ResponseBody(resp, body) | identifier_body | |
security_group_rules_client.py | # Copyright 2012 OpenStack Foundation
# 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.
from oslo_serialization import jsonutils as json
from tempest.lib.api_schema.response.compute.v2_1 import \
security_groups as schema
from tempest.lib.common import rest_client
class SecurityGroupRulesClient(rest_client.RestClient):
def create_security_group_rule(self, **kwargs):
"""Create a new security group rule.
Available params: see http://developer.openstack.org/
api-ref-compute-v2.1.html#createSecGroupRule
"""
post_body = json.dumps({'security_group_rule': kwargs}) | url = 'os-security-group-rules'
resp, body = self.post(url, post_body)
body = json.loads(body)
self.validate_response(schema.create_security_group_rule, resp, body)
return rest_client.ResponseBody(resp, body)
def delete_security_group_rule(self, group_rule_id):
"""Deletes the provided Security Group rule."""
resp, body = self.delete('os-security-group-rules/%s' %
group_rule_id)
self.validate_response(schema.delete_security_group_rule, resp, body)
return rest_client.ResponseBody(resp, body) | random_line_split | |
app.component.ts | import {Component, OnInit} from '@angular/core';
import {UserService} from './shared/services/user.service';
import {AuthenticationService} from './shared/services/authentication.service';
import {ShowProgressService} from './shared/services/show-progress.service';
import {Router} from '@angular/router';
import {APIInfoService} from './shared/services/data.service';
import {APIInfo} from './models/APIInfo';
import {isNullOrUndefined} from 'util';
import {RavenErrorHandler} from './shared/services/raven-error-handler.service';
import {MatSnackBar} from '@angular/material';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'app works!';
showProgressBar = false;
apiInfo: APIInfo;
constructor(private router: Router,
private authenticationService: AuthenticationService,
public userService: UserService,
private showProgress: ShowProgressService,
private apiInfoService: APIInfoService,
private ravenErrorHandler: RavenErrorHandler,
private snackBar: MatSnackBar) {
showProgress.toggleSidenav$.subscribe(
toggle => {
this.toggleProgressBar();
}
);
}
ngOnInit(): void {
this.authenticationService.reloadUser();
this.apiInfoService.readItems()
.then((info: any) => {
this.ravenErrorHandler.setup(info.sentryDsn);
this.apiInfo = info;
})
.catch((err) => {
this.snackBar.open('Error on init', '', {duration: 3000});
});
}
hasWarning() {
return !isNullOrUndefined(this.apiInfo) && !isNullOrUndefined(this.apiInfo.nonProductionWarning);
}
isLoggedIn() {
return this.authenticationService.isLoggedIn;
}
logout() {
this.authenticationService.logout();
}
toggleProgressBar() {
this.showProgressBar = !this.showProgressBar;
}
isAdmin(): boolean { | const routeTest = /^(\/|\/login|\/register)$/.test(this.router.url);
return (routeTest && !this.isLoggedIn()) ? 'special-style' : '';
}
} | return this.userService.isAdmin();
}
specialContainerStyle(): string { | random_line_split |
app.component.ts | import {Component, OnInit} from '@angular/core';
import {UserService} from './shared/services/user.service';
import {AuthenticationService} from './shared/services/authentication.service';
import {ShowProgressService} from './shared/services/show-progress.service';
import {Router} from '@angular/router';
import {APIInfoService} from './shared/services/data.service';
import {APIInfo} from './models/APIInfo';
import {isNullOrUndefined} from 'util';
import {RavenErrorHandler} from './shared/services/raven-error-handler.service';
import {MatSnackBar} from '@angular/material';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class | implements OnInit {
title = 'app works!';
showProgressBar = false;
apiInfo: APIInfo;
constructor(private router: Router,
private authenticationService: AuthenticationService,
public userService: UserService,
private showProgress: ShowProgressService,
private apiInfoService: APIInfoService,
private ravenErrorHandler: RavenErrorHandler,
private snackBar: MatSnackBar) {
showProgress.toggleSidenav$.subscribe(
toggle => {
this.toggleProgressBar();
}
);
}
ngOnInit(): void {
this.authenticationService.reloadUser();
this.apiInfoService.readItems()
.then((info: any) => {
this.ravenErrorHandler.setup(info.sentryDsn);
this.apiInfo = info;
})
.catch((err) => {
this.snackBar.open('Error on init', '', {duration: 3000});
});
}
hasWarning() {
return !isNullOrUndefined(this.apiInfo) && !isNullOrUndefined(this.apiInfo.nonProductionWarning);
}
isLoggedIn() {
return this.authenticationService.isLoggedIn;
}
logout() {
this.authenticationService.logout();
}
toggleProgressBar() {
this.showProgressBar = !this.showProgressBar;
}
isAdmin(): boolean {
return this.userService.isAdmin();
}
specialContainerStyle(): string {
const routeTest = /^(\/|\/login|\/register)$/.test(this.router.url);
return (routeTest && !this.isLoggedIn()) ? 'special-style' : '';
}
}
| AppComponent | identifier_name |
app.component.ts | import {Component, OnInit} from '@angular/core';
import {UserService} from './shared/services/user.service';
import {AuthenticationService} from './shared/services/authentication.service';
import {ShowProgressService} from './shared/services/show-progress.service';
import {Router} from '@angular/router';
import {APIInfoService} from './shared/services/data.service';
import {APIInfo} from './models/APIInfo';
import {isNullOrUndefined} from 'util';
import {RavenErrorHandler} from './shared/services/raven-error-handler.service';
import {MatSnackBar} from '@angular/material';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'app works!';
showProgressBar = false;
apiInfo: APIInfo;
constructor(private router: Router,
private authenticationService: AuthenticationService,
public userService: UserService,
private showProgress: ShowProgressService,
private apiInfoService: APIInfoService,
private ravenErrorHandler: RavenErrorHandler,
private snackBar: MatSnackBar) {
showProgress.toggleSidenav$.subscribe(
toggle => {
this.toggleProgressBar();
}
);
}
ngOnInit(): void |
hasWarning() {
return !isNullOrUndefined(this.apiInfo) && !isNullOrUndefined(this.apiInfo.nonProductionWarning);
}
isLoggedIn() {
return this.authenticationService.isLoggedIn;
}
logout() {
this.authenticationService.logout();
}
toggleProgressBar() {
this.showProgressBar = !this.showProgressBar;
}
isAdmin(): boolean {
return this.userService.isAdmin();
}
specialContainerStyle(): string {
const routeTest = /^(\/|\/login|\/register)$/.test(this.router.url);
return (routeTest && !this.isLoggedIn()) ? 'special-style' : '';
}
}
| {
this.authenticationService.reloadUser();
this.apiInfoService.readItems()
.then((info: any) => {
this.ravenErrorHandler.setup(info.sentryDsn);
this.apiInfo = info;
})
.catch((err) => {
this.snackBar.open('Error on init', '', {duration: 3000});
});
} | identifier_body |
testcases.py | import re
import unittest
from urlparse import urlsplit, urlunsplit
from xml.dom.minidom import parseString, Node
from django.conf import settings
from django.core import mail
from django.core.management import call_command
from django.core.urlresolvers import clear_url_caches
from django.db import transaction
from django.http import QueryDict
from django.test import _doctest as doctest
from django.test.client import Client
from django.utils import simplejson
normalize_long_ints = lambda s: re.sub(r'(?<![\w])(\d+)L(?![\w])', '\\1', s)
def to_list(value):
"""
Puts value into a list if it's not already one.
Returns an empty list if value is None.
"""
if value is None:
value = []
elif not isinstance(value, list):
value = [value]
return value
class OutputChecker(doctest.OutputChecker):
def check_output(self, want, got, optionflags):
"The entry method for doctest output checking. Defers to a sequence of child checkers"
checks = (self.check_output_default,
self.check_output_long,
self.check_output_xml,
self.check_output_json)
for check in checks:
if check(want, got, optionflags):
return True
return False
def check_output_default(self, want, got, optionflags):
"The default comparator provided by doctest - not perfect, but good for most purposes"
return doctest.OutputChecker.check_output(self, want, got, optionflags)
def check_output_long(self, want, got, optionflags):
"""Doctest does an exact string comparison of output, which means long
integers aren't equal to normal integers ("22L" vs. "22"). The
following code normalizes long integers so that they equal normal
integers.
"""
return normalize_long_ints(want) == normalize_long_ints(got)
def check_output_xml(self, want, got, optionsflags):
"""Tries to do a 'xml-comparision' of want and got. Plain string
comparision doesn't always work because, for example, attribute
ordering should not be important.
Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py
"""
_norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
def norm_whitespace(v):
return _norm_whitespace_re.sub(' ', v)
def child_text(element):
return ''.join([c.data for c in element.childNodes
if c.nodeType == Node.TEXT_NODE])
def children(element):
return [c for c in element.childNodes
if c.nodeType == Node.ELEMENT_NODE]
def norm_child_text(element):
return norm_whitespace(child_text(element))
def attrs_dict(element):
return dict(element.attributes.items())
def check_element(want_element, got_element):
if want_element.tagName != got_element.tagName:
return False
if norm_child_text(want_element) != norm_child_text(got_element):
return False
if attrs_dict(want_element) != attrs_dict(got_element):
return False
want_children = children(want_element)
got_children = children(got_element)
if len(want_children) != len(got_children):
return False
for want, got in zip(want_children, got_children):
if not check_element(want, got):
return False
return True
want, got = self._strip_quotes(want, got)
want = want.replace('\\n','\n')
got = got.replace('\\n','\n')
# If the string is not a complete xml document, we may need to add a
# root element. This allow us to compare fragments, like "<foo/><bar/>"
if not want.startswith('<?xml'):
wrapper = '<root>%s</root>'
want = wrapper % want
got = wrapper % got
# Parse the want and got strings, and compare the parsings.
try:
want_root = parseString(want).firstChild
got_root = parseString(got).firstChild
except:
return False
return check_element(want_root, got_root)
def check_output_json(self, want, got, optionsflags):
"Tries to compare want and got as if they were JSON-encoded data"
want, got = self._strip_quotes(want, got)
try:
want_json = simplejson.loads(want)
got_json = simplejson.loads(got)
except:
return False
return want_json == got_json
def _strip_quotes(self, want, got):
"""
Strip quotes of doctests output values:
>>> o = OutputChecker()
>>> o._strip_quotes("'foo'")
"foo"
>>> o._strip_quotes('"foo"')
"foo"
>>> o._strip_quotes("u'foo'")
"foo"
>>> o._strip_quotes('u"foo"')
"foo"
"""
def is_quoted_string(s):
s = s.strip()
return (len(s) >= 2
and s[0] == s[-1]
and s[0] in ('"', "'"))
def is_quoted_unicode(s):
s = s.strip()
return (len(s) >= 3
and s[0] == 'u'
and s[1] == s[-1]
and s[1] in ('"', "'"))
if is_quoted_string(want) and is_quoted_string(got):
want = want.strip()[1:-1]
got = got.strip()[1:-1]
elif is_quoted_unicode(want) and is_quoted_unicode(got):
want = want.strip()[2:-1]
got = got.strip()[2:-1]
return want, got
class DocTestRunner(doctest.DocTestRunner):
def __init__(self, *args, **kwargs):
doctest.DocTestRunner.__init__(self, *args, **kwargs)
self.optionflags = doctest.ELLIPSIS
def report_unexpected_exception(self, out, test, example, exc_info):
doctest.DocTestRunner.report_unexpected_exception(self, out, test,
example, exc_info)
# Rollback, in case of database errors. Otherwise they'd have
# side effects on other tests.
transaction.rollback_unless_managed()
class TestCase(unittest.TestCase):
def _pre_setup(self):
"""Performs any pre-test setup. This includes:
* Flushing the database.
* If the Test Case class has a 'fixtures' member, installing the
named fixtures.
* If the Test Case class has a 'urls' member, replace the
ROOT_URLCONF with it.
* Clearing the mail test outbox.
"""
call_command('flush', verbosity=0, interactive=False)
if hasattr(self, 'fixtures'):
# We have to use this slightly awkward syntax due to the fact
# that we're using *args and **kwargs together.
call_command('loaddata', *self.fixtures, **{'verbosity': 0})
if hasattr(self, 'urls'):
self._old_root_urlconf = settings.ROOT_URLCONF
settings.ROOT_URLCONF = self.urls
clear_url_caches()
mail.outbox = []
def __call__(self, result=None):
|
def _post_teardown(self):
""" Performs any post-test things. This includes:
* Putting back the original ROOT_URLCONF if it was changed.
"""
if hasattr(self, '_old_root_urlconf'):
settings.ROOT_URLCONF = self._old_root_urlconf
clear_url_caches()
def assertRedirects(self, response, expected_url, status_code=302,
target_status_code=200, host=None):
"""Asserts that a response redirected to a specific URL, and that the
redirect URL can be loaded.
Note that assertRedirects won't work for external links since it uses
TestClient to do a request.
"""
self.assertEqual(response.status_code, status_code,
("Response didn't redirect as expected: Response code was %d"
" (expected %d)" % (response.status_code, status_code)))
url = response['Location']
scheme, netloc, path, query, fragment = urlsplit(url)
e_scheme, e_netloc, e_path, e_query, e_fragment = urlsplit(expected_url)
if not (e_scheme or e_netloc):
expected_url = urlunsplit(('http', host or 'testserver', e_path,
e_query, e_fragment))
self.assertEqual(url, expected_url,
"Response redirected to '%s', expected '%s'" % (url, expected_url))
# Get the redirection page, using the same client that was used
# to obtain the original response.
redirect_response = response.client.get(path, QueryDict(query))
self.assertEqual(redirect_response.status_code, target_status_code,
("Couldn't retrieve redirection page '%s': response code was %d"
" (expected %d)") %
(path, redirect_response.status_code, target_status_code))
def assertContains(self, response, text, count=None, status_code=200):
"""
Asserts that a response indicates that a page was retrieved
successfully, (i.e., the HTTP status code was as expected), and that
``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn't matter - the assertion is true
if the text occurs at least once in the response.
"""
self.assertEqual(response.status_code, status_code,
"Couldn't retrieve page: Response code was %d (expected %d)'" %
(response.status_code, status_code))
real_count = response.content.count(text)
if count is not None:
self.assertEqual(real_count, count,
"Found %d instances of '%s' in response (expected %d)" %
(real_count, text, count))
else:
self.failUnless(real_count != 0,
"Couldn't find '%s' in response" % text)
def assertNotContains(self, response, text, status_code=200):
"""
Asserts that a response indicates that a page was retrieved
successfully, (i.e., the HTTP status code was as expected), and that
``text`` doesn't occurs in the content of the response.
"""
self.assertEqual(response.status_code, status_code,
"Couldn't retrieve page: Response code was %d (expected %d)'" %
(response.status_code, status_code))
self.assertEqual(response.content.count(text), 0,
"Response should not contain '%s'" % text)
def assertFormError(self, response, form, field, errors):
"""
Asserts that a form used to render the response has a specific field
error.
"""
# Put context(s) into a list to simplify processing.
contexts = to_list(response.context)
if not contexts:
self.fail('Response did not use any contexts to render the'
' response')
# Put error(s) into a list to simplify processing.
errors = to_list(errors)
# Search all contexts for the error.
found_form = False
for i,context in enumerate(contexts):
if form not in context:
continue
found_form = True
for err in errors:
if field:
if field in context[form].errors:
field_errors = context[form].errors[field]
self.failUnless(err in field_errors,
"The field '%s' on form '%s' in"
" context %d does not contain the"
" error '%s' (actual errors: %s)" %
(field, form, i, err,
repr(field_errors)))
elif field in context[form].fields:
self.fail("The field '%s' on form '%s' in context %d"
" contains no errors" % (field, form, i))
else:
self.fail("The form '%s' in context %d does not"
" contain the field '%s'" %
(form, i, field))
else:
non_field_errors = context[form].non_field_errors()
self.failUnless(err in non_field_errors,
"The form '%s' in context %d does not contain the"
" non-field error '%s' (actual errors: %s)" %
(form, i, err, non_field_errors))
if not found_form:
self.fail("The form '%s' was not used to render the response" %
form)
def assertTemplateUsed(self, response, template_name):
"""
Asserts that the template with the provided name was used in rendering
the response.
"""
template_names = [t.name for t in to_list(response.template)]
if not template_names:
self.fail('No templates used to render the response')
self.failUnless(template_name in template_names,
(u"Template '%s' was not a template used to render the response."
u" Actual template(s) used: %s") % (template_name,
u', '.join(template_names)))
def assertTemplateNotUsed(self, response, template_name):
"""
Asserts that the template with the provided name was NOT used in
rendering the response.
"""
template_names = [t.name for t in to_list(response.template)]
self.failIf(template_name in template_names,
(u"Template '%s' was used unexpectedly in rendering the"
u" response") % template_name)
| """
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
"""
self.client = Client()
try:
self._pre_setup()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
import sys
result.addError(self, sys.exc_info())
return
super(TestCase, self).__call__(result)
try:
self._post_teardown()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
import sys
result.addError(self, sys.exc_info())
return | identifier_body |
testcases.py | import re
import unittest
from urlparse import urlsplit, urlunsplit
from xml.dom.minidom import parseString, Node
from django.conf import settings
from django.core import mail
from django.core.management import call_command
from django.core.urlresolvers import clear_url_caches
from django.db import transaction
from django.http import QueryDict
from django.test import _doctest as doctest
from django.test.client import Client
from django.utils import simplejson
normalize_long_ints = lambda s: re.sub(r'(?<![\w])(\d+)L(?![\w])', '\\1', s)
def to_list(value):
"""
Puts value into a list if it's not already one.
Returns an empty list if value is None.
"""
if value is None:
value = []
elif not isinstance(value, list):
value = [value]
return value
class OutputChecker(doctest.OutputChecker):
def check_output(self, want, got, optionflags):
"The entry method for doctest output checking. Defers to a sequence of child checkers"
checks = (self.check_output_default,
self.check_output_long,
self.check_output_xml,
self.check_output_json)
for check in checks:
if check(want, got, optionflags):
return True
return False
def check_output_default(self, want, got, optionflags):
"The default comparator provided by doctest - not perfect, but good for most purposes"
return doctest.OutputChecker.check_output(self, want, got, optionflags)
def check_output_long(self, want, got, optionflags):
"""Doctest does an exact string comparison of output, which means long
integers aren't equal to normal integers ("22L" vs. "22"). The
following code normalizes long integers so that they equal normal
integers.
"""
return normalize_long_ints(want) == normalize_long_ints(got)
def check_output_xml(self, want, got, optionsflags):
"""Tries to do a 'xml-comparision' of want and got. Plain string
comparision doesn't always work because, for example, attribute
ordering should not be important.
Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py
"""
_norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
def norm_whitespace(v):
return _norm_whitespace_re.sub(' ', v)
def child_text(element):
return ''.join([c.data for c in element.childNodes
if c.nodeType == Node.TEXT_NODE])
def children(element):
return [c for c in element.childNodes
if c.nodeType == Node.ELEMENT_NODE]
def norm_child_text(element):
return norm_whitespace(child_text(element))
def attrs_dict(element):
return dict(element.attributes.items())
def check_element(want_element, got_element):
if want_element.tagName != got_element.tagName:
return False
if norm_child_text(want_element) != norm_child_text(got_element):
return False
if attrs_dict(want_element) != attrs_dict(got_element):
return False
want_children = children(want_element)
got_children = children(got_element)
if len(want_children) != len(got_children):
return False
for want, got in zip(want_children, got_children):
if not check_element(want, got):
return False
return True
want, got = self._strip_quotes(want, got)
want = want.replace('\\n','\n')
got = got.replace('\\n','\n')
# If the string is not a complete xml document, we may need to add a
# root element. This allow us to compare fragments, like "<foo/><bar/>"
if not want.startswith('<?xml'):
wrapper = '<root>%s</root>'
want = wrapper % want
got = wrapper % got
# Parse the want and got strings, and compare the parsings.
try:
want_root = parseString(want).firstChild
got_root = parseString(got).firstChild
except:
return False
return check_element(want_root, got_root)
def check_output_json(self, want, got, optionsflags):
"Tries to compare want and got as if they were JSON-encoded data"
want, got = self._strip_quotes(want, got)
try:
want_json = simplejson.loads(want)
got_json = simplejson.loads(got)
except:
return False
return want_json == got_json
def _strip_quotes(self, want, got):
"""
Strip quotes of doctests output values:
>>> o = OutputChecker()
>>> o._strip_quotes("'foo'")
"foo"
>>> o._strip_quotes('"foo"')
"foo"
>>> o._strip_quotes("u'foo'")
"foo"
>>> o._strip_quotes('u"foo"')
"foo"
"""
def is_quoted_string(s):
s = s.strip()
return (len(s) >= 2
and s[0] == s[-1]
and s[0] in ('"', "'"))
def is_quoted_unicode(s):
s = s.strip()
return (len(s) >= 3
and s[0] == 'u'
and s[1] == s[-1]
and s[1] in ('"', "'"))
if is_quoted_string(want) and is_quoted_string(got):
want = want.strip()[1:-1]
got = got.strip()[1:-1]
elif is_quoted_unicode(want) and is_quoted_unicode(got):
want = want.strip()[2:-1]
got = got.strip()[2:-1]
return want, got
class DocTestRunner(doctest.DocTestRunner):
def __init__(self, *args, **kwargs):
doctest.DocTestRunner.__init__(self, *args, **kwargs)
self.optionflags = doctest.ELLIPSIS
def report_unexpected_exception(self, out, test, example, exc_info):
doctest.DocTestRunner.report_unexpected_exception(self, out, test,
example, exc_info)
# Rollback, in case of database errors. Otherwise they'd have
# side effects on other tests.
transaction.rollback_unless_managed()
class TestCase(unittest.TestCase):
def _pre_setup(self):
"""Performs any pre-test setup. This includes:
* Flushing the database.
* If the Test Case class has a 'fixtures' member, installing the
named fixtures.
* If the Test Case class has a 'urls' member, replace the
ROOT_URLCONF with it.
* Clearing the mail test outbox.
"""
call_command('flush', verbosity=0, interactive=False)
if hasattr(self, 'fixtures'):
# We have to use this slightly awkward syntax due to the fact
# that we're using *args and **kwargs together.
call_command('loaddata', *self.fixtures, **{'verbosity': 0})
if hasattr(self, 'urls'):
self._old_root_urlconf = settings.ROOT_URLCONF
settings.ROOT_URLCONF = self.urls
clear_url_caches()
mail.outbox = []
def __call__(self, result=None):
"""
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
"""
self.client = Client()
try:
self._pre_setup()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
import sys
result.addError(self, sys.exc_info())
return
super(TestCase, self).__call__(result)
try:
self._post_teardown()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
import sys
result.addError(self, sys.exc_info())
return
def _post_teardown(self):
""" Performs any post-test things. This includes:
* Putting back the original ROOT_URLCONF if it was changed.
"""
if hasattr(self, '_old_root_urlconf'):
settings.ROOT_URLCONF = self._old_root_urlconf
clear_url_caches()
def assertRedirects(self, response, expected_url, status_code=302,
target_status_code=200, host=None):
"""Asserts that a response redirected to a specific URL, and that the
redirect URL can be loaded.
Note that assertRedirects won't work for external links since it uses
TestClient to do a request.
"""
self.assertEqual(response.status_code, status_code,
("Response didn't redirect as expected: Response code was %d"
" (expected %d)" % (response.status_code, status_code)))
url = response['Location']
scheme, netloc, path, query, fragment = urlsplit(url)
e_scheme, e_netloc, e_path, e_query, e_fragment = urlsplit(expected_url)
if not (e_scheme or e_netloc):
expected_url = urlunsplit(('http', host or 'testserver', e_path,
e_query, e_fragment))
self.assertEqual(url, expected_url,
"Response redirected to '%s', expected '%s'" % (url, expected_url))
# Get the redirection page, using the same client that was used
# to obtain the original response.
redirect_response = response.client.get(path, QueryDict(query))
self.assertEqual(redirect_response.status_code, target_status_code,
("Couldn't retrieve redirection page '%s': response code was %d"
" (expected %d)") %
(path, redirect_response.status_code, target_status_code))
def assertContains(self, response, text, count=None, status_code=200):
"""
Asserts that a response indicates that a page was retrieved
successfully, (i.e., the HTTP status code was as expected), and that
``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn't matter - the assertion is true
if the text occurs at least once in the response.
"""
self.assertEqual(response.status_code, status_code,
"Couldn't retrieve page: Response code was %d (expected %d)'" %
(response.status_code, status_code))
real_count = response.content.count(text)
if count is not None:
self.assertEqual(real_count, count,
"Found %d instances of '%s' in response (expected %d)" %
(real_count, text, count))
else:
self.failUnless(real_count != 0,
"Couldn't find '%s' in response" % text)
def assertNotContains(self, response, text, status_code=200):
"""
Asserts that a response indicates that a page was retrieved
successfully, (i.e., the HTTP status code was as expected), and that
``text`` doesn't occurs in the content of the response.
"""
self.assertEqual(response.status_code, status_code,
"Couldn't retrieve page: Response code was %d (expected %d)'" %
(response.status_code, status_code))
self.assertEqual(response.content.count(text), 0,
"Response should not contain '%s'" % text)
def assertFormError(self, response, form, field, errors):
"""
Asserts that a form used to render the response has a specific field
error.
"""
# Put context(s) into a list to simplify processing.
contexts = to_list(response.context)
if not contexts:
self.fail('Response did not use any contexts to render the'
' response')
# Put error(s) into a list to simplify processing.
errors = to_list(errors)
# Search all contexts for the error.
found_form = False
for i,context in enumerate(contexts):
if form not in context:
continue
found_form = True
for err in errors:
if field:
if field in context[form].errors:
field_errors = context[form].errors[field]
self.failUnless(err in field_errors,
"The field '%s' on form '%s' in"
" context %d does not contain the"
" error '%s' (actual errors: %s)" %
(field, form, i, err,
repr(field_errors)))
elif field in context[form].fields:
self.fail("The field '%s' on form '%s' in context %d"
" contains no errors" % (field, form, i))
else:
self.fail("The form '%s' in context %d does not"
" contain the field '%s'" %
(form, i, field))
else:
non_field_errors = context[form].non_field_errors()
self.failUnless(err in non_field_errors,
"The form '%s' in context %d does not contain the"
" non-field error '%s' (actual errors: %s)" %
(form, i, err, non_field_errors))
if not found_form:
self.fail("The form '%s' was not used to render the response" %
form)
def assertTemplateUsed(self, response, template_name):
"""
Asserts that the template with the provided name was used in rendering
the response.
"""
template_names = [t.name for t in to_list(response.template)]
if not template_names:
self.fail('No templates used to render the response')
self.failUnless(template_name in template_names,
(u"Template '%s' was not a template used to render the response."
u" Actual template(s) used: %s") % (template_name,
u', '.join(template_names)))
def | (self, response, template_name):
"""
Asserts that the template with the provided name was NOT used in
rendering the response.
"""
template_names = [t.name for t in to_list(response.template)]
self.failIf(template_name in template_names,
(u"Template '%s' was used unexpectedly in rendering the"
u" response") % template_name)
| assertTemplateNotUsed | identifier_name |
testcases.py | import re
import unittest
from urlparse import urlsplit, urlunsplit
from xml.dom.minidom import parseString, Node
from django.conf import settings
from django.core import mail
from django.core.management import call_command
from django.core.urlresolvers import clear_url_caches
from django.db import transaction
from django.http import QueryDict
from django.test import _doctest as doctest
from django.test.client import Client
from django.utils import simplejson
normalize_long_ints = lambda s: re.sub(r'(?<![\w])(\d+)L(?![\w])', '\\1', s)
def to_list(value):
"""
Puts value into a list if it's not already one.
Returns an empty list if value is None.
"""
if value is None:
value = []
elif not isinstance(value, list):
value = [value]
return value
class OutputChecker(doctest.OutputChecker):
def check_output(self, want, got, optionflags):
"The entry method for doctest output checking. Defers to a sequence of child checkers"
checks = (self.check_output_default,
self.check_output_long,
self.check_output_xml,
self.check_output_json)
for check in checks:
if check(want, got, optionflags):
return True
return False
def check_output_default(self, want, got, optionflags):
"The default comparator provided by doctest - not perfect, but good for most purposes"
return doctest.OutputChecker.check_output(self, want, got, optionflags)
def check_output_long(self, want, got, optionflags):
"""Doctest does an exact string comparison of output, which means long
integers aren't equal to normal integers ("22L" vs. "22"). The
following code normalizes long integers so that they equal normal
integers.
"""
return normalize_long_ints(want) == normalize_long_ints(got)
def check_output_xml(self, want, got, optionsflags):
"""Tries to do a 'xml-comparision' of want and got. Plain string
comparision doesn't always work because, for example, attribute
ordering should not be important.
Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py
"""
_norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
def norm_whitespace(v):
return _norm_whitespace_re.sub(' ', v)
def child_text(element):
return ''.join([c.data for c in element.childNodes
if c.nodeType == Node.TEXT_NODE])
def children(element):
return [c for c in element.childNodes
if c.nodeType == Node.ELEMENT_NODE]
def norm_child_text(element):
return norm_whitespace(child_text(element))
def attrs_dict(element):
return dict(element.attributes.items())
def check_element(want_element, got_element):
if want_element.tagName != got_element.tagName:
return False
if norm_child_text(want_element) != norm_child_text(got_element):
return False
if attrs_dict(want_element) != attrs_dict(got_element):
return False
want_children = children(want_element)
got_children = children(got_element)
if len(want_children) != len(got_children):
return False
for want, got in zip(want_children, got_children):
if not check_element(want, got):
return False
return True
want, got = self._strip_quotes(want, got)
want = want.replace('\\n','\n')
got = got.replace('\\n','\n')
# If the string is not a complete xml document, we may need to add a
# root element. This allow us to compare fragments, like "<foo/><bar/>"
if not want.startswith('<?xml'):
wrapper = '<root>%s</root>'
want = wrapper % want
got = wrapper % got
# Parse the want and got strings, and compare the parsings.
try:
want_root = parseString(want).firstChild
got_root = parseString(got).firstChild
except:
return False
return check_element(want_root, got_root)
def check_output_json(self, want, got, optionsflags):
"Tries to compare want and got as if they were JSON-encoded data"
want, got = self._strip_quotes(want, got)
try:
want_json = simplejson.loads(want)
got_json = simplejson.loads(got)
except:
return False
return want_json == got_json
def _strip_quotes(self, want, got):
""" | >>> o = OutputChecker()
>>> o._strip_quotes("'foo'")
"foo"
>>> o._strip_quotes('"foo"')
"foo"
>>> o._strip_quotes("u'foo'")
"foo"
>>> o._strip_quotes('u"foo"')
"foo"
"""
def is_quoted_string(s):
s = s.strip()
return (len(s) >= 2
and s[0] == s[-1]
and s[0] in ('"', "'"))
def is_quoted_unicode(s):
s = s.strip()
return (len(s) >= 3
and s[0] == 'u'
and s[1] == s[-1]
and s[1] in ('"', "'"))
if is_quoted_string(want) and is_quoted_string(got):
want = want.strip()[1:-1]
got = got.strip()[1:-1]
elif is_quoted_unicode(want) and is_quoted_unicode(got):
want = want.strip()[2:-1]
got = got.strip()[2:-1]
return want, got
class DocTestRunner(doctest.DocTestRunner):
def __init__(self, *args, **kwargs):
doctest.DocTestRunner.__init__(self, *args, **kwargs)
self.optionflags = doctest.ELLIPSIS
def report_unexpected_exception(self, out, test, example, exc_info):
doctest.DocTestRunner.report_unexpected_exception(self, out, test,
example, exc_info)
# Rollback, in case of database errors. Otherwise they'd have
# side effects on other tests.
transaction.rollback_unless_managed()
class TestCase(unittest.TestCase):
def _pre_setup(self):
"""Performs any pre-test setup. This includes:
* Flushing the database.
* If the Test Case class has a 'fixtures' member, installing the
named fixtures.
* If the Test Case class has a 'urls' member, replace the
ROOT_URLCONF with it.
* Clearing the mail test outbox.
"""
call_command('flush', verbosity=0, interactive=False)
if hasattr(self, 'fixtures'):
# We have to use this slightly awkward syntax due to the fact
# that we're using *args and **kwargs together.
call_command('loaddata', *self.fixtures, **{'verbosity': 0})
if hasattr(self, 'urls'):
self._old_root_urlconf = settings.ROOT_URLCONF
settings.ROOT_URLCONF = self.urls
clear_url_caches()
mail.outbox = []
def __call__(self, result=None):
"""
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
"""
self.client = Client()
try:
self._pre_setup()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
import sys
result.addError(self, sys.exc_info())
return
super(TestCase, self).__call__(result)
try:
self._post_teardown()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
import sys
result.addError(self, sys.exc_info())
return
def _post_teardown(self):
""" Performs any post-test things. This includes:
* Putting back the original ROOT_URLCONF if it was changed.
"""
if hasattr(self, '_old_root_urlconf'):
settings.ROOT_URLCONF = self._old_root_urlconf
clear_url_caches()
def assertRedirects(self, response, expected_url, status_code=302,
target_status_code=200, host=None):
"""Asserts that a response redirected to a specific URL, and that the
redirect URL can be loaded.
Note that assertRedirects won't work for external links since it uses
TestClient to do a request.
"""
self.assertEqual(response.status_code, status_code,
("Response didn't redirect as expected: Response code was %d"
" (expected %d)" % (response.status_code, status_code)))
url = response['Location']
scheme, netloc, path, query, fragment = urlsplit(url)
e_scheme, e_netloc, e_path, e_query, e_fragment = urlsplit(expected_url)
if not (e_scheme or e_netloc):
expected_url = urlunsplit(('http', host or 'testserver', e_path,
e_query, e_fragment))
self.assertEqual(url, expected_url,
"Response redirected to '%s', expected '%s'" % (url, expected_url))
# Get the redirection page, using the same client that was used
# to obtain the original response.
redirect_response = response.client.get(path, QueryDict(query))
self.assertEqual(redirect_response.status_code, target_status_code,
("Couldn't retrieve redirection page '%s': response code was %d"
" (expected %d)") %
(path, redirect_response.status_code, target_status_code))
def assertContains(self, response, text, count=None, status_code=200):
"""
Asserts that a response indicates that a page was retrieved
successfully, (i.e., the HTTP status code was as expected), and that
``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn't matter - the assertion is true
if the text occurs at least once in the response.
"""
self.assertEqual(response.status_code, status_code,
"Couldn't retrieve page: Response code was %d (expected %d)'" %
(response.status_code, status_code))
real_count = response.content.count(text)
if count is not None:
self.assertEqual(real_count, count,
"Found %d instances of '%s' in response (expected %d)" %
(real_count, text, count))
else:
self.failUnless(real_count != 0,
"Couldn't find '%s' in response" % text)
def assertNotContains(self, response, text, status_code=200):
"""
Asserts that a response indicates that a page was retrieved
successfully, (i.e., the HTTP status code was as expected), and that
``text`` doesn't occurs in the content of the response.
"""
self.assertEqual(response.status_code, status_code,
"Couldn't retrieve page: Response code was %d (expected %d)'" %
(response.status_code, status_code))
self.assertEqual(response.content.count(text), 0,
"Response should not contain '%s'" % text)
def assertFormError(self, response, form, field, errors):
"""
Asserts that a form used to render the response has a specific field
error.
"""
# Put context(s) into a list to simplify processing.
contexts = to_list(response.context)
if not contexts:
self.fail('Response did not use any contexts to render the'
' response')
# Put error(s) into a list to simplify processing.
errors = to_list(errors)
# Search all contexts for the error.
found_form = False
for i,context in enumerate(contexts):
if form not in context:
continue
found_form = True
for err in errors:
if field:
if field in context[form].errors:
field_errors = context[form].errors[field]
self.failUnless(err in field_errors,
"The field '%s' on form '%s' in"
" context %d does not contain the"
" error '%s' (actual errors: %s)" %
(field, form, i, err,
repr(field_errors)))
elif field in context[form].fields:
self.fail("The field '%s' on form '%s' in context %d"
" contains no errors" % (field, form, i))
else:
self.fail("The form '%s' in context %d does not"
" contain the field '%s'" %
(form, i, field))
else:
non_field_errors = context[form].non_field_errors()
self.failUnless(err in non_field_errors,
"The form '%s' in context %d does not contain the"
" non-field error '%s' (actual errors: %s)" %
(form, i, err, non_field_errors))
if not found_form:
self.fail("The form '%s' was not used to render the response" %
form)
def assertTemplateUsed(self, response, template_name):
"""
Asserts that the template with the provided name was used in rendering
the response.
"""
template_names = [t.name for t in to_list(response.template)]
if not template_names:
self.fail('No templates used to render the response')
self.failUnless(template_name in template_names,
(u"Template '%s' was not a template used to render the response."
u" Actual template(s) used: %s") % (template_name,
u', '.join(template_names)))
def assertTemplateNotUsed(self, response, template_name):
"""
Asserts that the template with the provided name was NOT used in
rendering the response.
"""
template_names = [t.name for t in to_list(response.template)]
self.failIf(template_name in template_names,
(u"Template '%s' was used unexpectedly in rendering the"
u" response") % template_name) | Strip quotes of doctests output values:
| random_line_split |
testcases.py | import re
import unittest
from urlparse import urlsplit, urlunsplit
from xml.dom.minidom import parseString, Node
from django.conf import settings
from django.core import mail
from django.core.management import call_command
from django.core.urlresolvers import clear_url_caches
from django.db import transaction
from django.http import QueryDict
from django.test import _doctest as doctest
from django.test.client import Client
from django.utils import simplejson
normalize_long_ints = lambda s: re.sub(r'(?<![\w])(\d+)L(?![\w])', '\\1', s)
def to_list(value):
"""
Puts value into a list if it's not already one.
Returns an empty list if value is None.
"""
if value is None:
value = []
elif not isinstance(value, list):
value = [value]
return value
class OutputChecker(doctest.OutputChecker):
def check_output(self, want, got, optionflags):
"The entry method for doctest output checking. Defers to a sequence of child checkers"
checks = (self.check_output_default,
self.check_output_long,
self.check_output_xml,
self.check_output_json)
for check in checks:
if check(want, got, optionflags):
return True
return False
def check_output_default(self, want, got, optionflags):
"The default comparator provided by doctest - not perfect, but good for most purposes"
return doctest.OutputChecker.check_output(self, want, got, optionflags)
def check_output_long(self, want, got, optionflags):
"""Doctest does an exact string comparison of output, which means long
integers aren't equal to normal integers ("22L" vs. "22"). The
following code normalizes long integers so that they equal normal
integers.
"""
return normalize_long_ints(want) == normalize_long_ints(got)
def check_output_xml(self, want, got, optionsflags):
"""Tries to do a 'xml-comparision' of want and got. Plain string
comparision doesn't always work because, for example, attribute
ordering should not be important.
Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py
"""
_norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
def norm_whitespace(v):
return _norm_whitespace_re.sub(' ', v)
def child_text(element):
return ''.join([c.data for c in element.childNodes
if c.nodeType == Node.TEXT_NODE])
def children(element):
return [c for c in element.childNodes
if c.nodeType == Node.ELEMENT_NODE]
def norm_child_text(element):
return norm_whitespace(child_text(element))
def attrs_dict(element):
return dict(element.attributes.items())
def check_element(want_element, got_element):
if want_element.tagName != got_element.tagName:
return False
if norm_child_text(want_element) != norm_child_text(got_element):
return False
if attrs_dict(want_element) != attrs_dict(got_element):
return False
want_children = children(want_element)
got_children = children(got_element)
if len(want_children) != len(got_children):
return False
for want, got in zip(want_children, got_children):
if not check_element(want, got):
return False
return True
want, got = self._strip_quotes(want, got)
want = want.replace('\\n','\n')
got = got.replace('\\n','\n')
# If the string is not a complete xml document, we may need to add a
# root element. This allow us to compare fragments, like "<foo/><bar/>"
if not want.startswith('<?xml'):
wrapper = '<root>%s</root>'
want = wrapper % want
got = wrapper % got
# Parse the want and got strings, and compare the parsings.
try:
want_root = parseString(want).firstChild
got_root = parseString(got).firstChild
except:
return False
return check_element(want_root, got_root)
def check_output_json(self, want, got, optionsflags):
"Tries to compare want and got as if they were JSON-encoded data"
want, got = self._strip_quotes(want, got)
try:
want_json = simplejson.loads(want)
got_json = simplejson.loads(got)
except:
return False
return want_json == got_json
def _strip_quotes(self, want, got):
"""
Strip quotes of doctests output values:
>>> o = OutputChecker()
>>> o._strip_quotes("'foo'")
"foo"
>>> o._strip_quotes('"foo"')
"foo"
>>> o._strip_quotes("u'foo'")
"foo"
>>> o._strip_quotes('u"foo"')
"foo"
"""
def is_quoted_string(s):
s = s.strip()
return (len(s) >= 2
and s[0] == s[-1]
and s[0] in ('"', "'"))
def is_quoted_unicode(s):
s = s.strip()
return (len(s) >= 3
and s[0] == 'u'
and s[1] == s[-1]
and s[1] in ('"', "'"))
if is_quoted_string(want) and is_quoted_string(got):
want = want.strip()[1:-1]
got = got.strip()[1:-1]
elif is_quoted_unicode(want) and is_quoted_unicode(got):
want = want.strip()[2:-1]
got = got.strip()[2:-1]
return want, got
class DocTestRunner(doctest.DocTestRunner):
def __init__(self, *args, **kwargs):
doctest.DocTestRunner.__init__(self, *args, **kwargs)
self.optionflags = doctest.ELLIPSIS
def report_unexpected_exception(self, out, test, example, exc_info):
doctest.DocTestRunner.report_unexpected_exception(self, out, test,
example, exc_info)
# Rollback, in case of database errors. Otherwise they'd have
# side effects on other tests.
transaction.rollback_unless_managed()
class TestCase(unittest.TestCase):
def _pre_setup(self):
"""Performs any pre-test setup. This includes:
* Flushing the database.
* If the Test Case class has a 'fixtures' member, installing the
named fixtures.
* If the Test Case class has a 'urls' member, replace the
ROOT_URLCONF with it.
* Clearing the mail test outbox.
"""
call_command('flush', verbosity=0, interactive=False)
if hasattr(self, 'fixtures'):
# We have to use this slightly awkward syntax due to the fact
# that we're using *args and **kwargs together.
call_command('loaddata', *self.fixtures, **{'verbosity': 0})
if hasattr(self, 'urls'):
self._old_root_urlconf = settings.ROOT_URLCONF
settings.ROOT_URLCONF = self.urls
clear_url_caches()
mail.outbox = []
def __call__(self, result=None):
"""
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
"""
self.client = Client()
try:
self._pre_setup()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
import sys
result.addError(self, sys.exc_info())
return
super(TestCase, self).__call__(result)
try:
self._post_teardown()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
import sys
result.addError(self, sys.exc_info())
return
def _post_teardown(self):
""" Performs any post-test things. This includes:
* Putting back the original ROOT_URLCONF if it was changed.
"""
if hasattr(self, '_old_root_urlconf'):
settings.ROOT_URLCONF = self._old_root_urlconf
clear_url_caches()
def assertRedirects(self, response, expected_url, status_code=302,
target_status_code=200, host=None):
"""Asserts that a response redirected to a specific URL, and that the
redirect URL can be loaded.
Note that assertRedirects won't work for external links since it uses
TestClient to do a request.
"""
self.assertEqual(response.status_code, status_code,
("Response didn't redirect as expected: Response code was %d"
" (expected %d)" % (response.status_code, status_code)))
url = response['Location']
scheme, netloc, path, query, fragment = urlsplit(url)
e_scheme, e_netloc, e_path, e_query, e_fragment = urlsplit(expected_url)
if not (e_scheme or e_netloc):
expected_url = urlunsplit(('http', host or 'testserver', e_path,
e_query, e_fragment))
self.assertEqual(url, expected_url,
"Response redirected to '%s', expected '%s'" % (url, expected_url))
# Get the redirection page, using the same client that was used
# to obtain the original response.
redirect_response = response.client.get(path, QueryDict(query))
self.assertEqual(redirect_response.status_code, target_status_code,
("Couldn't retrieve redirection page '%s': response code was %d"
" (expected %d)") %
(path, redirect_response.status_code, target_status_code))
def assertContains(self, response, text, count=None, status_code=200):
"""
Asserts that a response indicates that a page was retrieved
successfully, (i.e., the HTTP status code was as expected), and that
``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn't matter - the assertion is true
if the text occurs at least once in the response.
"""
self.assertEqual(response.status_code, status_code,
"Couldn't retrieve page: Response code was %d (expected %d)'" %
(response.status_code, status_code))
real_count = response.content.count(text)
if count is not None:
self.assertEqual(real_count, count,
"Found %d instances of '%s' in response (expected %d)" %
(real_count, text, count))
else:
self.failUnless(real_count != 0,
"Couldn't find '%s' in response" % text)
def assertNotContains(self, response, text, status_code=200):
"""
Asserts that a response indicates that a page was retrieved
successfully, (i.e., the HTTP status code was as expected), and that
``text`` doesn't occurs in the content of the response.
"""
self.assertEqual(response.status_code, status_code,
"Couldn't retrieve page: Response code was %d (expected %d)'" %
(response.status_code, status_code))
self.assertEqual(response.content.count(text), 0,
"Response should not contain '%s'" % text)
def assertFormError(self, response, form, field, errors):
"""
Asserts that a form used to render the response has a specific field
error.
"""
# Put context(s) into a list to simplify processing.
contexts = to_list(response.context)
if not contexts:
self.fail('Response did not use any contexts to render the'
' response')
# Put error(s) into a list to simplify processing.
errors = to_list(errors)
# Search all contexts for the error.
found_form = False
for i,context in enumerate(contexts):
if form not in context:
continue
found_form = True
for err in errors:
if field:
if field in context[form].errors:
field_errors = context[form].errors[field]
self.failUnless(err in field_errors,
"The field '%s' on form '%s' in"
" context %d does not contain the"
" error '%s' (actual errors: %s)" %
(field, form, i, err,
repr(field_errors)))
elif field in context[form].fields:
|
else:
self.fail("The form '%s' in context %d does not"
" contain the field '%s'" %
(form, i, field))
else:
non_field_errors = context[form].non_field_errors()
self.failUnless(err in non_field_errors,
"The form '%s' in context %d does not contain the"
" non-field error '%s' (actual errors: %s)" %
(form, i, err, non_field_errors))
if not found_form:
self.fail("The form '%s' was not used to render the response" %
form)
def assertTemplateUsed(self, response, template_name):
"""
Asserts that the template with the provided name was used in rendering
the response.
"""
template_names = [t.name for t in to_list(response.template)]
if not template_names:
self.fail('No templates used to render the response')
self.failUnless(template_name in template_names,
(u"Template '%s' was not a template used to render the response."
u" Actual template(s) used: %s") % (template_name,
u', '.join(template_names)))
def assertTemplateNotUsed(self, response, template_name):
"""
Asserts that the template with the provided name was NOT used in
rendering the response.
"""
template_names = [t.name for t in to_list(response.template)]
self.failIf(template_name in template_names,
(u"Template '%s' was used unexpectedly in rendering the"
u" response") % template_name)
| self.fail("The field '%s' on form '%s' in context %d"
" contains no errors" % (field, form, i)) | conditional_block |
helm.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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 std::ffi::OsString;
use common::ui::UI;
use error::Result;
const EXPORT_CMD: &'static str = "hab-pkg-export-helm";
const EXPORT_CMD_ENVVAR: &'static str = "HAB_PKG_EXPORT_HELM_BINARY";
const EXPORT_PKG_IDENT: &'static str = "core/hab-pkg-export-helm";
const EXPORT_PKG_IDENT_ENVVAR: &'static str = "HAB_PKG_EXPORT_HELM_PKG_IDENT";
pub fn | (ui: &mut UI, args: Vec<OsString>) -> Result<()> {
::command::pkg::export::export_common::start(
ui,
args,
EXPORT_CMD,
EXPORT_CMD_ENVVAR,
EXPORT_PKG_IDENT,
EXPORT_PKG_IDENT_ENVVAR,
)
}
| start | identifier_name |
helm.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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 std::ffi::OsString;
use common::ui::UI;
use error::Result;
| pub fn start(ui: &mut UI, args: Vec<OsString>) -> Result<()> {
::command::pkg::export::export_common::start(
ui,
args,
EXPORT_CMD,
EXPORT_CMD_ENVVAR,
EXPORT_PKG_IDENT,
EXPORT_PKG_IDENT_ENVVAR,
)
} | const EXPORT_CMD: &'static str = "hab-pkg-export-helm";
const EXPORT_CMD_ENVVAR: &'static str = "HAB_PKG_EXPORT_HELM_BINARY";
const EXPORT_PKG_IDENT: &'static str = "core/hab-pkg-export-helm";
const EXPORT_PKG_IDENT_ENVVAR: &'static str = "HAB_PKG_EXPORT_HELM_PKG_IDENT";
| random_line_split |
helm.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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 std::ffi::OsString;
use common::ui::UI;
use error::Result;
const EXPORT_CMD: &'static str = "hab-pkg-export-helm";
const EXPORT_CMD_ENVVAR: &'static str = "HAB_PKG_EXPORT_HELM_BINARY";
const EXPORT_PKG_IDENT: &'static str = "core/hab-pkg-export-helm";
const EXPORT_PKG_IDENT_ENVVAR: &'static str = "HAB_PKG_EXPORT_HELM_PKG_IDENT";
pub fn start(ui: &mut UI, args: Vec<OsString>) -> Result<()> | {
::command::pkg::export::export_common::start(
ui,
args,
EXPORT_CMD,
EXPORT_CMD_ENVVAR,
EXPORT_PKG_IDENT,
EXPORT_PKG_IDENT_ENVVAR,
)
} | identifier_body | |
AlunoANEE.js | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* @author Municipio de Itajaí - Secretaria de Educação - DITEC *
* @updated 30/06/2016 *
* Pacote: Erudio *
* *
* Copyright (C) 2016 Prefeitura de Itajaí - Secretaria de Educação *
* DITEC - Diretoria de Tecnologias educacionais *
* ditec@itajai.sc.gov.br *
* *
* Este programa é software livre, você pode redistribuí-lo e/ou *
* modificá-lo sob os termos da Licença Pública Geral GNU, conforme *
* publicada pela Free Software Foundation, tanto a versão 2 da *
* Licença como (a seu critério) qualquer versão mais nova. *
* *
* Este programa é distribuído na expectativa de ser útil, mas SEM *
* QUALQUER GARANTIA. Sem mesmo a garantia implícita de COMERCIALI- *
* ZAÇÃO ou de ADEQUAÇÃO A QUALQUER PROPÓSITO EM PARTICULAR. Con- *
* sulte a Licença Pública Geral GNU para obter mais detalhes. *
* *
* Você deve ter recebido uma cópia da Licença Pública Geral GNU *
* junto com este programa. Se não, escreva para a Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA *
* 02111-1307, USA. *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
(function (){
/*
* @ErudioDoc Alunos ANEE Service
* @Module alunosANEE
* @Service AlunoANEEService
*/
'use strict';
class AlunoANEEService { | this.urlPorInstituicao = this.erudioConfig.urlRelatorios+'/alunos/anee-nominal-instituicao';
}
/*
* @method getURL
* @methodReturn String
* @methodParams unidade|Int
* @methodDescription Busca a url para gerar o relatório de ANEE por unidade.
*/
getURL(unidade){ return this.url+'?unidade='+unidade; }
/*
* @method getURLPorInstituicao
* @methodReturn String
* @methodParams instituicao|Int
* @methodDescription Busca a url para gerar o relatório de ANEE por instituição.
*/
getURLPorInstituicao(instituicao){ return this.urlPorInstituicao+'?instituicao='+instituicao; }
};
angular.module('AlunoANEEService',['erudioConfig']).service('AlunoANEEService',AlunoANEEService);
AlunoANEEService.$inject = ["BaseService","ErudioConfig"];
})(); | constructor(rest,erudioConfig){
this.rest = rest;
this.erudioConfig = erudioConfig;
this.url = this.erudioConfig.urlRelatorios+'/alunos/anee-nominal-unidade'; | random_line_split |
AlunoANEE.js | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* @author Municipio de Itajaí - Secretaria de Educação - DITEC *
* @updated 30/06/2016 *
* Pacote: Erudio *
* *
* Copyright (C) 2016 Prefeitura de Itajaí - Secretaria de Educação *
* DITEC - Diretoria de Tecnologias educacionais *
* ditec@itajai.sc.gov.br *
* *
* Este programa é software livre, você pode redistribuí-lo e/ou *
* modificá-lo sob os termos da Licença Pública Geral GNU, conforme *
* publicada pela Free Software Foundation, tanto a versão 2 da *
* Licença como (a seu critério) qualquer versão mais nova. *
* *
* Este programa é distribuído na expectativa de ser útil, mas SEM *
* QUALQUER GARANTIA. Sem mesmo a garantia implícita de COMERCIALI- *
* ZAÇÃO ou de ADEQUAÇÃO A QUALQUER PROPÓSITO EM PARTICULAR. Con- *
* sulte a Licença Pública Geral GNU para obter mais detalhes. *
* *
* Você deve ter recebido uma cópia da Licença Pública Geral GNU *
* junto com este programa. Se não, escreva para a Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA *
* 02111-1307, USA. *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
(function (){
/*
* @ErudioDoc Alunos ANEE Service
* @Module alunosANEE
* @Service AlunoANEEService
*/
'use strict';
class AlunoANEEService {
constructor(rest,erudioConfig){
this.rest = rest;
| getURL
* @methodReturn String
* @methodParams unidade|Int
* @methodDescription Busca a url para gerar o relatório de ANEE por unidade.
*/
getURL(unidade){ return this.url+'?unidade='+unidade; }
/*
* @method getURLPorInstituicao
* @methodReturn String
* @methodParams instituicao|Int
* @methodDescription Busca a url para gerar o relatório de ANEE por instituição.
*/
getURLPorInstituicao(instituicao){ return this.urlPorInstituicao+'?instituicao='+instituicao; }
};
angular.module('AlunoANEEService',['erudioConfig']).service('AlunoANEEService',AlunoANEEService);
AlunoANEEService.$inject = ["BaseService","ErudioConfig"];
})(); | this.erudioConfig = erudioConfig;
this.url = this.erudioConfig.urlRelatorios+'/alunos/anee-nominal-unidade';
this.urlPorInstituicao = this.erudioConfig.urlRelatorios+'/alunos/anee-nominal-instituicao';
}
/*
* @method | identifier_body |
AlunoANEE.js | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* @author Municipio de Itajaí - Secretaria de Educação - DITEC *
* @updated 30/06/2016 *
* Pacote: Erudio *
* *
* Copyright (C) 2016 Prefeitura de Itajaí - Secretaria de Educação *
* DITEC - Diretoria de Tecnologias educacionais *
* ditec@itajai.sc.gov.br *
* *
* Este programa é software livre, você pode redistribuí-lo e/ou *
* modificá-lo sob os termos da Licença Pública Geral GNU, conforme *
* publicada pela Free Software Foundation, tanto a versão 2 da *
* Licença como (a seu critério) qualquer versão mais nova. *
* *
* Este programa é distribuído na expectativa de ser útil, mas SEM *
* QUALQUER GARANTIA. Sem mesmo a garantia implícita de COMERCIALI- *
* ZAÇÃO ou de ADEQUAÇÃO A QUALQUER PROPÓSITO EM PARTICULAR. Con- *
* sulte a Licença Pública Geral GNU para obter mais detalhes. *
* *
* Você deve ter recebido uma cópia da Licença Pública Geral GNU *
* junto com este programa. Se não, escreva para a Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA *
* 02111-1307, USA. *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
(function (){
/*
* @ErudioDoc Alunos ANEE Service
* @Module alunosANEE
* @Service AlunoANEEService
*/
'use strict';
class AlunoANEEService {
const | ioConfig){
this.rest = rest;
this.erudioConfig = erudioConfig;
this.url = this.erudioConfig.urlRelatorios+'/alunos/anee-nominal-unidade';
this.urlPorInstituicao = this.erudioConfig.urlRelatorios+'/alunos/anee-nominal-instituicao';
}
/*
* @method getURL
* @methodReturn String
* @methodParams unidade|Int
* @methodDescription Busca a url para gerar o relatório de ANEE por unidade.
*/
getURL(unidade){ return this.url+'?unidade='+unidade; }
/*
* @method getURLPorInstituicao
* @methodReturn String
* @methodParams instituicao|Int
* @methodDescription Busca a url para gerar o relatório de ANEE por instituição.
*/
getURLPorInstituicao(instituicao){ return this.urlPorInstituicao+'?instituicao='+instituicao; }
};
angular.module('AlunoANEEService',['erudioConfig']).service('AlunoANEEService',AlunoANEEService);
AlunoANEEService.$inject = ["BaseService","ErudioConfig"];
})(); | ructor(rest,erud | identifier_name |
exampleFour.js | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Digia Plc and its Subsidiary(-ies) 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
//![0]
// exampleFour.js
.import Qt.example 1.0 as QtExample
function | () {
var component = Qt.createComponent("exampleTwo.qml");
var exampleOneElement = component.createObject(null);
var avatarExample = exampleOneElement.a;
var retn = avatarExample.avatar;
retn.preserve();
return retn;
}
function releaseAvatar(avatar) {
avatar.destroy();
}
//![0] | importAvatar | identifier_name |
exampleFour.js | /****************************************************************************
** | ** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Digia Plc and its Subsidiary(-ies) 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
//![0]
// exampleFour.js
.import Qt.example 1.0 as QtExample
function importAvatar() {
var component = Qt.createComponent("exampleTwo.qml");
var exampleOneElement = component.createObject(null);
var avatarExample = exampleOneElement.a;
var retn = avatarExample.avatar;
retn.preserve();
return retn;
}
function releaseAvatar(avatar) {
avatar.destroy();
}
//![0] | ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation of the Qt Toolkit.
** | random_line_split |
exampleFour.js | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Digia Plc and its Subsidiary(-ies) 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
//![0]
// exampleFour.js
.import Qt.example 1.0 as QtExample
function importAvatar() {
var component = Qt.createComponent("exampleTwo.qml");
var exampleOneElement = component.createObject(null);
var avatarExample = exampleOneElement.a;
var retn = avatarExample.avatar;
retn.preserve();
return retn;
}
function releaseAvatar(avatar) |
//![0] | {
avatar.destroy();
} | identifier_body |
15.4.4.22-9-c-ii-32.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.4/15.4.4/15.4.4.22/15.4.4.22-9-c-ii-32.js
* @description Array.prototype.reduceRight - RegExp Object can be used as accumulator
*/
function testcase() |
runTestCase(testcase);
| {
var accessed = false;
var objRegExp = new RegExp();
function callbackfn(prevVal, curVal, idx, obj) {
accessed = true;
return prevVal === objRegExp;
}
var obj = { 0: 11, length: 1 };
return Array.prototype.reduceRight.call(obj, callbackfn, objRegExp) === true && accessed;
} | identifier_body |
15.4.4.22-9-c-ii-32.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.4/15.4.4/15.4.4.22/15.4.4.22-9-c-ii-32.js
* @description Array.prototype.reduceRight - RegExp Object can be used as accumulator
*/
function testcase() {
var accessed = false;
var objRegExp = new RegExp();
function callbackfn(prevVal, curVal, idx, obj) {
| }
var obj = { 0: 11, length: 1 };
return Array.prototype.reduceRight.call(obj, callbackfn, objRegExp) === true && accessed;
}
runTestCase(testcase); | accessed = true;
return prevVal === objRegExp;
| random_line_split |
15.4.4.22-9-c-ii-32.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.4/15.4.4/15.4.4.22/15.4.4.22-9-c-ii-32.js
* @description Array.prototype.reduceRight - RegExp Object can be used as accumulator
*/
function | () {
var accessed = false;
var objRegExp = new RegExp();
function callbackfn(prevVal, curVal, idx, obj) {
accessed = true;
return prevVal === objRegExp;
}
var obj = { 0: 11, length: 1 };
return Array.prototype.reduceRight.call(obj, callbackfn, objRegExp) === true && accessed;
}
runTestCase(testcase);
| testcase | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.