repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
ProbonoBonobo/reg-machine | resources/public/cljs/out/schema/utils.js | 24973 | // Compiled by ClojureScript 1.9.227 {}
goog.provide('schema.utils');
goog.require('cljs.core');
goog.require('goog.string.format');
goog.require('goog.string');
/**
* Like assoc but only assocs when value is truthy. Copied from plumbing.core so that
* schema need not depend on plumbing.
*/
schema.utils.assoc_when = (function schema$utils$assoc_when(var_args){
var args__25833__auto__ = [];
var len__25826__auto___29810 = arguments.length;
var i__25827__auto___29811 = (0);
while(true){
if((i__25827__auto___29811 < len__25826__auto___29810)){
args__25833__auto__.push((arguments[i__25827__auto___29811]));
var G__29812 = (i__25827__auto___29811 + (1));
i__25827__auto___29811 = G__29812;
continue;
} else {
}
break;
}
var argseq__25834__auto__ = ((((1) < args__25833__auto__.length))?(new cljs.core.IndexedSeq(args__25833__auto__.slice((1)),(0),null)):null);
return schema.utils.assoc_when.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),argseq__25834__auto__);
});
schema.utils.assoc_when.cljs$core$IFn$_invoke$arity$variadic = (function (m,kvs){
if(cljs.core.even_QMARK_.call(null,cljs.core.count.call(null,kvs))){
} else {
throw (new Error("Assert failed: (even? (count kvs))"));
}
return cljs.core.into.call(null,(function (){var or__24751__auto__ = m;
if(cljs.core.truth_(or__24751__auto__)){
return or__24751__auto__;
} else {
return cljs.core.PersistentArrayMap.EMPTY;
}
})(),(function (){var iter__25531__auto__ = (function schema$utils$iter__29794(s__29795){
return (new cljs.core.LazySeq(null,(function (){
var s__29795__$1 = s__29795;
while(true){
var temp__4657__auto__ = cljs.core.seq.call(null,s__29795__$1);
if(temp__4657__auto__){
var s__29795__$2 = temp__4657__auto__;
if(cljs.core.chunked_seq_QMARK_.call(null,s__29795__$2)){
var c__25529__auto__ = cljs.core.chunk_first.call(null,s__29795__$2);
var size__25530__auto__ = cljs.core.count.call(null,c__25529__auto__);
var b__29797 = cljs.core.chunk_buffer.call(null,size__25530__auto__);
if((function (){var i__29796 = (0);
while(true){
if((i__29796 < size__25530__auto__)){
var vec__29804 = cljs.core._nth.call(null,c__25529__auto__,i__29796);
var k = cljs.core.nth.call(null,vec__29804,(0),null);
var v = cljs.core.nth.call(null,vec__29804,(1),null);
if(cljs.core.truth_(v)){
cljs.core.chunk_append.call(null,b__29797,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [k,v], null));
var G__29813 = (i__29796 + (1));
i__29796 = G__29813;
continue;
} else {
var G__29814 = (i__29796 + (1));
i__29796 = G__29814;
continue;
}
} else {
return true;
}
break;
}
})()){
return cljs.core.chunk_cons.call(null,cljs.core.chunk.call(null,b__29797),schema$utils$iter__29794.call(null,cljs.core.chunk_rest.call(null,s__29795__$2)));
} else {
return cljs.core.chunk_cons.call(null,cljs.core.chunk.call(null,b__29797),null);
}
} else {
var vec__29807 = cljs.core.first.call(null,s__29795__$2);
var k = cljs.core.nth.call(null,vec__29807,(0),null);
var v = cljs.core.nth.call(null,vec__29807,(1),null);
if(cljs.core.truth_(v)){
return cljs.core.cons.call(null,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [k,v], null),schema$utils$iter__29794.call(null,cljs.core.rest.call(null,s__29795__$2)));
} else {
var G__29815 = cljs.core.rest.call(null,s__29795__$2);
s__29795__$1 = G__29815;
continue;
}
}
} else {
return null;
}
break;
}
}),null,null));
});
return iter__25531__auto__.call(null,cljs.core.partition.call(null,(2),kvs));
})());
});
schema.utils.assoc_when.cljs$lang$maxFixedArity = (1);
schema.utils.assoc_when.cljs$lang$applyTo = (function (seq29792){
var G__29793 = cljs.core.first.call(null,seq29792);
var seq29792__$1 = cljs.core.next.call(null,seq29792);
return schema.utils.assoc_when.cljs$core$IFn$_invoke$arity$variadic(G__29793,seq29792__$1);
});
schema.utils.type_of = (function schema$utils$type_of(x){
return typeof x;
});
/**
* What class can we associate the fn schema with? In Clojure use the class of the fn; in
* cljs just use the fn itself.
*/
schema.utils.fn_schema_bearer = (function schema$utils$fn_schema_bearer(f){
return f;
});
schema.utils.format_STAR_ = (function schema$utils$format_STAR_(var_args){
var args__25833__auto__ = [];
var len__25826__auto___29818 = arguments.length;
var i__25827__auto___29819 = (0);
while(true){
if((i__25827__auto___29819 < len__25826__auto___29818)){
args__25833__auto__.push((arguments[i__25827__auto___29819]));
var G__29820 = (i__25827__auto___29819 + (1));
i__25827__auto___29819 = G__29820;
continue;
} else {
}
break;
}
var argseq__25834__auto__ = ((((1) < args__25833__auto__.length))?(new cljs.core.IndexedSeq(args__25833__auto__.slice((1)),(0),null)):null);
return schema.utils.format_STAR_.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),argseq__25834__auto__);
});
schema.utils.format_STAR_.cljs$core$IFn$_invoke$arity$variadic = (function (fmt,args){
return cljs.core.apply.call(null,goog.string.format,fmt,args);
});
schema.utils.format_STAR_.cljs$lang$maxFixedArity = (1);
schema.utils.format_STAR_.cljs$lang$applyTo = (function (seq29816){
var G__29817 = cljs.core.first.call(null,seq29816);
var seq29816__$1 = cljs.core.next.call(null,seq29816);
return schema.utils.format_STAR_.cljs$core$IFn$_invoke$arity$variadic(G__29817,seq29816__$1);
});
/**
* Provide a descriptive short name for a value.
*/
schema.utils.value_name = (function schema$utils$value_name(value){
var t = schema.utils.type_of.call(null,value);
if((cljs.core.count.call(null,[cljs.core.str(value)].join('')) < (20))){
return value;
} else {
return cljs.core.symbol.call(null,[cljs.core.str("a-"),cljs.core.str(t)].join(''));
}
});
/**
* Identity version of memoize, because many schemas are records, and records
* don't cache their hash codes (at least in Clojure 1.5.1).
* Not thread safe, and doesn't cache falsey values.
*/
schema.utils.memoize_id = (function schema$utils$memoize_id(f){
return cljs.core.memoize.call(null,f);
});
schema.utils.record_QMARK_ = (function schema$utils$record_QMARK_(x){
if(!((x == null))){
if(((x.cljs$lang$protocol_mask$partition0$ & (67108864))) || (x.cljs$core$IRecord$)){
return true;
} else {
if((!x.cljs$lang$protocol_mask$partition0$)){
return cljs.core.native_satisfies_QMARK_.call(null,cljs.core.IRecord,x);
} else {
return false;
}
}
} else {
return cljs.core.native_satisfies_QMARK_.call(null,cljs.core.IRecord,x);
}
});
/**
* @constructor
* @implements {cljs.core.IPrintWithWriter}
*/
schema.utils.ValidationError = (function (schema,value,expectation_delay,fail_explanation){
this.schema = schema;
this.value = value;
this.expectation_delay = expectation_delay;
this.fail_explanation = fail_explanation;
this.cljs$lang$protocol_mask$partition0$ = 2147483648;
this.cljs$lang$protocol_mask$partition1$ = 0;
})
schema.utils.ValidationError.prototype.cljs$core$IPrintWithWriter$_pr_writer$arity$3 = (function (this$,writer,opts){
var self__ = this;
var this$__$1 = this;
return cljs.core._pr_writer.call(null,schema.utils.validation_error_explain.call(null,this$__$1),writer,opts);
});
schema.utils.ValidationError.getBasis = (function (){
return new cljs.core.PersistentVector(null, 4, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Symbol(null,"schema","schema",58529736,null),new cljs.core.Symbol(null,"value","value",1946509744,null),new cljs.core.Symbol(null,"expectation-delay","expectation-delay",-1886214669,null),new cljs.core.Symbol(null,"fail-explanation","fail-explanation",530278923,null)], null);
});
schema.utils.ValidationError.cljs$lang$type = true;
schema.utils.ValidationError.cljs$lang$ctorStr = "schema.utils/ValidationError";
schema.utils.ValidationError.cljs$lang$ctorPrWriter = (function (this__25357__auto__,writer__25358__auto__,opt__25359__auto__){
return cljs.core._write.call(null,writer__25358__auto__,"schema.utils/ValidationError");
});
schema.utils.__GT_ValidationError = (function schema$utils$__GT_ValidationError(schema__$1,value,expectation_delay,fail_explanation){
return (new schema.utils.ValidationError(schema__$1,value,expectation_delay,fail_explanation));
});
schema.utils.validation_error_explain = (function schema$utils$validation_error_explain(err){
var x__25585__auto__ = (function (){var or__24751__auto__ = err.fail_explanation;
if(cljs.core.truth_(or__24751__auto__)){
return or__24751__auto__;
} else {
return new cljs.core.Symbol(null,"not","not",1044554643,null);
}
})();
return cljs.core._conj.call(null,(function (){var x__25585__auto____$1 = cljs.core.deref.call(null,err.expectation_delay);
return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__25585__auto____$1);
})(),x__25585__auto__);
});
/**
* for cljs sake (easier than normalizing imports in macros.clj)
*/
schema.utils.__GT_ValidationError = (function schema$utils$__GT_ValidationError(schema__$1,value,expectation_delay,fail_explanation){
return (new schema.utils.ValidationError(schema__$1,value,expectation_delay,fail_explanation));
});
/**
* @constructor
* @implements {cljs.core.IPrintWithWriter}
*/
schema.utils.NamedError = (function (name,error){
this.name = name;
this.error = error;
this.cljs$lang$protocol_mask$partition0$ = 2147483648;
this.cljs$lang$protocol_mask$partition1$ = 0;
})
schema.utils.NamedError.prototype.cljs$core$IPrintWithWriter$_pr_writer$arity$3 = (function (this$,writer,opts){
var self__ = this;
var this$__$1 = this;
return cljs.core._pr_writer.call(null,schema.utils.named_error_explain.call(null,this$__$1),writer,opts);
});
schema.utils.NamedError.getBasis = (function (){
return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Symbol(null,"name","name",-810760592,null),new cljs.core.Symbol(null,"error","error",661562495,null)], null);
});
schema.utils.NamedError.cljs$lang$type = true;
schema.utils.NamedError.cljs$lang$ctorStr = "schema.utils/NamedError";
schema.utils.NamedError.cljs$lang$ctorPrWriter = (function (this__25357__auto__,writer__25358__auto__,opt__25359__auto__){
return cljs.core._write.call(null,writer__25358__auto__,"schema.utils/NamedError");
});
schema.utils.__GT_NamedError = (function schema$utils$__GT_NamedError(name,error){
return (new schema.utils.NamedError(name,error));
});
schema.utils.named_error_explain = (function schema$utils$named_error_explain(err){
return cljs.core._conj.call(null,(function (){var x__25585__auto__ = err.error;
return cljs.core._conj.call(null,(function (){var x__25585__auto____$1 = err.name;
return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__25585__auto____$1);
})(),x__25585__auto__);
})(),new cljs.core.Symbol(null,"named","named",1218138048,null));
});
/**
* for cljs sake (easier than normalizing imports in macros.clj)
*/
schema.utils.__GT_NamedError = (function schema$utils$__GT_NamedError(name,error){
return (new schema.utils.NamedError(name,error));
});
/**
* @constructor
* @implements {cljs.core.IRecord}
* @implements {cljs.core.IEquiv}
* @implements {cljs.core.IHash}
* @implements {cljs.core.ICollection}
* @implements {cljs.core.ICounted}
* @implements {cljs.core.ISeqable}
* @implements {cljs.core.IMeta}
* @implements {cljs.core.ICloneable}
* @implements {cljs.core.IPrintWithWriter}
* @implements {cljs.core.IIterable}
* @implements {cljs.core.IWithMeta}
* @implements {cljs.core.IAssociative}
* @implements {cljs.core.IMap}
* @implements {cljs.core.ILookup}
*/
schema.utils.ErrorContainer = (function (error,__meta,__extmap,__hash){
this.error = error;
this.__meta = __meta;
this.__extmap = __extmap;
this.__hash = __hash;
this.cljs$lang$protocol_mask$partition0$ = 2229667594;
this.cljs$lang$protocol_mask$partition1$ = 8192;
})
schema.utils.ErrorContainer.prototype.cljs$core$ILookup$_lookup$arity$2 = (function (this__25373__auto__,k__25374__auto__){
var self__ = this;
var this__25373__auto____$1 = this;
return cljs.core._lookup.call(null,this__25373__auto____$1,k__25374__auto__,null);
});
schema.utils.ErrorContainer.prototype.cljs$core$ILookup$_lookup$arity$3 = (function (this__25375__auto__,k29824,else__25376__auto__){
var self__ = this;
var this__25375__auto____$1 = this;
var G__29826 = (((k29824 instanceof cljs.core.Keyword))?k29824.fqn:null);
switch (G__29826) {
case "error":
return self__.error;
break;
default:
return cljs.core.get.call(null,self__.__extmap,k29824,else__25376__auto__);
}
});
schema.utils.ErrorContainer.prototype.cljs$core$IPrintWithWriter$_pr_writer$arity$3 = (function (this__25387__auto__,writer__25388__auto__,opts__25389__auto__){
var self__ = this;
var this__25387__auto____$1 = this;
var pr_pair__25390__auto__ = ((function (this__25387__auto____$1){
return (function (keyval__25391__auto__){
return cljs.core.pr_sequential_writer.call(null,writer__25388__auto__,cljs.core.pr_writer,""," ","",opts__25389__auto__,keyval__25391__auto__);
});})(this__25387__auto____$1))
;
return cljs.core.pr_sequential_writer.call(null,writer__25388__auto__,pr_pair__25390__auto__,"#schema.utils.ErrorContainer{",", ","}",opts__25389__auto__,cljs.core.concat.call(null,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [(new cljs.core.PersistentVector(null,2,(5),cljs.core.PersistentVector.EMPTY_NODE,[new cljs.core.Keyword(null,"error","error",-978969032),self__.error],null))], null),self__.__extmap));
});
schema.utils.ErrorContainer.prototype.cljs$core$IIterable$ = true;
schema.utils.ErrorContainer.prototype.cljs$core$IIterable$_iterator$arity$1 = (function (G__29823){
var self__ = this;
var G__29823__$1 = this;
return (new cljs.core.RecordIter((0),G__29823__$1,1,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"error","error",-978969032)], null),cljs.core._iterator.call(null,self__.__extmap)));
});
schema.utils.ErrorContainer.prototype.cljs$core$IMeta$_meta$arity$1 = (function (this__25371__auto__){
var self__ = this;
var this__25371__auto____$1 = this;
return self__.__meta;
});
schema.utils.ErrorContainer.prototype.cljs$core$ICloneable$_clone$arity$1 = (function (this__25367__auto__){
var self__ = this;
var this__25367__auto____$1 = this;
return (new schema.utils.ErrorContainer(self__.error,self__.__meta,self__.__extmap,self__.__hash));
});
schema.utils.ErrorContainer.prototype.cljs$core$ICounted$_count$arity$1 = (function (this__25377__auto__){
var self__ = this;
var this__25377__auto____$1 = this;
return (1 + cljs.core.count.call(null,self__.__extmap));
});
schema.utils.ErrorContainer.prototype.cljs$core$IHash$_hash$arity$1 = (function (this__25368__auto__){
var self__ = this;
var this__25368__auto____$1 = this;
var h__25186__auto__ = self__.__hash;
if(!((h__25186__auto__ == null))){
return h__25186__auto__;
} else {
var h__25186__auto____$1 = cljs.core.hash_imap.call(null,this__25368__auto____$1);
self__.__hash = h__25186__auto____$1;
return h__25186__auto____$1;
}
});
schema.utils.ErrorContainer.prototype.cljs$core$IEquiv$_equiv$arity$2 = (function (this__25369__auto__,other__25370__auto__){
var self__ = this;
var this__25369__auto____$1 = this;
if(cljs.core.truth_((function (){var and__24739__auto__ = other__25370__auto__;
if(cljs.core.truth_(and__24739__auto__)){
var and__24739__auto____$1 = (this__25369__auto____$1.constructor === other__25370__auto__.constructor);
if(and__24739__auto____$1){
return cljs.core.equiv_map.call(null,this__25369__auto____$1,other__25370__auto__);
} else {
return and__24739__auto____$1;
}
} else {
return and__24739__auto__;
}
})())){
return true;
} else {
return false;
}
});
schema.utils.ErrorContainer.prototype.cljs$core$IMap$_dissoc$arity$2 = (function (this__25382__auto__,k__25383__auto__){
var self__ = this;
var this__25382__auto____$1 = this;
if(cljs.core.contains_QMARK_.call(null,new cljs.core.PersistentHashSet(null, new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"error","error",-978969032),null], null), null),k__25383__auto__)){
return cljs.core.dissoc.call(null,cljs.core.with_meta.call(null,cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,this__25382__auto____$1),self__.__meta),k__25383__auto__);
} else {
return (new schema.utils.ErrorContainer(self__.error,self__.__meta,cljs.core.not_empty.call(null,cljs.core.dissoc.call(null,self__.__extmap,k__25383__auto__)),null));
}
});
schema.utils.ErrorContainer.prototype.cljs$core$IAssociative$_assoc$arity$3 = (function (this__25380__auto__,k__25381__auto__,G__29823){
var self__ = this;
var this__25380__auto____$1 = this;
var pred__29827 = cljs.core.keyword_identical_QMARK_;
var expr__29828 = k__25381__auto__;
if(cljs.core.truth_(pred__29827.call(null,new cljs.core.Keyword(null,"error","error",-978969032),expr__29828))){
return (new schema.utils.ErrorContainer(G__29823,self__.__meta,self__.__extmap,null));
} else {
return (new schema.utils.ErrorContainer(self__.error,self__.__meta,cljs.core.assoc.call(null,self__.__extmap,k__25381__auto__,G__29823),null));
}
});
schema.utils.ErrorContainer.prototype.cljs$core$ISeqable$_seq$arity$1 = (function (this__25385__auto__){
var self__ = this;
var this__25385__auto____$1 = this;
return cljs.core.seq.call(null,cljs.core.concat.call(null,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [(new cljs.core.PersistentVector(null,2,(5),cljs.core.PersistentVector.EMPTY_NODE,[new cljs.core.Keyword(null,"error","error",-978969032),self__.error],null))], null),self__.__extmap));
});
schema.utils.ErrorContainer.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = (function (this__25372__auto__,G__29823){
var self__ = this;
var this__25372__auto____$1 = this;
return (new schema.utils.ErrorContainer(self__.error,G__29823,self__.__extmap,self__.__hash));
});
schema.utils.ErrorContainer.prototype.cljs$core$ICollection$_conj$arity$2 = (function (this__25378__auto__,entry__25379__auto__){
var self__ = this;
var this__25378__auto____$1 = this;
if(cljs.core.vector_QMARK_.call(null,entry__25379__auto__)){
return cljs.core._assoc.call(null,this__25378__auto____$1,cljs.core._nth.call(null,entry__25379__auto__,(0)),cljs.core._nth.call(null,entry__25379__auto__,(1)));
} else {
return cljs.core.reduce.call(null,cljs.core._conj,this__25378__auto____$1,entry__25379__auto__);
}
});
schema.utils.ErrorContainer.getBasis = (function (){
return new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Symbol(null,"error","error",661562495,null)], null);
});
schema.utils.ErrorContainer.cljs$lang$type = true;
schema.utils.ErrorContainer.cljs$lang$ctorPrSeq = (function (this__25407__auto__){
return cljs.core._conj.call(null,cljs.core.List.EMPTY,"schema.utils/ErrorContainer");
});
schema.utils.ErrorContainer.cljs$lang$ctorPrWriter = (function (this__25407__auto__,writer__25408__auto__){
return cljs.core._write.call(null,writer__25408__auto__,"schema.utils/ErrorContainer");
});
schema.utils.__GT_ErrorContainer = (function schema$utils$__GT_ErrorContainer(error){
return (new schema.utils.ErrorContainer(error,null,null,null));
});
schema.utils.map__GT_ErrorContainer = (function schema$utils$map__GT_ErrorContainer(G__29825){
return (new schema.utils.ErrorContainer(new cljs.core.Keyword(null,"error","error",-978969032).cljs$core$IFn$_invoke$arity$1(G__29825),null,cljs.core.dissoc.call(null,G__29825,new cljs.core.Keyword(null,"error","error",-978969032)),null));
});
/**
* Distinguish a value (must be non-nil) as an error.
*/
schema.utils.error = (function schema$utils$error(x){
if(cljs.core.truth_(x)){
} else {
throw (new Error("Assert failed: x"));
}
return schema.utils.__GT_ErrorContainer.call(null,x);
});
schema.utils.error_QMARK_ = (function schema$utils$error_QMARK_(x){
return (x instanceof schema.utils.ErrorContainer);
});
schema.utils.error_val = (function schema$utils$error_val(x){
if(cljs.core.truth_(schema.utils.error_QMARK_.call(null,x))){
return x.error;
} else {
return null;
}
});
/**
* If maybe-error is an error, wrap the inner value in a NamedError; otherwise, return as-is
*/
schema.utils.wrap_error_name = (function schema$utils$wrap_error_name(name,maybe_error){
var temp__4655__auto__ = schema.utils.error_val.call(null,maybe_error);
if(cljs.core.truth_(temp__4655__auto__)){
var e = temp__4655__auto__;
return schema.utils.error.call(null,schema.utils.__GT_NamedError.call(null,name,e));
} else {
return maybe_error;
}
});
/**
* Build up a result by conjing values, producing an error if at least one
* sub-value returns an error.
*/
schema.utils.result_builder = (function schema$utils$result_builder(lift_to_error){
return (function schema$utils$result_builder_$_conjer(m,e){
var temp__4655__auto__ = schema.utils.error_val.call(null,e);
if(cljs.core.truth_(temp__4655__auto__)){
var err = temp__4655__auto__;
return schema.utils.error.call(null,cljs.core.conj.call(null,(function (){var or__24751__auto__ = schema.utils.error_val.call(null,m);
if(cljs.core.truth_(or__24751__auto__)){
return or__24751__auto__;
} else {
return lift_to_error.call(null,m);
}
})(),err));
} else {
var temp__4655__auto____$1 = schema.utils.error_val.call(null,m);
if(cljs.core.truth_(temp__4655__auto____$1)){
var merr = temp__4655__auto____$1;
return schema.utils.error.call(null,cljs.core.conj.call(null,merr,null));
} else {
return cljs.core.conj.call(null,m,e);
}
}
});
});
schema.utils.declare_class_schema_BANG_ = (function schema$utils$declare_class_schema_BANG_(klass,schema__$1){
return (klass["schema$utils$schema"] = schema__$1);
});
schema.utils.class_schema = (function schema$utils$class_schema(klass){
return (klass["schema$utils$schema"]);
});
/**
* @interface
*/
schema.utils.PSimpleCell = function(){};
schema.utils.get_cell = (function schema$utils$get_cell(this$){
if((!((this$ == null))) && (!((this$.schema$utils$PSimpleCell$get_cell$arity$1 == null)))){
return this$.schema$utils$PSimpleCell$get_cell$arity$1(this$);
} else {
var x__25414__auto__ = (((this$ == null))?null:this$);
var m__25415__auto__ = (schema.utils.get_cell[goog.typeOf(x__25414__auto__)]);
if(!((m__25415__auto__ == null))){
return m__25415__auto__.call(null,this$);
} else {
var m__25415__auto____$1 = (schema.utils.get_cell["_"]);
if(!((m__25415__auto____$1 == null))){
return m__25415__auto____$1.call(null,this$);
} else {
throw cljs.core.missing_protocol.call(null,"PSimpleCell.get_cell",this$);
}
}
}
});
schema.utils.set_cell = (function schema$utils$set_cell(this$,x){
if((!((this$ == null))) && (!((this$.schema$utils$PSimpleCell$set_cell$arity$2 == null)))){
return this$.schema$utils$PSimpleCell$set_cell$arity$2(this$,x);
} else {
var x__25414__auto__ = (((this$ == null))?null:this$);
var m__25415__auto__ = (schema.utils.set_cell[goog.typeOf(x__25414__auto__)]);
if(!((m__25415__auto__ == null))){
return m__25415__auto__.call(null,this$,x);
} else {
var m__25415__auto____$1 = (schema.utils.set_cell["_"]);
if(!((m__25415__auto____$1 == null))){
return m__25415__auto____$1.call(null,this$,x);
} else {
throw cljs.core.missing_protocol.call(null,"PSimpleCell.set_cell",this$);
}
}
}
});
/**
* @constructor
* @implements {schema.utils.PSimpleCell}
*/
schema.utils.SimpleVCell = (function (q){
this.q = q;
})
schema.utils.SimpleVCell.prototype.schema$utils$PSimpleCell$ = true;
schema.utils.SimpleVCell.prototype.schema$utils$PSimpleCell$get_cell$arity$1 = (function (this$){
var self__ = this;
var this$__$1 = this;
return self__.q;
});
schema.utils.SimpleVCell.prototype.schema$utils$PSimpleCell$set_cell$arity$2 = (function (this$,x){
var self__ = this;
var this$__$1 = this;
return self__.q = x;
});
schema.utils.SimpleVCell.getBasis = (function (){
return new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.with_meta(new cljs.core.Symbol(null,"q","q",-1965434072,null),new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"tag","tag",-1290361223),new cljs.core.Symbol(null,"boolean","boolean",-278886877,null),new cljs.core.Keyword(null,"volatile-mutable","volatile-mutable",1731728411),true], null))], null);
});
schema.utils.SimpleVCell.cljs$lang$type = true;
schema.utils.SimpleVCell.cljs$lang$ctorStr = "schema.utils/SimpleVCell";
schema.utils.SimpleVCell.cljs$lang$ctorPrWriter = (function (this__25357__auto__,writer__25358__auto__,opt__25359__auto__){
return cljs.core._write.call(null,writer__25358__auto__,"schema.utils/SimpleVCell");
});
schema.utils.__GT_SimpleVCell = (function schema$utils$__GT_SimpleVCell(q){
return (new schema.utils.SimpleVCell(q));
});
/**
* Turn on run-time function validation for functions compiled when
* s/compile-fn-validation was true -- has no effect for functions compiled
* when it is false.
*/
schema.utils.use_fn_validation = (new schema.utils.SimpleVCell(false));
schema.utils.use_fn_validation.get_cell = cljs.core.partial.call(null,schema.utils.get_cell,schema.utils.use_fn_validation);
schema.utils.use_fn_validation.set_cell = cljs.core.partial.call(null,schema.utils.set_cell,schema.utils.use_fn_validation);
//# sourceMappingURL=utils.js.map?rel=1478445823254 | epl-1.0 |
maxeler/eclipse | eclipse.jdt.core/org.eclipse.jdt.apt.tests/src/org/eclipse/jdt/apt/tests/DeclarationVisitorTests.java | 13720 | /*******************************************************************************
* Copyright (c) 2006 BEA Systems, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* sbandow@bea.com - initial API and implementation
*
*******************************************************************************/
package org.eclipse.jdt.apt.tests;
import java.util.ArrayList;
import java.util.Collection;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.apt.tests.annotations.generic.AbstractGenericProcessor;
import org.eclipse.jdt.apt.tests.annotations.generic.GenericFactory;
import com.sun.mirror.declaration.AnnotationTypeDeclaration;
import com.sun.mirror.declaration.AnnotationTypeElementDeclaration;
import com.sun.mirror.declaration.ClassDeclaration;
import com.sun.mirror.declaration.ConstructorDeclaration;
import com.sun.mirror.declaration.Declaration;
import com.sun.mirror.declaration.EnumConstantDeclaration;
import com.sun.mirror.declaration.EnumDeclaration;
import com.sun.mirror.declaration.ExecutableDeclaration;
import com.sun.mirror.declaration.FieldDeclaration;
import com.sun.mirror.declaration.InterfaceDeclaration;
import com.sun.mirror.declaration.MemberDeclaration;
import com.sun.mirror.declaration.MethodDeclaration;
import com.sun.mirror.declaration.PackageDeclaration;
import com.sun.mirror.declaration.ParameterDeclaration;
import com.sun.mirror.declaration.TypeDeclaration;
import com.sun.mirror.declaration.TypeParameterDeclaration;
import com.sun.mirror.util.DeclarationVisitor;
/**
* Tests for the JDT-APT implementation of Declaration Visitors
*/
public class DeclarationVisitorTests extends APTTestBase {
public DeclarationVisitorTests(final String name) {
super(name);
}
public static Test suite() {
return new TestSuite(DeclarationVisitorTests.class);
}
public void testPackageDeclarationVisitor() {
testCaseIdentifier = Cases.PackageDeclaration;
runProcessorBasedTest();
}
public void testClassDeclarationVisitor() {
testCaseIdentifier = Cases.ClassDeclaration;
runProcessorBasedTest();
}
public void testEnumDeclarationVisitor() {
testCaseIdentifier = Cases.EnumDeclaration;
runProcessorBasedTest();
}
public void testInterfaceDeclarationVisitor() {
testCaseIdentifier = Cases.InterfaceDeclaration;
runProcessorBasedTest();
}
public void testAnnotationTypeDeclarationVisitor() {
testCaseIdentifier = Cases.AnnotationTypeDeclaration;
runProcessorBasedTest();
}
public void testFieldDeclarationVisitor() {
testCaseIdentifier = Cases.FieldDeclaration;
runProcessorBasedTest();
}
public void testEnumConstantDeclarationVisitor() {
testCaseIdentifier = Cases.EnumConstantDeclaration;
runProcessorBasedTest();
}
public void testConstructorDeclarationVisitor() {
testCaseIdentifier = Cases.ConstructorDeclaration;
runProcessorBasedTest();
}
public void testMethodDeclarationVisitor() {
testCaseIdentifier = Cases.MethodDeclaration;
runProcessorBasedTest();
}
public void testAnnotationTypeElementDeclarationVisitor() {
testCaseIdentifier = Cases.AnnotationTypeElementDeclaration;
runProcessorBasedTest();
}
public void testParameterDeclarationVisitor() {
testCaseIdentifier = Cases.ParameterDeclaration;
runProcessorBasedTest();
}
public void testTypeParameterDeclarationVisitor() {
testCaseIdentifier = Cases.TypeParameterDeclaration;
runProcessorBasedTest();
}
/**
* Instantiate the AnnotationProcessor to run the actual tests
*/
void runProcessorBasedTest() {
DeclarationVisitorProc p = new DeclarationVisitorProc();
GenericFactory.PROCESSOR = p;
IProject project = env.getProject(getProjectName());
IPath srcRoot = getSourcePath();
env.addClass(srcRoot, "test", "Test", code);
fullBuild( project.getFullPath() );
expectingNoProblems();
assertTrue("Processor not invoked", p.called);
}
/**
* Annotation Processor containing the actual tests
*/
class DeclarationVisitorProc extends AbstractGenericProcessor {
boolean called;
public void _process() {
called = true;
assertTrue(decls.size() == 1);
initDeclVisitList();
TypeDeclaration typeDecl = env.getTypeDeclarations().iterator().next();
Collection<TypeDeclaration> nestedTypes = typeDecl.getNestedTypes();
ClassDeclaration classDecl = null;
EnumDeclaration enumDecl = null;
InterfaceDeclaration interfaceDecl = null;
AnnotationTypeDeclaration annoTypeDecl = null;
EnumConstantDeclaration enumConstantDecl = null;
MethodDeclaration methodDecl = null;
switch (testCaseIdentifier) {
case PackageDeclaration :
PackageDeclaration packageDecl = typeDecl.getPackage();
packageDecl.accept(new DeclarationVisitorImpl());
assertEquals("Expect one visitor", 1, declarationsVisited.size());
assertEquals("Expected PackageDeclaration visitor", "PackageDeclarationImpl", declarationsVisited.get(0).getClass().getSimpleName());
break;
case ClassDeclaration :
for(TypeDeclaration tempDecl : nestedTypes) {
if(tempDecl.getSimpleName().equals("C")) {
classDecl = (ClassDeclaration)tempDecl;
}
}
classDecl.accept(new DeclarationVisitorImpl());
assertEquals("Expect one visitor", 1, declarationsVisited.size());
assertEquals("Expected ClassDeclaration visitor", "ClassDeclarationImpl", declarationsVisited.get(0).getClass().getSimpleName());
break;
case EnumDeclaration :
for(TypeDeclaration tempDecl : nestedTypes) {
if(tempDecl.getSimpleName().equals("E")) {
enumDecl = (EnumDeclaration)tempDecl;
}
}
enumDecl.accept(new DeclarationVisitorImpl());
assertEquals("Expect one visitor", 1, declarationsVisited.size());
assertEquals("Expected EnumDeclaration visitor", "EnumDeclarationImpl", declarationsVisited.get(0).getClass().getSimpleName());
break;
case InterfaceDeclaration :
for(TypeDeclaration tempDecl : nestedTypes) {
if(tempDecl.getSimpleName().equals("I")) {
interfaceDecl = (InterfaceDeclaration)tempDecl;
}
}
interfaceDecl.accept(new DeclarationVisitorImpl());
assertEquals("Expect one visitor", 1, declarationsVisited.size());
assertEquals("Expected InterfaceDeclaration visitor", "InterfaceDeclarationImpl", declarationsVisited.get(0).getClass().getSimpleName());
break;
case AnnotationTypeDeclaration :
for(TypeDeclaration tempDecl : nestedTypes) {
if(tempDecl.getSimpleName().equals("A")) {
annoTypeDecl = (AnnotationTypeDeclaration)tempDecl;
}
}
annoTypeDecl.accept(new DeclarationVisitorImpl());
assertEquals("Expect one visitor", 1, declarationsVisited.size());
assertEquals("Expected AnnotationTypeDeclaration visitor", "AnnotationDeclarationImpl", declarationsVisited.get(0).getClass().getSimpleName());
break;
case FieldDeclaration :
FieldDeclaration fieldDecl = typeDecl.getFields().iterator().next();
fieldDecl.accept(new DeclarationVisitorImpl());
assertEquals("Expect one visitor", 1, declarationsVisited.size());
assertEquals("Expected FieldDeclaration visitor", "FieldDeclarationImpl", declarationsVisited.get(0).getClass().getSimpleName());
break;
case EnumConstantDeclaration :
for(TypeDeclaration tempDecl : nestedTypes) {
if(tempDecl.getSimpleName().equals("E")) {
enumDecl = (EnumDeclaration)tempDecl;
}
}
enumConstantDecl = enumDecl.getEnumConstants().iterator().next();
enumConstantDecl.accept(new DeclarationVisitorImpl());
assertEquals("Expect one visitor", 1, declarationsVisited.size());
assertEquals("Expected EnumConstantDeclaration visitor", "EnumConstantDeclarationImpl", declarationsVisited.get(0).getClass().getSimpleName());
break;
case ConstructorDeclaration :
for(TypeDeclaration tempDecl : nestedTypes) {
if(tempDecl.getSimpleName().equals("C")) {
classDecl = (ClassDeclaration)tempDecl;
}
}
ConstructorDeclaration constructorDecl = classDecl.getConstructors().iterator().next();
constructorDecl.accept(new DeclarationVisitorImpl());
assertEquals("Expect one visitor", 1, declarationsVisited.size());
assertEquals("Expected ConstructorDeclaration visitor", "ConstructorDeclarationImpl", declarationsVisited.get(0).getClass().getSimpleName());
break;
case MethodDeclaration :
methodDecl = typeDecl.getMethods().iterator().next();
methodDecl.accept(new DeclarationVisitorImpl());
assertEquals("Expect one visitor", 1, declarationsVisited.size());
assertEquals("Expected MethodDeclaration visitor", "MethodDeclarationImpl", declarationsVisited.get(0).getClass().getSimpleName());
break;
case AnnotationTypeElementDeclaration :
for(TypeDeclaration tempDecl : nestedTypes) {
if(tempDecl.getSimpleName().equals("A")) {
annoTypeDecl = (AnnotationTypeDeclaration)tempDecl;
}
}
AnnotationTypeElementDeclaration annoTypeElementDecl = annoTypeDecl.getMethods().iterator().next();
annoTypeElementDecl.accept(new DeclarationVisitorImpl());
assertEquals("Expect one visitor", 1, declarationsVisited.size());
assertEquals("Expected AnnotationTypeElementDeclaration visitor", "AnnotationElementDeclarationImpl", declarationsVisited.get(0).getClass().getSimpleName());
break;
case ParameterDeclaration :
methodDecl = typeDecl.getMethods().iterator().next();
ParameterDeclaration paramDecl = methodDecl.getParameters().iterator().next();
paramDecl.accept(new DeclarationVisitorImpl());
assertEquals("Expect one visitor", 1, declarationsVisited.size());
assertEquals("Expected ParameterDeclaration visitor", "SourceParameterDeclarationImpl", declarationsVisited.get(0).getClass().getSimpleName());
break;
case TypeParameterDeclaration :
for(TypeDeclaration tempDecl : nestedTypes) {
if(tempDecl.getSimpleName().equals("P")) {
classDecl = (ClassDeclaration)tempDecl;
}
}
TypeParameterDeclaration typeParamDecl = classDecl.getFormalTypeParameters().iterator().next();
typeParamDecl.accept(new DeclarationVisitorImpl());
assertEquals("Expect one visitor", 1, declarationsVisited.size());
assertEquals("Expected TypeParameterDeclaration visitor", "TypeParameterDeclarationImpl", declarationsVisited.get(0).getClass().getSimpleName());
break;
}
}
}
/**
* DeclarationVisitor implementation for the purposes of these tests
*/
class DeclarationVisitorImpl implements DeclarationVisitor {
public void visitDeclaration(Declaration d) {
fail("Should never visit a Declaration, only a subclass: " + d);
}
public void visitPackageDeclaration(PackageDeclaration d) {
declarationVisited(d);
}
public void visitMemberDeclaration(MemberDeclaration d) {
fail("Should never visit a Member, only a subclass: " + d);
}
public void visitTypeDeclaration(TypeDeclaration d) {
fail("Should never visit a Type, only a subclass: " + d);
}
public void visitClassDeclaration(ClassDeclaration d) {
declarationVisited(d);
}
public void visitEnumDeclaration(EnumDeclaration d) {
declarationVisited(d);
}
public void visitInterfaceDeclaration(InterfaceDeclaration d) {
declarationVisited(d);
}
public void visitAnnotationTypeDeclaration(AnnotationTypeDeclaration d) {
declarationVisited(d);
}
public void visitFieldDeclaration(FieldDeclaration d) {
declarationVisited(d);
}
public void visitEnumConstantDeclaration(EnumConstantDeclaration d) {
declarationVisited(d);
}
public void visitExecutableDeclaration(ExecutableDeclaration d) {
fail("Should never visit an ExecutableDeclaration, only a subclass: " + d);
}
public void visitConstructorDeclaration(ConstructorDeclaration d) {
declarationVisited(d);
}
public void visitMethodDeclaration(MethodDeclaration d) {
declarationVisited(d);
}
public void visitAnnotationTypeElementDeclaration(AnnotationTypeElementDeclaration d) {
declarationVisited(d);
}
public void visitParameterDeclaration(ParameterDeclaration d) {
declarationVisited(d);
}
public void visitTypeParameterDeclaration(TypeParameterDeclaration d) {
declarationVisited(d);
}
}
/*
* Utilities for running the DeclarationVisitor tests
*/
enum Cases {
PackageDeclaration,
ClassDeclaration,
EnumDeclaration,
InterfaceDeclaration,
AnnotationTypeDeclaration,
FieldDeclaration,
EnumConstantDeclaration,
ConstructorDeclaration,
MethodDeclaration,
AnnotationTypeElementDeclaration,
ParameterDeclaration,
TypeParameterDeclaration
}
Cases testCaseIdentifier;
ArrayList<Declaration> declarationsVisited = new ArrayList<Declaration>();
void declarationVisited(Declaration d) {
declarationsVisited.add(d);
}
void initDeclVisitList() {
if(declarationsVisited.size() > 0) {
declarationsVisited.clear();
}
}
final String code =
"package test;" + "\n" +
"import org.eclipse.jdt.apt.tests.annotations.generic.*;" + "\n" +
"@GenericAnnotation public class Test" + "\n" +
"{" + "\n" +
" Test() {}" + "\n" +
" String s;" + "\n" +
" class C {}" + "\n" +
" class P<T> {}" + "\n" +
" interface I {}" + "\n" +
" void m(int i) {}" + "\n" +
" enum E { elephant }" + "\n" +
" @interface A { String strValue() default \"\"; }" + "\n" +
"}";
}
| epl-1.0 |
sehrgut/minecraft-smp-mocreatures | moCreatures/server/core/sources/net/minecraft/src/Packet102WindowClick.java | 2143 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode
package net.minecraft.src;
import java.io.*;
// Referenced classes of package net.minecraft.src:
// Packet, ItemStack, NetHandler
public class Packet102WindowClick extends Packet
{
public Packet102WindowClick()
{
}
public void processPacket(NetHandler nethandler)
{
nethandler.func_20007_a(this);
}
public void readPacketData(DataInputStream datainputstream) throws IOException
{
window_Id = datainputstream.readByte();
inventorySlot = datainputstream.readShort();
mouseClick = datainputstream.readByte();
action = datainputstream.readShort();
field_27039_f = datainputstream.readBoolean();
short word0 = datainputstream.readShort();
if(word0 >= 0)
{
byte byte0 = datainputstream.readByte();
short word1 = datainputstream.readShort();
itemStack = new ItemStack(word0, byte0, word1);
} else
{
itemStack = null;
}
}
public void writePacketData(DataOutputStream dataoutputstream) throws IOException
{
dataoutputstream.writeByte(window_Id);
dataoutputstream.writeShort(inventorySlot);
dataoutputstream.writeByte(mouseClick);
dataoutputstream.writeShort(action);
dataoutputstream.writeBoolean(field_27039_f);
if(itemStack == null)
{
dataoutputstream.writeShort(-1);
} else
{
dataoutputstream.writeShort(itemStack.itemID);
dataoutputstream.writeByte(itemStack.stackSize);
dataoutputstream.writeShort(itemStack.getItemDamage());
}
}
public int getPacketSize()
{
return 11;
}
public int window_Id;
public int inventorySlot;
public int mouseClick;
public short action;
public ItemStack itemStack;
public boolean field_27039_f;
}
| epl-1.0 |
cyclingengineer/UpnpHomeAutomationBridge | src/com/cyclingengineer/upnphomeautomationbridge/eq3max/upnpservices/Eq3MaxHvacUserOperatingModeServiceSystemUserMode.java | 659 | package com.cyclingengineer.upnphomeautomationbridge.eq3max.upnpservices;
import com.cyclingengineer.upnphomeautomationbridge.upnpservices.HvacUserOperatingModeServiceSystemUserMode;
public class Eq3MaxHvacUserOperatingModeServiceSystemUserMode extends
HvacUserOperatingModeServiceSystemUserMode {
@Override
protected void nameUpdate(String setNameValue) {
// do nothing
}
@Override
protected void modeTargetUpdate(String setModeTargetValue) {
// TODO do something when status update is requested
modeStatus = setModeTargetValue;
}
@Override
protected String modeStatusRequest() {
// just return the status
return modeStatus;
}
}
| epl-1.0 |
ProgPrak/Projekt2016 | serverengine_sw/Figur.java | 979 | package serverengine_sw;
//Oberklasse f�r Monster und Spieler
public class Figur {
//Attribute
int ID;
int Gesundheit;
int MaxGesundheit;
int Schaden;
int posx,posy;
//Getter und Setter
public void setPos(int x,int y){
this.posx=x;
this.posy=y;
}
public int getPosY(){
return posy;
}
public int getPosX(){
return posx;
}
public int getGesundheit(){
return Gesundheit;
}
public void setGesundheit(int g){
this.Gesundheit=g;
if(Gesundheit>MaxGesundheit){
Gesundheit=MaxGesundheit;
}
}
public void setMaxGesundheit(int g){
this.MaxGesundheit=g;
}
public int getSchaden(){
return Schaden;
}
public int getID(){
return ID;
}
public void setID(int i){
this.ID=i;
}
//Bewegung einer Figur
public void hoch(){
posy--;
}
public void runter(){
posy++;
}
public void rechts(){
posx++;
}
public void links(){
posx--;
}
} | epl-1.0 |
DavidGutknecht/elexis-3-base | bundles/at.medevit.medelexis.text.msword/src/at/medevit/medelexis/text/msword/plugin/util/OleWordColumn.java | 1470 | /*******************************************************************************
* Copyright (c) 2012, MEDEVIT OG and MEDELEXIS AG
* All rights reserved.
******************************************************************************/
package at.medevit.medelexis.text.msword.plugin.util;
import java.util.HashMap;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.Variant;
import org.eclipse.swt.widgets.Display;
public class OleWordColumn extends OleWrapper {
public OleWordColumn(OleAutomation oleAuto, Display display, OleWrapperManager manager){
super(oleAuto, display, manager);
}
public OleWordCells getCells(OleWrapperManager manager){
OleAutomation oleAuto = runGetOleAutomationProperty("Cells"); //$NON-NLS-1$
return new OleWordCells(oleAuto, display, manager);
}
public void setWidth(int points){
Variant[] arguments = new Variant[2];
arguments[0] = new Variant(points);
arguments[1] = new Variant(OleWordConstants.wdAdjustNone);
runInvoke("SetWidth", arguments); //$NON-NLS-1$
arguments[0].dispose();
arguments[1].dispose();
}
protected static HashMap<String, Integer> memberIdMap = new HashMap<String, Integer>();
@Override
protected synchronized int getIdForMember(String member){
Integer id = memberIdMap.get(member);
if (id == null) {
id = OleUtil.getMemberId(oleObj, member);
memberIdMap.put(member, id);
}
return id;
}
}
| epl-1.0 |
djelinek/reddeer | plugins/org.eclipse.reddeer.eclipse/src/org/eclipse/reddeer/eclipse/datatools/ui/FlatFileProfile.java | 3001 | /*******************************************************************************
* Copyright (c) 2017 Red Hat, Inc and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat Inc. - initial API and implementation
*******************************************************************************/
package org.eclipse.reddeer.eclipse.datatools.ui;
/**
* Flat Data Source Profile.
*
* @author apodhrad
*
*/
public class FlatFileProfile {
private String name;
private String folder;
private String charset;
private String style;
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Sets the name.
*
* @param name the new name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the folder.
*
* @return the folder
*/
public String getFolder() {
return folder;
}
/**
* Sets the folder.
*
* @param folder the new folder
*/
public void setFolder(String folder) {
this.folder = folder;
}
/**
* Gets the charset.
*
* @return the charset
*/
public String getCharset() {
return charset;
}
/**
* Sets the charset.
*
* @param charset the new charset
*/
public void setCharset(String charset) {
this.charset = charset;
}
/**
* Gets the style.
*
* @return the style
*/
public String getStyle() {
return style;
}
/**
* Sets the style.
*
* @param style the new style
*/
public void setStyle(String style) {
this.style = style;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((charset == null) ? 0 : charset.hashCode());
result = prime * result + ((folder == null) ? 0 : folder.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((style == null) ? 0 : style.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FlatFileProfile other = (FlatFileProfile) obj;
if (charset == null) {
if (other.charset != null)
return false;
} else if (!charset.equals(other.charset))
return false;
if (folder == null) {
if (other.folder != null)
return false;
} else if (!folder.equals(other.folder))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (style == null) {
if (other.style != null)
return false;
} else if (!style.equals(other.style))
return false;
return true;
}
}
| epl-1.0 |
ModelWriter/Deliverables | WP2/D2.5.2_Generation/Jeni/lib/weka-src/src/main/java/weka/filters/unsupervised/attribute/NumericTransform.java | 13383 | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* NumericTransform.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.Range;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.Utils;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Transforms numeric attributes using a given
* transformation method.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of columns to transform. First and last are
* valid indexes (default none). Non-numeric columns are
* skipped.
* </pre>
*
* <pre>
* -V
* Invert matching sense.
* </pre>
*
* <pre>
* -C <string>
* Sets the class containing transformation method.
* (default java.lang.Math)
* </pre>
*
* <pre>
* -M <string>
* Sets the method. (default abs)
* </pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision: 12037 $
*/
public class NumericTransform extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler {
/** for serialization */
static final long serialVersionUID = -8561413333351366934L;
/** Stores which columns to transform. */
private final Range m_Cols = new Range();
/** Class containing transformation method. */
private String m_Class;
/** Transformation method. */
private String m_Method;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Transforms numeric attributes using a given transformation method.";
}
/**
* Default constructor -- sets the default transform method to
* java.lang.Math.abs().
*/
public NumericTransform() {
m_Class = "java.lang.Math";
m_Method = "abs";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Sets the format of the input instances.
*
* @param instanceInfo an Instances object containing the input instance
* structure (any instances contained in the object are ignored -
* only the structure is required).
* @return true if the outputFormat may be collected immediately
* @throws Exception if the input format can't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
if (m_Class == null) {
throw new IllegalStateException("No class has been set.");
}
if (m_Method == null) {
throw new IllegalStateException("No method has been set.");
}
super.setInputFormat(instanceInfo);
m_Cols.setUpper(instanceInfo.numAttributes() - 1);
setOutputFormat(instanceInfo);
return true;
}
/**
* Input an instance for filtering. The instance is processed and made
* available for output immediately.
*
* @param instance the input instance
* @return true if the filtered instance may now be collected with output().
* @throws IllegalStateException if no input format has been set.
* @throws InvocationTargetException if there is a problem applying the
* configured transform method.
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
Method m = (Class.forName(m_Class)).getMethod(m_Method,
new Class[] { Double.TYPE });
double[] vals = new double[instance.numAttributes()];
Double[] params = new Double[1];
Double newVal;
for (int i = 0; i < instance.numAttributes(); i++) {
if (instance.isMissing(i)) {
vals[i] = Utils.missingValue();
} else {
if (m_Cols.isInRange(i) && instance.attribute(i).isNumeric()) {
params[0] = new Double(instance.value(i));
newVal = (Double) m.invoke(null, (Object[]) params);
if (newVal.isNaN() || newVal.isInfinite()) {
vals[i] = Utils.missingValue();
} else {
vals[i] = newVal.doubleValue();
}
} else {
vals[i] = instance.value(i);
}
}
}
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
inst.setDataset(instance.dataset());
push(inst, false); // No need to copy
return true;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(4);
newVector.addElement(new Option(
"\tSpecify list of columns to transform. First and last are\n"
+ "\tvalid indexes (default none). Non-numeric columns are \n"
+ "\tskipped.", "R", 1, "-R <index1,index2-index4,...>"));
newVector.addElement(new Option("\tInvert matching sense.", "V", 0, "-V"));
newVector.addElement(new Option(
"\tSets the class containing transformation method.\n"
+ "\t(default java.lang.Math)", "C", 1, "-C <string>"));
newVector.addElement(new Option("\tSets the method. (default abs)", "M", 1,
"-M <string>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of columns to transform. First and last are
* valid indexes (default none). Non-numeric columns are
* skipped.
* </pre>
*
* <pre>
* -V
* Invert matching sense.
* </pre>
*
* <pre>
* -C <string>
* Sets the class containing transformation method.
* (default java.lang.Math)
* </pre>
*
* <pre>
* -M <string>
* Sets the method. (default abs)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
setAttributeIndices(Utils.getOption('R', options));
setInvertSelection(Utils.getFlag('V', options));
String classString = Utils.getOption('C', options);
if (classString.length() != 0) {
setClassName(classString);
}
String methodString = Utils.getOption('M', options);
if (methodString.length() != 0) {
setMethodName(methodString);
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (getInvertSelection()) {
options.add("-V");
}
if (!getAttributeIndices().equals("")) {
options.add("-R");
options.add(getAttributeIndices());
}
if (m_Class != null) {
options.add("-C");
options.add(getClassName());
}
if (m_Method != null) {
options.add("-M");
options.add(getMethodName());
}
return options.toArray(new String[0]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String classNameTipText() {
return "Name of the class containing the method used for the transformation.";
}
/**
* Get the class containing the transformation method.
*
* @return string describing the class
*/
public String getClassName() {
return m_Class;
}
/**
* Sets the class containing the transformation method.
*
* @param name the name of the class
* @throws ClassNotFoundException if class can't be found
*/
public void setClassName(String name) throws ClassNotFoundException {
m_Class = name;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String methodNameTipText() {
return "Name of the method used for the transformation.";
}
/**
* Get the transformation method.
*
* @return string describing the transformation method.
*/
public String getMethodName() {
return m_Method;
}
/**
* Set the transformation method.
*
* @param name the name of the method
* @throws NoSuchMethodException if method can't be found in class
*/
public void setMethodName(String name) throws NoSuchMethodException {
m_Method = name;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Whether to process the inverse of the given attribute ranges.";
}
/**
* Get whether the supplied columns are to be transformed or not
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return m_Cols.getInvert();
}
/**
* Set whether selected columns should be transformed or not.
*
* @param invert the new invert setting
*/
public void setInvertSelection(boolean invert) {
m_Cols.setInvert(invert);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Get the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_Cols.getRanges();
}
/**
* Set which attributes are to be transformed (or kept if invert is true).
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br>
* eg: first-3,5,6-last
* @throws InvalidArgumentException if an invalid range list is supplied
*/
public void setAttributeIndices(String rangeList) {
m_Cols.setRanges(rangeList);
}
/**
* Set which attributes are to be transformed (or kept if invert is true)
*
* @param attributes an array containing indexes of attributes to select.
* Since the array will typically come from a program, attributes are
* indexed from 0.
* @throws InvalidArgumentException if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(int[] attributes) {
setAttributeIndices(Range.indicesToRangeList(attributes));
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 12037 $");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new NumericTransform(), argv);
}
}
| epl-1.0 |
UCDenver-ccp/biomedner | src/main/java/bioner/normalization/feature/builder/SpeciesInParagraphFeatureBuilder.java | 1283 | package bioner.normalization.feature.builder;
import java.util.Vector;
import bioner.data.document.BioNERDocument;
import bioner.data.document.BioNEREntity;
import bioner.data.document.BioNERParagraph;
import bioner.data.document.BioNERSentence;
import bioner.normalization.SpeciesParentFinder;
import bioner.normalization.data.BioNERCandidate;
import bioner.normalization.feature.NormalizationPairFeatureBuilder;
public class SpeciesInParagraphFeatureBuilder implements
NormalizationPairFeatureBuilder {
@Override
public String extractFeature(BioNERCandidate candidate) {
// TODO Auto-generated method stub
BioNERDocument document = candidate.getEntity().getDocument();
Vector<BioNEREntity> speciesVector = SpeciesEntityStore.getSpeciesEntities(document);
BioNERParagraph paragraph = candidate.getEntity().getParagraph();
String recordSpeciesID = candidate.getRecord().getSpeciesID();
int num=0;
for(BioNEREntity entity : speciesVector)
{
if(entity.getParagraph()==paragraph)
{
if(entity.hasID(recordSpeciesID) || SpeciesParentFinder.hasParent(recordSpeciesID, entity.getID()))
{
num++;
}
}
}
if(num>0) return "1";
else return "0";
//return Integer.toString(num);
}
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/workbench/tests/com.odcgroup.workbench.core.tests/src/com/odcgroup/template/TemplateDescriptorTest.java | 5683 | package com.odcgroup.template;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.junit.Assert;
import org.junit.Test;
import com.odcgroup.workbench.core.OfsCore;
/**
* @author yan
*/
public class TemplateDescriptorTest {
@Test
public void testDescriptorCase1() throws IOException {
TemplateDescriptor descriptor = getTemplateDescriptor("resources/templates/descriptors/case1");
Assert.assertEquals("case1", descriptor.getName());
Assert.assertEquals("Wrong template description", "Case 1 template, no parameter", descriptor.getDescription());
Assert.assertEquals("Shouldn't have an autowire module pom defined", "", descriptor.getAutowireModulePom());
}
@Test
public void testDescriptorCase2() throws IOException {
TemplateDescriptor descriptor = getTemplateDescriptor("resources/templates/descriptors/case2");
Assert.assertEquals("case2", descriptor.getName());
Assert.assertEquals("Wrong template description", "Case 2 template, no parameter, but with autowire", descriptor.getDescription());
Assert.assertEquals("Should have an autowire module pom defined", "custo/pom.xml", descriptor.getAutowireModulePom());
}
@Test
public void testDescriptorCase3() throws IOException {
TemplateDescriptor descriptor = getTemplateDescriptor("resources/templates/descriptors/case3");
Assert.assertEquals("case3", descriptor.getName());
Assert.assertEquals("Wrong template description", "Case 3 template, with unordered parameters", descriptor.getDescription());
testParameters(descriptor);
}
@Test
public void testDescriptorCase4() throws IOException {
TemplateDescriptor descriptor = getTemplateDescriptor("resources/templates/descriptors/case4");
Assert.assertEquals("case4", descriptor.getName());
Assert.assertEquals("Wrong template description", "Case 4 template, with ordered parameters", descriptor.getDescription());
testParameters(descriptor);
// Test parameters order
Assert.assertEquals("Wrong order", "first", descriptor.getParameters().get(0).getName());
Assert.assertEquals("Wrong order", "second", descriptor.getParameters().get(1).getName());
Assert.assertEquals("Wrong order", "third", descriptor.getParameters().get(2).getName());
}
@Test
public void testDescriptorCase5() throws IOException {
TemplateDescriptor descriptor = getTemplateDescriptor("resources/templates/descriptors/case5");
Assert.assertEquals("case5", descriptor.getName());
Assert.assertEquals("Wrong template description", "Case 5 template, with ordered parameters", descriptor.getDescription());
testParameters(descriptor);
// Test parameters order
Assert.assertEquals("Wrong order", "third", descriptor.getParameters().get(0).getName());
Assert.assertEquals("Wrong order", "second", descriptor.getParameters().get(1).getName());
Assert.assertEquals("Wrong order", "first", descriptor.getParameters().get(2).getName());
}
@Test
public void testDescriptorCase6() throws IOException {
TemplateDescriptor descriptor = getTemplateDescriptor("resources/templates/descriptors/case6");
Assert.assertEquals("case6", descriptor.getName());
Assert.assertEquals("Wrong template description", "Case 6 template, with partially ordered parameters", descriptor.getDescription());
// Test parameters order
// Forced order
Assert.assertEquals("Wrong order", "third", descriptor.getParameters().get(0).getName());
Assert.assertEquals("Wrong order", "second", descriptor.getParameters().get(1).getName());
// Alphabetical order
Assert.assertEquals("Wrong order", "fifth", descriptor.getParameters().get(2).getName());
Assert.assertEquals("Wrong order", "first", descriptor.getParameters().get(3).getName());
Assert.assertEquals("Wrong order", "forth", descriptor.getParameters().get(4).getName());
}
private TemplateDescriptor getTemplateDescriptor(String path) throws IOException {
URL url = FileLocator.find(OfsCore.getDefault().getBundle(),
new Path(path), null);
File template = new File(FileLocator.toFileURL(url).getPath(), TemplateCreator.TEMPLATE_DESCRIPTOR_PROPERTIES);
InputStream is = null;
try {
is = new FileInputStream(template);
return TemplateCreator.instance().getTemplateDescriptor(template, is, new ArrayList<String>());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}
/**
* @param descriptor
*/
private void testParameters(TemplateDescriptor descriptor) {
Assert.assertEquals("Wrong number of parameters", 3, descriptor.getParameters().size());
for (TemplateParameterDescriptor parameter : descriptor.getParameters()) {
if (parameter.getName().equals("first")) {
Assert.assertEquals("Wrong default value", "First default value", parameter.getDefaultValue());
Assert.assertEquals("Wrong description", "First description", parameter.getDescription());
} else if (parameter.getName().equals("second")) {
Assert.assertEquals("Wrong default value", "", parameter.getDefaultValue());
Assert.assertEquals("Wrong description", "Second description (no default value, no mandatory parameter)", parameter.getDescription());
} else if (parameter.getName().equals("third")) {
Assert.assertEquals("Wrong default value", "", parameter.getDefaultValue());
Assert.assertEquals("Wrong description", "Third description (no default value, not mandatory)", parameter.getDescription());
} else {
Assert.fail("Shouldn't have other parameter");
}
}
}
}
| epl-1.0 |
miklossy/xtext-core | org.eclipse.xtext/src/org/eclipse/xtext/resource/IGlobalServiceProvider.java | 2661 | /*******************************************************************************
* Copyright (c) 2010 itemis AG (http://www.itemis.eu) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.xtext.resource;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.resource.Resource;
import com.google.inject.ImplementedBy;
import com.google.inject.Inject;
/**
* @author Sven Efftinge - Initial contribution and API
*/
@ImplementedBy(IGlobalServiceProvider.ResourceServiceProviderImpl.class)
public interface IGlobalServiceProvider {
/**
* @return an instance of the demanded service class for the given {@link URI}'s language implementation, or null if no
* service or language implementation could be found.
*/
<T> T findService(URI uri, Class<T> serviceClazz);
/**
* @return an instance of the demanded service class for the given {@link EObject}'s language implementation, or null if no
* service or language implementation could be found.
*/
<T> T findService(EObject eObject, Class<T> serviceClazz);
public static class ResourceServiceProviderImpl implements IGlobalServiceProvider {
private IResourceServiceProvider.Registry registry;
private IResourceServiceProvider thisLanguageServiceProvider;
@Inject
public ResourceServiceProviderImpl(IResourceServiceProvider.Registry registry, IResourceServiceProvider thisLanguageServiceProvider) {
this.registry = registry;
this.thisLanguageServiceProvider = thisLanguageServiceProvider;
}
@Override
public <T> T findService(URI uri, Class<T> serviceClazz) {
if (thisLanguageServiceProvider.canHandle(uri))
return thisLanguageServiceProvider.get(serviceClazz);
IResourceServiceProvider serviceProvider = registry.getResourceServiceProvider(uri);
if (serviceProvider==null)
return null;
final T result = serviceProvider.get(serviceClazz);
return result;
}
@Override
public <T> T findService(EObject eObject, Class<T> serviceClazz) {
if (eObject.eIsProxy()) {
return findService(((InternalEObject)eObject).eProxyURI(),serviceClazz);
} else {
Resource eResource = eObject.eResource();
if(eResource != null)
return findService(eResource.getURI(),serviceClazz);
}
return null;
}
}
}
| epl-1.0 |
martinmathewhuawei/daylight-cisco-ctrl | opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginOutTopologyService.java | 1724 | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.sal.topology;
import java.util.List;
import java.util.Set;
import org.opendaylight.controller.sal.core.Edge;
import org.opendaylight.controller.sal.core.Property;
import org.opendaylight.controller.sal.core.UpdateType;
/**
* @file IPluginOutTopologyService.java
*
* @brief Methods that are invoked from Protocol Plugin toward SAL
*
* Every time a protocol plugin update the topology, it will call this
* service provided by SAL so the update can migrate upward toward the
* applications
*/
/**
* Methods that are invoked from Protocol Plugin toward SAL
*
*/
public interface IPluginOutTopologyService {
/**
* Called to update on Edge in the topology graph
*
* @param topoedgeupdateList
* List of topoedgeupdates Each topoedgeupdate includes edge, its
* Properties ( BandWidth and/or Latency etc) and update type.
*/
public void edgeUpdate(List<TopoEdgeUpdate> topoedgeupdateList);
/**
* Called when an Edge utilization is above the safety threshold configured
* on the controller
*
* @param edge
*/
public void edgeOverUtilized(Edge edge);
/**
* Called when the Edge utilization is back to normal, below the safety
* threshold level configured on the controller
*
* @param edge
*/
public void edgeUtilBackToNormal(Edge edge);
}
| epl-1.0 |
bradsdavis/windup | rules-java/src/main/java/org/jboss/windup/rules/apps/java/model/JavaClassModel.java | 6340 | package org.jboss.windup.rules.apps.java.model;
import org.jboss.windup.graph.model.WindupVertexFrame;
import org.jboss.windup.graph.model.resource.FileModel;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.frames.Adjacency;
import com.tinkerpop.frames.Property;
import com.tinkerpop.frames.annotations.gremlin.GremlinGroovy;
import com.tinkerpop.frames.annotations.gremlin.GremlinParam;
import com.tinkerpop.frames.modules.typedgraph.TypeValue;
/**
* Represents a JavaClass, either from a .class file or a .java source file.
*
*/
@TypeValue(JavaClassModel.TYPE)
public interface JavaClassModel extends WindupVertexFrame
{
public static final String JAVA_METHOD = "javaMethod";
public static final String CLASS_FILE = "classFile";
public static final String ORIGINAL_SOURCE = "originalSource";
public static final String DECOMPILED_SOURCE = "decompiledSource";
public static final String IMPLEMENTS = "implements";
public static final String EXTENDS = "extends";
public static final String IMPORTS = "imports";
public static final String TYPE = "JavaClassResource";
public static final String PROPERTY_QUALIFIED_NAME = "qualifiedName";
public static final String CLASS_NAME = "className";
public static final String PACKAGE_NAME = "packageName";
public static final String CUSTOMER_PACKAGE = "customerPackage";
public static final String MAJOR_VERSION = "majorVersion";
public static final String MINOR_VERSION = "minorVersion";
/**
* Contains the simple name of the class (no package)
*/
@Property(CLASS_NAME)
public void setSimpleName(String className);
/**
* Contains the simple name of the class (no package)
*/
@Property(CLASS_NAME)
public String getClassName();
/**
* Contains the fully qualified name of the class
*/
@Property(PROPERTY_QUALIFIED_NAME)
public String getQualifiedName();
/**
* Contains the fully qualified name of the class
*/
@Property(PROPERTY_QUALIFIED_NAME)
public void setQualifiedName(String qualifiedName);
/**
* Contains the class' package name
*/
@Property(PACKAGE_NAME)
public String getPackageName();
/**
* Contains the class' package name
*/
@Property(PACKAGE_NAME)
public void setPackageName(String packageName);
/**
* Lists classes imported by this class
*/
@Adjacency(label = IMPORTS, direction = Direction.OUT)
public void addImport(final JavaClassModel javaImport);
/**
* Lists classes imported by this class
*/
@Adjacency(label = IMPORTS, direction = Direction.OUT)
public Iterable<JavaClassModel> getImports();
/**
* Lists classes extended by this class
*/
@Adjacency(label = EXTENDS, direction = Direction.OUT)
public JavaClassModel getExtends();
/**
* Lists classes extended by this class
*/
@Adjacency(label = EXTENDS, direction = Direction.OUT)
public void setExtends(final JavaClassModel javaFacet);
/**
* Lists classes implemented by this class
*/
@Adjacency(label = IMPLEMENTS, direction = Direction.OUT)
public void addImplements(final JavaClassModel javaFacet);
/**
* Lists classes implemented by this class
*/
@Adjacency(label = IMPLEMENTS, direction = Direction.OUT)
public Iterable<JavaClassModel> getImplements();
/**
* Contains the {@link JavaSourceFileModel} of the decompiled version of this file (assuming that it originally was decompiled from a .class file)
*/
@Adjacency(label = DECOMPILED_SOURCE, direction = Direction.OUT)
public void setDecompiledSource(JavaSourceFileModel source);
/**
* Contains the {@link JavaSourceFileModel} of the decompiled version of this file (assuming that it originally was decompiled from a .class file)
*/
@Adjacency(label = DECOMPILED_SOURCE, direction = Direction.OUT)
public JavaSourceFileModel getDecompiledSource();
/**
* Contains the original source code of this file, assuming that it was originally provided in source form (and not via a decompilation).
*/
@Adjacency(label = ORIGINAL_SOURCE, direction = Direction.OUT)
public void setOriginalSource(JavaSourceFileModel source);
/**
* Contains the original source code of this file, assuming that it was originally provided in source form (and not via a decompilation).
*/
@Adjacency(label = ORIGINAL_SOURCE, direction = Direction.OUT)
public JavaSourceFileModel getOriginalSource();
/**
* Contains the original .class file, assuming that it was originally provided in binary form (as a java .class file)
*/
@Adjacency(label = CLASS_FILE, direction = Direction.OUT)
public FileModel getClassFile();
/**
* Contains the original .class file, assuming that it was originally provided in binary form (as a java .class file)
*/
@Adjacency(label = CLASS_FILE, direction = Direction.OUT)
public FileModel setClassFile(FileModel file);
/**
* Gets the {@link JavaMethodNodel} by name
*/
@GremlinGroovy("it.out('" + JAVA_METHOD + "').has('" + JavaMethodModel.METHOD_NAME + "', methodName)")
public Iterable<JavaMethodModel> getMethod(@GremlinParam("methodName") String methodName);
/**
* Adds a {@link JavaMethodModel} to this {@link JavaClassModel}
*/
@Adjacency(label = JAVA_METHOD, direction = Direction.OUT)
public void addJavaMethod(final JavaMethodModel javaMethod);
/**
* Adds a {@link JavaMethodModel} to this {@link JavaClassModel}
*/
@Adjacency(label = JAVA_METHOD, direction = Direction.OUT)
public Iterable<JavaMethodModel> getJavaMethods();
/**
* Returns the {@link JavaClassModel}s that this class depends on
*/
@GremlinGroovy("it.sideEffect{x=it}.out('" + EXTENDS + "', '" + IMPORTS + "', '" + IMPLEMENTS
+ "').dedup().filter{it!=x}")
public Iterable<JavaClassModel> dependsOnJavaClass();
/**
* Returns the {@link JavaClassModel}s that depend on this class
*/
@GremlinGroovy("it.sideEffect{x=it}.in('" + EXTENDS + "', '" + IMPORTS + "', '" + IMPLEMENTS
+ "').dedup().filter{it!=x}")
public Iterable<JavaClassModel> providesForJavaClass();
}
| epl-1.0 |
fappel/xiliary | com.codeaffine.test.util/src/com/codeaffine/test/util/util/concurrent/RunInThreadStatement.java | 1365 | /**
* Copyright (c) 2014 - 2022 Frank Appel
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Frank Appel - initial API and implementation
*/
package com.codeaffine.test.util.util.concurrent;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import org.junit.runners.model.Statement;
class RunInThreadStatement extends Statement {
private final RunInThreadSynchronizer synchronizer;
private final Statement baseStatement;
private volatile Throwable throwable;
RunInThreadStatement( Statement baseStatement ) {
this.synchronizer = new RunInThreadSynchronizer();
this.baseStatement = baseStatement;
}
@Override
public void evaluate() throws Throwable {
synchronizer.run( newSingleThreadExecutor(), new Runnable() {
@Override
public void run() {
doEvaluate();
}
} );
rethrowProblem();
}
private void doEvaluate() {
try {
baseStatement.evaluate();
} catch( Throwable throwable ) {
this.throwable = throwable;
}
}
private void rethrowProblem() throws Throwable {
if( throwable != null ) {
throw throwable;
}
}
} | epl-1.0 |
codenvy/platform-api-client-java | api/src/main/java/com/codenvy/client/model/builder/BuilderMetric.java | 733 | /*******************************************************************************
* Copyright (c) 2014 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package com.codenvy.client.model.builder;
import com.codenvy.client.model.Metric;
/**
* Metric that can be specific to a builder.
*
* @author Florent Benoit
*/
public interface BuilderMetric extends Metric {
}
| epl-1.0 |
smarr/OmniVM | vm/src/runtime/error_handling.cpp | 2378 | /******************************************************************************
* Copyright (c) 2008 - 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David Ungar, IBM Research - Initial Implementation
* Sam Adams, IBM Research - Initial Implementation
* Stefan Marr, Vrije Universiteit Brussel - Port to x86 Multi-Core Systems
******************************************************************************/
#include "headers.h"
ON_TILERA_OR_ELSE(int, void) assert_failure(const char* func, const char* file, const int line, const char* pred, const char* msg) {
const char* safe_func = On_Tilera ? "<unknown>" : func;
if (Memory_Semantics::cores_are_initialized())
error_printer->printf("%s: file %s, line %d, function %s, predicate %s, rank %d, main_rank %d, pid %d\n",
msg, file, line, safe_func, pred, Logical_Core::my_rank(), Logical_Core::main_rank, getpid());
else
fprintf(stderr, "%s: file %s, line %d, function %s, predicate %s, pid %d\n",
msg, file, line, safe_func, pred, getpid());
OS_Interface::abort();
ON_TILERA_OR_ELSE(return 0, );
}
ON_TILERA_OR_ELSE(int, void) assert_eq_failure(const char* func, const char* file, const int line, const char* pred, const char* msg, void* a, void* b) {
static char buf[10000]; // threadsafe? does not really matter here anymore...
error_printer->printf("%s: file %s, line %d, function %s, predicate %s, pid %d, 0x%x != 0x%x",
msg, file, line, func, pred, getpid(), a, b);
error_printer->printf("%s\n", buf);
OS_Interface::abort();
ON_TILERA_OR_ELSE(return 0, );
}
ON_TILERA_OR_ELSE(int, void) assert_eq_failure(const char* func, const char* file, const int line, const char* pred, const char* msg, int a, int b) {
assert_eq_failure(func, file, line, pred, msg, (void*)a, (void*)b);
ON_TILERA_OR_ELSE(return 0, );
}
void breakpoint() {
OS_Interface::breakpoint();
}
void unt(const char* m, const char* f) {
dittoing_stdout_printer->printf("%s: %s\n", m, f);
}
void unte(const char* m, const char* f) {
dittoing_stdout_printer->printf("%s: %s\n", m, f);
}
| epl-1.0 |
asupdev/asup | org.asup.db.core/src/org/asup/db/core/QQualifiedName.java | 1740 | /**
* Copyright (c) 2012, 2014 Sme.UP and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.asup.db.core;
import java.util.List;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Qualified Name</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.asup.db.core.QQualifiedName#getQualifiers <em>Qualifiers</em>}</li>
* </ul>
* </p>
*
* @see org.asup.db.core.QDatabaseCorePackage#getQualifiedName()
* @model
* @generated
*/
public interface QQualifiedName {
/**
* Returns the value of the '<em><b>Qualifiers</b></em>' attribute list.
* The list contents are of type {@link java.lang.String}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Qualifiers</em>' attribute list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Qualifiers</em>' attribute list.
* @see org.asup.db.core.QDatabaseCorePackage#getQualifiedName_Qualifiers()
* @model required="true" upper="3"
* @generated
*/
List<String> getQualifiers();
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @model kind="operation" required="true"
* @generated
*/
String getFirstQualifier();
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @model kind="operation" required="true"
* @generated
*/
String getLastQualifier();
} // QQualifiedName
| epl-1.0 |
tiansin/mincrt | crtfix/chkfix.cpp | 689 | #include "crtfix.h"
#ifdef _WIN64
#define DEFAULT_SECURITY_COOKIE 0x00002B992DDFA232
#else /* _WIN64 */
#define DEFAULT_SECURITY_COOKIE 0xBB40E64E
#endif /* _WIN64 */
/*
* The global security cookie. This name is known to the compiler.
* Initialize to a garbage non-zero value just in case we have a buffer overrun
* in any code that gets run before __security_init_cookie() has a chance to
* initialize the cookie to the final value.
*/
DECLSPEC_SELECTANY UINT_PTR __security_cookie = DEFAULT_SECURITY_COOKIE;
DECLSPEC_SELECTANY UINT_PTR __security_cookie_complement = ~(DEFAULT_SECURITY_COOKIE);
void __fastcall __security_check_cookie(UINT_PTR cookie)
{
}
| epl-1.0 |
wdliu/egit | org.eclipse.egit.core/src/org/eclipse/egit/core/Activator.java | 16549 | /*******************************************************************************
* Copyright (C) 2008, 2013 Shawn O. Pearce <spearce@spearce.org> and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.egit.core;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.egit.core.internal.CoreText;
import org.eclipse.egit.core.internal.indexdiff.IndexDiffCache;
import org.eclipse.egit.core.internal.job.JobUtil;
import org.eclipse.egit.core.internal.trace.GitTraceLocation;
import org.eclipse.egit.core.internal.util.ResourceUtil;
import org.eclipse.egit.core.op.ConnectProviderOperation;
import org.eclipse.egit.core.op.IgnoreOperation;
import org.eclipse.egit.core.project.GitProjectData;
import org.eclipse.egit.core.project.RepositoryFinder;
import org.eclipse.egit.core.project.RepositoryMapping;
import org.eclipse.egit.core.securestorage.EGitSecureStore;
import org.eclipse.equinox.security.storage.SecurePreferencesFactory;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.util.FS;
import org.eclipse.osgi.service.debug.DebugOptions;
import org.eclipse.osgi.service.debug.DebugOptionsListener;
import org.eclipse.team.core.RepositoryProvider;
import org.osgi.framework.BundleContext;
/**
* The plugin class for the org.eclipse.egit.core plugin. This
* is a singleton class.
*/
public class Activator extends Plugin implements DebugOptionsListener {
private static Activator plugin;
private static String pluginId;
private RepositoryCache repositoryCache;
private IndexDiffCache indexDiffCache;
private RepositoryUtil repositoryUtil;
private EGitSecureStore secureStore;
private AutoShareProjects shareGitProjectsJob;
private IResourceChangeListener preDeleteProjectListener;
private IgnoreDerivedResources ignoreDerivedResourcesListener;
/**
* @return the singleton {@link Activator}
*/
public static Activator getDefault() {
return plugin;
}
/**
* @return the name of this plugin
*/
public static String getPluginId() {
return pluginId;
}
/**
* Utility to create an error status for this plug-in.
*
* @param message User comprehensible message
* @param thr cause
* @return an initialized error status
*/
public static IStatus error(final String message, final Throwable thr) {
return new Status(IStatus.ERROR, getPluginId(), 0, message, thr);
}
/**
* Utility method to log errors in the Egit plugin.
* @param message User comprehensible message
* @param thr The exception through which we noticed the error
*/
public static void logError(final String message, final Throwable thr) {
getDefault().getLog().log(error(message, thr));
}
/**
* Log an info message for this plug-in
*
* @param message
*/
public static void logInfo(final String message) {
getDefault().getLog().log(
new Status(IStatus.INFO, getPluginId(), 0, message, null));
}
/**
* Utility to create a warning status for this plug-in.
*
* @param message
* User comprehensible message
* @param thr
* cause
* @return an initialized warning status
*/
public static IStatus warning(final String message, final Throwable thr) {
return new Status(IStatus.WARNING, getPluginId(), 0, message, thr);
}
/**
* Utility method to log warnings for this plug-in.
*
* @param message
* User comprehensible message
* @param thr
* The exception through which we noticed the warning
*/
public static void logWarning(final String message, final Throwable thr) {
getDefault().getLog().log(warning(message, thr));
}
/**
* Construct the {@link Activator} singleton instance
*/
public Activator() {
Activator.setActivator(this);
}
private static void setActivator(Activator a) {
plugin = a;
}
public void start(final BundleContext context) throws Exception {
super.start(context);
pluginId = context.getBundle().getSymbolicName();
// we want to be notified about debug options changes
Dictionary<String, String> props = new Hashtable<String, String>(4);
props.put(DebugOptions.LISTENER_SYMBOLICNAME, pluginId);
context.registerService(DebugOptionsListener.class.getName(), this,
props);
repositoryCache = new RepositoryCache();
indexDiffCache = new IndexDiffCache();
try {
GitProjectData.reconfigureWindowCache();
} catch (RuntimeException e) {
logError(CoreText.Activator_ReconfigureWindowCacheError, e);
}
GitProjectData.attachToWorkspace(true);
repositoryUtil = new RepositoryUtil();
secureStore = new EGitSecureStore(SecurePreferencesFactory.getDefault());
registerAutoShareProjects();
registerAutoIgnoreDerivedResources();
registerPreDeleteResourceChangeListener();
}
private void registerPreDeleteResourceChangeListener() {
if (preDeleteProjectListener == null) {
preDeleteProjectListener = new IResourceChangeListener() {
public void resourceChanged(IResourceChangeEvent event) {
IResource resource = event.getResource();
if (resource instanceof IProject) {
IProject project = (IProject) resource;
if (project.isAccessible()) {
if (ResourceUtil.isSharedWithGit(project)) {
IResource dotGit = project
.findMember(Constants.DOT_GIT);
if (dotGit != null && dotGit
.getType() == IResource.FOLDER) {
GitProjectData.reconfigureWindowCache();
}
}
} else {
// bug 419706: project is closed - use java.io API
IPath locationPath = project.getLocation();
if (locationPath != null) {
File locationDir = locationPath.toFile();
File dotGit = new File(locationDir,
Constants.DOT_GIT);
if (dotGit.exists() && dotGit.isDirectory()) {
GitProjectData.reconfigureWindowCache();
}
}
}
}
}
};
ResourcesPlugin.getWorkspace().addResourceChangeListener(preDeleteProjectListener, IResourceChangeEvent.PRE_DELETE);
}
}
public void optionsChanged(DebugOptions options) {
// initialize the trace stuff
GitTraceLocation.initializeFromOptions(options, isDebugging());
}
/**
* @return cache for Repository objects
*/
public RepositoryCache getRepositoryCache() {
return repositoryCache;
}
/**
* @return cache for index diffs
*/
public IndexDiffCache getIndexDiffCache() {
return indexDiffCache;
}
/**
* @return the {@link RepositoryUtil} instance
*/
public RepositoryUtil getRepositoryUtil() {
return repositoryUtil;
}
/**
* @return the secure store
*/
public EGitSecureStore getSecureStore() {
return secureStore;
}
public void stop(final BundleContext context) throws Exception {
GitProjectData.detachFromWorkspace();
repositoryCache = null;
indexDiffCache.dispose();
indexDiffCache = null;
repositoryUtil.dispose();
repositoryUtil = null;
secureStore = null;
super.stop(context);
plugin = null;
if (preDeleteProjectListener != null) {
ResourcesPlugin.getWorkspace().removeResourceChangeListener(preDeleteProjectListener);
preDeleteProjectListener = null;
}
if (ignoreDerivedResourcesListener != null) {
ResourcesPlugin.getWorkspace().removeResourceChangeListener(
ignoreDerivedResourcesListener);
ignoreDerivedResourcesListener = null;
}
if (shareGitProjectsJob != null) {
ResourcesPlugin.getWorkspace().removeResourceChangeListener(
shareGitProjectsJob);
shareGitProjectsJob = null;
}
}
private void registerAutoShareProjects() {
shareGitProjectsJob = new AutoShareProjects();
ResourcesPlugin.getWorkspace().addResourceChangeListener(
shareGitProjectsJob, IResourceChangeEvent.POST_CHANGE);
}
private static class AutoShareProjects implements IResourceChangeListener {
private static int INTERESTING_CHANGES = IResourceDelta.ADDED
| IResourceDelta.OPEN;
private final CheckProjectsToShare checkProjectsJob;
public AutoShareProjects() {
checkProjectsJob = new CheckProjectsToShare();
}
private boolean doAutoShare() {
IEclipsePreferences d = DefaultScope.INSTANCE.getNode(Activator
.getPluginId());
IEclipsePreferences p = InstanceScope.INSTANCE.getNode(Activator
.getPluginId());
return p.getBoolean(GitCorePreferences.core_autoShareProjects, d
.getBoolean(GitCorePreferences.core_autoShareProjects,
true));
}
public void resourceChanged(IResourceChangeEvent event) {
if (!doAutoShare()) {
return;
}
try {
final Set<IProject> projectCandidates = new LinkedHashSet<>();
event.getDelta().accept(new IResourceDeltaVisitor() {
public boolean visit(IResourceDelta delta)
throws CoreException {
return collectOpenedProjects(delta,
projectCandidates);
}
});
if(!projectCandidates.isEmpty()){
checkProjectsJob.addProjectsToCheck(projectCandidates);
}
} catch (CoreException e) {
Activator.logError(e.getMessage(), e);
return;
}
}
/*
* This method should not use RepositoryMapping.getMapping(project) or
* RepositoryProvider.getProvider(project) which can trigger
* RepositoryProvider.map(project) and deadlock current thread. See
* https://bugs.eclipse.org/bugs/show_bug.cgi?id=468270
*/
private boolean collectOpenedProjects(IResourceDelta delta,
Set<IProject> projects) {
if (delta.getKind() == IResourceDelta.CHANGED
&& (delta.getFlags() & INTERESTING_CHANGES) == 0) {
return true;
}
final IResource resource = delta.getResource();
if (resource.getType() == IResource.ROOT) {
return true;
}
if (resource.getType() != IResource.PROJECT) {
return false;
}
if (!resource.isAccessible()) {
return false;
}
projects.add((IProject) resource);
return false;
}
}
private static class CheckProjectsToShare extends Job {
private Object lock = new Object();
private Set<IProject> projectCandidates;
public CheckProjectsToShare() {
super(CoreText.Activator_AutoShareJobName);
this.projectCandidates = new LinkedHashSet<IProject>();
setUser(false);
setSystem(true);
}
public void addProjectsToCheck(Set<IProject> projects) {
synchronized (lock) {
this.projectCandidates.addAll(projects);
if (!projectCandidates.isEmpty()) {
schedule(100);
}
}
}
@Override
protected IStatus run(IProgressMonitor monitor) {
Set<IProject> projectsToCheck;
synchronized (lock) {
projectsToCheck = projectCandidates;
projectCandidates = new LinkedHashSet<>();
}
if (projectsToCheck.isEmpty()) {
return Status.OK_STATUS;
}
final Map<IProject, File> projects = new HashMap<IProject, File>();
for (IProject project : projectsToCheck) {
if (project.isAccessible()) {
try {
visitConnect(project, projects);
} catch (CoreException e) {
logError(e.getMessage(), e);
}
}
}
if (monitor.isCanceled()) {
return Status.CANCEL_STATUS;
}
if (projects.size() > 0) {
ConnectProviderOperation op = new ConnectProviderOperation(
projects);
JobUtil.scheduleUserJob(op,
CoreText.Activator_AutoShareJobName,
JobFamilies.AUTO_SHARE);
}
return Status.OK_STATUS;
}
private void visitConnect(IProject project,
final Map<IProject, File> projects) throws CoreException {
if (RepositoryMapping.getMapping(project) != null) {
return;
}
RepositoryProvider provider = RepositoryProvider
.getProvider(project);
// respect if project is already shared with another
// team provider
if (provider != null) {
return;
}
RepositoryFinder f = new RepositoryFinder(project);
f.setFindInChildren(false);
Collection<RepositoryMapping> mappings = f.find(new NullProgressMonitor());
if (mappings.size() != 1) {
return;
}
RepositoryMapping m = mappings.iterator().next();
IPath gitDirPath = m.getGitDirAbsolutePath();
if (gitDirPath == null || gitDirPath.segmentCount() == 0) {
return;
}
IPath workingDir = gitDirPath.removeLastSegments(1);
// Don't connect "/" or "C:\"
if (workingDir.isRoot()) {
return;
}
File userHome = FS.DETECTED.userHome();
if (userHome != null) {
Path userHomePath = new Path(userHome.getAbsolutePath());
// Don't connect "/home" or "/home/username"
if (workingDir.isPrefixOf(userHomePath)) {
return;
}
}
// connect
final File repositoryDir = gitDirPath.toFile();
projects.put(project, repositoryDir);
try {
Activator.getDefault().getRepositoryUtil()
.addConfiguredRepository(repositoryDir);
} catch (IllegalArgumentException e) {
logError(CoreText.Activator_AutoSharingFailed, e);
}
}
}
private void registerAutoIgnoreDerivedResources() {
ignoreDerivedResourcesListener = new IgnoreDerivedResources();
ResourcesPlugin.getWorkspace().addResourceChangeListener(
ignoreDerivedResourcesListener,
IResourceChangeEvent.POST_CHANGE);
}
/**
* @return true if the derived resources should be automatically added to
* the .gitignore files
*/
public static boolean autoIgnoreDerived() {
IEclipsePreferences d = DefaultScope.INSTANCE
.getNode(Activator.getPluginId());
IEclipsePreferences p = InstanceScope.INSTANCE
.getNode(Activator.getPluginId());
return p.getBoolean(GitCorePreferences.core_autoIgnoreDerivedResources,
d.getBoolean(GitCorePreferences.core_autoIgnoreDerivedResources,
true));
}
private static class IgnoreDerivedResources implements
IResourceChangeListener {
public void resourceChanged(IResourceChangeEvent event) {
try {
IResourceDelta d = event.getDelta();
if (d == null || !autoIgnoreDerived()) {
return;
}
final Set<IPath> toBeIgnored = new LinkedHashSet<IPath>();
d.accept(new IResourceDeltaVisitor() {
public boolean visit(IResourceDelta delta)
throws CoreException {
if ((delta.getKind() & (IResourceDelta.ADDED | IResourceDelta.CHANGED)) == 0)
return false;
int flags = delta.getFlags();
if ((flags != 0)
&& ((flags & IResourceDelta.DERIVED_CHANGED) == 0))
return false;
final IResource r = delta.getResource();
// don't consider resources contained in a project not
// shared with Git team provider
if ((r.getProject() != null)
&& (RepositoryMapping.getMapping(r) == null))
return false;
if (r.isTeamPrivateMember())
return false;
if (r.isDerived()) {
try {
IPath location = r.getLocation();
if (RepositoryUtil.canBeAutoIgnored(location)) {
toBeIgnored.add(location);
}
} catch (IOException e) {
logError(
MessageFormat.format(
CoreText.Activator_ignoreResourceFailed,
r.getFullPath()), e);
}
return false;
}
return true;
}
});
if (toBeIgnored.size() > 0)
JobUtil.scheduleUserJob(new IgnoreOperation(toBeIgnored),
CoreText.Activator_autoIgnoreDerivedResources,
JobFamilies.AUTO_IGNORE);
} catch (CoreException e) {
Activator.logError(e.getMessage(), e);
return;
}
}
}
}
| epl-1.0 |
ShubhankarRaj/JavaCodingFolder | Eclipse Workspace/myProject/src/ExamG/Maker.java | 830 | package ExamG;
import java.io.*;
import java.util.Scanner;
import java.util.*;
public class Maker {
public static void main(String[] args){
// File dir = new File("Swapnildir");
// dir.mkdir();
// File RajDir = new File("RajRenamedir");
// dir.renameTo(RajDir);
//
// File f1 = new File(dir, "test2.txt");
// try{
// f1.createNewFile();
// }catch(IOException e){}
//
// File newDir = new File("newDir");
// dir.renameTo(newDir);
String csv = "Sue,5,true,3";
Scanner scn = new Scanner(csv);
System.out.println(csv);
scn.useDelimiter(",");
int age = scn.nextInt();
System.out.println(age);
// String x = scn.next();
// System.out.println(x);
// String x1 = scn.next();
// System.out.println(x1);
// int i=0;
// while(scn.hasNext()){
// System.out.println(" "+scn.next());
// }
}
}
| epl-1.0 |
debrief/debrief | org.mwc.cmap.legacy/src/MWC/GUI/RubberBanding/RubberbandLine.java | 1314 | /*******************************************************************************
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2020, Deep Blue C Technology Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*******************************************************************************/
package MWC.GUI.RubberBanding;
import java.awt.Component;
import java.awt.Graphics;
import MWC.GUI.Rubberband;
public class RubberbandLine extends Rubberband {
/**
*
*/
private static final long serialVersionUID = 1L;
public RubberbandLine() {
}
public RubberbandLine(final Component component) {
super(component);
}
@Override
public void drawLast(final Graphics graphics) {
graphics.drawLine(anchorPt.x, anchorPt.y, lastPt.x, lastPt.y);
}
@Override
public void drawNext(final Graphics graphics) {
graphics.drawLine(anchorPt.x, anchorPt.y, stretchedPt.x, stretchedPt.y);
}
}
| epl-1.0 |
mdbergmann/smarthome | bundles/core/org.eclipse.smarthome.core/src/main/java/org/eclipse/smarthome/core/library/types/PointType.java | 7602 | /**
* Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.core.library.types;
import java.math.BigDecimal;
import java.util.SortedMap;
import java.util.TreeMap;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.ComplexType;
import org.eclipse.smarthome.core.types.PrimitiveType;
import org.eclipse.smarthome.core.types.State;
/**
* This type can be used for items that are dealing with GPS or
* location awareness functionality.
*
* @author Gaël L'hopital
*
*/
public class PointType implements ComplexType, Command, State {
public static final double EARTH_GRAVITATIONAL_CONSTANT = 3.986004418e14;
public static final double WGS84_a = 6378137; // The equatorial radius of WGS84 ellipsoid (6378137 m).
private BigDecimal latitude = BigDecimal.ZERO; // in decimal degrees
private BigDecimal longitude = BigDecimal.ZERO; // in decimal degrees
private BigDecimal altitude = BigDecimal.ZERO; // in decimal meters
// constants for the constituents
static final public String KEY_LATITUDE = "lat";
static final public String KEY_LONGITUDE = "long";
static final public String KEY_ALTITUDE = "alt";
private static final BigDecimal circle = new BigDecimal(360);
private static final BigDecimal flat = new BigDecimal(180);
private static final BigDecimal right = new BigDecimal(90);
/**
* Default constructor creates a point at sea level where the equator
* (0° latitude) and the prime meridian (0° longitude) intersect.
* A nullary constructor is needed by
* {@link org.eclipse.smarthome.core.internal.items.ItemUpdater#receiveUpdate})
*/
public PointType() {
}
public PointType(DecimalType latitude, DecimalType longitude) {
canonicalize(latitude, longitude);
}
public PointType(DecimalType latitude, DecimalType longitude, DecimalType altitude) {
this(latitude, longitude);
setAltitude(altitude);
}
public PointType(StringType latitude, StringType longitude) {
this(new DecimalType(latitude.toString()), new DecimalType(longitude.toString()));
}
public PointType(StringType latitude, StringType longitude, StringType altitude) {
this(new DecimalType(latitude.toString()), new DecimalType(longitude.toString()),
new DecimalType(altitude.toString()));
}
public PointType(String value) {
if (!value.isEmpty()) {
String[] elements = value.split(",");
if (elements.length >= 2) {
canonicalize(new DecimalType(elements[0]), new DecimalType(elements[1]));
if (elements.length == 3) {
setAltitude(new DecimalType(elements[2]));
}
} else {
throw new IllegalArgumentException(value + " is not a valid PointType syntax");
}
} else {
throw new IllegalArgumentException("Constructor argument must not be blank");
}
}
public DecimalType getLatitude() {
return new DecimalType(latitude);
}
public DecimalType getLongitude() {
return new DecimalType(longitude);
}
public DecimalType getAltitude() {
return new DecimalType(altitude);
}
public void setAltitude(DecimalType altitude) {
this.altitude = altitude.toBigDecimal();
}
public DecimalType getGravity() {
double latRad = Math.toRadians(latitude.doubleValue());
double deltaG = -2000.0 * (altitude.doubleValue() / 1000) * EARTH_GRAVITATIONAL_CONSTANT
/ (Math.pow(WGS84_a, 3.0));
double sin2lat = Math.sin(latRad) * Math.sin(latRad);
double sin22lat = Math.sin(2.0 * latRad) * Math.sin(2.0 * latRad);
double result = (9.780327 * (1.0 + 5.3024e-3 * sin2lat - 5.8e-6 * sin22lat) + deltaG);
return new DecimalType(result);
}
/**
* Return the distance in meters from otherPoint, ignoring altitude. This algorithm also
* ignores the oblate spheroid shape of Earth and assumes a perfect sphere, so results
* are inexact.
*
* @param otherPoint
* @return distance in meters
* @see <a href="https://en.wikipedia.org/wiki/Haversine_formula">Haversine formula</a>
*/
public DecimalType distanceFrom(PointType otherPoint) {
double dLat = Math.toRadians(otherPoint.latitude.doubleValue() - this.latitude.doubleValue());
double dLong = Math.toRadians(otherPoint.longitude.doubleValue() - this.longitude.doubleValue());
double a = Math.pow(Math.sin(dLat / 2D), 2D) + Math.cos(Math.toRadians(this.latitude.doubleValue()))
* Math.cos(Math.toRadians(otherPoint.latitude.doubleValue())) * Math.pow(Math.sin(dLong / 2D), 2D);
double c = 2D * Math.atan2(Math.sqrt(a), Math.sqrt(1D - a));
return new DecimalType(WGS84_a * c);
}
/**
* <p>
* Formats the value of this type according to a pattern (@see {@link Formatter}). One single value of this type can
* be referenced by the pattern using an index. The item order is defined by the natural (alphabetical) order of
* their keys.
* </p>
*
* @param pattern the pattern to use containing indexes to reference the
* single elements of this type.
*/
@Override
public String format(String pattern) {
return String.format(pattern, getConstituents().values().toArray());
}
public static PointType valueOf(String value) {
return new PointType(value);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(latitude.toPlainString());
sb.append(',');
sb.append(longitude.toPlainString());
if (!altitude.equals(BigDecimal.ZERO)) {
sb.append(',');
sb.append(altitude.toPlainString());
}
return sb.toString();
}
@Override
public SortedMap<String, PrimitiveType> getConstituents() {
SortedMap<String, PrimitiveType> result = new TreeMap<String, PrimitiveType>();
result.put(KEY_LATITUDE, getLatitude());
result.put(KEY_LONGITUDE, getLongitude());
result.put(KEY_ALTITUDE, getAltitude());
return result;
}
/**
* Canonicalize the current latitude and longitude values such that:
*
* <pre>
* -90 <= latitude <= +90 - 180 < longitude <= +180
* </pre>
*/
private void canonicalize(DecimalType aLat, DecimalType aLon) {
latitude = flat.add(aLat.toBigDecimal()).remainder(circle);
longitude = aLon.toBigDecimal();
if (latitude.compareTo(BigDecimal.ZERO) == -1)
latitude.add(circle);
latitude = latitude.subtract(flat);
if (latitude.compareTo(right) == 1) {
latitude = flat.subtract(latitude);
longitude = longitude.add(flat);
} else if (latitude.compareTo(right.negate()) == -1) {
latitude = flat.negate().subtract(latitude);
longitude = longitude.add(flat);
}
longitude = flat.add(longitude).remainder(circle);
if (longitude.compareTo(BigDecimal.ZERO) <= 0)
longitude = longitude.add(circle);
longitude = longitude.subtract(flat);
}
}
| epl-1.0 |
shrishty/HeadFirstDesignPatterns | DesignPatterns/src/strategy/MiniDuckSimulator.java | 307 |
public class MiniDuckSimulator {
public static void main(String[] args) {
Duck mallard = new MallardDuck();
mallard.performQuack();
mallard.performFly();
Duck model = new ModelDuck();
model.performFly();
model.setFlyBehavior(new FlyRocketPowered());
model.performFly();
}
}
| epl-1.0 |
aravol/Jacinth | Jacinth/Components/InheritComponentKeyAttribute.cs | 360 | using System;
namespace Jacinth.Components
{
/// <summary>
/// Attribute to indicate the marked comopnent should use it's base class's ComponentTypeKey.
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class InheritComponentKeyAttribute : Attribute
{
// Nothing to do here but exist
}
}
| epl-1.0 |
arcanefoam/jgrapht | jgrapht-core/src/main/java/org/jgrapht/WeightedGraph.java | 1624 | /* ==========================================
* JGraphT : a free Java graph-theory library
* ==========================================
*
* Project Info: http://jgrapht.sourceforge.net/
* Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh)
*
* (C) Copyright 2003-2008, by Barak Naveh and Contributors.
*
* This program and the accompanying materials are dual-licensed under
* either
*
* (a) the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation, or (at your option) any
* later version.
*
* or (per the licensee's choosing)
*
* (b) the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation.
*/
/* ------------------
* WeightedGraph.java
* ------------------
* (C) Copyright 2003-2008, by Barak Naveh and Contributors.
*
* Original Author: Barak Naveh
* Contributor(s): Christian Hammer
*
* $Id$
*
* Changes
* -------
* 24-Jul-2003 : Initial revision (BN);
* 13-Aug-2003 : Included weight methods in Edge interface (BN);
* 11-Mar-2004 : Made generic (CH);
*
*/
package org.jgrapht;
/**
* An interface for a graph whose edges have non-uniform weights.
*
* @author Barak Naveh
* @since Jul 23, 2003
*/
public interface WeightedGraph<V, E>
extends Graph<V, E>
{
/**
* The default weight for an edge.
*/
double DEFAULT_EDGE_WEIGHT = 1.0;
/**
* Assigns a weight to an edge.
*
* @param e edge on which to set weight
* @param weight new weight for edge
*/
void setEdgeWeight(E e, double weight);
}
// End WeightedGraph.java
| epl-1.0 |
codenvy/che-core | commons/che-core-commons-lang/src/main/java/org/eclipse/che/commons/lang/Strings.java | 4794 | /*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.commons.lang;
import java.util.ArrayList;
import java.util.List;
/**
* Utility class to work with String */
@Deprecated
public class Strings {
private Strings() {
}
/**
* Returns the given string if it is non-null; the empty string otherwise.
*
* @param string
* the string to test and possibly return
* @return {@code string} itself if it is non-null; {@code ""} if it is null
* @deprecated use guava com.google.common.base.Strings.nullToEmpty
*/
@Deprecated
public static String nullToEmpty(String string) {
return (string == null) ? "" : string;
}
/**
* Returns the given string if it is nonempty; {@code null} otherwise.
*
* @param string
* the string to test and possibly return
* @return {@code string} itself if it is nonempty; {@code null} if it is
* empty or null
*
* @deprecated use guava com.google.common.base.Strings.emptyToNull
*/
@Deprecated
public static String emptyToNull(String string) {
return isNullOrEmpty(string) ? null : string;
}
/**
* Returns {@code true} if the given string is null or is the empty string.
* <p/>
* <p>Consider normalizing your string references with {@link #nullToEmpty}.
* If you do, you can use {@link String#isEmpty()} instead of this
* method, and you won't need special null-safe forms of methods like {@link
* String#toUpperCase} either. Or, if you'd like to normalize "in the other
* direction," converting empty strings to {@code null}, you can use {@link
* #emptyToNull}.
*
* @param string
* a string reference to check
* @return {@code true} if the string is null or is the empty string
* @deprecated use guava com.google.common.base.Strings.isNullOrEmpty
*/
@Deprecated
public static boolean isNullOrEmpty(String string) {
return string == null || string.length() == 0;
}
/**
* Returns a string containing the string representation of each of parts,
* using configured separator between each.
*
* @param delimiter
* separator placed between consecutive elements.
* @param parts
* strings to concatenate
* @return string containing the string representation of each of parts separated by delimiter
* @deprecated use guava com.google.common.base.Joiner
*/
@Deprecated
public static String join(String delimiter, String... parts) {
if (delimiter == null) {
throw new IllegalArgumentException("First argument can't be null.");
}
StringBuilder sb = new StringBuilder();
for (String alias : parts) {
if (sb.length() != 0) {
sb.append(delimiter);
}
sb.append(alias);
}
return sb.toString();
}
/**
* Splits string by delimiter.
* @deprecated use guava com.google.common.base.Splitter
* */
@Deprecated
public static String[] split(String raw, char ch) {
final List<String> list = new ArrayList<>(4);
int n = 0;
int p;
while ((p = raw.indexOf(ch, n)) != -1) {
list.add(raw.substring(n, p).trim());
n = p + 1;
}
list.add(raw.substring(n).trim());
return list.toArray(new String[list.size()]);
}
/**
* Search longest common prefix.
*
* @param input
* - input array.
* @return - longest common prefix of the input array of the string
* @deprecated use guava com.google.common.base.Strings.commonPrefix
*/
@Deprecated
public static String longestCommonPrefix(String... input) {
String prefix = "";
if (input.length > 0) {
prefix = input[0];
}
for (int i = 1; i < input.length; ++i) {
String s = input[i];
int j = 0;
for (int length = Math.min(prefix.length(), s.length()); j < length; ++j) {
if (prefix.charAt(j) != s.charAt(j)) {
break;
}
}
prefix = prefix.substring(0, j);
}
return prefix;
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/jpa/parsing/VariableNode.java | 12074 | /*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.internal.jpa.parsing;
import java.util.*;
// TopLink imports
import org.eclipse.persistence.exceptions.*;
import org.eclipse.persistence.expressions.*;
import org.eclipse.persistence.internal.expressions.ConstantExpression;
import org.eclipse.persistence.queries.ObjectLevelReadQuery;
import org.eclipse.persistence.queries.ReportQuery;
/**
* INTERNAL
* <p><b>Purpose</b>: The node that represents typed variables, local variables, remote variables and TYPE constants
* </ul>
* @author Jon Driscoll and Joel Lucuik
* @since TopLink 4.0
*/
public class VariableNode extends Node implements AliasableNode {
/** */
private String variableName;
/** */
private String canonicalName;
/** if this represents a type constant, this value will be populated by validate **/
private Object classConstant = null;
/**
* VariableNode constructor comment.
*/
public VariableNode() {
super();
}
public VariableNode(String newVariableName) {
setVariableName(newVariableName);
}
public String getVariableName() {
return variableName;
}
public void setVariableName(String newVariableName) {
variableName = newVariableName;
canonicalName = IdentificationVariableDeclNode.calculateCanonicalName(newVariableName);
}
/** */
public String getCanonicalVariableName() {
return canonicalName;
}
/**
* INTERNAL
* Is this node a VariableNode
*/
public boolean isVariableNode() {
return true;
}
/**
* INTERNAL
* Apply this node to the passed query
*/
public void applyToQuery(ObjectLevelReadQuery theQuery, GenerationContext generationContext) {
String name = getCanonicalVariableName();
if (theQuery instanceof ReportQuery) {
ReportQuery reportQuery = (ReportQuery)theQuery;
Expression expression = generationContext.expressionFor(name);
if (expression == null) {
expression = generateExpression(generationContext);
}
addAttributeWithFetchJoins(reportQuery, expression, generationContext);
} else {
addFetchJoins(theQuery, generationContext);
}
}
/**
* INTERNAL
* Add the variable as ReportQuery item. The method checks for any JOIN
* FETCH nodes of the current variable and adds them as part of the
* ReportQuery item.
*/
private void addAttributeWithFetchJoins(ReportQuery reportQuery,
Expression expression,
GenerationContext context) {
String name = getCanonicalVariableName();
List fetchJoinNodes = context.getParseTreeContext().getFetchJoins(name);
if (fetchJoinNodes == null) {
reportQuery.addAttribute(name, expression);
} else {
List fetchJoinExprs = new ArrayList(fetchJoinNodes.size());
for (Iterator i = fetchJoinNodes.iterator(); i.hasNext(); ) {
Node node = (Node)i.next();
fetchJoinExprs.add(node.generateExpression(context));
}
reportQuery.addItem(name, expression, fetchJoinExprs);
}
}
/**
* INTERNAL
* Check for any JOIN FETCH nodes of the current variable and add them as
* joined attributes. This method is called in case of a non ReportQuery
* instance.
*/
private void addFetchJoins(ObjectLevelReadQuery theQuery,
GenerationContext context) {
String name = getCanonicalVariableName();
List fetchJoinNodes = context.getParseTreeContext().getFetchJoins(name);
if (fetchJoinNodes != null) {
for (Iterator i = fetchJoinNodes.iterator(); i.hasNext(); ) {
Node node = (Node)i.next();
theQuery.addJoinedAttribute(node.generateExpression(context));
}
}
}
/**
* INTERNAL
* This node represent an unqualified field access in the case the method
* is called and the variableName is not defined as identification variable.
* The method returns a DotNode representing a qualified field access with
* the base variable as left child node. The right child node is an
* AttributeNode using the variableName as field name.
*/
public Node qualifyAttributeAccess(ParseTreeContext context) {
return context.isVariable(variableName) ? this :
(Node)context.getNodeFactory().newQualifiedAttribute(
getLine(), getColumn(), context.getBaseVariable(), variableName);
}
/**
* INTERNAL
* Validate node and calculate its type.
*/
public void validate(ParseTreeContext context) {
TypeHelper typeHelper = context.getTypeHelper();
classConstant = typeHelper.resolveSchema(variableName);
if (classConstant != null){
setType(Class.class);
return;
}
String name = getCanonicalVariableName();
if (context.isRangeVariable(name)) {
String schema = context.schemaForVariable(name);
setType(typeHelper.resolveSchema(schema));
} else {
Node path = context.pathForVariable(name);
if (path == null) {
throw JPQLException.aliasResolutionException(
context.getQueryInfo(), getLine(), getColumn(), name);
} else {
setType(path.getType());
}
}
context.usedVariable(name);
if (context.isDeclaredInOuterScope(name)) {
context.registerOuterScopeVariable(name);
}
}
public Expression generateBaseBuilderExpression(GenerationContext context) {
//create builder, and add it, and answer it
//BUG 3106877: Need to create builder using the actual class (if using parallel expressions)
return new ExpressionBuilder(this.resolveClass(context));
}
public Expression generateExpression(GenerationContext generationContext) {
Expression myExpression = null;
String name = getCanonicalVariableName();
//is there a cached Expression?
myExpression = generationContext.expressionFor(name);
if (myExpression != null) {
return myExpression;
}
//Either I have an alias type, or I'm an IN declaration
if (classConstant != null){
myExpression = new ConstantExpression(classConstant, generationContext.getBaseExpression());
} else if (generationContext.getParseTreeContext().isRangeVariable(name)) {
myExpression = generateBaseBuilderExpression(generationContext);
} else {
myExpression = generateExpressionForAlias(generationContext);
}
generationContext.addExpression(myExpression, name);
return myExpression;
}
public Expression generateExpressionForAlias(GenerationContext context) {
// BUG 3105651: Verify if we need to resolve this alias, or just use
// an empty ExpressionBuilder. See OrderByItemNode.generateExpression()
// for more details
if (context.getParseTree().getQueryNode().isSelectNode() && context.shouldCheckSelectNodeBeforeResolving() && (((SelectNode)context.getParseTree().getQueryNode()).isSelected(this.getCanonicalVariableName()))) {
return new ExpressionBuilder();
}
Node nodeForAlias = getNodeForAlias(context);
//assume that if there is no node available for the given variable, then
//there must be an alias mismatch. Assume they know their attribute names better
//than their alias names. - JGL
if (nodeForAlias == null) {
throw JPQLException.aliasResolutionException(
context.getParseTreeContext().getQueryInfo(),
getLine(), getColumn(), getVariableName());
}
//create builder, and answer it
return nodeForAlias.generateExpression(context);
}
public Node getNodeForAlias(GenerationContext context) {
//Node node = context.getParseTreeContext().nodeForIdentifier(getCanonicalVariableName());
//return node != null ? ((IdentificationVariableDeclNode)node).getPath() : null;
return context.getParseTreeContext().pathForVariable(getCanonicalVariableName());
}
/**
* isAlias: Answer true if this variable represents an alias in the FROM clause.
* i.e. "FROM Employee emp" declares "emp" as an alias
*/
public boolean isAlias(GenerationContext context) {
return isAlias(context.getParseTreeContext());
}
public boolean isAlias(ParseTreeContext context) {
String classNameForAlias = context.schemaForVariable(getCanonicalVariableName());
return classNameForAlias != null;
}
/**
* resolveClass: Answer the class which corresponds to my variableName. This is the class for
* an alias, where the variableName is registered to an alias.
*/
public Class resolveClass(GenerationContext generationContext) {
Class clazz = null;
String name = getCanonicalVariableName();
ParseTreeContext context = generationContext.getParseTreeContext();
if (context.isRangeVariable(name)) {
String schema = context.schemaForVariable(name);
clazz = context.classForSchemaName(schema, generationContext);
} else {
DotNode path = (DotNode)context.pathForVariable(name);
if (path == null) {
throw JPQLException.aliasResolutionException(
context.getQueryInfo(), getLine(), getColumn(), name);
} else {
clazz = path.resolveClass(generationContext);
}
}
return clazz;
}
public String toString(int indent) {
StringBuffer buffer = new StringBuffer();
toStringIndent(indent, buffer);
buffer.append(toStringDisplayName() + "[" + getVariableName() + "]");
return buffer.toString();
}
/**
* INTERNAL
* Get the string representation of this node.
*/
public String getAsString() {
return getVariableName();
}
public Object getTypeForMapKey(ParseTreeContext context){
String name = getCanonicalVariableName();
if (context.isRangeVariable(name)) {
throw JPQLException.variableCannotHaveMapKey(context.getQueryInfo(), getLine(), getColumn(), name);
} else {
DotNode path = (DotNode)context.pathForVariable(name);
if (path == null) {
throw JPQLException.aliasResolutionException(
context.getQueryInfo(), getLine(), getColumn(), name);
} else {
return path.getTypeForMapKey(context);
}
}
}
public boolean isAliasableNode(){
return true;
}
}
| epl-1.0 |
opendaylight/bgpcep | bgp/openconfig-rp-statement/src/main/java/org/opendaylight/protocol/bgp/openconfig/routing/policy/statement/actions/SetClusterIdPrependHandler.java | 3502 | /*
* Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.protocol.bgp.openconfig.routing.policy.statement.actions;
import java.util.ArrayList;
import java.util.List;
import org.opendaylight.protocol.bgp.openconfig.routing.policy.spi.RouteEntryBaseAttributes;
import org.opendaylight.protocol.bgp.openconfig.routing.policy.spi.policy.action.BgpActionAugPolicy;
import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryExportParameters;
import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryImportParameters;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.path.attributes.Attributes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.path.attributes.AttributesBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.path.attributes.attributes.ClusterIdBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.ClusterIdentifier;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.odl.bgp._default.policy.rev200120.SetClusterIdPrepend;
/**
* Prepend Cluster Id.
*/
public final class SetClusterIdPrependHandler implements BgpActionAugPolicy<SetClusterIdPrepend> {
private static final SetClusterIdPrependHandler INSTANCE = new SetClusterIdPrependHandler();
private SetClusterIdPrependHandler() {
}
public static SetClusterIdPrependHandler getInstance() {
return INSTANCE;
}
@Override
public Attributes applyImportAction(
final RouteEntryBaseAttributes routeEntryInfo,
final BGPRouteEntryImportParameters importParameters,
final Attributes attributes,
final SetClusterIdPrepend bgpActions) {
final ClusterIdentifier clusterIdLocal = importParameters.getFromClusterId() == null
? routeEntryInfo.getClusterId() : importParameters.getFromClusterId();
return prependClusterId(attributes, clusterIdLocal);
}
private static Attributes prependClusterId(final Attributes attributes, final ClusterIdentifier clusterId) {
final AttributesBuilder newAtt = new AttributesBuilder(attributes);
final List<ClusterIdentifier> newClusterList = new ArrayList<>();
newClusterList.add(clusterId);
if (attributes.getClusterId() != null && !attributes.getClusterId().getCluster().isEmpty()) {
final List<ClusterIdentifier> oldList = attributes.getClusterId().getCluster();
newClusterList.addAll(oldList);
}
return newAtt.setClusterId(new ClusterIdBuilder().setCluster(newClusterList).build()).build();
}
@Override
public Attributes applyExportAction(
final RouteEntryBaseAttributes routeEntryInfo,
final BGPRouteEntryExportParameters exportParameters,
final Attributes attributes,
final SetClusterIdPrepend bgpActions) {
final ClusterIdentifier clusterIdLocal = exportParameters.getFromClusterId() == null
? routeEntryInfo.getClusterId() : exportParameters.getFromClusterId();
return prependClusterId(attributes, clusterIdLocal);
}
}
| epl-1.0 |
polarsys/eplmp | eplmp-server/eplmp-server-rest/src/main/java/org/polarsys/eplmp/server/rest/dto/ComponentDTO.java | 8691 | /*******************************************************************************
* Copyright (c) 2017-2019 DocDoku.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* DocDoku - initial API and implementation
*******************************************************************************/
package org.polarsys.eplmp.server.rest.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* @author Julien Maffre
*/
@XmlRootElement
@ApiModel(value = "ComponentDTO", description = "This class is the representation of a {@link org.polarsys.eplmp.core.product.Component} entity")
public class ComponentDTO implements Serializable {
@ApiModelProperty(value = "Part author name")
private String author;
@ApiModelProperty(value = "Part author login")
private String authorLogin;
@ApiModelProperty(value = "Part number")
private String number;
@ApiModelProperty(value = "Part name")
private String name = "";
@ApiModelProperty(value = "Part version")
private String version;
@ApiModelProperty(value = "Part iteration")
private int iteration;
@ApiModelProperty(value = "Part description")
private String description;
@ApiModelProperty(value = "Standard part flag")
private boolean standardPart;
@ApiModelProperty(value = "Assembly flag")
private boolean assembly;
@ApiModelProperty(value = "Substitute flag")
private boolean substitute;
@ApiModelProperty(value = "Component usage link id")
private String partUsageLinkId;
@ApiModelProperty(value = "Component usage link description")
private String partUsageLinkReferenceDescription;
@ApiModelProperty(value = "List of children components")
private List<ComponentDTO> components;
@ApiModelProperty(value = "Amount of component")
private double amount;
@ApiModelProperty(value = "Unit for amount")
private String unit;
@ApiModelProperty(value = "List of part iteration attributes")
private List<InstanceAttributeDTO> attributes;
@ApiModelProperty(value = "Check out user if any")
private UserDTO checkOutUser;
@ApiModelProperty(value = "Check out date if any")
private Date checkOutDate;
@ApiModelProperty(value = "Released flag")
private boolean released;
@ApiModelProperty(value = "Obsolete flag")
private boolean obsolete;
@ApiModelProperty(value = "Optional flag")
private boolean optional;
@ApiModelProperty(value = "Last part iteration number")
@XmlElement(nillable = true)
private int lastIterationNumber;
@ApiModelProperty(value = "Denied access flag")
@XmlElement(nillable = true)
private boolean accessDeny;
@ApiModelProperty(value = "Available substitutes list")
@XmlElement(nillable = true)
private List<String> substituteIds;
@ApiModelProperty(value = "Hooked modifications notifications")
private List<ModificationNotificationDTO> notifications;
@ApiModelProperty(value = "Contains structure path data flag")
private boolean hasPathData;
@ApiModelProperty(value = "Is virtual component flag")
private boolean isVirtual;
@ApiModelProperty(value = "Component path in context")
private String path;
public ComponentDTO() {
}
public ComponentDTO(String number) {
this.number = number;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public boolean isAssembly() {
return assembly;
}
public void setAssembly(boolean assembly) {
this.assembly = assembly;
}
public boolean isStandardPart() {
return standardPart;
}
public void setStandardPart(boolean standardPart) {
this.standardPart = standardPart;
}
public int getIteration() {
return iteration;
}
public void setIteration(int iteration) {
this.iteration = iteration;
}
public List<ComponentDTO> getComponents() {
return components;
}
public void setComponents(List<ComponentDTO> components) {
this.components = components;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getPartUsageLinkId() {
return partUsageLinkId;
}
public void setPartUsageLinkId(String partUsageLinkId) {
this.partUsageLinkId = partUsageLinkId;
}
public List<InstanceAttributeDTO> getAttributes() {
return attributes;
}
public void setAttributes(List<InstanceAttributeDTO> attributes) {
this.attributes = attributes;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthorLogin() {
return authorLogin;
}
public void setAuthorLogin(String authorLogin) {
this.authorLogin = authorLogin;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public UserDTO getCheckOutUser() {
return checkOutUser;
}
public void setCheckOutUser(UserDTO checkOutUser) {
this.checkOutUser = checkOutUser;
}
public Date getCheckOutDate() {
return (checkOutDate != null) ? (Date) checkOutDate.clone() : null;
}
public void setCheckOutDate(Date checkOutDate) {
this.checkOutDate = (checkOutDate != null) ? (Date) checkOutDate.clone() : null;
}
public int getLastIterationNumber() {
return lastIterationNumber;
}
public void setLastIterationNumber(int lastIterationNumber) {
this.lastIterationNumber = lastIterationNumber;
}
public boolean isAccessDeny() {
return accessDeny;
}
public void setAccessDeny(boolean accessDeny) {
this.accessDeny = accessDeny;
}
public boolean isReleased() {
return released;
}
public void setReleased(boolean released) {
this.released = released;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public boolean isSubstitute() {
return substitute;
}
public void setSubstitute(boolean substitute) {
this.substitute = substitute;
}
public List<ModificationNotificationDTO> getNotifications() {
return notifications;
}
public void setNotifications(List<ModificationNotificationDTO> notifications) {
this.notifications = notifications;
}
public boolean isObsolete() {
return obsolete;
}
public void setObsolete(boolean obsolete) {
this.obsolete = obsolete;
}
public String getPartUsageLinkReferenceDescription() {
return partUsageLinkReferenceDescription;
}
public void setPartUsageLinkReferenceDescription(String partUsageLinkReferenceDescription) {
this.partUsageLinkReferenceDescription = partUsageLinkReferenceDescription;
}
public boolean isOptional() {
return optional;
}
public void setOptional(boolean optional) {
this.optional = optional;
}
public boolean isHasPathData() {
return hasPathData;
}
public void setHasPathData(boolean hasPathData) {
this.hasPathData = hasPathData;
}
public boolean isVirtual() {
return isVirtual;
}
public void setVirtual(boolean isVirtual) {
this.isVirtual = isVirtual;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public List<String> getSubstituteIds() {
return substituteIds;
}
public void setSubstituteIds(List<String> substituteIds) {
this.substituteIds = substituteIds;
}
}
| epl-1.0 |
sleshchenko/che | wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/hc/probe/HttpProbe.java | 2368 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.api.workspace.server.hc.probe;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* Probes a HTTP(s) URL for a response with code >=200 and <400
*
* @author Alexander Garagatyi
*/
public class HttpProbe extends Probe {
private static final String CONNECTION_HEADER = "Connection";
private static final String CONNECTION_CLOSE = "close";
private final URL url;
private final int timeout;
private final Map<String, String> headers;
private HttpURLConnection httpURLConnection;
/**
* Creates probe
*
* @param url HTTP endpoint to probe
* @param timeout connection and read timeouts
*/
public HttpProbe(URL url, int timeout, Map<String, String> headers) {
this.url = url;
this.timeout = timeout;
this.headers = new HashMap<>();
if (headers != null) {
this.headers.putAll(headers);
}
this.headers.put(CONNECTION_HEADER, CONNECTION_CLOSE);
}
@Override
public boolean doProbe() {
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(timeout);
httpURLConnection.setReadTimeout(timeout);
headers.forEach((name, value) -> httpURLConnection.setRequestProperty(name, value));
return isConnectionSuccessful(httpURLConnection);
} catch (IOException e) {
return false;
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
}
/**
* More effectively cancels the probe than cancellation inherited from {@link Probe}.
*
* @see Probe#cancel()
*/
@Override
public void cancel() {
httpURLConnection.disconnect();
}
private boolean isConnectionSuccessful(HttpURLConnection conn) {
try {
int responseCode = conn.getResponseCode();
return responseCode >= 200 && responseCode < 400;
} catch (IOException e) {
return false;
}
}
}
| epl-1.0 |
diverse-project/kcvl | fr.inria.diverse.kcvl.metamodel/src/main/java/org/omg/CVLMetamodelMaster/cvl/impl/LinkHandleImpl.java | 3486 | /**
*/
package org.omg.CVLMetamodelMaster.cvl.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.omg.CVLMetamodelMaster.cvl.CvlPackage;
import org.omg.CVLMetamodelMaster.cvl.LinkHandle;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Link Handle</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.omg.CVLMetamodelMaster.cvl.impl.LinkHandleImpl#getMOFRef <em>MOF Ref</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class LinkHandleImpl extends BaseModelHandleImpl implements LinkHandle {
/**
* The default value of the '{@link #getMOFRef() <em>MOF Ref</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMOFRef()
* @generated
* @ordered
*/
protected static final String MOF_REF_EDEFAULT = null;
/**
* The cached value of the '{@link #getMOFRef() <em>MOF Ref</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMOFRef()
* @generated
* @ordered
*/
protected String mofRef = MOF_REF_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected LinkHandleImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return CvlPackage.Literals.LINK_HANDLE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getMOFRef() {
return mofRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMOFRef(String newMOFRef) {
String oldMOFRef = mofRef;
mofRef = newMOFRef;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, CvlPackage.LINK_HANDLE__MOF_REF, oldMOFRef, mofRef));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case CvlPackage.LINK_HANDLE__MOF_REF:
return getMOFRef();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case CvlPackage.LINK_HANDLE__MOF_REF:
setMOFRef((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case CvlPackage.LINK_HANDLE__MOF_REF:
setMOFRef(MOF_REF_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case CvlPackage.LINK_HANDLE__MOF_REF:
return MOF_REF_EDEFAULT == null ? mofRef != null : !MOF_REF_EDEFAULT.equals(mofRef);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (MOFRef: ");
result.append(mofRef);
result.append(')');
return result.toString();
}
} //LinkHandleImpl
| epl-1.0 |
jaytaylor/persistit | src/main/java/com/persistit/exception/TransactionFailedException.java | 1043 | /**
* Copyright © 2005-2012 Akiban Technologies, Inc. All rights reserved.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This program may also be available under different license terms.
* For more information, see www.akiban.com or contact licensing@akiban.com.
*
* Contributors:
* Akiban Technologies, Inc.
*/
package com.persistit.exception;
/**
* Thrown by {@link com.persistit.Transaction} when a transaction fails due to
* excessive rollbacks.
*
* @version 1.0
*/
public class TransactionFailedException extends PersistitException {
private static final long serialVersionUID = 4333338222080863109L;
public TransactionFailedException() {
super();
}
public TransactionFailedException(String msg) {
super(msg);
}
public TransactionFailedException(Throwable t) {
super(t);
}
}
| epl-1.0 |
pgaufillet/topcased-req | plugins/org.topcased.requirement.core/src/org/topcased/requirement/core/handlers/HierarchicalHandler.java | 3309 | /*****************************************************************************
* Copyright (c) 2010 Communication & Systems
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors : Maxime AUDRAIN (CS) - initial API and implementation
*
*****************************************************************************/
package org.topcased.requirement.core.handlers;
import org.eclipse.core.commands.AbstractHandlerWithState;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.State;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.handlers.RegistryToggleState;
import org.topcased.requirement.core.utils.RequirementHelper;
import org.topcased.requirement.core.views.upstream.UpstreamPage;
/**
* Handler of the hierarchical command
*
* @author <a href="mailto:maxime.audrain@c-s.fr">Maxime AUDRAIN</a>
*
*/
public class HierarchicalHandler extends AbstractHandlerWithState
{
/** Reference to the upstream page **/
private UpstreamPage page;
/**
* FIXME : for now there is two RegisteryTOGGLEState for each commands who should be RADIO styled!! Tried to put the
* RegisteryRadioState for each but having bugs with this state
*
* @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent)
*/
public Object execute(ExecutionEvent event) throws ExecutionException
{
ICommandService cs = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
Command flatCmd = cs.getCommand(ICommandConstants.FLAT_ID);
HandlerUtil.toggleCommandState(event.getCommand());
flatCmd.getState(RegistryToggleState.STATE_ID).setValue(!(Boolean) event.getCommand().getState(RegistryToggleState.STATE_ID).getValue());
return null;
}
/**
* Applies the right representation of the tree contents
*
* @param isFlat should we use the flat representation or the tree one ?
*/
private void applyRepresentation(boolean isFlat)
{
page = RequirementHelper.INSTANCE.getUpstreamPage();
if (page != null && !page.getViewer().getControl().isDisposed())
{
page.getUpstreamRequirementContentProvider().setIsFlat(isFlat);
if (page.getViewer() instanceof StructuredViewer)
{
((StructuredViewer) page.getViewer()).refresh(false);
}
else
{
page.getViewer().refresh();
}
}
}
/**
* @see org.eclipse.core.commands.AbstractHandlerWithState#handleStateChange(org.eclipse.core.commands.State,
* java.lang.Object)
*/
public void handleStateChange(State state, Object oldValue)
{
if (state.getValue().equals(true))
{
applyRepresentation(false);
}
}
}
| epl-1.0 |
gijss/rFSM-tooling | be.kuleuven.graph.rfsm/src/be/kuleuven/graph/rfsm/features/TransitionCreateFeature.java | 3879 | package be.kuleuven.graph.rfsm.features;
import org.eclipse.graphiti.features.IFeatureProvider;
import org.eclipse.graphiti.features.context.ICreateConnectionContext;
import org.eclipse.graphiti.features.context.impl.AddConnectionContext;
import org.eclipse.graphiti.features.impl.AbstractCreateConnectionFeature;
import org.eclipse.graphiti.mm.pictograms.Anchor;
import org.eclipse.graphiti.mm.pictograms.AnchorContainer;
import org.eclipse.graphiti.mm.pictograms.Connection;
import org.eclipse.graphiti.mm.pictograms.PictogramElement;
import be.kuleuven.model.rfsm.RfsmFactory;
import be.kuleuven.model.rfsm.RfsmGraph;
import be.kuleuven.model.rfsm.State;
import be.kuleuven.model.rfsm.Transition;
public class TransitionCreateFeature extends AbstractCreateConnectionFeature {
private static int counter = 0;
public TransitionCreateFeature(IFeatureProvider fp) {
super(fp, "Tansition", "Create a Transition");
}
@Override
public boolean canCreate(ICreateConnectionContext context) {
Anchor sourceAnchor = context.getSourceAnchor();
Anchor targetAnchor = context.getTargetAnchor();
if (sourceAnchor != null && targetAnchor != null) {
AnchorContainer sourceParent = sourceAnchor.getParent();
if (sourceParent != null
&& sourceParent.equals(targetAnchor.getParent())) {
return false;
}
}
PictogramElement sourcePe = context.getSourcePictogramElement();
PictogramElement targetPe = context.getTargetPictogramElement();
if (sourcePe != null && sourcePe.equals(targetPe)) {
return false;
}
Object sourceBo = getBusinessObjectForPictogramElement(sourcePe);
Object targetBo = getBusinessObjectForPictogramElement(targetPe);
if ((sourceBo instanceof State) & (targetBo instanceof State)) {
return true;
}
return false;
}
@Override
public boolean canStartConnection(ICreateConnectionContext context) {
if (context.getSourceAnchor() != null) {
return true;
}
return false;
}
@Override
public Connection create(ICreateConnectionContext context) {
PictogramElement sourcePe = context.getSourcePictogramElement();
PictogramElement targetPe = context.getTargetPictogramElement();
Object sourceBo = getBusinessObjectForPictogramElement(sourcePe);
Object targetBo = getBusinessObjectForPictogramElement(targetPe);
Connection newConnection = null;
if ((sourceBo instanceof State) & (targetBo instanceof State)) {
newConnection = createStateToStateTransition(context);
}
return newConnection;
}
private Connection createStateToStateTransition(
ICreateConnectionContext context) {
State source = getState(context.getSourceAnchor());
State target = getState(context.getTargetAnchor());
Connection newConnection = null;
if (source != null && target != null) {
Transition transtiion = createTransition(source, target);
addTransitionToHyperGraph(transtiion);
AddConnectionContext addContext = new AddConnectionContext(
context.getSourceAnchor(), context.getTargetAnchor());
addContext.setNewObject(transtiion);
newConnection = (Connection) getFeatureProvider().addIfPossible(
addContext);
}
return newConnection;
}
private void addTransitionToHyperGraph(Transition transtiion) {
RfsmGraph rfsmGraph = (RfsmGraph) getBusinessObjectForPictogramElement(getDiagram());
rfsmGraph.getTransitions().add(transtiion);
}
private State getState(Anchor anchor) {
if (anchor != null) {
Object object = getBusinessObjectForPictogramElement(anchor
.getParent());
if (object instanceof State) {
return (State) object;
}
}
return null;
}
private Transition createTransition(State source, State target) {
Transition transition = RfsmFactory.eINSTANCE.createTransition();
transition.setName("Transtion_" + counter++);
transition.getSource().add(source);
transition.getTarget().add(target);
return transition;
}
}
| epl-1.0 |
FlatGUI/flatguisamples | src/java/flatgui/samples/FGHelloWorldDemo.java | 1244 | /*
* Copyright (c) 2015 Denys Lebediev and contributors. All rights reserved.
* The use and distribution terms for this software are covered by the
* Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
* which can be found in the file LICENSE at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
*/
package flatgui.samples;
import flatgui.run.FGDesktopRunner;
import flatgui.run.FGRunUtil;
import java.awt.*;
/**
* @author Denis Lebedev
*/
public class FGHelloWorldDemo
{
public static final String CONTAINER_NS = "flatgui.samples.forms.helloworld";
public static final String CONTAINER_VAR_NAME = "root-panel";
public static final String ICON_RESOURCE = "flatgui/samples/images/icon_FlatGUI_32x32.png";
public static final String TITLE = "FlatGUI Demo - Hello world";
public static void main(String[] args)
{
Image logoIcon = FGRunUtil.loadIconFromClasspath(ICON_RESOURCE, e -> e.printStackTrace());
FGDesktopRunner.runDesktop(CONTAINER_NS, CONTAINER_VAR_NAME, TITLE, logoIcon, e -> e.printStackTrace());
}
}
| epl-1.0 |
Jose-Badeau/boomslang-examples | boomslang.example.web.jhapp/src/main/webapp/app/account/activate/activate.state.js | 989 | (function() {
'use strict';
angular
.module('jhappApp')
.config(stateConfig);
stateConfig.$inject = ['$stateProvider'];
function stateConfig($stateProvider) {
$stateProvider.state('activate', {
parent: 'account',
url: '/activate?key',
data: {
authorities: [],
pageTitle: 'activate.title'
},
views: {
'content@': {
templateUrl: 'app/account/activate/activate.html',
controller: 'ActivationController',
controllerAs: 'vm'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('activate');
return $translate.refresh();
}]
}
});
}
})();
| epl-1.0 |
rmcilroy/HeraJVM | rvm/src/org/jikesrvm/compilers/opt/OPT_Queue.java | 1011 | /*
* This file is part of the Jikes RVM project (http://jikesrvm.org).
*
* This file is licensed to You under the Common Public License (CPL);
* You may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.opensource.org/licenses/cpl1.0.php
*
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership.
*/
package org.jikesrvm.compilers.opt;
import java.util.Iterator;
import org.jikesrvm.util.VM_LinkedList;
final class OPT_Queue<T> implements Iterable<T> {
private final VM_LinkedList<T> elements = new VM_LinkedList<T>();
OPT_Queue() { }
OPT_Queue(T e) {
elements.add(e);
}
T insert(T e) {
elements.add(e); // Insert at tail
return e;
}
T remove() {
return elements.remove(0); // Remove from head
}
boolean isEmpty() {
return elements.isEmpty();
}
public Iterator<T> iterator() {
return elements.iterator();
}
}
| epl-1.0 |
whichname/YIWeather | src/from/mrw/yiweather/WeatherURL.java | 543 | package from.mrw.yiweather;
import java.net.URLEncoder;
public class WeatherURL {
// Òª²éѯµÄ³ÇÊÐ
private String city;
// Òª²éѯµÄÓïÑÔ
private String language = "zh-chs";
// ζȵ¥Î»
private String unit = "c";
// aqi
private String aqi = "city";
// key
private String key = "IXOP31EQDO";
public WeatherURL(String city)
{
this.city = city;
}
// »ñµÃURLÃû
public String getURL()
{
return "https://api.thinkpage.cn/v2/weather/all.json?city=" + city+"&language=" + language +"&unit="+unit +"&aqi="+ aqi + "&key="+ key;
}
}
| epl-1.0 |
ghillairet/gef-gwt | src/main/java/org/eclipse/jface/resource/URLImageDescriptor.java | 4065 | /*******************************************************************************
* Copyright (c) 2000, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.resource;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
/**
* An ImageDescriptor that gets its information from a URL. This class is not
* public API. Use ImageDescriptor#createFromURL to create a descriptor that
* uses a URL.
*/
class URLImageDescriptor extends ImageDescriptor {
public ImageData getImageData() {
// TODO Auto-generated method stub
return null;
}
/**
* Constant for the file protocol for optimized loading
*/
// private static final String FILE_PROTOCOL = "file"; //$NON-NLS-1$
// private URL url;
//
// /**
// * Creates a new URLImageDescriptor.
// *
// * @param url
// * The URL to load the image from. Must be non-null.
// */
// URLImageDescriptor(URL url) {
// this.url = url;
// }
//
// /*
// * (non-Javadoc) Method declared on Object.
// */
// public boolean equals(Object o) {
// if (!(o instanceof URLImageDescriptor)) {
// return false;
// }
// return ((URLImageDescriptor) o).url.toExternalForm().equals(
// this.url.toExternalForm());
// }
//
// /*
// * (non-Javadoc) Method declared on ImageDesciptor. Returns null if the
// * image data cannot be read.
// */
// public ImageData getImageData() {
// ImageData result = null;
// InputStream in = getStream();
// if (in != null) {
// try {
// // result = new ImageData(in);
// } catch (SWTException e) {
// if (e.code != SWT.ERROR_INVALID_IMAGE) {
// throw e;
// // fall through otherwise
// }
// } finally {
// try {
// in.close();
// } catch (IOException e) {
// Policy.getLog().log(
// new Status(IStatus.ERROR, Policy.JFACE, e
// .getLocalizedMessage(), e));
// }
// }
// }
// return result;
// }
//
// /**
// * Returns a stream on the image contents. Returns null if a stream could
// * not be opened.
// *
// * @return the stream for loading the data
// */
// protected InputStream getStream() {
// try {
// return new BufferedInputStream(url.openStream());
// } catch (IOException e) {
// return null;
// }
// }
//
// /*
// * (non-Javadoc) Method declared on Object.
// */
// public int hashCode() {
// return url.toExternalForm().hashCode();
// }
//
// /*
// * (non-Javadoc) Method declared on Object.
// */
// /**
// * The <code>URLImageDescriptor</code> implementation of this
// * <code>Object</code> method returns a string representation of this
// object
// * which is suitable only for debugging.
// */
// public String toString() {
// return "URLImageDescriptor(" + url + ")"; //$NON-NLS-1$ //$NON-NLS-2$
// }
//
// /**
// * Returns the filename for the ImageData.
// *
// * @return {@link String} or <code>null</code> if the file cannot be found
// */
// private String getFilePath() {
//
// if (!InternalPolicy.OSGI_AVAILABLE) {
// if (FILE_PROTOCOL.equalsIgnoreCase(url.getProtocol()))
// // return new Path(url.getFile()).toOSString();
// return null;
// }
//
// // URL locatedURL = FileLocator.toFileURL(url);
// // if (FILE_PROTOCOL.equalsIgnoreCase(locatedURL.getProtocol()))
// // return new Path(locatedURL.getPath()).toOSString();
// return null;
// }
//
String url;
public URLImageDescriptor(String url) {
this.url = url;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.resource.ImageDescriptor#createImage(boolean,
* org.eclipse.swt.graphics.Device)
*/
public Image createImage(boolean returnMissingImageOnError, Device device) {
return new Image(device, url);
}
}
| epl-1.0 |
Nasdanika/amur-it-js | org.nasdanika.amur.it.js.edit/src/org/nasdanika/amur/it/js/provider/ComponentItemProvider.java | 8844 | /**
*/
package org.nasdanika.amur.it.js.provider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import org.eclipse.emf.edit.provider.ViewerNotification;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Control;
import org.nasdanika.amur.it.js.Component;
import org.nasdanika.amur.it.js.JsPackage;
import org.nasdanika.amur.lang.Source;
import org.nasdanika.amur.lang.provider.ui.SourceDialog;
import org.nasdanika.common.Activator;
import org.nasdanika.common.DialogItemPropertyDescriptorImpl;
/**
* This is the item provider adapter for a {@link org.nasdanika.amur.it.js.Component} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class ComponentItemProvider
extends ItemProviderAdapter
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ComponentItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
// Shadows superclass array for easy detection of errors.
protected Map<Object, List<IItemPropertyDescriptor>> itemPropertyDescriptors = new HashMap<>();
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors.get(object) == null) {
itemPropertyDescriptors.put(object, new ArrayList<IItemPropertyDescriptor>());
addDeclarationsPropertyDescriptor(object);
addStartPropertyDescriptor(object);
addStopPropertyDescriptor(object);
}
return itemPropertyDescriptors.get(object);
}
/**
* This adds a property descriptor for the Declarations feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
protected void addDeclarationsPropertyDescriptor(Object object) {
ItemPropertyDescriptor ipd = createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Component_declarations_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Component_declarations_feature", "_UI_Component_type"),
JsPackage.Literals.COMPONENT__DECLARATIONS,
true,
false,
false,
Activator.getImageDescriptor("icons/fat-cow-farm-fresh-web-icons/16x16/source_code.png"),
// getResourceLocator().getImage("full/obj16/script.png"),
getString("_UI_LifecyclePropertyCategory"),
null);
itemPropertyDescriptors.get(object).add
(new DialogItemPropertyDescriptorImpl(ipd, null) {
@Override
public Object openDialogBox(Control cellEditorWindow, Object initialValue, AdapterFactory adapterFactory) {
SourceDialog d = new SourceDialog(
cellEditorWindow.getShell(),
"Declarations",
(Source) initialValue,
((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
null); // TODO
return d.open()==Window.OK ? d.getValue() : null;
}
});
}
/**
* This adds a property descriptor for the Start feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
protected void addStartPropertyDescriptor(Object object) {
ItemPropertyDescriptor ipd = createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Component_start_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Component_start_feature", "_UI_Component_type"),
JsPackage.Literals.COMPONENT__START,
true,
false,
false,
Activator.getImageDescriptor("icons/fat-cow-farm-fresh-web-icons/16x16/source_code.png"),
getString("_UI_LifecyclePropertyCategory"),
null);
itemPropertyDescriptors.get(object).add
(new DialogItemPropertyDescriptorImpl(ipd, null) {
@Override
public Object openDialogBox(Control cellEditorWindow, Object initialValue, AdapterFactory adapterFactory) {
SourceDialog d = new SourceDialog(
cellEditorWindow.getShell(),
"Start",
(Source) initialValue,
((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
null); // TODO - completions from declarations.
return d.open()==Window.OK ? d.getValue() : null;
}
});
}
/**
* This adds a property descriptor for the Stop feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
protected void addStopPropertyDescriptor(Object object) {
ItemPropertyDescriptor ipd = createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Component_stop_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Component_stop_feature", "_UI_Component_type"),
JsPackage.Literals.COMPONENT__STOP,
true,
false,
false,
Activator.getImageDescriptor("icons/fat-cow-farm-fresh-web-icons/16x16/source_code.png"),
getString("_UI_LifecyclePropertyCategory"),
null);
itemPropertyDescriptors.get(object).add
(new DialogItemPropertyDescriptorImpl(ipd, null) {
@Override
public Object openDialogBox(Control cellEditorWindow, Object initialValue, AdapterFactory adapterFactory) {
SourceDialog d = new SourceDialog(
cellEditorWindow.getShell(),
"Stop",
(Source) initialValue,
((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
null); // TODO - completions from declarations and start.
return d.open()==Window.OK ? d.getValue() : null;
}
});
}
/**
* This returns Component.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/Component"));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected boolean shouldComposeCreationImage() {
return true;
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((Component)object).getName();
return label == null || label.length() == 0 ?
getString("_UI_Component_type") :
getString("_UI_Component_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(Component.class)) {
case JsPackage.COMPONENT__NAME:
case JsPackage.COMPONENT__ID:
case JsPackage.COMPONENT__DESCRIPTION:
case JsPackage.COMPONENT__DECLARATIONS:
case JsPackage.COMPONENT__START:
case JsPackage.COMPONENT__STOP:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
/**
* Return the resource locator for this item provider's resources.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ResourceLocator getResourceLocator() {
return JsEditPlugin.INSTANCE;
}
}
| epl-1.0 |
citycloud-bigdata/mondrian | testsrc/main/mondrian/util/ObjectPoolTest.java | 9932 | /*
// This software is subject to the terms of the Eclipse Public License v1.0
// Agreement, available at the following URL:
// http://www.eclipse.org/legal/epl-v10.html.
// You must accept the terms of that agreement to use this software.
//
// Copyright (C) 2006-2014 Pentaho and others
// All Rights Reserved.
*/
package mondrian.util;
import mondrian.olap.Util;
import junit.framework.TestCase;
import java.util.*;
/**
* Test case for {@link ObjectPool}.
*
* @author Richard Emberson
*/
public class ObjectPoolTest extends TestCase {
public ObjectPoolTest() {
super();
}
public ObjectPoolTest(String name) {
super(name);
}
static class KeyValue {
long key;
Object value;
KeyValue(long key, Object value) {
this.key = key;
this.value = value;
}
public int hashCode() {
return (int)(key ^ (key >>> 32));
}
public boolean equals(Object o) {
return (o instanceof KeyValue)
? (((KeyValue) o).key == this.key)
: false;
}
public String toString() {
return value.toString();
}
}
public void testString() throws Exception {
// for reasons unknown this fails with java4
if (Util.PreJdk15) {
return;
}
ObjectPool<String> strings = new ObjectPool<String>();
int nos = 100000;
String[] ss1 = genStringsArray(nos);
for (int i = 0; i < nos; i++) {
strings.add(ss1[i]);
}
assertEquals("size not equal", nos, strings.size());
// second array of strings, same as the first but different objects
String[] ss2 = genStringsArray(nos);
for (int i = 0; i < nos; i++) {
String s = strings.add(ss2[i]);
assertEquals("string not equal: " + s, s, ss2[i]);
// REVIEW jvs 16-Jan-2008: This failed for me when
// I ran with a 1GB JVM heap size on JDK 1.5, probably
// because of interning (I tried changing genStringsList to add a
// gratuitous String constructor call, but that did not help). If
// there's a reason this test is on strings explicitly, then
// this needs to stay disabled; if the datatype can be changed
// to something which doesn't have any magic interning, then
// it can be re-enabled. This probably explains the
// Util.PreJdk15 "unknown reasons" above.
/*
assertFalse("same object", (s == ss2[i]));
*/
}
strings.clear();
assertEquals("size not equal", 0, strings.size());
nos = 25;
ss1 = genStringsArray(nos);
for (int i = 0; i < nos; i++) {
strings.add(ss1[i]);
}
assertEquals("size not equal", nos, strings.size());
List<String> l = genStringsList(nos);
Iterator<String> it = strings.iterator();
while (it.hasNext()) {
String s = it.next();
l.remove(s);
}
assertTrue("list not empty", l.isEmpty());
}
public void testKeyValue() throws Exception {
ObjectPool<KeyValue> op = new ObjectPool<KeyValue>();
int nos = 100000;
KeyValue[] kv1 = genKeyValueArray(nos);
for (int i = 0; i < nos; i++) {
op.add(kv1[i]);
}
assertEquals("size not equal", nos, op.size());
// second array of KeyValues, same as the first but different objects
KeyValue[] kv2 = genKeyValueArray(nos);
for (int i = 0; i < nos; i++) {
KeyValue kv = op.add(kv2[i]);
assertEquals("KeyValue not equal: " + kv, kv, kv2[i]);
assertFalse("same object", (kv == kv2[i]));
}
op.clear();
assertEquals("size not equal", 0, op.size());
nos = 25;
kv1 = genKeyValueArray(nos);
for (int i = 0; i < nos; i++) {
op.add(kv1[i]);
}
assertEquals("size not equal", nos, op.size());
List<KeyValue> l = genKeyValueList(nos);
Iterator<KeyValue> it = op.iterator();
while (it.hasNext()) {
KeyValue kv = it.next();
l.remove(kv);
}
assertTrue("list not empty", l.isEmpty());
}
/**
* Tests ObjectPools containing large numbers of integer and string keys,
* and makes sure they return the same results as HashSet. Optionally
* measures performance.
*/
public void testLarge() {
// Some typical results (2.4 GHz Intel dual-core).
// Key type: Integer String
// Implementation: ObjectPool HashSet ObjectPool HashSet
// ========== ========== ========== ==========
// With density=0.01, 298,477 distinct entries, 7,068 hits
// 300,000 adds 221 ms 252 ms 293 ms 1013 ms
// 700,000 gets 164 ms 148 ms 224 ms 746 ms
//
// With density=0.5, 236,022 distinct entries, 275,117 hits
// 300,000 adds 175 ms 250 ms 116 ms 596 ms
// 700,000 gets 147 ms 176 ms 190 ms 757 ms
//
// With density=0.999, 189,850 distinct entries, 442,618 hits
// 300,000 adds 128 ms 185 ms 99 ms 614 ms
// 700,000 gets 133 ms 184 ms 130 ms 830 ms
checkLargeMulti(300000, 0.01, 700000, 298477, 7068);
checkLargeMulti(300000, 0.5, 700000, 236022, 275117);
checkLargeMulti(300000, 0.999, 700000, 189850, 442618);
}
private void checkLargeMulti(
int entryCount,
double density,
int retrieveCount,
int expectedDistinct,
int expectedHits)
{
checkLarge(
true, true, entryCount, density, retrieveCount,
expectedDistinct, expectedHits);
checkLarge(
false, true, entryCount, density, retrieveCount,
expectedDistinct, expectedHits);
checkLarge(
false, true, entryCount, density, retrieveCount,
expectedDistinct, expectedHits);
checkLarge(
false, false, entryCount, density, retrieveCount,
expectedDistinct, expectedHits);
}
private void checkLarge(
boolean usePool,
boolean intKey,
int entryCount,
double density,
int retrieveCount,
int expectedDistinct,
int expectedHits)
{
final boolean print = false;
final long t1 = System.currentTimeMillis();
assert density > 0 && density <= 1;
int space = (int) (entryCount / density);
ObjectPool<Object> objectPool = new ObjectPool<Object>();
HashSet<Object> set = new HashSet<Object>();
Random random = new Random(1234);
int distinctCount = 0;
final String longString =
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyy";
for (int i = 0; i < entryCount; i++) {
final Object key = intKey
? random.nextInt(space)
: longString + random.nextInt(space);
if (usePool) {
if (objectPool.add(key) != null) {
++distinctCount;
}
} else {
if (set.add(key)) {
++distinctCount;
}
}
}
final long t2 = System.currentTimeMillis();
int hitCount = 0;
for (int i = 0; i < retrieveCount; i++) {
final Object key = intKey
? random.nextInt(space)
: longString + random.nextInt(space);
if (usePool) {
if (objectPool.contains(key)) {
++hitCount;
}
} else {
if (set.contains(key)) {
++hitCount;
}
}
}
final long t3 = System.currentTimeMillis();
if (usePool) {
// todo: assertEquals(expectedDistinct, objectPool.size());
distinctCount = objectPool.size();
} else {
assertEquals(expectedDistinct, set.size());
}
if (print) {
System.out.println(
"Using " + (usePool ? "ObjectPool" : "HashSet")
+ ", density=" + density
+ ", " + distinctCount + " distinct entries, "
+ hitCount + " hits");
System.out.println(
entryCount + " adds took " + (t2 - t1) + " milliseconds");
System.out.println(
retrieveCount + " gets took " + (t3 - t2) + " milliseconds");
}
assertEquals(expectedDistinct, distinctCount);
assertEquals(expectedHits, hitCount);
}
/////////////////////////////////////////////////////////////////////////
// helpers
/////////////////////////////////////////////////////////////////////////
private static String[] genStringsArray(int nos) {
List l = genStringsList(nos);
return (String[]) l.toArray(new String[l.size()]);
}
private static List<String> genStringsList(int nos) {
List<String> l = new ArrayList<String>(nos);
for (int i = 0; i < nos; i++) {
l.add(Integer.valueOf(i).toString());
}
return l;
}
private static KeyValue[] genKeyValueArray(int nos) {
List<KeyValue> l = genKeyValueList(nos);
return (KeyValue[]) l.toArray(new KeyValue[l.size()]);
}
private static List<KeyValue> genKeyValueList(int nos) {
List<KeyValue> l = new ArrayList<KeyValue>(nos);
for (int i = 0; i < nos; i++) {
l.add(new KeyValue((long)i, Integer.valueOf(i)));
}
return l;
}
}
// End ObjectPoolTest.java
| epl-1.0 |
bradsdavis/cxml-api | src/main/java/org/cxml/invoicedetail/PartialAmount.java | 1297 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.09.23 at 10:57:51 AM CEST
//
package org.cxml.invoicedetail;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"money"
})
@XmlRootElement(name = "PartialAmount")
public class PartialAmount {
@XmlElement(name = "Money", required = true)
protected Money money;
/**
* Gets the value of the money property.
*
* @return
* possible object is
* {@link Money }
*
*/
public Money getMoney() {
return money;
}
/**
* Sets the value of the money property.
*
* @param value
* allowed object is
* {@link Money }
*
*/
public void setMoney(Money value) {
this.money = value;
}
}
| epl-1.0 |
miklossy/xtext-core | org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/testlanguage/TestLanguageRuntimeModule.java | 2191 | /**
* Copyright (c) 2016 TypeFox GmbH (http://www.typefox.io) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.xtext.ide.tests.testlanguage;
import org.eclipse.xtext.formatting2.IFormatter2;
import org.eclipse.xtext.ide.editor.syntaxcoloring.ISemanticHighlightingCalculator;
import org.eclipse.xtext.ide.server.coloring.IColoringService;
import org.eclipse.xtext.ide.server.semanticHighlight.ISemanticHighlightingStyleToTokenMapper;
import org.eclipse.xtext.ide.server.signatureHelp.ISignatureHelpService;
import org.eclipse.xtext.ide.tests.testlanguage.AbstractTestLanguageRuntimeModule;
import org.eclipse.xtext.ide.tests.testlanguage.coloring.ColoringServiceImpl;
import org.eclipse.xtext.ide.tests.testlanguage.editor.syntaxcoloring.SemanticHighlightingCalculatorImpl;
import org.eclipse.xtext.ide.tests.testlanguage.editor.syntaxcoloring.SemanticHighlightingStyleToTokenMapper;
import org.eclipse.xtext.ide.tests.testlanguage.formatting2.TestLanguageFormatter;
import org.eclipse.xtext.ide.tests.testlanguage.signatureHelp.SignatureHelpServiceImpl;
/**
* Use this class to register components to be used at runtime / without the Equinox extension registry.
*/
@SuppressWarnings("all")
public class TestLanguageRuntimeModule extends AbstractTestLanguageRuntimeModule {
public Class<? extends IFormatter2> bindIFormatter2() {
return TestLanguageFormatter.class;
}
public Class<? extends ISignatureHelpService> bindSignatureHelpService() {
return SignatureHelpServiceImpl.class;
}
public Class<? extends IColoringService> bindIColoringService() {
return ColoringServiceImpl.class;
}
public Class<? extends ISemanticHighlightingCalculator> bindISemanticHighlightingCalculator() {
return SemanticHighlightingCalculatorImpl.class;
}
public Class<? extends ISemanticHighlightingStyleToTokenMapper> bindISemanticHighlightingStyleToTokenMapper() {
return SemanticHighlightingStyleToTokenMapper.class;
}
}
| epl-1.0 |
darkpeach/AlgorithmCoding | _143_ReorderList.py | 1023 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if not head or not head.next or not head.next.next:
return
pSlow = head.next
pFast = head.next.next
while pFast and pFast.next:
pSlow = pSlow.next
pFast = pFast.next.next
pFast = pSlow.next
pSlow.next = None
pNext = pFast.next
pFast.next = None
while pNext:
temp = pNext.next
pNext.next = pFast
pFast = pNext
pNext = temp
pSlow = head
while pFast:
pNext = pFast.next
pFast.next = pSlow.next
pSlow.next = pFast
pSlow = pSlow.next.next
pFast = pNext
return | epl-1.0 |
IBM-i2/Data-Acquisition-Accelerators | Data-Acquisition-Accelerators/Acxiom_Accelerator/acxiom-UI/acxiom-visual-studio-project/Acxiom/AcxiomConstants.cs | 4445 | /*******************************************************************************
* Licensed Materials - Property of IBM
* (C) Copyright IBM Corp. 2015 All Rights Reserved
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*******************************************************************************/
using System;
using System.Globalization;
using i2.Apollo.Common;
using i2.Apollo.Common.DependencyInjection;
using i2.Apollo.Common.Preferences;
namespace Acxiom
{
/// <summary>
/// Interface for the external apollo client settings for <see cref="AcxiomConstants"/>.
/// </summary>
[ImplementedBy(typeof(AcxiomConstants), singleton: true)]
public interface IAcxiomConstants
{
/// <summary>
/// Gets the location of the external subset generation UI.
/// </summary>
Uri ExternalSubsetGenerationUri { get; }
/// <summary>
/// Gets external data source (DAOD) context root.
/// </summary>
string AcxiomDaodExternalContextRoot { get; }
/// <summary>
/// Gets the source Path where the external xml files are located.
/// </summary>
string AcxiomDaodXmlSourcePath { get; }
/// <summary>
/// Gets the transform XSLT Path where the external xml files are located.
/// </summary>
string AcxiomDaodTransformSourcePath { get; }
}
/// <summary>
/// Constants used throughout Acxiom to get External Subset Generation Uri and Daod Intent Handler Name
/// </summary>
public class AcxiomConstants : IAcxiomConstants
{
private static readonly string DEFAULT_EXT_CONTEXT_ROOT = "daod";
private static readonly string DEFAULT_XML_SRC_PATH = "c:/i2-integration/xml/";
private static readonly string DEFAULT_NO_TRANSFORM_PATH = ""; //default to empty
// To override these preferences without modifying the xap/dll's add entries to ApolloClientSettings.xml
private static readonly ApplicationPreference<string> GenerationUILocationPreference =
ApplicationPreference.Register("AcxiomUIURL",
ApplicationPreference.DefaultStringParser,
"http://localhost/Acxiom.html");
private static readonly ApplicationPreference<string> DaodExternalContextRoot =
ApplicationPreference.Register("AcxiomDaodExternalContextRoot",
ApplicationPreference.DefaultStringParser,
DEFAULT_EXT_CONTEXT_ROOT);
private static readonly ApplicationPreference<string> DaodXmlSourcePath =
ApplicationPreference.Register("AcxiomDaodXmlSourcePath",
ApplicationPreference.DefaultStringParser,
DEFAULT_XML_SRC_PATH);
private static readonly ApplicationPreference<string> DaodTransformSourcePath =
ApplicationPreference.Register("AcxiomDaodTransformSourcePath",
ApplicationPreference.DefaultStringParser,
DEFAULT_NO_TRANSFORM_PATH);
/// <summary>
/// Initializes a new instance of the <see cref="AcxiomConstants"/> class.
/// </summary>
public AcxiomConstants(IApplicationPreferences applicationPreferences)
{
var generationUi = applicationPreferences.GetValue(GenerationUILocationPreference);
ExternalSubsetGenerationUri = new Uri(generationUi, UriKind.RelativeOrAbsolute);
AcxiomDaodExternalContextRoot = applicationPreferences.GetValue(DaodExternalContextRoot);
AcxiomDaodXmlSourcePath = applicationPreferences.GetValue(DaodXmlSourcePath);
AcxiomDaodTransformSourcePath = applicationPreferences.GetValue(DaodTransformSourcePath);
}
/// <inheritdoc />
public Uri ExternalSubsetGenerationUri { get; private set; }
/// <inheritdoc />
public string AcxiomDaodExternalContextRoot { get; private set; }
/// <inheritdoc />
public string AcxiomDaodXmlSourcePath { get; private set; }
/// <inheritdoc />
public string AcxiomDaodTransformSourcePath { get; private set; }
}
}
| epl-1.0 |
ctron/kura | kura/org.eclipse.kura.core.cloud/src/main/java/org/eclipse/kura/core/cloud/CloudServiceImpl.java | 45772 | /*******************************************************************************
* Copyright (c) 2011, 2021 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech
*******************************************************************************/
package org.eclipse.kura.core.cloud;
import static java.util.Objects.isNull;
import static org.eclipse.kura.cloud.CloudPayloadEncoding.KURA_PROTOBUF;
import static org.eclipse.kura.cloud.CloudPayloadEncoding.SIMPLE_JSON;
import static org.eclipse.kura.configuration.ConfigurationService.KURA_SERVICE_PID;
import static org.eclipse.kura.core.message.MessageConstants.APP_ID;
import static org.eclipse.kura.core.message.MessageConstants.APP_TOPIC;
import static org.eclipse.kura.core.message.MessageConstants.CONTROL;
import static org.eclipse.kura.core.message.MessageConstants.FULL_TOPIC;
import static org.eclipse.kura.core.message.MessageConstants.PRIORITY;
import static org.eclipse.kura.core.message.MessageConstants.QOS;
import static org.eclipse.kura.core.message.MessageConstants.RETAIN;
import static org.osgi.framework.Constants.SERVICE_PID;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.eclipse.kura.KuraConnectException;
import org.eclipse.kura.KuraErrorCode;
import org.eclipse.kura.KuraException;
import org.eclipse.kura.KuraInvalidMessageException;
import org.eclipse.kura.certificate.CertificatesService;
import org.eclipse.kura.cloud.CloudClient;
import org.eclipse.kura.cloud.CloudConnectionEstablishedEvent;
import org.eclipse.kura.cloud.CloudConnectionLostEvent;
import org.eclipse.kura.cloud.CloudPayloadEncoding;
import org.eclipse.kura.cloud.CloudPayloadProtoBufDecoder;
import org.eclipse.kura.cloud.CloudPayloadProtoBufEncoder;
import org.eclipse.kura.cloud.CloudService;
import org.eclipse.kura.cloudconnection.CloudConnectionManager;
import org.eclipse.kura.cloudconnection.CloudEndpoint;
import org.eclipse.kura.cloudconnection.listener.CloudConnectionListener;
import org.eclipse.kura.cloudconnection.listener.CloudDeliveryListener;
import org.eclipse.kura.cloudconnection.message.KuraMessage;
import org.eclipse.kura.cloudconnection.publisher.CloudNotificationPublisher;
import org.eclipse.kura.cloudconnection.request.RequestHandler;
import org.eclipse.kura.cloudconnection.request.RequestHandlerRegistry;
import org.eclipse.kura.cloudconnection.subscriber.listener.CloudSubscriberListener;
import org.eclipse.kura.configuration.ConfigurableComponent;
import org.eclipse.kura.configuration.ConfigurationService;
import org.eclipse.kura.core.cloud.publisher.NotificationPublisherImpl;
import org.eclipse.kura.core.cloud.subscriber.CloudSubscriptionRecord;
import org.eclipse.kura.core.data.DataServiceImpl;
import org.eclipse.kura.data.DataService;
import org.eclipse.kura.data.listener.DataServiceListener;
import org.eclipse.kura.marshalling.Marshaller;
import org.eclipse.kura.marshalling.Unmarshaller;
import org.eclipse.kura.message.KuraApplicationTopic;
import org.eclipse.kura.message.KuraPayload;
import org.eclipse.kura.net.NetworkService;
import org.eclipse.kura.net.modem.ModemReadyEvent;
import org.eclipse.kura.position.PositionLockedEvent;
import org.eclipse.kura.position.PositionService;
import org.eclipse.kura.security.tamper.detection.TamperDetectionService;
import org.eclipse.kura.security.tamper.detection.TamperEvent;
import org.eclipse.kura.system.SystemAdminService;
import org.eclipse.kura.system.SystemService;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CloudServiceImpl
implements CloudService, DataServiceListener, ConfigurableComponent, EventHandler, CloudPayloadProtoBufEncoder,
CloudPayloadProtoBufDecoder, RequestHandlerRegistry, CloudConnectionManager, CloudEndpoint {
private static final String ERROR = "ERROR";
private static final String NOTIFICATION_PUBLISHER_PID = "org.eclipse.kura.cloud.publisher.CloudNotificationPublisher";
private static final Logger logger = LoggerFactory.getLogger(CloudServiceImpl.class);
private static final String TOPIC_BA_APP = "BA";
private static final String TOPIC_MQTT_APP = "MQTT";
private static final String CONNECTION_EVENT_PID_PROPERTY_KEY = "cloud.service.pid";
private static final int NUM_CONCURRENT_CALLBACKS = 2;
private static ExecutorService callbackExecutor = Executors.newFixedThreadPool(NUM_CONCURRENT_CALLBACKS);
private ComponentContext ctx;
private CloudServiceOptions options;
private DataService dataService;
private SystemService systemService;
private SystemAdminService systemAdminService;
private NetworkService networkService;
private PositionService positionService;
private EventAdmin eventAdmin;
private CertificatesService certificatesService;
private Unmarshaller jsonUnmarshaller;
private Marshaller jsonMarshaller;
// use a synchronized implementation for the list
private final List<CloudClientImpl> cloudClients;
private final Set<CloudConnectionListener> registeredCloudConnectionListeners;
private final Set<CloudPublisherDeliveryListener> registeredCloudPublisherDeliveryListeners;
private final Set<CloudDeliveryListener> registeredCloudDeliveryListeners;
private final Map<CloudSubscriptionRecord, List<CloudSubscriberListener>> registeredSubscribers;
// package visibility for LyfeCyclePayloadBuilder
String imei;
String iccid;
String imsi;
String rssi;
String modemFwVer;
private boolean subscribed;
private boolean birthPublished;
private final AtomicInteger messageId;
private ServiceRegistration<?> cloudServiceRegistration;
private final Map<String, RequestHandler> registeredRequestHandlers;
private ServiceRegistration<?> notificationPublisherRegistration;
private final CloudNotificationPublisher notificationPublisher;
private Set<TamperDetectionService> tamperDetectionServices = new HashSet<>();
private String ownPid;
public CloudServiceImpl() {
this.cloudClients = new CopyOnWriteArrayList<>();
this.messageId = new AtomicInteger();
this.registeredRequestHandlers = new HashMap<>();
this.registeredSubscribers = new ConcurrentHashMap<>();
this.registeredCloudConnectionListeners = new CopyOnWriteArraySet<>();
this.registeredCloudPublisherDeliveryListeners = new CopyOnWriteArraySet<>();
this.registeredCloudDeliveryListeners = new CopyOnWriteArraySet<>();
this.notificationPublisher = new NotificationPublisherImpl(this);
}
// ----------------------------------------------------------------
//
// Dependencies
//
// ----------------------------------------------------------------
public void setDataService(DataService dataService) {
this.dataService = dataService;
}
public void unsetDataService(DataService dataService) {
this.dataService = null;
}
public DataService getDataService() {
return this.dataService;
}
public void setSystemAdminService(SystemAdminService systemAdminService) {
this.systemAdminService = systemAdminService;
}
public void unsetSystemAdminService(SystemAdminService systemAdminService) {
this.systemAdminService = null;
}
public SystemAdminService getSystemAdminService() {
return this.systemAdminService;
}
public void setSystemService(SystemService systemService) {
this.systemService = systemService;
}
public void unsetSystemService(SystemService systemService) {
this.systemService = null;
}
public SystemService getSystemService() {
return this.systemService;
}
public void setNetworkService(NetworkService networkService) {
this.networkService = networkService;
}
public void unsetNetworkService(NetworkService networkService) {
this.networkService = null;
}
public NetworkService getNetworkService() {
return this.networkService;
}
public void setPositionService(PositionService positionService) {
this.positionService = positionService;
}
public void unsetPositionService(PositionService positionService) {
this.positionService = null;
}
public PositionService getPositionService() {
return this.positionService;
}
public void setEventAdmin(EventAdmin eventAdmin) {
this.eventAdmin = eventAdmin;
}
public void unsetEventAdmin(EventAdmin eventAdmin) {
this.eventAdmin = null;
}
public void setJsonUnmarshaller(Unmarshaller jsonUnmarshaller) {
this.jsonUnmarshaller = jsonUnmarshaller;
}
public void unsetJsonUnmarshaller(Unmarshaller jsonUnmarshaller) {
this.jsonUnmarshaller = null;
}
public void setJsonMarshaller(Marshaller jsonMarshaller) {
this.jsonMarshaller = jsonMarshaller;
}
public void unsetJsonMarshaller(Marshaller jsonMarshaller) {
this.jsonMarshaller = null;
}
public void setTamperDetectionService(final TamperDetectionService tamperDetectionService) {
synchronized (this.tamperDetectionServices) {
this.tamperDetectionServices.add(tamperDetectionService);
}
}
public void unsetTamperDetectionService(final TamperDetectionService tamperDetectionService) {
synchronized (this.tamperDetectionServices) {
this.tamperDetectionServices.remove(tamperDetectionService);
}
}
// ----------------------------------------------------------------
//
// Activation APIs
//
// ----------------------------------------------------------------
protected void activate(ComponentContext componentContext, Map<String, Object> properties) {
this.ownPid = (String) properties.get(ConfigurationService.KURA_SERVICE_PID);
logger.info("activate {}...", ownPid);
//
// save the bundle context and the properties
this.ctx = componentContext;
this.options = new CloudServiceOptions(properties, this.systemService);
//
// install event listener for GPS locked event
Dictionary<String, Object> props = new Hashtable<>();
String[] eventTopics = { PositionLockedEvent.POSITION_LOCKED_EVENT_TOPIC,
ModemReadyEvent.MODEM_EVENT_READY_TOPIC, TamperEvent.TAMPER_EVENT_TOPIC };
props.put(EventConstants.EVENT_TOPIC, eventTopics);
this.cloudServiceRegistration = this.ctx.getBundleContext().registerService(EventHandler.class.getName(), this,
props);
this.dataService.addDataServiceListener(this);
Dictionary<String, Object> notificationPublisherProps = new Hashtable<>();
notificationPublisherProps.put(KURA_SERVICE_PID, NOTIFICATION_PUBLISHER_PID);
notificationPublisherProps.put(SERVICE_PID, NOTIFICATION_PUBLISHER_PID);
this.notificationPublisherRegistration = this.ctx.getBundleContext().registerService(
CloudNotificationPublisher.class.getName(), this.notificationPublisher, notificationPublisherProps);
//
// Usually the cloud connection is setup in the
// onConnectionEstablished callback.
// Since the callback may be lost if we are activated
// too late (the DataService is already connected) we
// setup the cloud connection here.
if (isConnected()) {
logger.warn("DataService is already connected. Publish BIRTH certificate");
try {
setupCloudConnection(true);
} catch (KuraException e) {
logger.warn("Cannot setup cloud service connection", e);
}
}
}
public void updated(Map<String, Object> properties) {
logger.info("updated {}...", properties.get(ConfigurationService.KURA_SERVICE_PID));
// Update properties and re-publish Birth certificate
this.options = new CloudServiceOptions(properties, this.systemService);
if (isConnected()) {
try {
setupCloudConnection(false);
} catch (KuraException e) {
logger.warn("Cannot setup cloud service connection");
}
}
}
protected void deactivate(ComponentContext componentContext) {
logger.info("deactivate {}...", componentContext.getProperties().get(ConfigurationService.KURA_SERVICE_PID));
if (isConnected()) {
try {
publishDisconnectCertificate();
} catch (KuraException e) {
logger.warn("Cannot publish disconnect certificate");
}
}
this.dataService.removeDataServiceListener(this);
// no need to release the cloud clients as the updated app
// certificate is already published due the missing dependency
// we only need to empty our CloudClient list
this.cloudClients.clear();
this.dataService = null;
this.systemService = null;
this.systemAdminService = null;
this.networkService = null;
this.positionService = null;
this.eventAdmin = null;
this.certificatesService = null;
this.cloudServiceRegistration.unregister();
this.notificationPublisherRegistration.unregister();
}
@Override
public void handleEvent(Event event) {
if (PositionLockedEvent.POSITION_LOCKED_EVENT_TOPIC.contains(event.getTopic())) {
handlePositionLockedEvent();
} else if (ModemReadyEvent.MODEM_EVENT_READY_TOPIC.contains(event.getTopic())) {
handleModemReadyEvent(event);
} else if (TamperEvent.TAMPER_EVENT_TOPIC.equals(event.getTopic()) && this.dataService.isConnected()
&& this.options.getRepubBirthCertOnTamperEvent()) {
tryPublishBirthCertificate();
}
}
private void tryPublishBirthCertificate() {
try {
publishBirthCertificate();
} catch (KuraException e) {
logger.warn("Cannot publish birth certificate", e);
}
}
private void handleModemReadyEvent(Event event) {
logger.info("Handling ModemReadyEvent");
ModemReadyEvent modemReadyEvent = (ModemReadyEvent) event;
// keep these identifiers around until we can publish the certificate
this.imei = (String) modemReadyEvent.getProperty(ModemReadyEvent.IMEI);
this.imsi = (String) modemReadyEvent.getProperty(ModemReadyEvent.IMSI);
this.iccid = (String) modemReadyEvent.getProperty(ModemReadyEvent.ICCID);
this.rssi = (String) modemReadyEvent.getProperty(ModemReadyEvent.RSSI);
this.modemFwVer = (String) modemReadyEvent.getProperty(ModemReadyEvent.FW_VERSION);
logger.trace("handleEvent() :: IMEI={}", this.imei);
logger.trace("handleEvent() :: IMSI={}", this.imsi);
logger.trace("handleEvent() :: ICCID={}", this.iccid);
logger.trace("handleEvent() :: RSSI={}", this.rssi);
logger.trace("handleEvent() :: FW_VERSION={}", this.modemFwVer);
if (this.dataService.isConnected() && this.options.getRepubBirthCertOnModemDetection() && isModemInfoValid()) {
logger.debug("handleEvent() :: publishing BIRTH certificate ...");
tryPublishBirthCertificate();
}
}
private boolean isModemInfoValid(final String modemInfo) {
return !(modemInfo == null || modemInfo.length() == 0 || modemInfo.equals(ERROR));
}
public boolean isModemInfoValid() {
return isModemInfoValid(this.imei) && isModemInfoValid(this.imsi) && isModemInfoValid(this.iccid);
}
private void handlePositionLockedEvent() {
// if we get a position locked event,
// republish the birth certificate only if we are configured to
logger.info("Handling PositionLockedEvent");
if (this.dataService.isConnected() && this.options.getRepubBirthCertOnGpsLock()) {
tryPublishBirthCertificate();
}
}
// ----------------------------------------------------------------
//
// Service APIs
//
// ----------------------------------------------------------------
@Override
public CloudClient newCloudClient(String applicationId) throws KuraException {
// create new instance
CloudClientImpl cloudClient = new CloudClientImpl(applicationId, this.dataService, this);
this.cloudClients.add(cloudClient);
// publish updated birth certificate with list of active apps
if (isConnected()) {
publishAppCertificate();
}
// return
return cloudClient;
}
@Override
public String[] getCloudApplicationIdentifiers() {
List<String> appIds = new ArrayList<>();
for (CloudClientImpl cloudClient : this.cloudClients) {
appIds.add(cloudClient.getApplicationId());
}
for (Entry<String, RequestHandler> entry : this.registeredRequestHandlers.entrySet()) {
appIds.add(entry.getKey());
}
return appIds.toArray(new String[0]);
}
@Override
public boolean isConnected() {
return this.dataService != null && this.dataService.isConnected();
}
// ----------------------------------------------------------------
//
// Package APIs
//
// ----------------------------------------------------------------
public CloudServiceOptions getCloudServiceOptions() {
return this.options;
}
public void removeCloudClient(CloudClientImpl cloudClient) {
// remove the client
this.cloudClients.remove(cloudClient);
// publish updated birth certificate with updated list of active apps
if (isConnected()) {
try {
publishAppCertificate();
} catch (KuraException e) {
logger.warn("Cannot publish app certificate");
}
}
}
public byte[] encodePayload(KuraPayload payload) throws KuraException {
byte[] bytes;
CloudPayloadEncoding preferencesEncoding = this.options.getPayloadEncoding();
if (preferencesEncoding == KURA_PROTOBUF) {
bytes = encodeProtobufPayload(payload);
} else if (preferencesEncoding == SIMPLE_JSON) {
bytes = encodeJsonPayload(payload);
} else {
throw new KuraException(KuraErrorCode.ENCODE_ERROR, "KuraPayload");
}
return bytes;
}
// ----------------------------------------------------------------
//
// DataServiceListener API
//
// ----------------------------------------------------------------
@Override
public void onConnectionEstablished() {
try {
setupCloudConnection(true);
} catch (KuraException e) {
logger.warn("Cannot setup cloud service connection");
}
this.registeredSubscribers.keySet().forEach(this::subscribe);
postConnectionStateChangeEvent(true);
this.cloudClients.forEach(CloudClientImpl::onConnectionEstablished);
this.registeredCloudConnectionListeners.forEach(CloudConnectionListener::onConnectionEstablished);
}
private void setupDeviceSubscriptions(boolean subscribe) throws KuraException {
StringBuilder sbDeviceSubscription = new StringBuilder();
sbDeviceSubscription.append(this.options.getTopicControlPrefix())
.append(CloudServiceOptions.getTopicSeparator()).append(CloudServiceOptions.getTopicAccountToken())
.append(CloudServiceOptions.getTopicSeparator()).append(CloudServiceOptions.getTopicClientIdToken())
.append(CloudServiceOptions.getTopicSeparator()).append(CloudServiceOptions.getTopicWildCard());
// restore or remove default subscriptions
if (subscribe) {
this.dataService.subscribe(sbDeviceSubscription.toString(), 1);
} else {
this.dataService.unsubscribe(sbDeviceSubscription.toString());
}
}
@Override
public void onDisconnecting() {
// publish disconnect certificate
try {
publishDisconnectCertificate();
} catch (KuraException e) {
logger.warn("Cannot publish disconnect certificate");
}
this.birthPublished = false;
}
@Override
public void onDisconnected() {
// raise event
postConnectionStateChangeEvent(false);
this.registeredCloudConnectionListeners.forEach(CloudConnectionListener::onDisconnected);
}
@Override
public void onConnectionLost(Throwable cause) {
// raise event
postConnectionStateChangeEvent(false);
this.cloudClients.forEach(CloudClientImpl::onConnectionLost);
this.registeredCloudConnectionListeners.forEach(CloudConnectionListener::onConnectionLost);
}
@Override
public void onMessageArrived(String topic, byte[] payload, int qos, boolean retained) {
logger.info("Message arrived on topic: {}", topic);
// notify listeners
KuraTopicImpl kuraTopic = new KuraTopicImpl(topic, this.options.getTopicControlPrefix());
if (TOPIC_MQTT_APP.equals(kuraTopic.getApplicationId()) || TOPIC_BA_APP.equals(kuraTopic.getApplicationId())) {
logger.info("Ignoring feedback message from {}", topic);
} else {
KuraPayload kuraPayload = encodeKuraPayload(topic, payload);
try {
if (this.options.getTopicControlPrefix().equals(kuraTopic.getPrefix())) {
boolean validMessage = isValidMessage(kuraTopic, kuraPayload);
if (validMessage) {
dispatchControlMessage(qos, retained, kuraTopic, kuraPayload);
} else {
logger.warn("Message verification failed! Not valid signature or message not signed.");
}
} else {
dispatchDataMessage(qos, retained, kuraTopic, kuraPayload);
}
} catch (Exception e) {
logger.error("Error during CloudClientListener notification.", e);
}
}
}
private KuraPayload encodeKuraPayload(String topic, byte[] payload) {
KuraPayload kuraPayload = null;
if (this.options.getPayloadEncoding() == SIMPLE_JSON) {
try {
kuraPayload = createKuraPayloadFromJson(payload);
} catch (KuraException e) {
logger.warn("Error creating Kura Payload from Json", e);
}
} else if (this.options.getPayloadEncoding() == KURA_PROTOBUF) {
kuraPayload = createKuraPayloadFromProtoBuf(topic, payload);
}
return kuraPayload;
}
private void dispatchControlMessage(int qos, boolean retained, KuraTopicImpl kuraTopic, KuraPayload kuraPayload) {
String applicationId = kuraTopic.getApplicationId();
RequestHandler cloudlet = this.registeredRequestHandlers.get(applicationId);
if (cloudlet != null) {
StringBuilder sb = new StringBuilder(applicationId).append("/").append("REPLY");
if (kuraTopic.getApplicationTopic().startsWith(sb.toString())) {
// Ignore replies
return;
}
callbackExecutor.submit(new MessageHandlerCallable(cloudlet, applicationId, kuraTopic.getApplicationTopic(),
kuraPayload, this));
}
this.cloudClients.stream()
.filter(cloudClient -> cloudClient.getApplicationId().equals(kuraTopic.getApplicationId()))
.forEach(cloudClient -> cloudClient.onControlMessageArrived(kuraTopic.getDeviceId(),
kuraTopic.getApplicationTopic(), kuraPayload, qos, retained));
Map<String, Object> properties = new HashMap<>();
properties.put("deviceId", kuraTopic.getDeviceId());
properties.put("appTopic", kuraTopic.getApplicationTopic());
KuraMessage receivedMessage = new KuraMessage(kuraPayload, properties);
this.registeredSubscribers.entrySet().stream()
.filter(cloudSubscriberEntry -> cloudSubscriberEntry.getKey().matches(kuraTopic.getFullTopic()))
.forEach(e -> dispatchMessage(receivedMessage, e.getValue()));
}
private void dispatchDataMessage(int qos, boolean retained, KuraTopicImpl kuraTopic, KuraPayload kuraPayload) {
this.cloudClients.stream()
.filter(cloudClient -> cloudClient.getApplicationId().equals(kuraTopic.getApplicationId()))
.forEach(cloudClient -> cloudClient.onMessageArrived(kuraTopic.getDeviceId(),
kuraTopic.getApplicationTopic(), kuraPayload, qos, retained));
Map<String, Object> properties = new HashMap<>();
properties.put("deviceId", kuraTopic.getDeviceId());
properties.put("appTopic", kuraTopic.getApplicationTopic());
KuraMessage receivedMessage = new KuraMessage(kuraPayload, properties);
this.registeredSubscribers.entrySet().stream()
.filter(cloudSubscriberEntry -> cloudSubscriberEntry.getKey().matches(kuraTopic.getFullTopic()))
.forEach(e -> dispatchMessage(receivedMessage, e.getValue()));
}
private static void dispatchMessage(final KuraMessage message, final List<CloudSubscriberListener> listeners) {
for (final CloudSubscriberListener listener : listeners) {
try {
listener.onMessageArrived(message);
} catch (final Exception e) {
logger.warn("unhandled exception in CloudSubscriberListener", e);
}
}
}
private boolean isValidMessage(KuraApplicationTopic kuraTopic, KuraPayload kuraPayload) {
if (this.certificatesService == null) {
ServiceReference<CertificatesService> sr = this.ctx.getBundleContext()
.getServiceReference(CertificatesService.class);
if (sr != null) {
this.certificatesService = this.ctx.getBundleContext().getService(sr);
}
}
boolean validMessage = false;
if (this.certificatesService == null || this.certificatesService.verifySignature(kuraTopic, kuraPayload)) {
validMessage = true;
}
return validMessage;
}
@Override
public void onMessagePublished(int messageId, String topic) {
synchronized (this.messageId) {
if (this.messageId.get() != -1 && this.messageId.get() == messageId) {
if (CloudServiceOptions.getLifeCycleMessageQos() == 0) {
this.messageId.set(-1);
}
this.messageId.notifyAll();
return;
}
}
// notify listeners
KuraApplicationTopic kuraTopic = new KuraTopicImpl(topic, this.options.getTopicControlPrefix());
this.cloudClients.stream()
.filter(cloudClient -> cloudClient.getApplicationId().equals(kuraTopic.getApplicationId()))
.collect(Collectors.toList())
.forEach(cloudClient -> cloudClient.onMessagePublished(messageId, kuraTopic.getApplicationTopic()));
}
@Override
public void onMessageConfirmed(int messageId, String topic) {
synchronized (this.messageId) {
if (this.messageId.get() != -1 && this.messageId.get() == messageId) {
this.messageId.set(-1);
this.messageId.notifyAll();
return;
}
}
// notify listeners
KuraApplicationTopic kuraTopic = new KuraTopicImpl(topic, this.options.getTopicControlPrefix());
this.cloudClients.stream()
.filter(cloudClient -> cloudClient.getApplicationId().equals(kuraTopic.getApplicationId()))
.collect(Collectors.toList())
.forEach(cloudClient -> cloudClient.onMessageConfirmed(messageId, kuraTopic.getApplicationTopic()));
this.registeredCloudPublisherDeliveryListeners
.forEach(deliveryListener -> deliveryListener.onMessageConfirmed(String.valueOf(messageId), topic));
this.registeredCloudDeliveryListeners
.forEach(deliveryListener -> deliveryListener.onMessageConfirmed(String.valueOf(messageId)));
}
// ----------------------------------------------------------------
//
// CloudPayloadProtoBufEncoder API
//
// ----------------------------------------------------------------
@Override
public byte[] getBytes(KuraPayload kuraPayload, boolean gzipped) throws KuraException {
CloudPayloadEncoder encoder = new CloudPayloadProtoBufEncoderImpl(kuraPayload);
if (gzipped) {
encoder = new CloudPayloadGZipEncoder(encoder);
}
byte[] bytes;
try {
bytes = encoder.getBytes();
return bytes;
} catch (IOException e) {
throw new KuraException(KuraErrorCode.ENCODE_ERROR, "KuraPayload", e);
}
}
// ----------------------------------------------------------------
//
// CloudPayloadProtoBufDecoder API
//
// ----------------------------------------------------------------
@Override
public KuraPayload buildFromByteArray(byte[] payload) throws KuraException {
CloudPayloadProtoBufDecoderImpl encoder = new CloudPayloadProtoBufDecoderImpl(payload);
KuraPayload kuraPayload;
try {
kuraPayload = encoder.buildFromByteArray();
return kuraPayload;
} catch (KuraInvalidMessageException | IOException e) {
throw new KuraException(KuraErrorCode.DECODER_ERROR, "KuraPayload", e);
}
}
// ----------------------------------------------------------------
//
// Birth and Disconnect Certificates
//
// ----------------------------------------------------------------
private void setupCloudConnection(boolean onConnect) throws KuraException {
// assume we are not yet subscribed
if (onConnect) {
this.subscribed = false;
}
// publish birth certificate unless it has already been published
// and republish is disabled
boolean publishBirth = true;
if (this.birthPublished && !this.options.getRepubBirthCertOnReconnect()) {
publishBirth = false;
logger.info("Birth certificate republish is disabled in configuration");
}
// publish birth certificate
if (publishBirth) {
publishBirthCertificate();
this.birthPublished = true;
}
// restore or remove default subscriptions
if (this.options.getEnableDefaultSubscriptions()) {
if (!this.subscribed) {
setupDeviceSubscriptions(true);
this.subscribed = true;
}
} else {
logger.info("Default subscriptions are disabled in configuration");
if (this.subscribed) {
setupDeviceSubscriptions(false);
this.subscribed = false;
}
}
}
private void publishBirthCertificate() throws KuraException {
if (this.options.isLifecycleCertsDisabled()) {
return;
}
StringBuilder sbTopic = new StringBuilder();
sbTopic.append(this.options.getTopicControlPrefix()).append(CloudServiceOptions.getTopicSeparator())
.append(CloudServiceOptions.getTopicAccountToken()).append(CloudServiceOptions.getTopicSeparator())
.append(CloudServiceOptions.getTopicClientIdToken()).append(CloudServiceOptions.getTopicSeparator())
.append(CloudServiceOptions.getTopicBirthSuffix());
String topic = sbTopic.toString();
KuraPayload payload = createBirthPayload();
publishLifeCycleMessage(topic, payload);
}
private void publishDisconnectCertificate() throws KuraException {
if (this.options.isLifecycleCertsDisabled()) {
return;
}
StringBuilder sbTopic = new StringBuilder();
sbTopic.append(this.options.getTopicControlPrefix()).append(CloudServiceOptions.getTopicSeparator())
.append(CloudServiceOptions.getTopicAccountToken()).append(CloudServiceOptions.getTopicSeparator())
.append(CloudServiceOptions.getTopicClientIdToken()).append(CloudServiceOptions.getTopicSeparator())
.append(CloudServiceOptions.getTopicDisconnectSuffix());
String topic = sbTopic.toString();
KuraPayload payload = createDisconnectPayload();
publishLifeCycleMessage(topic, payload);
}
private void publishAppCertificate() throws KuraException {
if (this.options.isLifecycleCertsDisabled()) {
return;
}
StringBuilder sbTopic = new StringBuilder();
sbTopic.append(this.options.getTopicControlPrefix()).append(CloudServiceOptions.getTopicSeparator())
.append(CloudServiceOptions.getTopicAccountToken()).append(CloudServiceOptions.getTopicSeparator())
.append(CloudServiceOptions.getTopicClientIdToken()).append(CloudServiceOptions.getTopicSeparator())
.append(CloudServiceOptions.getTopicAppsSuffix());
String topic = sbTopic.toString();
KuraPayload payload = createBirthPayload();
publishLifeCycleMessage(topic, payload);
}
private KuraPayload createBirthPayload() {
LifeCyclePayloadBuilder payloadBuilder = new LifeCyclePayloadBuilder(this);
return payloadBuilder.buildBirthPayload();
}
private KuraPayload createDisconnectPayload() {
LifeCyclePayloadBuilder payloadBuilder = new LifeCyclePayloadBuilder(this);
return payloadBuilder.buildDisconnectPayload();
}
private void publishLifeCycleMessage(String topic, KuraPayload payload) throws KuraException {
// track the message ID and block until the message
// has been published (i.e. written to the socket).
synchronized (this.messageId) {
this.messageId.set(-1);
// add a timestamp to the message
payload.setTimestamp(new Date());
byte[] encodedPayload = encodePayload(payload);
int messageId = this.dataService.publish(topic, encodedPayload,
CloudServiceOptions.getLifeCycleMessageQos(), CloudServiceOptions.getLifeCycleMessageRetain(),
CloudServiceOptions.getLifeCycleMessagePriority());
this.messageId.set(messageId);
try {
this.messageId.wait(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.info("Interrupted while waiting for the message to be published", e);
}
}
}
private byte[] encodeProtobufPayload(KuraPayload payload) throws KuraException {
byte[] bytes = new byte[0];
if (payload == null) {
return bytes;
}
CloudPayloadEncoder encoder = new CloudPayloadProtoBufEncoderImpl(payload);
if (this.options.getEncodeGzip()) {
encoder = new CloudPayloadGZipEncoder(encoder);
}
try {
bytes = encoder.getBytes();
} catch (IOException e) {
throw new KuraException(KuraErrorCode.ENCODE_ERROR, "KuraPayload", e);
}
return bytes;
}
private byte[] encodeJsonPayload(KuraPayload payload) throws KuraException {
return this.jsonMarshaller.marshal(payload).getBytes(StandardCharsets.UTF_8);
}
private KuraPayload createKuraPayloadFromJson(byte[] payload) throws KuraException {
return this.jsonUnmarshaller.unmarshal(new String(payload), KuraPayload.class);
}
private KuraPayload createKuraPayloadFromProtoBuf(String topic, byte[] payload) {
KuraPayload kuraPayload;
try {
// try to decode the message into an KuraPayload
kuraPayload = new CloudPayloadProtoBufDecoderImpl(payload).buildFromByteArray();
} catch (Exception e) {
// Wrap the received bytes payload into an KuraPayload
logger.debug("Received message on topic {} that could not be decoded. Wrapping it into an KuraPayload.",
topic);
kuraPayload = new KuraPayload();
kuraPayload.setBody(payload);
}
return kuraPayload;
}
private void postConnectionStateChangeEvent(final boolean isConnected) {
final Map<String, Object> eventProperties = Collections.singletonMap(CONNECTION_EVENT_PID_PROPERTY_KEY,
(String) this.ctx.getProperties().get(ConfigurationService.KURA_SERVICE_PID));
final Event event = isConnected ? new CloudConnectionEstablishedEvent(eventProperties)
: new CloudConnectionLostEvent(eventProperties);
this.eventAdmin.postEvent(event);
}
@Override
public void registerRequestHandler(String appId, RequestHandler requestHandler) {
this.registeredRequestHandlers.put(appId, requestHandler);
if (isConnected()) {
try {
publishAppCertificate();
} catch (KuraException e) {
logger.warn("Unable to publish updated App Certificate");
}
}
}
@Override
public void unregister(String appId) {
this.registeredRequestHandlers.remove(appId);
if (isConnected()) {
try {
publishAppCertificate();
} catch (KuraException e) {
logger.warn("Unable to publish updated App Certificate");
}
}
}
@Override
public void connect() throws KuraConnectException {
if (this.dataService != null) {
this.dataService.connect();
}
}
@Override
public void disconnect() {
if (this.dataService != null) {
this.dataService.disconnect(10);
}
}
@Override
public Map<String, String> getInfo() {
DataServiceImpl dataServiceImpl = (DataServiceImpl) this.dataService;
return dataServiceImpl.getConnectionInfo();
}
public String getNotificationPublisherPid() {
return NOTIFICATION_PUBLISHER_PID;
}
public CloudNotificationPublisher getNotificationPublisher() {
return this.notificationPublisher;
}
@Override
public void registerCloudConnectionListener(CloudConnectionListener cloudConnectionListener) {
this.registeredCloudConnectionListeners.add(cloudConnectionListener);
}
@Override
public void unregisterCloudConnectionListener(CloudConnectionListener cloudConnectionListener) {
this.registeredCloudConnectionListeners.remove(cloudConnectionListener);
}
public void registerCloudPublisherDeliveryListener(CloudPublisherDeliveryListener cloudPublisherDeliveryListener) {
this.registeredCloudPublisherDeliveryListeners.add(cloudPublisherDeliveryListener);
}
public void unregisterCloudPublisherDeliveryListener(
CloudPublisherDeliveryListener cloudPublisherDeliveryListener) {
this.registeredCloudPublisherDeliveryListeners.remove(cloudPublisherDeliveryListener);
}
@Override
public String publish(KuraMessage message) throws KuraException {
Map<String, Object> messageProps = message.getProperties();
int qos = (Integer) messageProps.get(QOS.name());
boolean retain = (Boolean) messageProps.get(RETAIN.name());
int priority = (Integer) messageProps.get(PRIORITY.name());
String fullTopic = (String) messageProps.get(FULL_TOPIC.name());
if (isNull(fullTopic)) {
String appId = (String) messageProps.get(APP_ID.name());
String appTopic = (String) messageProps.get(APP_TOPIC.name());
boolean isControl = (Boolean) messageProps.get(CONTROL.name());
String deviceId = CloudServiceOptions.getTopicClientIdToken();
fullTopic = encodeTopic(appId, deviceId, appTopic, isControl);
}
byte[] appPayload = encodePayload(message.getPayload());
int id = this.dataService.publish(fullTopic, appPayload, qos, retain, priority);
if (qos == 0) {
return null;
}
return String.valueOf(id);
}
@Override
public void registerSubscriber(Map<String, Object> subscriptionProperties, CloudSubscriberListener subscriber) {
String appId = (String) subscriptionProperties.get(APP_ID.name());
String appTopic = (String) subscriptionProperties.get(APP_TOPIC.name());
int qos = (Integer) subscriptionProperties.get(QOS.name());
boolean isControl = (Boolean) subscriptionProperties.get(CONTROL.name());
if (isNull(appId) || isNull(appTopic)) {
return;
}
String fullTopic = encodeTopic(appId, CloudServiceOptions.getTopicClientIdToken(), appTopic, isControl);
CloudSubscriptionRecord subscriptionRecord = new CloudSubscriptionRecord(fullTopic, qos);
final List<CloudSubscriberListener> subscribers;
synchronized (this) {
subscribers = this.registeredSubscribers.compute(subscriptionRecord, (t, list) -> {
if (list == null) {
return new CopyOnWriteArrayList<>(Collections.singletonList(subscriber));
}
list.add(subscriber);
return list;
});
}
if (subscribers.size() == 1) {
subscribe(subscriptionRecord);
}
}
@Override
public void unregisterSubscriber(CloudSubscriberListener subscriber) {
final List<CloudSubscriptionRecord> toUnsubscribe = new ArrayList<>();
synchronized (this) {
this.registeredSubscribers.entrySet().removeIf(e -> {
final List<CloudSubscriberListener> subscribers = e.getValue();
subscribers.removeIf(s -> s == subscriber);
if (subscribers.isEmpty()) {
toUnsubscribe.add(e.getKey());
return true;
} else {
return false;
}
});
}
for (final CloudSubscriptionRecord subscription : toUnsubscribe) {
unsubscribe(subscription);
}
}
private synchronized void subscribe(CloudSubscriptionRecord subscriptionRecord) {
String fullTopic = subscriptionRecord.getTopic();
int qos = subscriptionRecord.getQos();
try {
this.dataService.subscribe(fullTopic, qos);
} catch (KuraException e) {
logger.info("Failed to subscribe");
}
}
private synchronized void unsubscribe(CloudSubscriptionRecord subscriptionRecord) {
String fullTopic = subscriptionRecord.getTopic();
try {
this.dataService.unsubscribe(fullTopic);
} catch (KuraException e) {
logger.info("Failed to unsubscribe");
}
}
private String encodeTopic(String appId, String deviceId, String appTopic, boolean isControl) {
StringBuilder sb = new StringBuilder();
if (isControl) {
sb.append(this.options.getTopicControlPrefix()).append(CloudServiceOptions.getTopicSeparator());
}
sb.append(CloudServiceOptions.getTopicAccountToken()).append(CloudServiceOptions.getTopicSeparator())
.append(deviceId).append(CloudServiceOptions.getTopicSeparator()).append(appId);
if (appTopic != null && !appTopic.isEmpty()) {
sb.append(CloudServiceOptions.getTopicSeparator()).append(appTopic);
}
return sb.toString();
}
@Override
public void registerCloudDeliveryListener(CloudDeliveryListener cloudDeliveryListener) {
this.registeredCloudDeliveryListeners.add(cloudDeliveryListener);
}
@Override
public void unregisterCloudDeliveryListener(CloudDeliveryListener cloudDeliveryListener) {
this.registeredCloudDeliveryListeners.remove(cloudDeliveryListener);
}
String getOwnPid() {
return ownPid;
}
void withTamperDetectionServices(final Consumer<Set<TamperDetectionService>> consumer) {
synchronized (this.tamperDetectionServices) {
consumer.accept(this.tamperDetectionServices);
}
}
}
| epl-1.0 |
zolko/onlab | orientdbenchmark/src/main/java/hu/bme/mit/trainbenchmark/benchmark/orientdb/benchmarkcases/OrientDbRouteSensorChecker.java | 115 | package hu.bme.mit.trainbenchmark.benchmark.orientdb.benchmarkcases;
public class OrientDbRouteSensorChecker {
}
| epl-1.0 |
Mark-Booth/daq-eclipse | uk.ac.diamond.org.apache.activemq/org/apache/activemq/TransactionContext.java | 29375 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.jms.JMSException;
import javax.jms.TransactionInProgressException;
import javax.jms.TransactionRolledBackException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.apache.activemq.command.Command;
import org.apache.activemq.command.ConnectionId;
import org.apache.activemq.command.DataArrayResponse;
import org.apache.activemq.command.DataStructure;
import org.apache.activemq.command.IntegerResponse;
import org.apache.activemq.command.LocalTransactionId;
import org.apache.activemq.command.Response;
import org.apache.activemq.command.TransactionId;
import org.apache.activemq.command.TransactionInfo;
import org.apache.activemq.command.XATransactionId;
import org.apache.activemq.transaction.Synchronization;
import org.apache.activemq.util.JMSExceptionSupport;
import org.apache.activemq.util.LongSequenceGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A TransactionContext provides the means to control a JMS transaction. It
* provides a local transaction interface and also an XAResource interface. <p/>
* An application server controls the transactional assignment of an XASession
* by obtaining its XAResource. It uses the XAResource to assign the session to
* a transaction, prepare and commit work on the transaction, and so on. <p/> An
* XAResource provides some fairly sophisticated facilities for interleaving
* work on multiple transactions, recovering a list of transactions in progress,
* and so on. A JTA aware JMS provider must fully implement this functionality.
* This could be done by using the services of a database that supports XA, or a
* JMS provider may choose to implement this functionality from scratch. <p/>
*
*
* @see javax.jms.Session
* @see javax.jms.QueueSession
* @see javax.jms.TopicSession
* @see javax.jms.XASession
*/
public class TransactionContext implements XAResource {
private static final Logger LOG = LoggerFactory.getLogger(TransactionContext.class);
// XATransactionId -> ArrayList of TransactionContext objects
private final static HashMap<TransactionId, List<TransactionContext>> ENDED_XA_TRANSACTION_CONTEXTS =
new HashMap<TransactionId, List<TransactionContext>>();
private final ActiveMQConnection connection;
private final LongSequenceGenerator localTransactionIdGenerator;
private final ConnectionId connectionId;
private List<Synchronization> synchronizations;
// To track XA transactions.
private Xid associatedXid;
private TransactionId transactionId;
private LocalTransactionEventListener localTransactionEventListener;
private int beforeEndIndex;
public TransactionContext(ActiveMQConnection connection) {
this.connection = connection;
this.localTransactionIdGenerator = connection.getLocalTransactionIdGenerator();
this.connectionId = connection.getConnectionInfo().getConnectionId();
}
public boolean isInXATransaction() {
if (transactionId != null && transactionId.isXATransaction()) {
return true;
} else {
if (!ENDED_XA_TRANSACTION_CONTEXTS.isEmpty()) {
synchronized(ENDED_XA_TRANSACTION_CONTEXTS) {
for(List<TransactionContext> transactions : ENDED_XA_TRANSACTION_CONTEXTS.values()) {
if (transactions.contains(this)) {
return true;
}
}
}
}
}
return false;
}
public boolean isInLocalTransaction() {
return transactionId != null && transactionId.isLocalTransaction();
}
public boolean isInTransaction() {
return transactionId != null;
}
/**
* @return Returns the localTransactionEventListener.
*/
public LocalTransactionEventListener getLocalTransactionEventListener() {
return localTransactionEventListener;
}
/**
* Used by the resource adapter to listen to transaction events.
*
* @param localTransactionEventListener The localTransactionEventListener to
* set.
*/
public void setLocalTransactionEventListener(LocalTransactionEventListener localTransactionEventListener) {
this.localTransactionEventListener = localTransactionEventListener;
}
// ///////////////////////////////////////////////////////////
//
// Methods that work with the Synchronization objects registered with
// the transaction.
//
// ///////////////////////////////////////////////////////////
public void addSynchronization(Synchronization s) {
if (synchronizations == null) {
synchronizations = new ArrayList<Synchronization>(10);
}
synchronizations.add(s);
}
private void afterRollback() throws JMSException {
if (synchronizations == null) {
return;
}
Throwable firstException = null;
int size = synchronizations.size();
for (int i = 0; i < size; i++) {
try {
synchronizations.get(i).afterRollback();
} catch (Throwable t) {
LOG.debug("Exception from afterRollback on " + synchronizations.get(i), t);
if (firstException == null) {
firstException = t;
}
}
}
synchronizations = null;
if (firstException != null) {
throw JMSExceptionSupport.create(firstException);
}
}
private void afterCommit() throws JMSException {
if (synchronizations == null) {
return;
}
Throwable firstException = null;
int size = synchronizations.size();
for (int i = 0; i < size; i++) {
try {
synchronizations.get(i).afterCommit();
} catch (Throwable t) {
LOG.debug("Exception from afterCommit on " + synchronizations.get(i), t);
if (firstException == null) {
firstException = t;
}
}
}
synchronizations = null;
if (firstException != null) {
throw JMSExceptionSupport.create(firstException);
}
}
private void beforeEnd() throws JMSException {
if (synchronizations == null) {
return;
}
int size = synchronizations.size();
try {
for (;beforeEndIndex < size;) {
synchronizations.get(beforeEndIndex++).beforeEnd();
}
} catch (JMSException e) {
throw e;
} catch (Throwable e) {
throw JMSExceptionSupport.create(e);
}
}
public TransactionId getTransactionId() {
return transactionId;
}
// ///////////////////////////////////////////////////////////
//
// Local transaction interface.
//
// ///////////////////////////////////////////////////////////
/**
* Start a local transaction.
* @throws javax.jms.JMSException on internal error
*/
public void begin() throws JMSException {
if (isInXATransaction()) {
throw new TransactionInProgressException("Cannot start local transaction. XA transaction is already in progress.");
}
if (transactionId == null) {
synchronizations = null;
beforeEndIndex = 0;
this.transactionId = new LocalTransactionId(connectionId, localTransactionIdGenerator.getNextSequenceId());
TransactionInfo info = new TransactionInfo(getConnectionId(), transactionId, TransactionInfo.BEGIN);
this.connection.ensureConnectionInfoSent();
this.connection.asyncSendPacket(info);
// Notify the listener that the tx was started.
if (localTransactionEventListener != null) {
localTransactionEventListener.beginEvent();
}
if (LOG.isDebugEnabled()) {
LOG.debug("Begin:" + transactionId);
}
}
}
/**
* Rolls back any work done in this transaction and releases any locks
* currently held.
*
* @throws JMSException if the JMS provider fails to roll back the
* transaction due to some internal error.
* @throws javax.jms.IllegalStateException if the method is not called by a
* transacted session.
*/
public void rollback() throws JMSException {
if (isInXATransaction()) {
throw new TransactionInProgressException("Cannot rollback() if an XA transaction is already in progress ");
}
try {
beforeEnd();
} catch (TransactionRolledBackException canOcurrOnFailover) {
LOG.warn("rollback processing error", canOcurrOnFailover);
}
if (transactionId != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Rollback: " + transactionId
+ " syncCount: "
+ (synchronizations != null ? synchronizations.size() : 0));
}
TransactionInfo info = new TransactionInfo(getConnectionId(), transactionId, TransactionInfo.ROLLBACK);
this.transactionId = null;
//make this synchronous - see https://issues.apache.org/activemq/browse/AMQ-2364
this.connection.syncSendPacket(info);
// Notify the listener that the tx was rolled back
if (localTransactionEventListener != null) {
localTransactionEventListener.rollbackEvent();
}
}
afterRollback();
}
/**
* Commits all work done in this transaction and releases any locks
* currently held.
*
* @throws JMSException if the JMS provider fails to commit the transaction
* due to some internal error.
* @throws javax.jms.IllegalStateException if the method is not called by a
* transacted session.
*/
public void commit() throws JMSException {
if (isInXATransaction()) {
throw new TransactionInProgressException("Cannot commit() if an XA transaction is already in progress ");
}
try {
beforeEnd();
} catch (JMSException e) {
rollback();
throw e;
}
// Only send commit if the transaction was started.
if (transactionId != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Commit: " + transactionId
+ " syncCount: "
+ (synchronizations != null ? synchronizations.size() : 0));
}
TransactionInfo info = new TransactionInfo(getConnectionId(), transactionId, TransactionInfo.COMMIT_ONE_PHASE);
this.transactionId = null;
// Notify the listener that the tx was committed back
try {
syncSendPacketWithInterruptionHandling(info);
if (localTransactionEventListener != null) {
localTransactionEventListener.commitEvent();
}
afterCommit();
} catch (JMSException cause) {
LOG.info("commit failed for transaction " + info.getTransactionId(), cause);
if (localTransactionEventListener != null) {
localTransactionEventListener.rollbackEvent();
}
afterRollback();
throw cause;
}
}
}
// ///////////////////////////////////////////////////////////
//
// XAResource Implementation
//
// ///////////////////////////////////////////////////////////
/**
* Associates a transaction with the resource.
*/
public void start(Xid xid, int flags) throws XAException {
if (LOG.isDebugEnabled()) {
LOG.debug("Start: " + xid);
}
if (isInLocalTransaction()) {
throw new XAException(XAException.XAER_PROTO);
}
// Are we already associated?
if (associatedXid != null) {
throw new XAException(XAException.XAER_PROTO);
}
// if ((flags & TMJOIN) == TMJOIN) {
// TODO: verify that the server has seen the xid
// // }
// if ((flags & TMJOIN) == TMRESUME) {
// // TODO: verify that the xid was suspended.
// }
// associate
synchronizations = null;
beforeEndIndex = 0;
setXid(xid);
}
/**
* @return connectionId for connection
*/
private ConnectionId getConnectionId() {
return connection.getConnectionInfo().getConnectionId();
}
public void end(Xid xid, int flags) throws XAException {
if (LOG.isDebugEnabled()) {
LOG.debug("End: " + xid);
}
if (isInLocalTransaction()) {
throw new XAException(XAException.XAER_PROTO);
}
if ((flags & (TMSUSPEND | TMFAIL)) != 0) {
// You can only suspend the associated xid.
if (!equals(associatedXid, xid)) {
throw new XAException(XAException.XAER_PROTO);
}
// TODO: we may want to put the xid in a suspended list.
try {
beforeEnd();
} catch (JMSException e) {
throw toXAException(e);
} finally {
setXid(null);
}
} else if ((flags & TMSUCCESS) == TMSUCCESS) {
// set to null if this is the current xid.
// otherwise this could be an asynchronous success call
if (equals(associatedXid, xid)) {
try {
beforeEnd();
} catch (JMSException e) {
throw toXAException(e);
} finally {
setXid(null);
}
}
} else {
throw new XAException(XAException.XAER_INVAL);
}
}
private boolean equals(Xid xid1, Xid xid2) {
if (xid1 == xid2) {
return true;
}
if (xid1 == null ^ xid2 == null) {
return false;
}
return xid1.getFormatId() == xid2.getFormatId() && Arrays.equals(xid1.getBranchQualifier(), xid2.getBranchQualifier())
&& Arrays.equals(xid1.getGlobalTransactionId(), xid2.getGlobalTransactionId());
}
public int prepare(Xid xid) throws XAException {
if (LOG.isDebugEnabled()) {
LOG.debug("Prepare: " + xid);
}
// We allow interleaving multiple transactions, so
// we don't limit prepare to the associated xid.
XATransactionId x;
// THIS SHOULD NEVER HAPPEN because end(xid, TMSUCCESS) should have been
// called first
if (xid == null || (equals(associatedXid, xid))) {
throw new XAException(XAException.XAER_PROTO);
} else {
// TODO: cache the known xids so we don't keep recreating this one??
x = new XATransactionId(xid);
}
try {
TransactionInfo info = new TransactionInfo(getConnectionId(), x, TransactionInfo.PREPARE);
// Find out if the server wants to commit or rollback.
IntegerResponse response = (IntegerResponse)syncSendPacketWithInterruptionHandling(info);
if (XAResource.XA_RDONLY == response.getResult()) {
// transaction stops now, may be syncs that need a callback
synchronized(ENDED_XA_TRANSACTION_CONTEXTS) {
List<TransactionContext> l = ENDED_XA_TRANSACTION_CONTEXTS.remove(x);
if (l != null && !l.isEmpty()) {
if (LOG.isDebugEnabled()) {
LOG.debug("firing afterCommit callbacks on XA_RDONLY from prepare: " + xid);
}
for (TransactionContext ctx : l) {
ctx.afterCommit();
}
}
}
}
return response.getResult();
} catch (JMSException e) {
LOG.warn("prepare of: " + x + " failed with: " + e, e);
synchronized(ENDED_XA_TRANSACTION_CONTEXTS) {
List<TransactionContext> l = ENDED_XA_TRANSACTION_CONTEXTS.remove(x);
if (l != null && !l.isEmpty()) {
for (TransactionContext ctx : l) {
try {
ctx.afterRollback();
} catch (Throwable ignored) {
if (LOG.isDebugEnabled()) {
LOG.debug("failed to firing afterRollback callbacks on prepare failure, txid: " +
x + ", context: " + ctx, ignored);
}
}
}
}
}
throw toXAException(e);
}
}
public void rollback(Xid xid) throws XAException {
if (LOG.isDebugEnabled()) {
LOG.debug("Rollback: " + xid);
}
// We allow interleaving multiple transactions, so
// we don't limit rollback to the associated xid.
XATransactionId x;
if (xid == null) {
throw new XAException(XAException.XAER_PROTO);
}
if (equals(associatedXid, xid)) {
// I think this can happen even without an end(xid) call. Need to
// check spec.
x = (XATransactionId)transactionId;
} else {
x = new XATransactionId(xid);
}
try {
this.connection.checkClosedOrFailed();
this.connection.ensureConnectionInfoSent();
// Let the server know that the tx is rollback.
TransactionInfo info = new TransactionInfo(getConnectionId(), x, TransactionInfo.ROLLBACK);
syncSendPacketWithInterruptionHandling(info);
synchronized(ENDED_XA_TRANSACTION_CONTEXTS) {
List<TransactionContext> l = ENDED_XA_TRANSACTION_CONTEXTS.remove(x);
if (l != null && !l.isEmpty()) {
for (TransactionContext ctx : l) {
ctx.afterRollback();
}
}
}
} catch (JMSException e) {
throw toXAException(e);
}
}
// XAResource interface
public void commit(Xid xid, boolean onePhase) throws XAException {
if (LOG.isDebugEnabled()) {
LOG.debug("Commit: " + xid + ", onePhase=" + onePhase);
}
// We allow interleaving multiple transactions, so
// we don't limit commit to the associated xid.
XATransactionId x;
if (xid == null || (equals(associatedXid, xid))) {
// should never happen, end(xid,TMSUCCESS) must have been previously
// called
throw new XAException(XAException.XAER_PROTO);
} else {
x = new XATransactionId(xid);
}
try {
this.connection.checkClosedOrFailed();
this.connection.ensureConnectionInfoSent();
// Notify the server that the tx was committed back
TransactionInfo info = new TransactionInfo(getConnectionId(), x, onePhase ? TransactionInfo.COMMIT_ONE_PHASE : TransactionInfo.COMMIT_TWO_PHASE);
syncSendPacketWithInterruptionHandling(info);
synchronized(ENDED_XA_TRANSACTION_CONTEXTS) {
List<TransactionContext> l = ENDED_XA_TRANSACTION_CONTEXTS.remove(x);
if (l != null && !l.isEmpty()) {
for (TransactionContext ctx : l) {
try {
ctx.afterCommit();
} catch (Exception ignored) {
LOG.debug("ignoring exception from after completion on ended transaction: " + ignored, ignored);
}
}
}
}
} catch (JMSException e) {
LOG.warn("commit of: " + x + " failed with: " + e, e);
if (onePhase) {
synchronized(ENDED_XA_TRANSACTION_CONTEXTS) {
List<TransactionContext> l = ENDED_XA_TRANSACTION_CONTEXTS.remove(x);
if (l != null && !l.isEmpty()) {
for (TransactionContext ctx : l) {
try {
ctx.afterRollback();
} catch (Throwable ignored) {
if (LOG.isDebugEnabled()) {
LOG.debug("failed to firing afterRollback callbacks commit failure, txid: " + x + ", context: " + ctx, ignored);
}
}
}
}
}
}
throw toXAException(e);
}
}
public void forget(Xid xid) throws XAException {
if (LOG.isDebugEnabled()) {
LOG.debug("Forget: " + xid);
}
// We allow interleaving multiple transactions, so
// we don't limit forget to the associated xid.
XATransactionId x;
if (xid == null) {
throw new XAException(XAException.XAER_PROTO);
}
if (equals(associatedXid, xid)) {
// TODO determine if this can happen... I think not.
x = (XATransactionId)transactionId;
} else {
x = new XATransactionId(xid);
}
TransactionInfo info = new TransactionInfo(getConnectionId(), x, TransactionInfo.FORGET);
try {
// Tell the server to forget the transaction.
syncSendPacketWithInterruptionHandling(info);
} catch (JMSException e) {
throw toXAException(e);
}
synchronized(ENDED_XA_TRANSACTION_CONTEXTS) {
ENDED_XA_TRANSACTION_CONTEXTS.remove(x);
}
}
public boolean isSameRM(XAResource xaResource) throws XAException {
if (xaResource == null) {
return false;
}
if (!(xaResource instanceof TransactionContext)) {
return false;
}
TransactionContext xar = (TransactionContext)xaResource;
try {
return getResourceManagerId().equals(xar.getResourceManagerId());
} catch (Throwable e) {
throw (XAException)new XAException("Could not get resource manager id.").initCause(e);
}
}
public Xid[] recover(int flag) throws XAException {
if (LOG.isDebugEnabled()) {
LOG.debug("Recover: " + flag);
}
TransactionInfo info = new TransactionInfo(getConnectionId(), null, TransactionInfo.RECOVER);
try {
this.connection.checkClosedOrFailed();
this.connection.ensureConnectionInfoSent();
DataArrayResponse receipt = (DataArrayResponse)this.connection.syncSendPacket(info);
DataStructure[] data = receipt.getData();
XATransactionId[] answer;
if (data instanceof XATransactionId[]) {
answer = (XATransactionId[])data;
} else {
answer = new XATransactionId[data.length];
System.arraycopy(data, 0, answer, 0, data.length);
}
return answer;
} catch (JMSException e) {
throw toXAException(e);
}
}
public int getTransactionTimeout() throws XAException {
return 0;
}
public boolean setTransactionTimeout(int seconds) throws XAException {
return false;
}
// ///////////////////////////////////////////////////////////
//
// Helper methods.
//
// ///////////////////////////////////////////////////////////
private String getResourceManagerId() throws JMSException {
return this.connection.getResourceManagerId();
}
private void setXid(Xid xid) throws XAException {
try {
this.connection.checkClosedOrFailed();
this.connection.ensureConnectionInfoSent();
} catch (JMSException e) {
disassociate();
throw toXAException(e);
}
if (xid != null) {
// associate
associatedXid = xid;
transactionId = new XATransactionId(xid);
TransactionInfo info = new TransactionInfo(connectionId, transactionId, TransactionInfo.BEGIN);
try {
this.connection.asyncSendPacket(info);
if (LOG.isDebugEnabled()) {
LOG.debug("Started XA transaction: " + transactionId);
}
} catch (JMSException e) {
disassociate();
throw toXAException(e);
}
} else {
if (transactionId != null) {
TransactionInfo info = new TransactionInfo(connectionId, transactionId, TransactionInfo.END);
try {
syncSendPacketWithInterruptionHandling(info);
if (LOG.isDebugEnabled()) {
LOG.debug("Ended XA transaction: " + transactionId);
}
} catch (JMSException e) {
disassociate();
throw toXAException(e);
}
// Add our self to the list of contexts that are interested in
// post commit/rollback events.
synchronized(ENDED_XA_TRANSACTION_CONTEXTS) {
List<TransactionContext> l = ENDED_XA_TRANSACTION_CONTEXTS.get(transactionId);
if (l == null) {
l = new ArrayList<TransactionContext>(3);
ENDED_XA_TRANSACTION_CONTEXTS.put(transactionId, l);
l.add(this);
} else if (!l.contains(this)) {
l.add(this);
}
}
}
disassociate();
}
}
private void disassociate() {
// dis-associate
associatedXid = null;
transactionId = null;
}
/**
* Sends the given command. Also sends the command in case of interruption,
* so that important commands like rollback and commit are never interrupted.
* If interruption occurred, set the interruption state of the current
* after performing the action again.
*
* @return the response
*/
private Response syncSendPacketWithInterruptionHandling(Command command) throws JMSException {
try {
return this.connection.syncSendPacket(command);
} catch (JMSException e) {
if (e.getLinkedException() instanceof InterruptedIOException) {
try {
Thread.interrupted();
return this.connection.syncSendPacket(command);
} finally {
Thread.currentThread().interrupt();
}
}
throw e;
}
}
/**
* Converts a JMSException from the server to an XAException. if the
* JMSException contained a linked XAException that is returned instead.
*
* @param e JMSException to convert
* @return XAException wrapping original exception or its message
*/
private XAException toXAException(JMSException e) {
if (e.getCause() != null && e.getCause() instanceof XAException) {
XAException original = (XAException)e.getCause();
XAException xae = new XAException(original.getMessage());
xae.errorCode = original.errorCode;
if (xae.errorCode == XA_OK) {
// detail not unmarshalled see: org.apache.activemq.openwire.v1.BaseDataStreamMarshaller.createThrowable
// so use a valid generic error code in place of ok
xae.errorCode = XAException.XAER_RMERR;
}
xae.initCause(original);
return xae;
}
XAException xae = new XAException(e.getMessage());
xae.errorCode = XAException.XAER_RMFAIL;
xae.initCause(e);
return xae;
}
public ActiveMQConnection getConnection() {
return connection;
}
public void cleanup() {
associatedXid = null;
transactionId = null;
}
@Override
public String toString() {
return "TransactionContext{" +
"transactionId=" + transactionId +
'}';
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | jpa/eclipselink.jpa.wdf.test/src/org/eclipse/persistence/testing/models/wdf/jpa1/jpql/Criminal.java | 2184 | /*******************************************************************************
* Copyright (c) 2005, 2009 SAP. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* SAP - initial API and implementation
******************************************************************************/
package org.eclipse.persistence.testing.models.wdf.jpa1.jpql;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "TMP_CRIMINAL")
public class Criminal {
public enum CriminalType {
NICE, MEAN, UGLY, HARMFUL
}
@Enumerated(EnumType.STRING)
@Column(name = "TRANSMISSION_TYPE")
protected CriminalType cType;
@Id
protected long id;
@ManyToOne
protected Cop attachedCop;
@OneToMany
protected Collection<Criminal> parties;
public Criminal() {
this.cType = CriminalType.HARMFUL;
}
public Cop getAttachedCop() {
return attachedCop;
}
public void setAttachedCop(Cop attachedCop) {
this.attachedCop = attachedCop;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Collection<Criminal> getParties() {
return parties;
}
public void setParties(Collection<Criminal> parties) {
this.parties = parties;
}
public CriminalType getCType() {
return cType;
}
public void setCType(CriminalType type) {
cType = type;
}
}
| epl-1.0 |
pierrealexvezinet/excusedemerde | edm/src/fr/edm/activity/parent/EdmFragmentActivity.java | 14420 | package fr.edm.activity.parent;
import fr.activity.edm.R;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import com.octo.android.robospice.SpiceManager;
import com.octo.android.robospice.exception.NoNetworkException;
import com.octo.android.robospice.persistence.DurationInMillis;
import com.octo.android.robospice.persistence.exception.CacheLoadingException;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;
import fr.edm.EdmApplication;
import fr.edm.activity.*;
import fr.edm.adapter.EdmDrawerAdapter;
import fr.edm.fragment.AccueilFragment;
import fr.edm.fragment.LoginFragment.LoginRequestListener;
import fr.edm.fragment.LoginFragment.UserEdmsRequestListener;
import fr.edm.model.ListUsers;
import fr.edm.model.User;
import fr.edm.request.edm.LoginUserRequest;
import fr.edm.request.edm.UserEdmsRequest;
import fr.edm.utils.ApplicationConstants;
import fr.edm.utils.PreferenceHelper;
import fr.edm.webservice.EdmService;
import fr.edm.webservice.EdmSpiceService;
import fr.edm.webservice.UserService;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.DialogInterface.*;
import android.widget.AdapterView.OnItemClickListener;
@SuppressLint("ResourceAsColor")
public class EdmFragmentActivity extends ActionBarActivity {
/**
* @author pvezinet
*
*/
// /Users/Pierre-AlexandreVezinet/Documents/android-sdk-macosx/tools/emulator
// -avd AVD_for_Nexus_7 -dns-server 8.8.8.8
private DrawerLayout drawerLayout;
ListView listViewDrawer;
EdmDrawerAdapter adapter;
SharedPreferences preferences = null;
private static String ITEM_ACCUEIL = "Accueil";
private static String ITEM_POSTER_EDM = "Poster une EDM";
private static String ITEM_MES_EDMS = "Mes EDMs";
private static String ITEM_TOP_TEN = "Top 10";
private static String ITEM_ROI_DES_MYTHOS = "Roi des mythos";
private static String ITEM_PIPOTEK = "Pipotek";
private static String ITEM_PLUS = "Plus";
private static int POSITION_ITEM_ACCUEIL = 0;
private static int POSITION_ITEM_POSTER_EDM = 1;
private static int POSITION_ITEM_MES_EDMS = 2;
private static int POSITION_ITEM_TOP_TEN = 3;
private static int POSITION_ITEM_ROI_DES_MYTHOS = 4;
private static int POSITION_ITEM_PIPOTEK = 5;
private static int POSITION_ITEM_PLUS = 5;
protected static Activity EDM_ACTIVITY;
private ArrayList<String> menu_item;
private ActionBarDrawerToggle drawerToggle = null;
// UserService userService;
EdmService edmService = new EdmService();
UserService userService = new UserService();
Intent intent = null;
String loginUser, mdpUser, isSafedUser = "";
private SpiceManager spiceManager = new SpiceManager(EdmSpiceService.class);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("dede", "onCreate");
preferences = PreferenceManager.getDefaultSharedPreferences(this);
// CALL WS FOR GET USER INFO CONNECTED
isOnline();
setContentView(R.layout.edm_fragment_main_activity);
showFragment(new AccueilFragment());
menu_item = new ArrayList<String>();
listViewDrawer = new ListView(getApplicationContext());
menu_item.add(ITEM_ACCUEIL);
menu_item.add(ITEM_POSTER_EDM);
menu_item.add(ITEM_MES_EDMS);
menu_item.add(ITEM_TOP_TEN);
menu_item.add(ITEM_ROI_DES_MYTHOS);
menu_item.add(ITEM_PIPOTEK);
menu_item.add(ITEM_PLUS);
listViewDrawer = (ListView) findViewById(R.id.left_drawer);
adapter = new EdmDrawerAdapter(getApplicationContext(),
R.layout.menu_drawer, menu_item);
listViewDrawer.setAdapter(adapter);
initItemsDrawer();
listViewDrawer.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View item,
int position, long arg) {
selectedItem(item);
}
});
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_closed);
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
drawerToggle.syncState();
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
Log.d("dede", "onCreateOptionsMenu");
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
Log.d("dede",
"onOptionsItemSelected ouvert item selectionné : "
+ item.getTitle());
if (android.R.id.home == item.getItemId()) {
if (drawerLayout.isDrawerOpen(Gravity.LEFT) == false) {
drawerLayout.openDrawer(Gravity.LEFT);
} else {
drawerLayout.closeDrawers();
}
} else if (R.id.refresh == item.getItemId()) {
MenuItemCompat.setActionView(item, R.layout.progressbar);
}
return super.onOptionsItemSelected(item);
}
public boolean isCheckedSafeUserCase() {
isSafedUser = preferences.getString("safeUser", null);
if (isSafedUser.equals("ok")) {
return true;
} else {
return false;
}
}
public boolean isSafedConnectionUser() {
loginUser = preferences.getString("loginUser", null);
mdpUser = preferences.getString("mdpUser", null);
isSafedUser = preferences.getString("safeUser", null);
// Toast.makeText(this, "login : " + loginUser + " / mdp : " + mdpUser ,
// Toast.LENGTH_LONG).show();
if ((loginUser != null || mdpUser != null)) {
PreferenceHelper.setPseudo(loginUser);
PreferenceHelper.setMdp(mdpUser);
//User user = new User();
//user.setPseudo(loginUser);
//user.setMdp(mdpUser);
//PreferenceHelper.setUserInPreferences(user);
return true;
} else {
return false;
}
}
private void initItemsDrawer() {
/*
* listViewDrawer.getAdapter() .getView(POSITION_ITEM_ACCUEIL, null,
* listViewDrawer)
* .setBackgroundColor(fr.activity.edm.R.color.btn_accueil_color);
* listViewDrawer.getAdapter() .getView(POSITION_ITEM_POSTER_EDM, null,
* listViewDrawer)
* .setBackgroundColor(fr.activity.edm.R.color.btn_forum_color);
* listViewDrawer.getAdapter() .getView(POSITION_ITEM_SHOPPING, null,
* listViewDrawer)
* .setBackgroundColor(fr.activity.edm.R.color.btn_shopping_color);
* listViewDrawer.getAdapter() .getView(POSITION_ITEM_PIPOTEK, null,
* listViewDrawer)
* .setBackgroundColor(fr.activity.edm.R.color.btn_account_color);
* listViewDrawer.getAdapter() .getView(POSITION_ITEM_ACCOUNT, null,
* listViewDrawer)
* .setBackgroundColor(fr.activity.edm.R.color.btn_pipotek_color);
* listViewDrawer .getAdapter() .getView(POSITION_ITEM_PARAMETRES, null,
* listViewDrawer) .setBackgroundColor(
* fr.activity.edm.R.color.btn_parametres_color);
*/
}
private void selectedItem(View view) {
TextView v = (TextView) view;
Intent intent = null;
if (v.getText().equals(ITEM_ACCUEIL)) {
Log.d("dede", "selected Item Name is " + v.getText());
drawerLayout.closeDrawers();
/*
* EdmApplication.NB_INSTANCE_EDM_FRAGMENT_ACTIVITY++;
*
* if(EdmApplication.NB_INSTANCE_EDM_FRAGMENT_ACTIVITY > 1){
* finish(); }
*/
intent = new Intent(this, AccueilActivity.class);
startActivity(intent);
}
if (v.getText().equals(ITEM_POSTER_EDM)) {
Log.d("dede", "selected Item Name is " + v.getText());
if (isSafedConnectionUser()) {
intent = new Intent(this, PosterEdmActivity.class);
startActivity(intent);
} else {
if (PreferenceHelper.getUserInPreferences() != null) {
intent = new Intent(this, PosterEdmActivity.class);
startActivity(intent);
} else {
displayDialogMessageRetourActivity(
R.string.title_alert_dialog_retour_to_post_edm,
R.string.message_pas_connecte,
R.string.button_connect_me, new LoginActivity());
}
}
drawerLayout.closeDrawers();
}
if (v.getText().equals(ITEM_MES_EDMS)) {
Log.d("dede", "selected Item Name is " + v.getText());
drawerLayout.closeDrawers();
EdmApplication.showWaitingDialog(this);
if (isSafedConnectionUser()) {
intent = new Intent(this, MesEdmsActivity.class);
startActivity(intent);
} else if (!isSafedConnectionUser()) {
if (PreferenceHelper.getUserInPreferences() != null) {
intent = new Intent(this, MesEdmsActivity.class);
startActivity(intent);
} else {
displayDialogMessageRetourActivity(
R.string.title_alert_dialog_retour_accueil,
R.string.message_aucunes_edms_utilisateur,
R.string.button_valid_retour_accueil,
new AccueilActivity());
}
} else {
intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
EdmApplication.unShowWaitingDialog();
}
if (v.getText().equals(ITEM_TOP_TEN)) {
Log.d("dede", "selected Item Name is " + v.getText());
drawerLayout.closeDrawers();
intent = new Intent(this, ClassementTopTenDesMythosActivity.class);
startActivity(intent);
}
if (v.getText().equals(ITEM_ROI_DES_MYTHOS)) {
Log.d("dede", "selected Item Name is " + v.getText());
drawerLayout.closeDrawers();
intent = new Intent(this, RoiDesMythosActivity.class);
startActivity(intent);
}
if (v.getText().equals(ITEM_PIPOTEK)) {
Log.d("dede", "selected Item Name is " + v.getText());
drawerLayout.closeDrawers();
}
if (v.getText().equals(ITEM_PLUS)) {
Log.d("dede", "selected Item Name is " + v.getText());
isSafedConnectionUser();
drawerLayout.closeDrawers();
intent = new Intent(this, PlusActivity.class);
startActivity(intent);
}
}
@Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
spiceManager.start(this);
Log.d("dede", "onstart");
}
@Override
public void onPause() {
super.onPause();
Log.d("dede", "onpause");
}
@Override
public void onStop() {
super.onStop();
spiceManager.shouldStop();
Log.d("dede", "onstop");
}
@Override
public void onResume() {
super.onResume();
Log.d("dede", "onresume");
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
}
public void showFragment(final Fragment fragmenttoDisplay) {
if (fragmenttoDisplay == null)
return;
final FragmentManager fm = getSupportFragmentManager();
final FragmentTransaction ft = fm.beginTransaction();
// We can also animate the changing of fragment
// ft.setCustomAnimations(android.R.anim.slide_out_right,
// android.R.anim.slide_out_right);
ft.replace(R.id.content_frame, fragmenttoDisplay);
ft.commit();
}
public boolean isOnline() {
getApplicationContext();
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
Log.d("dede", "online online online online online ONLINE");
return true;
}
return false;
}
public void finishEdmApplication(int title, int message) {
final AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setCancelable(true)
.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
}
})
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
try {
if (getParent() != null) {
getParent().finish();
} else {
finish();
}
} catch (Exception e) {
Log.d("dede", e.getMessage());
}
}
}
})
.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).create();
alertDialog.show();
}
public void displayDialogMessageRetourActivity(int title, int message,
int buttonResource, final EdmFragmentActivity activity) {
final AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(buttonResource,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
dialog.cancel();
intent = new Intent(
getApplicationContext(), activity
.getClass());
startActivity(intent);
}
}
}).create();
alertDialog.show();
}
public SpiceManager getSpiceManager() {
return spiceManager;
}
public String getLoginUser() {
return loginUser;
}
public void setLoginUser(String loginUser) {
this.loginUser = loginUser;
}
public String getMdpUser() {
return mdpUser;
}
public void setMdpUser(String mdpUser) {
this.mdpUser = mdpUser;
}
public SharedPreferences getPreferences() {
return preferences;
}
public void setPreferences(SharedPreferences preferences) {
this.preferences = preferences;
}
}
| epl-1.0 |
SK-HOLDINGS-CC/NEXCORE-UML-Modeler | nexcore.tool.mda.model/src/java/nexcore/tool/mda/model/designer/transformation/impl/BehaviorTransformationDetailDataImpl.java | 17171 | /**
* Copyright (c) 2015 SK holdings Co., Ltd. All rights reserved.
* This software is the confidential and proprietary information of SK holdings.
* You shall not disclose such confidential information and shall use it only in
* accordance with the terms of the license agreement you entered into with SK holdings.
* (http://www.eclipse.org/legal/epl-v10.html)
*/
package nexcore.tool.mda.model.designer.transformation.impl;
import nexcore.tool.mda.model.designer.transformation.BehaviorTransformationDetailData;
import nexcore.tool.mda.model.designer.transformation.OperationType;
import nexcore.tool.mda.model.designer.transformation.TargetRelationType;
import nexcore.tool.mda.model.designer.transformation.TransformationPackage;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
/**
* <!-- begin-user-doc --> An implementation of the model object '
* <em><b>Behavior Transformation Detail Data</b></em>'. <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>
* {@link nexcore.tool.mda.model.designer.transformation.impl.BehaviorTransformationDetailDataImpl#getSequence
* <em>Sequence</em>}</li>
* <li>
* {@link nexcore.tool.mda.model.designer.transformation.impl.BehaviorTransformationDetailDataImpl#getTargetRelation
* <em>Target Relation</em>}</li>
* <li>
* {@link nexcore.tool.mda.model.designer.transformation.impl.BehaviorTransformationDetailDataImpl#getOperation
* <em>Operation</em>}</li>
* <li>
* {@link nexcore.tool.mda.model.designer.transformation.impl.BehaviorTransformationDetailDataImpl#getOperationApplicableStereotype
* <em>Operation Applicable Stereotype</em>}</li>
* <li>
* {@link nexcore.tool.mda.model.designer.transformation.impl.BehaviorTransformationDetailDataImpl#getMessage
* <em>Message</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class BehaviorTransformationDetailDataImpl extends EObjectImpl implements BehaviorTransformationDetailData {
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public static final String copyright = "";
/**
* The default value of the '{@link #getSequence() <em>Sequence</em>}'
* attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @see #getSequence()
* @generated
* @ordered
*/
protected static final int SEQUENCE_EDEFAULT = 0;
/**
* The cached value of the '{@link #getSequence() <em>Sequence</em>}'
* attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @see #getSequence()
* @generated
* @ordered
*/
protected int sequence = SEQUENCE_EDEFAULT;
/**
* The cached value of the '{@link #getTargetRelation()
* <em>Target Relation</em>}' containment reference. <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getTargetRelation()
* @generated
* @ordered
*/
protected TargetRelationType targetRelation;
/**
* The cached value of the '{@link #getOperation() <em>Operation</em>}'
* containment reference. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @see #getOperation()
* @generated
* @ordered
*/
protected OperationType operation;
/**
* The default value of the '{@link #getOperationApplicableStereotype()
* <em>Operation Applicable Stereotype</em>}' attribute. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @see #getOperationApplicableStereotype()
* @generated
* @ordered
*/
protected static final String OPERATION_APPLICABLE_STEREOTYPE_EDEFAULT = null;
/**
* The cached value of the '{@link #getOperationApplicableStereotype()
* <em>Operation Applicable Stereotype</em>}' attribute. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @see #getOperationApplicableStereotype()
* @generated
* @ordered
*/
protected String operationApplicableStereotype = OPERATION_APPLICABLE_STEREOTYPE_EDEFAULT;
/**
* The default value of the '{@link #getMessage() <em>Message</em>}'
* attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @see #getMessage()
* @generated
* @ordered
*/
protected static final String MESSAGE_EDEFAULT = null;
/**
* The cached value of the '{@link #getMessage() <em>Message</em>}'
* attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @see #getMessage()
* @generated
* @ordered
*/
protected String message = MESSAGE_EDEFAULT;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected BehaviorTransformationDetailDataImpl() {
super();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
protected EClass eStaticClass() {
return TransformationPackage.Literals.BEHAVIOR_TRANSFORMATION_DETAIL_DATA;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public int getSequence() {
return sequence;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setSequence(int newSequence) {
int oldSequence = sequence;
sequence = newSequence;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this,
Notification.SET,
TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__SEQUENCE,
oldSequence,
sequence));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public TargetRelationType getTargetRelation() {
return targetRelation;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public NotificationChain basicSetTargetRelation(TargetRelationType newTargetRelation, NotificationChain msgs) {
TargetRelationType oldTargetRelation = targetRelation;
targetRelation = newTargetRelation;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this,
Notification.SET,
TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__TARGET_RELATION,
oldTargetRelation,
newTargetRelation);
if (msgs == null)
msgs = notification;
else
msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setTargetRelation(TargetRelationType newTargetRelation) {
if (newTargetRelation != targetRelation) {
NotificationChain msgs = null;
if (targetRelation != null)
msgs = ((InternalEObject) targetRelation).eInverseRemove(this, EOPPOSITE_FEATURE_BASE
- TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__TARGET_RELATION, null, msgs);
if (newTargetRelation != null)
msgs = ((InternalEObject) newTargetRelation).eInverseAdd(this, EOPPOSITE_FEATURE_BASE
- TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__TARGET_RELATION, null, msgs);
msgs = basicSetTargetRelation(newTargetRelation, msgs);
if (msgs != null)
msgs.dispatch();
} else if (eNotificationRequired())
eNotify(new ENotificationImpl(this,
Notification.SET,
TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__TARGET_RELATION,
newTargetRelation,
newTargetRelation));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public OperationType getOperation() {
return operation;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public NotificationChain basicSetOperation(OperationType newOperation, NotificationChain msgs) {
OperationType oldOperation = operation;
operation = newOperation;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this,
Notification.SET,
TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION,
oldOperation,
newOperation);
if (msgs == null)
msgs = notification;
else
msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setOperation(OperationType newOperation) {
if (newOperation != operation) {
NotificationChain msgs = null;
if (operation != null)
msgs = ((InternalEObject) operation).eInverseRemove(this, EOPPOSITE_FEATURE_BASE
- TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION, null, msgs);
if (newOperation != null)
msgs = ((InternalEObject) newOperation).eInverseAdd(this, EOPPOSITE_FEATURE_BASE
- TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION, null, msgs);
msgs = basicSetOperation(newOperation, msgs);
if (msgs != null)
msgs.dispatch();
} else if (eNotificationRequired())
eNotify(new ENotificationImpl(this,
Notification.SET,
TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION,
newOperation,
newOperation));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public String getOperationApplicableStereotype() {
return operationApplicableStereotype;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setOperationApplicableStereotype(String newOperationApplicableStereotype) {
String oldOperationApplicableStereotype = operationApplicableStereotype;
operationApplicableStereotype = newOperationApplicableStereotype;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this,
Notification.SET,
TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION_APPLICABLE_STEREOTYPE,
oldOperationApplicableStereotype,
operationApplicableStereotype));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public String getMessage() {
return message;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setMessage(String newMessage) {
String oldMessage = message;
message = newMessage;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this,
Notification.SET,
TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__MESSAGE,
oldMessage,
message));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__TARGET_RELATION:
return basicSetTargetRelation(null, msgs);
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION:
return basicSetOperation(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__SEQUENCE:
return new Integer(getSequence());
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__TARGET_RELATION:
return getTargetRelation();
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION:
return getOperation();
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION_APPLICABLE_STEREOTYPE:
return getOperationApplicableStereotype();
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__MESSAGE:
return getMessage();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__SEQUENCE:
setSequence(((Integer) newValue).intValue());
return;
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__TARGET_RELATION:
setTargetRelation((TargetRelationType) newValue);
return;
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION:
setOperation((OperationType) newValue);
return;
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION_APPLICABLE_STEREOTYPE:
setOperationApplicableStereotype((String) newValue);
return;
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__MESSAGE:
setMessage((String) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__SEQUENCE:
setSequence(SEQUENCE_EDEFAULT);
return;
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__TARGET_RELATION:
setTargetRelation((TargetRelationType) null);
return;
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION:
setOperation((OperationType) null);
return;
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION_APPLICABLE_STEREOTYPE:
setOperationApplicableStereotype(OPERATION_APPLICABLE_STEREOTYPE_EDEFAULT);
return;
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__MESSAGE:
setMessage(MESSAGE_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__SEQUENCE:
return sequence != SEQUENCE_EDEFAULT;
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__TARGET_RELATION:
return targetRelation != null;
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION:
return operation != null;
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__OPERATION_APPLICABLE_STEREOTYPE:
return OPERATION_APPLICABLE_STEREOTYPE_EDEFAULT == null ? operationApplicableStereotype != null
: !OPERATION_APPLICABLE_STEREOTYPE_EDEFAULT.equals(operationApplicableStereotype);
case TransformationPackage.BEHAVIOR_TRANSFORMATION_DETAIL_DATA__MESSAGE:
return MESSAGE_EDEFAULT == null ? message != null : !MESSAGE_EDEFAULT.equals(message);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public String toString() {
if (eIsProxy())
return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (sequence: ");
result.append(sequence);
result.append(", operationApplicableStereotype: ");
result.append(operationApplicableStereotype);
result.append(", message: ");
result.append(message);
result.append(')');
return result.toString();
}
} // BehaviorTransformationDetailDataImpl
| epl-1.0 |
DAM2-GOW/FCM | FCM/src/gow/fcm/pantallas/PlayingGround.java | 12877 | package gow.fcm.pantallas;
import gow.fcm.footballcoachmanager.R;
import gow.fcm.fragments.FragmentFinishEvent;
import gow.fcm.fragments.FragmentFinishEvent.OnClickFinishEvent;
import gow.fcm.fragments.FragmentGridPlayers;
import gow.fcm.fragments.FragmentGridPlayers.OnGridPlayersFragment;
import gow.fcm.fragments.FragmentPlayingGroundPlayersOptions;
import gow.fcm.fragments.FragmentPlayingGroundPlayersOptions.OnPlayerOptionClickEvent;
import gow.fcm.fragments.FragmentSelectStartingPlayers;
import gow.fcm.fragments.FragmentSelectStartingPlayers.OnSelectStartingPlayers;
import gow.fcm.popups.PopUpPlayersSelector;
import gow.fcm.sentencias.SentenciasSQLitePlayingGround;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
public class PlayingGround extends Activity implements OnSelectStartingPlayers, OnGridPlayersFragment, OnClickFinishEvent, OnPlayerOptionClickEvent{
FrameLayout flTopLeft;
LinearLayout flBottom;
FragmentGridPlayers fgp;
FragmentSelectStartingPlayers fssp;
SentenciasSQLitePlayingGround sentences;
FragmentFinishEvent ffe;
FragmentManager fm;
FragmentTransaction ft;
int lastPlayerID = -1;
boolean entered = false; // Indica si se ha pulsado un jugador del grid de la lista de 11 jugadores.
String[] dataSummaryToShow = new String[4]; // Almacena el texto a mostrar en el fragment final de resumen de opciones de jugador.
private int lastDimensionShowed; // Indica la ultima dimension mostrada en los fragments de opciones de jugador.
private int[] playersID; // Almacena una lista de jugadores seleccionados y mostrados en el grid de 11 jugadores.
private int playerToBeChanged; // Almacena el jugador en el cual se quiere realizar un cambio.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_playing_ground);
flTopLeft = (FrameLayout) findViewById(R.id.FrameLayoutTopLeft);
flBottom = (LinearLayout) findViewById(R.id.LinearLayoutBottom);
sentences = new SentenciasSQLitePlayingGround(this);
fm = getFragmentManager();
fssp = new FragmentSelectStartingPlayers();
ffe = new FragmentFinishEvent();
ft = fm.beginTransaction();
ft.add(flTopLeft.getId(), fssp);
ft.add(flBottom.getId(), ffe);
ft.commit();
fm.addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
// Si BACKSTACK esta vacio entonces boton seleccionado de jugador sin pintar y 'Entered' false.
if(fm.getBackStackEntryCount() == 0){
Log.d("onBackStackChanged", "HA LLEGADO A 0");
entered = false;
lastPlayerID = -1;
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_playing_ground, menu);
return true;
}
@Override
public void onFinishEvent() {
// Este metodo es llamado por la clase Fragment 'FinishEventFragment' cuando se
// pulsa el boton de 'Finalizar Evento' dentro del partido.
// Preguntara primero si deseamos acabar este evento y mostrara un resumen de lo sucedido.
// Almacenara los datos en la DB.
Toast.makeText(getApplicationContext(), "Finalizacion de evento", Toast.LENGTH_SHORT).show();
}
@Override
public void onClickPlayerSelectionEvent(int playerID) {
// Este metodo es llamado por la clase Fragment 'GridPlayersFragment' cuando se
// selecciona un jugador desde el GridView.
// Permite la interaccion de los jugadores que estan en el terreno de juego.
if(playerID==lastPlayerID && !entered){
// Si el jugador seleccionado es igual al jugador seleccionado con anterioridad y no habias mostrado sus opciones, entonces lo borras todo y las creas.
fm.popBackStack("playerOptions", FragmentManager.POP_BACK_STACK_INCLUSIVE); // Aqui se reinicia la pila de fragments.
FragmentPlayingGroundPlayersOptions pgpo1 = new FragmentPlayingGroundPlayersOptions();
Bundle args = new Bundle();
args.putInt("playerID", playerID);
args.putInt("lastDimension",0);
args.putInt("comeFromRbtn",-1);
args.putInt("branchType",-1);
pgpo1.setArguments(args);
ft = fm.beginTransaction();
ft.setCustomAnimations(R.animator.slide_in, R.animator.slide_out); // Se le añade animacion ed entrada/salida.
ft.replace(flBottom.getId(), pgpo1);
ft.addToBackStack("playerOptions"); // Esto es la pila donde se almacenan los fragments añadidos.
ft.commit();
entered = true;
}else if(playerID==lastPlayerID && entered){
// Si el jugador seleccionado es igual al jugador seleccionado con anterioridad y ya habias mostrado sus opciones, entonces las borras(todo).
fm.popBackStack("playerOptions", FragmentManager.POP_BACK_STACK_INCLUSIVE); // Aqui se reinicia la pila de fragments.
entered = false;
}
if(playerID!=lastPlayerID){
// Si el jugador seleccionado es distinto al jugador seleccionado con anterioridad, lo borras todo y muestras las opciones pertinenetes a ese nuevo jugador.
fm.popBackStack("playerOptions", FragmentManager.POP_BACK_STACK_INCLUSIVE); // Aqui se reinicia la pila de fragments.
FragmentPlayingGroundPlayersOptions pgpo1 = new FragmentPlayingGroundPlayersOptions();
Bundle args = new Bundle();
args.putInt("playerID", playerID);
args.putInt("lastDimension",0);
args.putInt("comeFromRbtn",-1);
args.putInt("branchType",-1);
pgpo1.setArguments(args);
ft = fm.beginTransaction();
ft.setCustomAnimations(R.animator.slide_in, R.animator.slide_out); // Se le añade animacion ed entrada/salida.
ft.replace(flBottom.getId(), pgpo1);
ft.addToBackStack("playerOptions"); // Esto es la pila donde se almacenan los fragments añadidos.
ft.commit();
entered = true;
}
lastPlayerID = playerID; // Almaceno el ultimo jugador seleccionado.
int[] pid = new int[1];
pid[0] = playerID;
sentences.ObtenerDatosDelimitadosJugadores(this, pid); // Mandamos la orden de obtener los datos de los jugadores.
String[] pna = sentences.getNombreApellidos();
dataSummaryToShow[0] = pna[0]; // Se almacena el nombre del jugador que realiza la accion.
}
@Override
public void onLongClickPlayerSelectionEvent(int playerID, int playersInUse[]) {
// Este metodo es llamado por la clase Fragment 'GridPlayersFragment' cuando se
// selecciona con Long clic un jugador desde el GridView.
// Permite realizar cambios en el jugador seleccionado con Long clic.
Intent i = new Intent(this, PopUpPlayersSelector.class);
playerToBeChanged = playerID;
i.putExtra("player_selected", playerID);
i.putExtra("players_in_use", playersInUse);
i.putExtra("first_time", false);
startActivityForResult(i, 102);
}
@Override
public void onClickOptionEvent(int rbtnIDSelected,int lastDimension, int branchType, String dataSelected) {
// Este es llamado por la clase Fragment 'PlayingGroundPlayersOptions' cuando
// se hace clic sobre un objeto que ofrece un dato sobre lo que esta realizando
// el jugador y necesita ademas que inicie otro fragment para continuar la cadena.
//Log.d("DEBUG", "DATASELECT: "+dataSelected+"; RBTN: "+rbtnIDSelected+"; DIMENSION: "+lastDimension+"; RAMA: "+branchType);
//Log.d("BACKSTAB NUM",""+fm.getBackStackEntryCount());
this.lastDimensionShowed = fm.getBackStackEntryCount(); // Se almacena la ultima posicion del fragment que se muestra (1,2,3,4).
//Log.d("A BORRAR", "PETICION DESDE: "+lastDimension+"; ULTIMO MOSTRADO: "+lastDimensionShowed);
for(int i = 4; i > 0; i--){ // Aqui se borran los BackStab superiores a "lastDimension".
if(this.lastDimensionShowed > lastDimension){
fm.popBackStackImmediate(i, FragmentManager.POP_BACK_STACK_INCLUSIVE);
this.lastDimensionShowed = fm.getBackStackEntryCount();
}
}
dataSummaryToShow[lastDimension] = dataSelected; // Se almacenan los datos recibidos para ser mostrados en resumen al final.
FragmentPlayingGroundPlayersOptions pgpoX = new FragmentPlayingGroundPlayersOptions();
Bundle args = new Bundle();
args.putInt("lastDimension", lastDimension);
args.putInt("comeFromRbtn", rbtnIDSelected);
args.putInt("branchType", branchType);
if((branchType==0 && lastDimension==2 && rbtnIDSelected==0) || (lastDimension==3) || (branchType==2 && lastDimension==2 && (rbtnIDSelected==0 || rbtnIDSelected==1 || rbtnIDSelected==2 || rbtnIDSelected==3)) || (branchType==1 && lastDimension==2 && rbtnIDSelected==1))
// Si el fragment para mostrar fuera el ultimo se le pasa un parametro extra con lo seleccionado hasta el momento.
args.putStringArray("dataToShow", dataSummaryToShow);
if((branchType==0 && lastDimension==2 && rbtnIDSelected==3) || (branchType==1 && lastDimension==2 && rbtnIDSelected==2) || (branchType==2 && lastDimension==2 && rbtnIDSelected==4) || (branchType==0 && lastDimension==1 && rbtnIDSelected==2))
// Si el fragment para mostrar tuviera seleccion de Jugador se le pasa un parametro extra con el array de jugadores en el campo.
args.putIntArray("playersOnTheField", playersID);
pgpoX.setArguments(args);
ft = fm.beginTransaction();
ft.setCustomAnimations(R.animator.fade_in, R.animator.fade_out); // Se le añade animacion de entrada/salida.
ft.add(flBottom.getId(), pgpoX);
ft.addToBackStack(lastDimension+"D"); // Esto es la pila donde se almacenan los fragments añadidos.
ft.commit();
Log.d("BACKSTAB NUM-AFTER",""+fm.getBackStackEntryCount());
}
@Override
public void onClickFinalOptionEvent() {
// Este metodo se ejecuta por la clase 'PlayingGroundPlayersOptions' cuando
// se acepta lo mostrado en el resumen y almacena en la DB las diversas
// opciones que se han ido seleccionando.
Toast.makeText(getApplicationContext(), "Se almacenan los datos en la DB y se ejecutan las acciones", Toast.LENGTH_SHORT).show();
fm.popBackStack("playerOptions", FragmentManager.POP_BACK_STACK_INCLUSIVE); // Aqui se reinicia la pila de fragments.
}
@Override
public void onClickEvent() {
// Este metodo es llamado por la clase Fragment 'SelectStartingPlayers' cuando
// se hace clic en el cartel añadir los primeros 11 jugadores.
Intent i = new Intent(this, PopUpPlayersSelector.class);
i.putExtra("first_time", true);
startActivityForResult(i, 101);
}
private void showGridPlayersFragment(int[] ID){
fgp = new FragmentGridPlayers();
Bundle args = new Bundle();
args.putIntArray("players_selected", ID);
fgp.setArguments(args);
ft = fm.beginTransaction();
ft.replace(flTopLeft.getId(), fgp);
ft.commit();
}
/**
* Este metodo es llamado para realizar un cambio de jugador en
* el GridView.
* @param playerIDToChange : ID del jugador en la DB.
*/
private void OnPlayerChanged(int playerIDToChange){
for(int i = 0; i < playersID.length; i++){
// Comprueba cada uno de los strings almacenados.
// Cuando detecta una coincidencia, cambia el valor del
// jugador anterior por el nuevo jugador a cambiar.
if(playersID[i]==playerToBeChanged){
playersID[i] = playerIDToChange;
break;
}
}
playerToBeChanged = -1; // Se asigna un valor neutro una vez finalizado el intercambio.
fgp.onSwapPlayer(playerIDToChange);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Este metodo es llamado automaticamente cuando iniciamos un activity nuevo
// con un 'Intent' y el metodo 'startActivityForResult()', en este se reciben
// los datos que nos devuelve el Activity al terminar su vida util.
switch(requestCode){
case 101:
if(resultCode==Activity.RESULT_OK){
playersID = data.getExtras().getIntArray("players_selection");
showGridPlayersFragment(playersID);
}else{
Toast.makeText(getApplicationContext(), getString(R.string.playingGround_toast_no_player_selected), Toast.LENGTH_SHORT).show();
}
break;
case 102:
if(resultCode==Activity.RESULT_OK){
OnPlayerChanged(data.getExtras().getInt("player_swap")); // Se obtiene el nuevo jugador a cambiar.
}else{
Toast.makeText(getApplicationContext(), getString(R.string.playingGround_toast_cancel_swap_player), Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
} | epl-1.0 |
sifeier/One | app/src/main/java/com/one/util/AssertsUtil.java | 94 | package com.one.util;
/**
* Created by buke on 15/10/19.
*/
public class AssertsUtil {
} | epl-1.0 |
FTSRG/mondo-collab-framework | archive/workspaceTracker/VA/ikerlanEMF.edit/src/eu/mondo/collaboration/operationtracemodel/example/WTSpec/provider/CtrlUnit84ItemProvider.java | 16552 | /**
*/
package eu.mondo.collaboration.operationtracemodel.example.WTSpec.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit84;
import eu.mondo.collaboration.operationtracemodel.example.WTSpec.WTSpecPackage;
/**
* This is the item provider adapter for a {@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit84} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class CtrlUnit84ItemProvider
extends wtcItemProvider
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CtrlUnit84ItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addInput__iAngleGH1PropertyDescriptor(object);
addInput__iAngleGH2PropertyDescriptor(object);
addInput__iAngleGH3PropertyDescriptor(object);
addInput__iStopCommandPropertyDescriptor(object);
addInput__iFlBrakesPropertyDescriptor(object);
addOutput__oAngleReference1PropertyDescriptor(object);
addOutput__oAngleReference2PropertyDescriptor(object);
addOutput__oAngleReference3PropertyDescriptor(object);
addOutput__oSpeedReferencePropertyDescriptor(object);
addOutput__oAccelerationReferencePropertyDescriptor(object);
addParameter__pPitchBrakeAnglePropertyDescriptor(object);
addParameter__pPitchStdSpeedPropertyDescriptor(object);
addParameter__pPitchStdAccelerationPropertyDescriptor(object);
addParameter__pPitchRegulationSpeedPropertyDescriptor(object);
addParameter__pPitchRegulationAccelerationPropertyDescriptor(object);
addErrorReaction__erEmergencyPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Input iAngle GH1 feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addInput__iAngleGH1PropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Input__iAngleGH1_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Input__iAngleGH1_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Input__iAngleGH1(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Input iAngle GH2 feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addInput__iAngleGH2PropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Input__iAngleGH2_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Input__iAngleGH2_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Input__iAngleGH2(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Input iAngle GH3 feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addInput__iAngleGH3PropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Input__iAngleGH3_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Input__iAngleGH3_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Input__iAngleGH3(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Input iStop Command feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addInput__iStopCommandPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Input__iStopCommand_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Input__iStopCommand_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Input__iStopCommand(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Input iFl Brakes feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addInput__iFlBrakesPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Input__iFlBrakes_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Input__iFlBrakes_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Input__iFlBrakes(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Output oAngle Reference1 feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addOutput__oAngleReference1PropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Output__oAngleReference1_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Output__oAngleReference1_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Output__oAngleReference1(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Output oAngle Reference2 feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addOutput__oAngleReference2PropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Output__oAngleReference2_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Output__oAngleReference2_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Output__oAngleReference2(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Output oAngle Reference3 feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addOutput__oAngleReference3PropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Output__oAngleReference3_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Output__oAngleReference3_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Output__oAngleReference3(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Output oSpeed Reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addOutput__oSpeedReferencePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Output__oSpeedReference_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Output__oSpeedReference_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Output__oSpeedReference(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Output oAcceleration Reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addOutput__oAccelerationReferencePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Output__oAccelerationReference_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Output__oAccelerationReference_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Output__oAccelerationReference(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Parameter pPitch Brake Angle feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addParameter__pPitchBrakeAnglePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Parameter__pPitchBrakeAngle_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Parameter__pPitchBrakeAngle_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Parameter__pPitchBrakeAngle(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Parameter pPitch Std Speed feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addParameter__pPitchStdSpeedPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Parameter__pPitchStdSpeed_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Parameter__pPitchStdSpeed_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Parameter__pPitchStdSpeed(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Parameter pPitch Std Acceleration feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addParameter__pPitchStdAccelerationPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Parameter__pPitchStdAcceleration_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Parameter__pPitchStdAcceleration_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Parameter__pPitchStdAcceleration(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Parameter pPitch Regulation Speed feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addParameter__pPitchRegulationSpeedPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Parameter__pPitchRegulationSpeed_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Parameter__pPitchRegulationSpeed_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Parameter__pPitchRegulationSpeed(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Parameter pPitch Regulation Acceleration feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addParameter__pPitchRegulationAccelerationPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_Parameter__pPitchRegulationAcceleration_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_Parameter__pPitchRegulationAcceleration_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_Parameter__pPitchRegulationAcceleration(),
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Error Reaction er Emergency feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addErrorReaction__erEmergencyPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit84_ErrorReaction__erEmergency_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit84_ErrorReaction__erEmergency_feature", "_UI_CtrlUnit84_type"),
WTSpecPackage.eINSTANCE.getCtrlUnit84_ErrorReaction__erEmergency(),
true,
false,
true,
null,
null,
null));
}
/**
* This returns CtrlUnit84.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/CtrlUnit84"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((CtrlUnit84)object).getSysId();
return label == null || label.length() == 0 ?
getString("_UI_CtrlUnit84_type") :
getString("_UI_CtrlUnit84_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| epl-1.0 |
sleshchenko/che | wsmaster/che-core-api-user/src/main/java/org/eclipse/che/api/user/server/DtoConverter.java | 1018 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.api.user.server;
import org.eclipse.che.api.core.model.user.User;
import org.eclipse.che.api.user.shared.dto.UserDto;
import org.eclipse.che.dto.server.DtoFactory;
/**
* Helps to convert to/from DTOs related to user.
*
* @author Anatoliy Bazko
*/
public final class DtoConverter {
/** Converts {@link User} to {@link UserDto}. */
public static UserDto asDto(User user) {
return DtoFactory.getInstance()
.createDto(UserDto.class)
.withId(user.getId())
.withEmail(user.getEmail())
.withName(user.getName())
.withAliases(user.getAliases());
}
private DtoConverter() {}
}
| epl-1.0 |
DavidGutknecht/elexis-3-base | bundles/ch.elexis.laborimport.synlab/src/ch/elexis/laborimport/synlab/Messages.java | 557 | // Copyright 2010 (c) Niklaus Giger <niklaus.giger@member.fsf.org>
package ch.elexis.laborimport.synlab;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
private static final String BUNDLE_NAME = "ch.elexis.laborimport.synlab.messages"; //$NON-NLS-1$
public static String PreferencePage_DownloadDir;
public static String PreferencePage_JMedTrasferJar;
public static String PreferencePage_JMedTrasferJni;
static {
// initialize resource bundle
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
private Messages(){}
}
| epl-1.0 |
comutt/yukinoshita2 | src/org/unitarou/yukinoshita/view/jface/db/FingerprintFilterIgoBoard.java | 11282 | /*
* Copyright 2004-2009 unitarou <boss@unitarou.org>.
* All rights reserved.
*
* This program and the accompanying materials are made available under the terms of
* the Common Public License v1.0 which accompanies this distribution,
* and is available at http://opensource.org/licenses/cpl.php
*
* Contributors:
* unitarou - initial API and implementation
*/
package org.unitarou.yukinoshita.view.jface.db;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.unitarou.lang.ArgumentChecker;
import org.unitarou.lang.Strings;
import org.unitarou.sgf.Property;
import org.unitarou.sgf.RootGameTree;
import org.unitarou.sgf.SgfId;
import org.unitarou.sgf.Value;
import org.unitarou.sgf.type.GameType;
import org.unitarou.sgf.type.Handicap;
import org.unitarou.sgf.type.SgfColor;
import org.unitarou.sgf.type.SgfPoint;
import org.unitarou.sgf.type.SgfSize;
import org.unitarou.sgf.util.Fingerprint;
import org.unitarou.sgf.util.Fingerprints;
import org.unitarou.sgf.util.RootGameTreeFactory;
import org.unitarou.sgf.util.SgfRectangle;
import org.unitarou.sgf.util.Stone;
import org.unitarou.swt.Swts;
import org.unitarou.swt.WidgetContainer;
import org.unitarou.util.Filter;
import org.unitarou.yukinoshita.view.jface.board.RuledLinePainter;
import org.unitarou.yukinoshita.view.jface.board.SimpleRuledLinePainter;
import org.unitarou.yukinoshita.view.jface.board.bp.BoardPainter;
import org.unitarou.yukinoshita.view.jface.board.bp.SimpleBoardPainter;
import org.unitarou.yukinoshita.view.jface.board.mp.DimPointsPainter;
import org.unitarou.yukinoshita.view.jface.board.sp.StonePainter;
import org.unitarou.yukinoshita.view.jface.board.sp.StonePainterParameter;
/**
* FingerprintÅõ·é½ßÌplÅ·B
* ydlz
* FingerprintÌÝó¯æéB<br>
* ³·éÌæÍDMÅ\»·éB
* PainterAProviderÍÅè(«ReLXg˶³¹é)<br>
*@ÀWÆÏ»}Íñ\¦Åè<br>
* {ÌÝAn}ðæçÈ¢(SÄã«)<br>
* léÍÅÌSetupm[hÉA»êÈOÍÅI
èÉ·éB<br>
* VW,DMÉÍεĢéB<br>
* RGTªÝè³ê½iKÅImageÅ`æ·éBubNPÊÍȵB<br>
*
*
* @author UNITAROU <boss@unitarou.org>
*/
class FingerprintFilterIgoBoard implements WidgetContainer {
/** éÕÌØnð`æ·éIuWFNgÅ·B*/
private final BoardPainter boardPainter_;
/** rüð`æ·éIuWFNgÅ·B*/
private final RuledLinePainter ruledLinePainter_;
/** Îð`æ·éIuWFNgÅ·B*/
private final StonePainter stonePainter_;
/** tB^[ªð`æ·éIuWFNgÅ·B */
private final DimPointsPainter dimPointsPainter_;
/** ±ÌplÌgbvWidgetÅ·B*/
private Canvas canvas_;
/** `æ³ê½éÕÌC[Wð۵ܷB*/
private Image boardImage_;
/** tB^[pÌéÕ(f)Å·B*/
private RootGameTree rgt_;
/** »ÝÌÕÊÌíÊ(û©lé©)ð۵ܷB*/
private GameType gameType_;
/**
* ÕTCY19x19AûASÌæðõÎÛOÅú»µÜ·B
* @param gameType ûÌõÆléÌõÅ®ªá¤ÌÅKvBNOT NULL
*/
public FingerprintFilterIgoBoard(GameType gameType) {
super();
ArgumentChecker.throwIfNull(gameType);
boardPainter_ = new SimpleBoardPainter();
ruledLinePainter_ = new SimpleRuledLinePainter();
stonePainter_ = StonePainter.CONTEXT.defaultValue();
dimPointsPainter_ = new DimPointsPainter();
canvas_ = null;
boardImage_ = null;
rgt_ = RootGameTreeFactory.createGame(SgfSize.DEFAULT, new Handicap(0));
rgt_.setGameType(gameType);
rgt_.getRootNode().addProperty(
SgfId.DIM_POINTS.makeProperty(rgt_.getSize().all())
);
gameType_ = GameType.GAME;
}
/*
* @see org.unitarou.swt.WidgetContainer#createContents(org.eclipse.swt.widgets.Composite)
*/
public Canvas createContents(Composite parent) {
ArgumentChecker.throwIfNull(parent);
canvas_ = new Canvas(parent, SWT.NO_BACKGROUND);
boardImage_ = new Image(canvas_.getDisplay(), getBoardSize());
canvas_.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
if (boardImage_ == null) {
drawImage();
}
e.gc.drawImage(boardImage_, e.x, e.y, e.width, e.height, e.x, e.y, e.width, e.height);
}
});
canvas_.addControlListener(new ControlAdapter() {
/*
* @see org.eclipse.swt.events.ControlAdapter#controlResized(org.eclipse.swt.events.ControlEvent)
*/
@Override
public void controlResized(ControlEvent e) {
Swts.disposeQuietly(boardImage_);
boardImage_ = null;
}
});
return canvas_;
}
/**
* plÌÅãÊÌRg[ðԵܷB<br>
* ±ÌNXÅÍ[@link Canvas}IuWFNgðԵܷB
* @return CanvasIuWFNgB{@link #createContents(Composite)}ÌOÉÄÑo·ÆNULL
*/
public Canvas getControl() {
return canvas_;
}
/*
* @see org.unitarou.swt.WidgetContainer#close()
*/
public void close() {
Swts.disposeQuietly(boardImage_);
}
/**
* éÕÌTCYðÏXµÄAÕðú»µÜ·B
* @param gameType
* @param sgfSize
* @throws org.unitarou.lang.NullArgumentException øªnullÌê
*/
public void updateImage(GameType gameType, SgfSize sgfSize) {
ArgumentChecker.throwIfNull(gameType, sgfSize);
gameType_ = gameType;
rgt_.setSize(sgfSize);
if (canvas_ == null) {
return;
}
Swts.disposeQuietly(boardImage_);
boardImage_ = null;
canvas_.redraw();
}
/**
*
*/
private void drawImage() {
GC gc = null;
try {
boardImage_ = new Image(canvas_.getDisplay(), getBoardSize());
gc = new GC(boardImage_);
drawImageImpl(gc);
} finally {
Swts.disposeQuietly(gc);
}
}
/**
* TODO }WbNio[
* @return éÕÌTCY(px)
*/
private Rectangle getBoardSize() {
if (canvas_ == null) {
return new Rectangle(0,0,100,100);
}
Rectangle canvasRect = canvas_.getBounds();
if (canvasRect.width == 0 || canvasRect.height == 0) {
return new Rectangle(0,0,100,100);
}
return canvasRect;
}
/**
* ÀÛÉ`æðs¢Ü·B
* @param gc
*/
private void drawImageImpl(GC gc) {
Fingerprint fingerprint = Fingerprints.calcFingerprint(rgt_);
SgfPoint[] dimarea = getDimArea();
Set<SgfPoint> ntArea = new HashSet<SgfPoint>(dimarea.length);
Filter<SgfPoint> filter = fingerprint.getFilter();
for (SgfPoint point : dimarea) {
ntArea.add(filter.filter(point));
}
SgfSize sgfSize = rgt_.getSize();
SgfRectangle viewArea = calcViewArea(sgfSize, fingerprint);
Rectangle imageSize = boardImage_.getBounds();
int block = Math.min(
imageSize.width / viewArea.width(),
imageSize.height / viewArea.height());
// `æJn
// wiðhé
gc.setBackground(canvas_.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
gc.fillRectangle(imageSize);
if (block < 3) {
return;
}
Point offset = new Point(
(imageSize.width - block * viewArea.width()) / 2,
(imageSize.height - block * viewArea.height()) / 2);
// \¦TCYÆÊuÉ]ÁÄubNPÊÅ`æðs¤B
SgfPoint startPos = viewArea.getStart();
StonePainterParameter spParam = new StonePainterParameter();
for (int y = startPos.y(); y <= viewArea.getEnd().y(); ++y) {
for (int x = startPos.x(); x <= viewArea.getEnd().x(); ++x) {
SgfPoint sgfPoint = SgfPoint.create(sgfSize, x, y);
Rectangle paintArea = new Rectangle(
(x - 1) * block + offset.x,
(y - 1) * block + offset.y,
block,
block);
boardPainter_.paint(gc, sgfPoint, paintArea);
ruledLinePainter_.paint(gc, sgfPoint, paintArea);
SgfColor color = fingerprint.getColor(x, y);
if (color != null) {
Stone stone = new Stone(color, sgfPoint, null);
setParameters(spParam, stone);
stonePainter_.paintStone(gc, paintArea, spParam);
}
if (ntArea.contains(sgfPoint)) {
dimPointsPainter_.paint(gc, paintArea, false);
}
}
}
}
/**
* @return DMGAªSÄüÁ½zñBNOT NULL
*/
private SgfPoint[] getDimArea() {
Property p = rgt_.getRootNode().getProperty(SgfId.DIM_POINTS);
if (p == null) {
return new SgfPoint[0];
}
String[] strPoints = p.getStrings();
return SgfPoint.parse(rgt_.getSize(), strPoints);
}
/**
* `æÌæðԵܷB<br>
* FingerPrintÍK¸¶ã(1,1)¤ÉΪ éÌÅA
* Eº(19,19)©çÉíÁÄ¢«Ü·B
* @param sgfSize
* @param fingerprint tBK[vg
* @return `æÌæ
*/
private SgfRectangle calcViewArea(SgfSize sgfSize, Fingerprint fingerprint) {
SgfRectangle viewArea = new SgfRectangle();
viewArea.set(
SgfPoint.create(sgfSize, 1, 1),
SgfPoint.create(sgfSize, sgfSize.width(), sgfSize.height()));
if (!GameType.PROBLEM.equals(gameType_)) {
return viewArea;
}
int maxX = sgfSize.width();
for (int x = maxX; x >= 2; --x) {
boolean stoneFound = false;
for (int y = 1; y <= sgfSize.height(); ++y) {
if (null != fingerprint.getColor(x, y)) {
stoneFound = true;
break;
}
}
if (stoneFound) {
break;
}
maxX = x;
}
int maxY = sgfSize.height();
for (int y = maxY; y >= 2; --y) {
boolean stoneFound = false;
for (int x = 1; x <= sgfSize.width(); ++x) {
if (null != fingerprint.getColor(x, y)) {
stoneFound = true;
break;
}
}
if (stoneFound) {
break;
}
maxY = y;
}
viewArea.set(
SgfPoint.create(sgfSize, 1, 1),
SgfPoint.create(sgfSize, maxX, maxY));
return viewArea;
}
/**
* ÅI
èFfalseA§ßfalseÅÝèµÜ·B
* @param param
* @param stone
*/
private void setParameters(StonePainterParameter param, Stone stone) {
param.setSgfColor(stone.getColor());
param.setLastMove(false);
param.setTransient(false);
}
/**
* @return NOT NULL
*/
public SgfSize getSize() {
return rgt_.getSize();
}
/**
* @return Ô|¯ÌæBNOT NULL
*/
public Set<SgfPoint> getFilter() {
SgfPoint[] dimarea = getDimArea();
return new HashSet<SgfPoint>(Arrays.asList(dimarea));
}
/**
* @param dimArea
*/
public void setFilter(List<SgfPoint> dimArea) {
ArgumentChecker.throwIfNull(dimArea);
Property p = rgt_.getRootNode().getProperty(SgfId.DIM_POINTS);
if (p == null) {
p = new Property(SgfId.DIM_POINTS, Strings.EMPTY);
} else {
p.clearValue();
}
for (SgfPoint point : dimArea) {
p.addValue(new Value(point.getString()));
}
rgt_.getRootNode().addProperty(p);
}
/**
* @param rgt
*/
public void setGame(RootGameTree rgt) {
rgt_ = new RootGameTree(rgt);
boardImage_ = null;
canvas_.redraw();
}
/**
* @return NOT NULL
*/
public RootGameTree getGame() {
return new RootGameTree(rgt_);
}
}
| epl-1.0 |
SmithRWORNL/ice | src/org.eclipse.ice.viz/src/org/eclipse/ice/viz/csv/viewer/CSVDataTableViewer.java | 8288 | /*******************************************************************************
* Copyright (c) 2014 UT-Battelle, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Initial API and implementation and/or initial documentation - Jay Jay Billings,
* Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson,
* Claire Saunders, Matthew Wang, Anna Wojtowicz
*******************************************************************************/
package org.eclipse.ice.viz.csv.viewer;
import java.util.ArrayList;
import org.eclipse.ice.viz.VizFileViewer;
import org.eclipse.ice.viz.service.csv.CSVDataProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.part.ViewPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class extends the ViewPart class and provides a view in the
* Visualization Perspective to display the raw data associated with currently
* displayed CSV plot.
*
* @author Taylor Patterson, Matthew Wang
*
*/
public class CSVDataTableViewer extends ViewPart implements ISelectionListener {
/**
* Logger for handling event messages and other information.
*/
private static final Logger logger = LoggerFactory
.getLogger(CSVDataTableViewer.class);
/**
* The ID for this view
*/
public static final String ID = "org.eclipse.ice.viz.plotviewer.CSVDataTableViewer";
/**
* The TabFolder for the
*/
private TabFolder timesTabFolder;
/**
* The list of existing tabs
*/
private ArrayList<String> tabs;
/**
* (non-Javadoc)
*
* @see org.eclipse.ui.part.WorkbenchPart#createPartControl(Composite)
*/
@Override
public void createPartControl(Composite parent) {
// Initialize the TabFolder and the list of tabs
timesTabFolder = new TabFolder(parent, SWT.NONE);
tabs = new ArrayList<String>();
// Register as a listener to the VizFileViewer.
getSite().getWorkbenchWindow().getSelectionService()
.addPostSelectionListener(VizFileViewer.ID, this);
return;
}
/**
* (non-Javadoc)
*
* @see org.eclipse.ui.part.WorkbenchPart#setFocus()
*/
@Override
public void setFocus() {
// Do nothing yet.
return;
}
/**
* Update this view based on selections in the {@link VizFileViewer}.
*
* @see org.eclipse.ui.ISelectionListener#selectionChanged(IWorkbenchPart,
* ISelection)
*/
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
// FIXME Disabling this until the issues are resolved;
// // Check that the selection's source is the VizFileViewer.
// // Try to get the VizResource from the ISelection. We first have to
// // cast the ISelection to an IStructuredSelection, whose first
// // element should be a VizResource.
// if (part.getSite().getId().equals(VizFileViewer.ID)
// && selection != null
// && selection instanceof IStructuredSelection) {
// IStructuredSelection structuredSelection = (IStructuredSelection)
// selection;
// if (!structuredSelection.isEmpty()) {
// Object object = structuredSelection.getFirstElement();
//
// if (object instanceof VizResource) {
// VizResource resource = (VizResource) object;
// String fileName = "";
//
// if (resource.getFileSet() != null
// && resource.getFileSetTitle() != null) {
// fileName = resource.getFileSetTitle();
// } else {
// fileName = resource.getContents().getAbsolutePath();
// }
//
// // Create a CSVDataLoader and CSVDataProvider if the
// // selection is a .csv file set
// CSVDataProvider newDataProvider = null;
// CSVDataLoader newCSVDataLoader = null;
//
// // Handle a CSV file
// if (fileName.matches(".*\\.csv$")) {
//
// // Initialize the CSVDataLoader
// newCSVDataLoader = new CSVDataLoader();
//
// // Create the CSVDataProvider from a file set
// if (resource.getFileSet() != null
// && resource.getFileSetTitle() != null) {
//
// // Initialize the CSVDataProvider
// newDataProvider = newCSVDataLoader
// .loadAsFileSet(resource.getFileSet());
//
// // Set the source as the file name
// newDataProvider.setSource(resource
// .getFileSetTitle());
// }
//
// // Or create the CSVDataProvider from a file
// else {
//
// // Initialize the CSVDataProvider
// newDataProvider = newCSVDataLoader.load(fileName);
//
// // Set the source as the file name
// File file = resource.getContents();
// newDataProvider.setSource(file.getName());
// }
// } else {
// return;
// }
//
// // Refresh this view based on the selection
// refreshDataTable(newDataProvider);
// }
// }
// }
return;
}
/**
* This function creates a new data table in the CSV Data Table Viewer to
* display the new provider.
*
* @param newDataProvider
* The CSVDataProvider to populate the view
*/
public void refreshDataTable(CSVDataProvider newDataProvider) {
logger.info("CSVDataTableViewer Message: Refreshing the data "
+ "table: " + newDataProvider.getSourceInfo());
// Iterates through the times
for (Double time : newDataProvider.getTimes()) {
// Sets the time for the provider
newDataProvider.setTime(time);
// FIXME We need a better check for existing tabs
if (!tabs.contains(time.toString())) {
// Create a new tab of the time for the loaded file
TabItem newTimeTab = new TabItem(timesTabFolder, SWT.NONE);
newTimeTab.setText(time.toString());
// Add to the list of the existing tabs
tabs.add(time.toString());
// Get the independent variables and features from the
// new data provider to be used to set up the columns
ArrayList<String> independentVarsAndFeatures = new ArrayList<String>();
independentVarsAndFeatures.addAll(newDataProvider
.getIndependentVariables());
independentVarsAndFeatures.addAll(newDataProvider
.getFeaturesAtCurrentTime());
// Get the number of columns
int numColumns = independentVarsAndFeatures.size();
// Creating the composite for the table viewer
Composite tableViewerComp = new Composite(timesTabFolder,
SWT.BORDER);
tableViewerComp.setLayout(new GridLayout(1, false));
tableViewerComp.setLayoutData(new GridData(SWT.DEFAULT,
SWT.DEFAULT, true, true));
// Sets the control of the tab to the composite for the table
// view
newTimeTab.setControl(tableViewerComp);
// Creating the table viewer
TableViewer viewer = new TableViewer(tableViewerComp,
SWT.BORDER | SWT.FULL_SELECTION);
// Creating the layout of columns
TableLayout layout = new TableLayout();
for (int k = 0; k < numColumns; k++) {
layout.addColumnData(new ColumnWeightData(2,
ColumnWeightData.MINIMUM_WIDTH, true));
}
viewer.getTable().setLayout(layout);
// Setting the layout of the table
viewer.getControl().setLayoutData(
new GridData(SWT.FILL, SWT.FILL, true, true));
// Showing the headers
viewer.getTable().setLinesVisible(true);
viewer.getTable().setHeaderVisible(true);
// Set the content providers
viewer.setContentProvider(new DataTableContentProvider());
viewer.setLabelProvider(new DataTableLabelProvider());
// Setting the column text
for (String columnText : independentVarsAndFeatures) {
TableColumn newColumn = new TableColumn(viewer.getTable(),
SWT.CENTER);
newColumn.setText(columnText);
}
// Setting the input
viewer.setInput(newDataProvider);
// Refreshing the composite so the table will show
tableViewerComp.layout();
timesTabFolder.layout();
}
}
return;
}
}
| epl-1.0 |
oat-sa/tao-core | test/unit/models/classes/search/ResultSetMapperTest.php | 4815 | <?php
/**
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; under version 2
* of the License (non-upgradable).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright (c) 2020 (original work) Open Assessment Technologies SA;
*
*/
declare(strict_types=1);
namespace oat\tao\test\unit\model\search;
use oat\generis\test\TestCase;
use oat\tao\model\AdvancedSearch\AdvancedSearchChecker;
use oat\tao\model\search\ResultSetMapper;
class ResultSetMapperTest extends TestCase
{
/** @var ResultSetMapper */
private $subject;
private $advancedSearchChecker;
public function setUp(): void
{
$this->subject = new ResultSetMapper(
[
ResultSetMapper::OPTION_STRUCTURE_MAP => [
'default' => [
'label' => [
'id' => 'label',
'label' => __('Label'),
'sortable' => false
]
],
'results' => [
'default' => null,
'advanced' => [
'test_taker' => [
'id' => 'test_taker',
'label' => 'Test Taker',
'sortable' => false
],
'label' => [
'id' => 'label',
'label' => 'Label',
'sortable' => false
],
'test_taker_name' => [
'id' => 'test_taker_name',
'label' => 'Test Taker',
'sortable' => false
],
],
],
]
]
);
$this->advancedSearchChecker = $this->createMock(AdvancedSearchChecker::class);
$this->subject->setServiceLocator(
$this->getServiceLocatorMock(
[
AdvancedSearchChecker::class => $this->advancedSearchChecker
]
)
);
}
/**
* @dataProvider getScenariosData
*/
public function testGetPromiseModelResults(array $expectedResult, string $mappedField, bool $elasticSearchEnabled): void
{
$this->advancedSearchChecker
->expects($this->once())
->method('isEnabled')
->willReturn($elasticSearchEnabled);
$result = $this->subject->map($mappedField);
$this->assertEquals($expectedResult, $result);
}
public function getScenariosData()
{
return [
'result search with elastic search enabled' => [
[
'label' => [
'id' => 'label',
'label' => __('Label'),
'sortable' => false
],
'test_taker_name' => [
'id' => 'test_taker_name',
'label' => __('Test Taker'),
'sortable' => false
],
'test_taker' => [
'id' => 'test_taker',
'label' => __('Test Taker'),
'sortable' => false
],
],
'results',
true,
],
'result search with elastic search disabled' => [
[
'label' => [
'id' => 'label',
'label' => __('Label'),
'sortable' => false
],
],
'results',
false,
],
'different search with elastic search enabled' => [
[
'label' => [
'id' => 'label',
'label' => __('Label'),
'sortable' => false
],
],
'different',
true,
]
];
}
}
| gpl-2.0 |
Shigaru/shigaru | components/com_hwdvideoshare/assets/js/AC_OETags.js | 8078 |
//
// Flash Player Version Detection - Rev 1.6
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
function ControlVersion()
{
var version;
var axo;
var e;
// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry
try {
// version will be set for 7.X or greater players
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
version = axo.GetVariable("$version");
} catch (e) {
}
if (!version)
{
try {
// version will be set for 6.X players only
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
// installed player is some revision of 6.0
// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
// so we have to be careful.
// default to the first public version
version = "WIN 6,0,21,0";
// throws if AllowScripAccess does not exist (introduced in 6.0r47)
axo.AllowScriptAccess = "always";
// safe to call for 6.0r47 or greater
version = axo.GetVariable("$version");
} catch (e) {
}
}
if (!version)
{
try {
// version will be set for 4.X or 5.X player
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
version = axo.GetVariable("$version");
} catch (e) {
}
}
if (!version)
{
try {
// version will be set for 3.X player
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
version = "WIN 3,0,18,0";
} catch (e) {
}
}
if (!version)
{
try {
// version will be set for 2.X player
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
version = "WIN 2,0,0,11";
} catch (e) {
version = -1;
}
}
return version;
}
// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
// NS/Opera version >= 3 check for Flash plugin in plugin array
var flashVer = -1;
if (navigator.plugins != null && navigator.plugins.length > 0) {
if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
var descArray = flashDescription.split(" ");
var tempArrayMajor = descArray[2].split(".");
var versionMajor = tempArrayMajor[0];
var versionMinor = tempArrayMajor[1];
var versionRevision = descArray[3];
if (versionRevision == "") {
versionRevision = descArray[4];
}
if (versionRevision[0] == "d") {
versionRevision = versionRevision.substring(1);
} else if (versionRevision[0] == "r") {
versionRevision = versionRevision.substring(1);
if (versionRevision.indexOf("d") > 0) {
versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
}
}
var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
}
}
// MSN/WebTV 2.6 supports Flash 4
else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
// WebTV 2.5 supports Flash 3
else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
// older WebTV supports Flash 2
else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
else if ( isIE && isWin && !isOpera ) {
flashVer = ControlVersion();
}
return flashVer;
}
// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
versionStr = GetSwfVer();
if (versionStr == -1 ) {
return false;
} else if (versionStr != 0) {
if(isIE && isWin && !isOpera) {
// Given "WIN 2,0,0,11"
tempArray = versionStr.split(" "); // ["WIN", "2,0,0,11"]
tempString = tempArray[1]; // "2,0,0,11"
versionArray = tempString.split(","); // ['2', '0', '0', '11']
} else {
versionArray = versionStr.split(".");
}
var versionMajor = versionArray[0];
var versionMinor = versionArray[1];
var versionRevision = versionArray[2];
// is the major.revision >= requested major.revision AND the minor version >= requested minor
if (versionMajor > parseFloat(reqMajorVer)) {
return true;
} else if (versionMajor == parseFloat(reqMajorVer)) {
if (versionMinor > parseFloat(reqMinorVer))
return true;
else if (versionMinor == parseFloat(reqMinorVer)) {
if (versionRevision >= parseFloat(reqRevision))
return true;
}
}
return false;
}
}
function AC_AddExtension(src, ext)
{
if (src.indexOf('?') != -1)
return src.replace(/\?/, ext+'?');
else
return src + ext;
}
function AC_Generateobj(objAttrs, params, embedAttrs)
{
var str = '';
if (isIE && isWin && !isOpera)
{
str += '<object ';
for (var i in objAttrs)
str += i + '="' + objAttrs[i] + '" ';
str += '>';
for (var i in params)
str += '<param name="' + i + '" value="' + params[i] + '" /> ';
str += '</object>';
} else {
str += '<embed ';
for (var i in embedAttrs)
str += i + '="' + embedAttrs[i] + '" ';
str += '> </embed>';
}
document.write(str);
}
function AC_FL_RunContent(){
var ret =
AC_GetArgs
( arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
, "application/x-shockwave-flash"
);
AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
var ret = new Object();
ret.embedAttrs = new Object();
ret.params = new Object();
ret.objAttrs = new Object();
for (var i=0; i < args.length; i=i+2){
var currArg = args[i].toLowerCase();
switch (currArg){
case "classid":
break;
case "pluginspage":
ret.embedAttrs[args[i]] = args[i+1];
break;
case "src":
case "movie":
args[i+1] = AC_AddExtension(args[i+1], ext);
ret.embedAttrs["src"] = args[i+1];
ret.params[srcParamName] = args[i+1];
break;
case "onafterupdate":
case "onbeforeupdate":
case "onblur":
case "oncellchange":
case "onclick":
case "ondblClick":
case "ondrag":
case "ondragend":
case "ondragenter":
case "ondragleave":
case "ondragover":
case "ondrop":
case "onfinish":
case "onfocus":
case "onhelp":
case "onmousedown":
case "onmouseup":
case "onmouseover":
case "onmousemove":
case "onmouseout":
case "onkeypress":
case "onkeydown":
case "onkeyup":
case "onload":
case "onlosecapture":
case "onpropertychange":
case "onreadystatechange":
case "onrowsdelete":
case "onrowenter":
case "onrowexit":
case "onrowsinserted":
case "onstart":
case "onscroll":
case "onbeforeeditfocus":
case "onactivate":
case "onbeforedeactivate":
case "ondeactivate":
case "type":
case "codebase":
ret.objAttrs[args[i]] = args[i+1];
break;
case "id":
case "width":
case "height":
case "align":
case "vspace":
case "hspace":
case "class":
case "title":
case "accesskey":
case "name":
case "tabindex":
ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
break;
default:
ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
}
}
ret.objAttrs["classid"] = classid;
if (mimeType) ret.embedAttrs["type"] = mimeType;
return ret;
}
| gpl-2.0 |
FIRST-Team-2557-The-SOTABots/FRC_Robot | Robot/src/main/java/org/usfirst/frc/team2557/robot/commands/autonomous/sequences/Auto_Pos1Left.java | 745 | package org.usfirst.frc.team2557.robot.commands.autonomous.sequences;
import edu.wpi.first.wpilibj.command.CommandGroup;
import org.usfirst.frc.team2557.robot.commands.automation.Auto_LoadBall;
import org.usfirst.frc.team2557.robot.commands.chassis.EncoderPosDriveCommand;
import org.usfirst.frc.team2557.robot.commands.chassis.TurnByAngleCommand;
public class Auto_Pos1Left extends CommandGroup {
public Auto_Pos1Left() {
this.addParallel(new Auto_LoadBall());
this.addSequential(new EncoderPosDriveCommand(9088, 0.65));
this.addSequential(new TurnByAngleCommand(59.4));
this.addSequential(new EncoderPosDriveCommand(3023, 0.5));
this.addSequential(new Auto_CameraShootSequence());
}
}
| gpl-2.0 |
miiicmueller/TerraZoo | contiki-2.7/tools/cooja/java/se/sics/cooja/util/ArrayUtils.java | 4811 | /*
* Copyright (c) 2009, Swedish Institute of Computer Science. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the
* Institute 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 INSTITUTE 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 INSTITUTE 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.
*
*/
package se.sics.cooja.util;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Some utility methods for managing arrays.
*
* @author Niclas Finne, Fredrik Osterlind
*/
public class ArrayUtils {
@SuppressWarnings("unchecked")
public static <T> T[] add(T[] array, T value) {
T[] tmp = (T[]) java.lang.reflect.Array.newInstance(
((Class<? extends T>)array.getClass()).getComponentType(),
array.length + 1);
System.arraycopy(array, 0, tmp, 0, array.length);
tmp[array.length] = value;
return tmp;
}
@SuppressWarnings("unchecked")
public static <T> T[] remove(T[] array, int index) {
if ((index < 0) || (index >= array.length)) {
throw new ArrayIndexOutOfBoundsException(index);
}
T[] tmp = (T[]) java.lang.reflect.Array.newInstance(
((Class<? extends T>)array.getClass()).getComponentType(),
array.length - 1);
if (index > 0) {
System.arraycopy(array, 0, tmp, 0, index);
}
if (index < tmp.length) {
System.arraycopy(array, index + 1, tmp, index, tmp.length - index);
}
return tmp;
}
public static <T> T[] remove(T[] array, T element) {
int index = indexOf(array, element);
return (index >= 0) ? remove(array, index) : array;
}
public static <T> int indexOf(T[] array, T element) {
if (array != null) {
if (element == null) {
for (int i = 0, n = array.length; i < n; i++) {
if (array[i] == null) {
return i;
}
}
} else {
for (int i = 0, n = array.length; i < n; i++) {
if (element.equals(array[i])) {
return i;
}
}
}
}
return -1;
}
public static boolean writeToFile(File dest, byte[] data) {
try {
FileOutputStream writer = new FileOutputStream(dest);
writer.write(data);
writer.flush();
writer.close();
return true;
} catch (IOException e) {
return false;
}
}
public static byte[] readFromFile(File file) {
long fileSize = file.length();
byte[] fileData = new byte[(int) fileSize];
FileInputStream fileIn;
DataInputStream dataIn;
int offset = 0;
int numRead = 0;
try {
fileIn = new FileInputStream(file);
dataIn = new DataInputStream(fileIn);
while (offset < fileData.length
&& (numRead = dataIn.read(fileData, offset, fileData.length - offset)) >= 0) {
offset += numRead;
}
dataIn.close();
fileIn.close();
return fileData;
} catch (Exception ex) {
return null;
}
}
public static byte[] readFromStream(InputStream input) {
try {
int numRead = 0;
int offset = 0;
byte data[] = new byte[input.available()*2];
DataInputStream dataIn = new DataInputStream(input);
while ((numRead = dataIn.read(data, offset, data.length-offset)) >= 0) {
offset += numRead;
}
byte[] streamData = new byte[offset];
System.arraycopy(data, 0, streamData, 0, offset);
return streamData;
} catch (Exception ex) {
return null;
}
}
}
| gpl-2.0 |
gstiebler/vision_workbench | src/Windows/MainWindow.cpp | 5657 | /*
* MainWindow.cpp
*
* Created on: 18/10/2014
* Author: Guilherme
*/
#include "MainWindow.h"
#include <QStandardItemModel>
#include <QFileDialog>
#include <QMessageBox>
#include <string>
#include <opencv2/opencv.hpp>
#include <QFileDialog>
#include <QMouseEvent>
#include "VideoWindow.h"
#include "ThresholdWindow.h"
#include "FilesWindow.h"
#include "RegionGrowthWindow.h"
#include "ViewerWindow.h"
#include "PlateLocationWindow.h"
using namespace std;
using namespace cv;
static void SetLabelImage(QLabel *label, QPixmap &pixmap, int height)
{
pixmap = pixmap.scaledToHeight(height, Qt::SmoothTransformation);
label->setPixmap(pixmap);
label->show();
}
MainWindow::MainWindow(string initialImage)
{
setupUi(this);
srcImageLabel = initializeImageWidget("srcImage", 0);
dstImageLabel = initializeImageWidget("dstImage", 1);
QObject::connect( buttonExecute, &QPushButton::clicked, this, &MainWindow::executeClicked);
QObject::connect( srcImageLabel, &QMouseEventerImage::mousePressed, [this] (QMouseEvent *event) {
ViewerWindow *window = new ViewerWindow(this);
connect( this, &MainWindow::srcImageChanged, window, &ViewerWindow::imageChanged );
emit srcImageChanged(_srcImage);
QObject::connect( window, &ViewerWindow::mousePressed, this, &MainWindow::mousePressedOnViewerWindow);
window->show();
});
QObject::connect( dstImageLabel, &QMouseEventerImage::mousePressed, [this] (QMouseEvent *event) {
ViewerWindow *window = new ViewerWindow(this);
connect( this, &MainWindow::dstImageChanged, window, &ViewerWindow::imageChanged );
QObject::connect( window, &ViewerWindow::mousePressed, this, &MainWindow::mousePressedOnViewerWindow);
emit dstImageChanged(_dstImage);
window->show();
});
QObject::connect( videoWindowButton, &QPushButton::clicked, [this] () {
VideoWindow *window = new VideoWindow(this, this);
window->show();
});
QObject::connect( thresholdButton, &QPushButton::clicked, [this] () {
ThresholdWindow *window = new ThresholdWindow(this, *this);
window->show();
});
QObject::connect( filesWindowButton, &QPushButton::clicked, [this] () {
FilesWindow *window = new FilesWindow(this, *this);
window->show();
});
QObject::connect( regionGrowthWindowButton, &QPushButton::clicked, [this] () {
RegionGrowthWindow *window = new RegionGrowthWindow(this, *this);
QObject::connect(this, &MainWindow::mousePressedOnViewerWindow, window, &RegionGrowthWindow::mousePressed);
window->show();
});
QObject::connect( plateLocationButton, &QPushButton::clicked, [this] () {
PlateLocationWindow *window = new PlateLocationWindow(this, *this);
window->show();
});
QObject::connect( colorMapButton, &QPushButton::clicked, [this] () {
Mat grayImage, dstImage;
Mat ones(_srcImage.rows, _srcImage.cols, CV_8UC1, Scalar(255));
cvtColor( _srcImage, grayImage, CV_BGR2GRAY );
grayImage = ones - grayImage;
applyColorMap(grayImage, dstImage, COLORMAP_JET);
setDstImage(dstImage);
});
QObject::connect( saturationButton, &QPushButton::clicked, [this] () {
Mat dstImage, hsvImage;
cvtColor( _srcImage, hsvImage, CV_BGR2HSV );
vector<Mat> hsvVec(3);
split(hsvImage, hsvVec);
applyColorMap(hsvVec[1], dstImage, COLORMAP_JET);
setDstImage(dstImage);
});
QObject::connect( copyButton, &QPushButton::clicked, [this] () {
setSrcImage(_dstImage);
});
if(initialImage != "")
{
Mat srcImage = imread( initialImage.c_str(), 1 );
setSrcImage(srcImage);
}
}
MainWindow::~MainWindow()
{
}
QMouseEventerImage* MainWindow::initializeImageWidget(QString name, int index)
{
QMouseEventerImage *mei = new QMouseEventerImage(centralwidget);
mei->setObjectName(name);
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(mei->sizePolicy().hasHeightForWidth());
mei->setSizePolicy(sizePolicy);
mei->setMinimumSize(QSize(0, 400));
mei->setScaledContents(false);
verticalLayout_2->insertWidget(index, mei);
return mei;
}
void MainWindow::executeClicked()
{
QFileDialog dialog(NULL);
if ( dialog.exec() )
{
Mat srcImage = imread( dialog.selectedFiles()[0].toLatin1().data(), 1 );
if ( !srcImage.data )
{
printf("No image data \n");
return;
}
setSrcImage(srcImage);
}
}
void MainWindow::setSrcImage(Mat &image)
{
_srcImage = image;
QImage srcImage = QImage((const unsigned char*)(image.data),
image.cols, image.rows,
image.step, QImage::Format_RGB888).rgbSwapped();
QPixmap pixmap = QPixmap::fromImage(srcImage);
SetLabelImage(srcImageLabel, pixmap, srcImageLabel->minimumHeight());
char status[100];
sprintf(status, "%d x %d", image.rows, image.cols);
setStatus(status);
emit srcImageChanged(_srcImage);
}
void MainWindow::setDstImage(Mat &image)
{
QImage dstImage = QImage((const unsigned char*)(image.data),
image.cols, image.rows,
image.step, QImage::Format_RGB888).rgbSwapped();
QPixmap pixmap = QPixmap::fromImage(dstImage);
SetLabelImage(dstImageLabel, pixmap, dstImageLabel->minimumHeight());
emit dstImageChanged(image);
_dstImage = image;
}
cv::Mat& MainWindow::getSrcImage()
{
return _srcImage;
}
void MainWindow::setStatus(std::string status)
{
statusBar()->showMessage(tr(status.c_str()));
}
| gpl-2.0 |
savander1/sat-tracker | sat-tracker/App_Start/FilterConfig.cs | 266 | using System.Web;
using System.Web.Mvc;
namespace sat_tracker
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| gpl-2.0 |
NeiroNext/JccAPV | app/src/main/java/jcc2/parser/ASTNot.java | 504 | /* Generated By:JJTree: Do not edit this line. ASTNot.java Version 4.1 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=true,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package jcc2.parser;
public
class ASTNot extends SimpleNode {
public ASTNot(int id) {
super(id);
}
public ASTNot(Jcc2Parser p, int id) {
super(p, id);
}
}
/* JavaCC - OriginalChecksum=c737fdf0ddae197506dbd2506db440f4 (do not edit this line) */
| gpl-2.0 |
D4wN/brickv | src/brickv/bindings/bricklet_segment_display_4x7.py | 5792 | # -*- coding: utf-8 -*-
#############################################################
# This file was automatically generated on 2015-11-17. #
# #
# Bindings Version 2.1.6 #
# #
# If you have a bugfix for this file and want to commit it, #
# please fix the bug in the generator. You can find a link #
# to the generators git repository on tinkerforge.com #
#############################################################
try:
from collections import namedtuple
except ImportError:
try:
from .ip_connection import namedtuple
except ValueError:
from ip_connection import namedtuple
try:
from .ip_connection import Device, IPConnection, Error
except ValueError:
from ip_connection import Device, IPConnection, Error
GetSegments = namedtuple('Segments', ['segments', 'brightness', 'colon'])
GetIdentity = namedtuple('Identity', ['uid', 'connected_uid', 'position', 'hardware_version', 'firmware_version', 'device_identifier'])
class BrickletSegmentDisplay4x7(Device):
"""
Four 7-segment displays with switchable colon
"""
DEVICE_IDENTIFIER = 237
DEVICE_DISPLAY_NAME = 'Segment Display 4x7 Bricklet'
CALLBACK_COUNTER_FINISHED = 5
FUNCTION_SET_SEGMENTS = 1
FUNCTION_GET_SEGMENTS = 2
FUNCTION_START_COUNTER = 3
FUNCTION_GET_COUNTER_VALUE = 4
FUNCTION_GET_IDENTITY = 255
def __init__(self, uid, ipcon):
"""
Creates an object with the unique device ID *uid* and adds it to
the IP Connection *ipcon*.
"""
Device.__init__(self, uid, ipcon)
self.api_version = (2, 0, 0)
self.response_expected[BrickletSegmentDisplay4x7.FUNCTION_SET_SEGMENTS] = BrickletSegmentDisplay4x7.RESPONSE_EXPECTED_FALSE
self.response_expected[BrickletSegmentDisplay4x7.FUNCTION_GET_SEGMENTS] = BrickletSegmentDisplay4x7.RESPONSE_EXPECTED_ALWAYS_TRUE
self.response_expected[BrickletSegmentDisplay4x7.FUNCTION_START_COUNTER] = BrickletSegmentDisplay4x7.RESPONSE_EXPECTED_FALSE
self.response_expected[BrickletSegmentDisplay4x7.FUNCTION_GET_COUNTER_VALUE] = BrickletSegmentDisplay4x7.RESPONSE_EXPECTED_ALWAYS_TRUE
self.response_expected[BrickletSegmentDisplay4x7.CALLBACK_COUNTER_FINISHED] = BrickletSegmentDisplay4x7.RESPONSE_EXPECTED_ALWAYS_FALSE
self.response_expected[BrickletSegmentDisplay4x7.FUNCTION_GET_IDENTITY] = BrickletSegmentDisplay4x7.RESPONSE_EXPECTED_ALWAYS_TRUE
self.callback_formats[BrickletSegmentDisplay4x7.CALLBACK_COUNTER_FINISHED] = ''
def set_segments(self, segments, brightness, colon):
"""
The 7-segment display can be set with bitmaps. Every bit controls one
segment:
.. image:: /Images/Bricklets/bricklet_segment_display_4x7_bit_order.png
:scale: 100 %
:alt: Bit order of one segment
:align: center
For example to set a "5" you would want to activate segments 0, 2, 3, 5 and 6.
This is represented by the number 0b01101101 = 0x6d = 109.
The brightness can be set between 0 (dark) and 7 (bright). The colon
parameter turns the colon of the display on or off.
"""
self.ipcon.send_request(self, BrickletSegmentDisplay4x7.FUNCTION_SET_SEGMENTS, (segments, brightness, colon), '4B B ?', '')
def get_segments(self):
"""
Returns the segment, brightness and color data as set by
:func:`SetSegments`.
"""
return GetSegments(*self.ipcon.send_request(self, BrickletSegmentDisplay4x7.FUNCTION_GET_SEGMENTS, (), '', '4B B ?'))
def start_counter(self, value_from, value_to, increment, length):
"""
Starts a counter with the *from* value that counts to the *to*
value with the each step incremented by *increment*.
The *length* of the increment is given in ms.
Example: If you set *from* to 0, *to* to 100, *increment* to 1 and
*length* to 1000, a counter that goes from 0 to 100 with one second
pause between each increment will be started.
The maximum values for *from*, *to* and *increment* is 9999,
the minimum value is -999.
Using a negative increment allows to count backwards.
You can stop the counter at every time by calling :func:`SetSegments`.
"""
self.ipcon.send_request(self, BrickletSegmentDisplay4x7.FUNCTION_START_COUNTER, (value_from, value_to, increment, length), 'h h h I', '')
def get_counter_value(self):
"""
Returns the counter value that is currently shown on the display.
If there is no counter running a 0 will be returned.
"""
return self.ipcon.send_request(self, BrickletSegmentDisplay4x7.FUNCTION_GET_COUNTER_VALUE, (), '', 'H')
def get_identity(self):
"""
Returns the UID, the UID where the Bricklet is connected to,
the position, the hardware and firmware version as well as the
device identifier.
The position can be 'a', 'b', 'c' or 'd'.
The device identifier numbers can be found :ref:`here <device_identifier>`.
|device_identifier_constant|
"""
return GetIdentity(*self.ipcon.send_request(self, BrickletSegmentDisplay4x7.FUNCTION_GET_IDENTITY, (), '', '8s 8s c 3B 3B H'))
def register_callback(self, id, callback):
"""
Registers a callback with ID *id* to the function *callback*.
"""
self.registered_callbacks[id] = callback
SegmentDisplay4x7 = BrickletSegmentDisplay4x7 # for backward compatibility
| gpl-2.0 |
ahkab/ahkab | tests/time_functions/test_time_functions.py | 2933 | import numpy as np
import ahkab
from ahkab import ahkab, circuit, printing, time_functions, testing
cli = False
def test():
"""Test pulse and sin API"""
step = time_functions.pulse(v1=0, v2=1, td=500e-9, tr=1e-12, pw=1, tf=1e-12, per=2)
damped_sin = time_functions.sin(vo=0, va=1, td=500e-9, freq=15e3, theta=5e3, phi=90.)
exp = time_functions.exp(v1=.5, v2=-.05, td1=0, tau1=20e-6, td2=400e-6, tau2=20e-6)
mycircuit = circuit.Circuit(title="Butterworth Example circuit", filename=None)
gnd = mycircuit.get_ground_node()
mycircuit.add_resistor(part_id="R1", n1="n1", n2="n2", value=600)
mycircuit.add_inductor(part_id="L1", n1="n2", n2="n3", value=15.24e-3)
mycircuit.add_capacitor(part_id="C1", n1="n3", n2=gnd, value=119.37e-9)
mycircuit.add_inductor(part_id="L2", n1="n3", n2="n4", value=61.86e-3)
mycircuit.add_capacitor(part_id="C2", n1="n4", n2=gnd, value=155.12e-9)
mycircuit.add_resistor(part_id="R2", n1="n4", n2=gnd, value=1.2e3)
mycircuit.add_vsource("V1", n1="n1", n2='n5', dc_value=3.3333, ac_value=.33333, function=step)
mycircuit.add_vsource("V2", n1="n5", n2='n6', dc_value=3.3333, ac_value=.33333, function=damped_sin)
mycircuit.add_vsource("V3", n1="n6", n2=gnd, dc_value=3.3333, ac_value=.33333, function=exp)
op_analysis = ahkab.new_op(outfile='time_functions')
ac_analysis = ahkab.new_ac(start=1e3, stop=1e5, points=100, outfile='time_functions')
tran_analysis = ahkab.new_tran(tstart=0, tstop=1.2e-3, tstep=1e-6, x0=None, outfile='time_functions')
testbench = testing.APITest('time_functions', mycircuit,
[op_analysis, ac_analysis, tran_analysis],
skip_on_travis=True, er=1e-3, ea=1e-5)
testbench.setUp()
testbench.test()
if cli:
r = ahkab.run(mycircuit, an_list=[op_analysis, ac_analysis, tran_analysis])
fig = plt.figure()
plt.title(mycircuit.title + " - TRAN Simulation")
plt.plot(r['tran']['T'], r['tran']['VN1'], label="Input voltage")
plt.hold(True)
plt.plot(r['tran']['T'], r['tran']['VN4'], label="output voltage")
plt.legend()
plt.hold(False)
plt.grid(True)
#plt.ylim([0,1.2])
plt.ylabel('Step response')
plt.xlabel('Time [s]')
fig.savefig('tran_plot.png')
fig = plt.figure()
plt.subplot(211)
plt.semilogx(r['ac']['w'], np.abs(r['ac']['Vn4']), 'o-')
plt.ylabel('abs(V(n4)) [V]')
plt.title(mycircuit.title + " - AC Simulation")
plt.subplot(212)
plt.grid(True)
plt.semilogx(r['ac']['w'], np.angle(r['ac']['Vn4']), 'o-')
plt.xlabel('Angular frequency [rad/s]')
plt.ylabel('arg(V(n4)) [rad]')
fig.savefig('ac_plot.png')
else:
testbench.tearDown()
if __name__ == '__main__':
import pylab as plt
cli = True
test()
plt.show()
| gpl-2.0 |
dannychan4277/teak | wp-content/themes/gt3-wp-canvas/core/widgets/flickr.php | 2142 | <?php
class flickr extends WP_Widget {
function flickr() {
parent::__construct( false, 'Flickr (current theme)' );
}
function widget( $args, $instance ) {
extract($args);
echo $before_widget;
echo $before_title;
echo $instance['widget_title'];
echo $after_title;
#wp_enqueue_script('js_jflickrfeed', get_template_directory_uri() . '/js/jflickrfeed.js');
echo '<div class="flickr_widget_wrapper"><script src="http://www.flickr.com/badge_code_v2.gne?count='.$instance['flickr_widget_number'].'&display=latest&size=s&layout=x&source=user&user='.$instance['flickr_widget_id'].'"></script></div>';
echo $after_widget;
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['widget_title'] = esc_attr( $new_instance['widget_title'] );
$instance['flickr_widget_number'] = absint( $new_instance['flickr_widget_number'] );
$instance['flickr_widget_id'] = esc_attr( $new_instance['flickr_widget_id'] );
return $instance;
}
function form($instance) {
$defaultValues = array(
'widget_title' => 'Flickr Photostream',
'flickr_widget_number' => '8',
'flickr_widget_id' => '92335820@N08'
);
$instance = wp_parse_args((array) $instance, $defaultValues);
?>
<table class="fullwidth">
<tr>
<td>Title:</td>
<td><input type='text' class="fullwidth" name='<?php echo $this->get_field_name( 'widget_title' ); ?>' value='<?php echo $instance['widget_title']; ?>'/></td>
</tr>
<tr>
<td>Flickr ID:</td>
<td><input type='text' class="fullwidth" name='<?php echo $this->get_field_name( 'flickr_widget_id' ); ?>' value='<?php echo $instance['flickr_widget_id']; ?>'/></td>
</tr>
<tr>
<td>Number:</td>
<td><input type='text' class="fullwidth" name='<?php echo $this->get_field_name( 'flickr_widget_number' ); ?>' value='<?php echo $instance['flickr_widget_number']; ?>'/></td>
</tr>
</table>
<?php
}
}
function flickr_register_widgets() { register_widget( 'flickr' ); }
add_action( 'widgets_init', 'flickr_register_widgets' );
?> | gpl-2.0 |
Huluzai/DoonSketch | inkscape-0.48.5/src/libnr/nr-compose-transform.cpp | 10673 | #define __NR_COMPOSE_TRANSFORM_C__
/*
* Pixel buffer rendering library
*
* Authors:
* Lauris Kaplinski <lauris@kaplinski.com>
*
* This code is in public domain
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "nr-pixops.h"
#include "nr-matrix.h"
/*#ifdef WITH_MMX
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/ * fixme: * /
/ *int nr_have_mmx (void);
#define NR_PIXOPS_MMX (1 && nr_have_mmx ())
#ifdef __cplusplus
}
#endif //__cplusplus
#endif
*/
/* fixme: Implement missing (Lauris) */
/* fixme: PREMUL colors before calculating average (Lauris) */
/* Fixed point precision */
#define FBITS 12
#define FBITS_HP 18 // In some places we need a higher precision
void nr_R8G8B8A8_N_EMPTY_R8G8B8A8_N_TRANSFORM (unsigned char *px, int w, int h, int rs,
const unsigned char *spx, int sw, int sh, int srs,
const NR::Matrix &d2s, unsigned int alpha, int xd, int yd);
void nr_R8G8B8A8_N_EMPTY_R8G8B8A8_P_TRANSFORM (unsigned char *px, int w, int h, int rs,
const unsigned char *spx, int sw, int sh, int srs,
const NR::Matrix &d2s, unsigned int alpha, int xd, int yd);
void nr_R8G8B8A8_P_EMPTY_R8G8B8A8_N_TRANSFORM (unsigned char *px, int w, int h, int rs,
const unsigned char *spx, int sw, int sh, int srs,
const NR::Matrix &d2s, unsigned int alpha, int xd, int yd);
void nr_R8G8B8A8_P_EMPTY_R8G8B8A8_P_TRANSFORM (unsigned char *px, int w, int h, int rs,
const unsigned char *spx, int sw, int sh, int srs,
const NR::Matrix &d2s, unsigned int alpha, int xd, int yd);
void
nr_R8G8B8A8_N_R8G8B8A8_N_R8G8B8A8_N_TRANSFORM (unsigned char *px, int w, int h, int rs,
const unsigned char *spx, int sw, int sh, int srs,
const NR::Matrix &d2s, unsigned int alpha, int xd, int yd)
{
int xsize, ysize, size, dbits;
long FFs_x_x, FFs_x_y, FFs_y_x, FFs_y_y, FFs__x, FFs__y;
long FFs_x_x_S, FFs_x_y_S, FFs_y_x_S, FFs_y_y_S;
/* Subpixel positions */
int FF_sx_S[256];
int FF_sy_S[256];
unsigned char *d0;
int FFsx0, FFsy0;
int x, y;
if (alpha == 0) return;
if (alpha>255) {
g_warning("In transform PPN alpha=%u>255",alpha);
}
// The color component is stored temporarily with a range of [0,255^3], so more supersampling and we get an overflow (fortunately Inkscape's preferences also doesn't allow a higher setting)
if (xd+yd>8) {
xd = 4;
yd = 4;
}
xsize = (1 << xd);
ysize = (1 << yd);
size = xsize * ysize;
dbits = xd + yd;
unsigned int rounding_fix = size/2;
/* Set up fixed point matrix */
FFs_x_x = (long) floor(d2s[0] * (1 << FBITS) + 0.5);
FFs_x_y = (long) floor(d2s[1] * (1 << FBITS) + 0.5);
FFs_y_x = (long) floor(d2s[2] * (1 << FBITS) + 0.5);
FFs_y_y = (long) floor(d2s[3] * (1 << FBITS) + 0.5);
FFs__x = (long) floor(d2s[4] * (1 << FBITS) + 0.5);
FFs__y = (long) floor(d2s[5] * (1 << FBITS) + 0.5);
FFs_x_x_S = FFs_x_x >> xd;
FFs_x_y_S = FFs_x_y >> xd;
FFs_y_x_S = FFs_y_x >> yd;
FFs_y_y_S = FFs_y_y >> yd;
/* Set up subpixel matrix */
/* fixme: We can calculate that in floating point (Lauris) */
for (y = 0; y < ysize; y++) {
for (x = 0; x < xsize; x++) {
FF_sx_S[y * xsize + x] = FFs_x_x_S * x + FFs_y_x_S * y;
FF_sy_S[y * xsize + x] = FFs_x_y_S * x + FFs_y_y_S * y;
}
}
d0 = px;
FFsx0 = FFs__x;
FFsy0 = FFs__y;
for (y = 0; y < h; y++) {
unsigned char *d;
long FFsx, FFsy;
d = d0;
FFsx = FFsx0;
FFsy = FFsy0;
for (x = 0; x < w; x++) {
unsigned int r, g, b, a;
long sx, sy;
int i;
r = g = b = a = 0;
for (i = 0; i < size; i++) {
sx = (FFsx + FF_sx_S[i]) >> FBITS;
if ((sx >= 0) && (sx < sw)) {
sy = (FFsy + FF_sy_S[i]) >> FBITS;
if ((sy >= 0) && (sy < sh)) {
const unsigned char *s;
s = spx + sy * srs + sx * 4;
r += NR_PREMUL_112 (s[0], s[3]); // s in [0,255]
g += NR_PREMUL_112 (s[1], s[3]);
b += NR_PREMUL_112 (s[2], s[3]);
a += s[3];
// a=sum(s3)
// r,g,b in [0,sum(s3)*255]
}
}
}
a = (a*alpha + rounding_fix) >> dbits;
// a=sum(s3)*alpha/size=avg(s3)*alpha
// Compare to nr_R8G8B8A8_N_R8G8B8A8_N_R8G8B8A8_P
if (a != 0) {
r = (r*alpha + rounding_fix) >> dbits;
g = (g*alpha + rounding_fix) >> dbits;
b = (b*alpha + rounding_fix) >> dbits;
// r,g,b in [0,avg(s3)*alpha*255]=[0,a*255]
if (a == 255*255) {
/* Full coverage, demul src */
d[0] = NR_NORMALIZE_31(r);
d[1] = NR_NORMALIZE_31(g);
d[2] = NR_NORMALIZE_31(b);
d[3] = NR_NORMALIZE_21(a);
} else if (d[3] == 0) {
/* Only foreground, demul src */
d[0] = NR_DEMUL_321(r,a);
d[1] = NR_DEMUL_321(g,a);
d[2] = NR_DEMUL_321(b,a);
d[3] = NR_NORMALIZE_21(a);
} else {
unsigned int ca;
/* Full composition */
ca = NR_COMPOSEA_213(a, d[3]);
d[0] = NR_COMPOSEPNN_321131 (r, a, d[0], d[3], ca);
d[1] = NR_COMPOSEPNN_321131 (g, a, d[1], d[3], ca);
d[2] = NR_COMPOSEPNN_321131 (b, a, d[2], d[3], ca);
d[3] = NR_NORMALIZE_31(ca);
}
}
/* Advance pointers */
FFsx += FFs_x_x;
FFsy += FFs_x_y;
d += 4;
}
FFsx0 += FFs_y_x;
FFsy0 += FFs_y_y;
d0 += rs;
}
}
void nr_R8G8B8A8_N_R8G8B8A8_N_R8G8B8A8_P_TRANSFORM (unsigned char *px, int w, int h, int rs,
const unsigned char *spx, int sw, int sh, int srs,
const NR::Matrix &d2s, unsigned int alpha, int xd, int yd);
static void
nr_R8G8B8A8_P_R8G8B8A8_P_R8G8B8A8_N_TRANSFORM_0 (unsigned char *px, int w, int h, int rs,
const unsigned char *spx, int sw, int sh, int srs,
const long long *FFd2s, unsigned int alpha)
{
unsigned char *d0;
long long FFsx0, FFsy0;
int x, y;
d0 = px;
FFsx0 = FFd2s[4];
FFsy0 = FFd2s[5];
for (y = 0; y < h; y++) {
unsigned char *d;
long long FFsx, FFsy;
d = d0;
FFsx = FFsx0;
FFsy = FFsy0;
for (x = 0; x < w; x++) {
long sx, sy;
sx = long(FFsx >> FBITS_HP);
if ((sx >= 0) && (sx < sw)) {
sy = long(FFsy >> FBITS_HP);
if ((sy >= 0) && (sy < sh)) {
const unsigned char *s;
unsigned int a;
s = spx + sy * srs + sx * 4;
a = NR_PREMUL_112 (s[3], alpha);
if (a != 0) {
if ((a == 255*255) || (d[3] == 0)) {
/* Transparent BG, premul src */
d[0] = NR_PREMUL_121 (s[0], a);
d[1] = NR_PREMUL_121 (s[1], a);
d[2] = NR_PREMUL_121 (s[2], a);
d[3] = NR_NORMALIZE_21(a);
} else {
d[0] = NR_COMPOSENPP_1211 (s[0], a, d[0]);
d[1] = NR_COMPOSENPP_1211 (s[1], a, d[1]);
d[2] = NR_COMPOSENPP_1211 (s[2], a, d[2]);
d[3] = NR_COMPOSEA_211(a, d[3]);
}
}
}
}
/* Advance pointers */
FFsx += FFd2s[0];
FFsy += FFd2s[1];
d += 4;
}
FFsx0 += FFd2s[2];
FFsy0 += FFd2s[3];
d0 += rs;
}
}
static void
nr_R8G8B8A8_P_R8G8B8A8_P_R8G8B8A8_N_TRANSFORM_n (unsigned char *px, int w, int h, int rs,
const unsigned char *spx, int sw, int sh, int srs,
const long long *FFd2s, const long *FF_S, unsigned int alpha, int dbits)
{
int size;
unsigned char *d0;
long long FFsx0, FFsy0;
int x, y;
size = (1 << dbits);
unsigned int rounding_fix = size/2;
d0 = px;
FFsx0 = FFd2s[4];
FFsy0 = FFd2s[5];
for (y = 0; y < h; y++) {
unsigned char *d;
long long FFsx, FFsy;
d = d0;
FFsx = FFsx0;
FFsy = FFsy0;
for (x = 0; x < w; x++) {
unsigned int r, g, b, a;
int i;
r = g = b = a = 0;
for (i = 0; i < size; i++) {
long sx, sy;
sx = (long (FFsx >> (FBITS_HP - FBITS)) + FF_S[2 * i]) >> FBITS;
if ((sx >= 0) && (sx < sw)) {
sy = (long (FFsy >> (FBITS_HP - FBITS)) + FF_S[2 * i + 1]) >> FBITS;
if ((sy >= 0) && (sy < sh)) {
const unsigned char *s;
s = spx + sy * srs + sx * 4;
r += NR_PREMUL_112(s[0], s[3]);
g += NR_PREMUL_112(s[1], s[3]);
b += NR_PREMUL_112(s[2], s[3]);
a += s[3];
}
}
}
a = (a*alpha + rounding_fix) >> dbits;
if (a != 0) {
r = (r*alpha + rounding_fix) >> dbits;
g = (g*alpha + rounding_fix) >> dbits;
b = (b*alpha + rounding_fix) >> dbits;
if ((a == 255*255) || (d[3] == 0)) {
/* Transparent BG, premul src */
d[0] = NR_NORMALIZE_31(r);
d[1] = NR_NORMALIZE_31(g);
d[2] = NR_NORMALIZE_31(b);
d[3] = NR_NORMALIZE_21(a);
} else {
d[0] = NR_COMPOSEPPP_3211 (r, a, d[0]);
d[1] = NR_COMPOSEPPP_3211 (g, a, d[1]);
d[2] = NR_COMPOSEPPP_3211 (b, a, d[2]);
d[3] = NR_COMPOSEA_211(a, d[3]);
}
}
/* Advance pointers */
FFsx += FFd2s[0];
FFsy += FFd2s[1];
d += 4;
}
FFsx0 += FFd2s[2];
FFsy0 += FFd2s[3];
d0 += rs;
}
}
void nr_R8G8B8A8_P_R8G8B8A8_P_R8G8B8A8_N_TRANSFORM (unsigned char *px, int w, int h, int rs,
const unsigned char *spx, int sw, int sh, int srs,
const NR::Matrix &d2s, unsigned int alpha, int xd, int yd)
{
int dbits;
long FFd2s[6];
long long FFd2s_HP[6]; // with higher precision
int i;
if (alpha == 0) return;
if (alpha>255) {
g_warning("In transform PPN alpha=%u>255",alpha);
}
// The color component is stored temporarily with a range of [0,255^3], so more supersampling and we get an overflow (fortunately Inkscape's preferences also doesn't allow a higher setting)
if (xd+yd>8) {
xd = 4;
yd = 4;
}
dbits = xd + yd;
for (i = 0; i < 6; i++) {
FFd2s[i] = (long) floor(d2s[i] * (1 << FBITS) + 0.5);
FFd2s_HP[i] = (long long) floor(d2s[i] * (1 << FBITS_HP) + 0.5);;
}
if (dbits == 0) {
nr_R8G8B8A8_P_R8G8B8A8_P_R8G8B8A8_N_TRANSFORM_0 (px, w, h, rs, spx, sw, sh, srs, FFd2s_HP, alpha);
} else {
int xsize, ysize;
long FFs_x_x_S, FFs_x_y_S, FFs_y_x_S, FFs_y_y_S;
long FF_S[2 * 256];
int x, y;
xsize = (1 << xd);
ysize = (1 << yd);
FFs_x_x_S = FFd2s[0] >> xd;
FFs_x_y_S = FFd2s[1] >> xd;
FFs_y_x_S = FFd2s[2] >> yd;
FFs_y_y_S = FFd2s[3] >> yd;
/* Set up subpixel matrix */
/* fixme: We can calculate that in floating point (Lauris) */
for (y = 0; y < ysize; y++) {
for (x = 0; x < xsize; x++) {
FF_S[2 * (y * xsize + x)] = FFs_x_x_S * x + FFs_y_x_S * y;
FF_S[2 * (y * xsize + x) + 1] = FFs_x_y_S * x + FFs_y_y_S * y;
}
}
nr_R8G8B8A8_P_R8G8B8A8_P_R8G8B8A8_N_TRANSFORM_n (px, w, h, rs, spx, sw, sh, srs, FFd2s_HP, FF_S, alpha, dbits);
}
}
void nr_R8G8B8A8_P_R8G8B8A8_P_R8G8B8A8_P_TRANSFORM (unsigned char *px, int w, int h, int rs,
const unsigned char *spx, int sw, int sh, int srs,
const NR::Matrix &d2s, unsigned int alpha, int xd, int yd);
| gpl-2.0 |
xcaptain/discourse | lib/pretty_text.rb | 9852 | require 'mini_racer'
require 'nokogiri'
require 'erb'
require_dependency 'url_helper'
require_dependency 'excerpt_parser'
require_dependency 'post'
require_dependency 'discourse_tagging'
require_dependency 'pretty_text/helpers'
module PrettyText
@mutex = Mutex.new
@ctx_init = Mutex.new
def self.app_root
Rails.root
end
def self.find_file(root, filename)
return filename if File.file?("#{root}#{filename}")
es6_name = "#{filename}.js.es6"
return es6_name if File.file?("#{root}#{es6_name}")
js_name = "#{filename}.js"
return js_name if File.file?("#{root}#{js_name}")
erb_name = "#{filename}.js.es6.erb"
return erb_name if File.file?("#{root}#{erb_name}")
end
def self.apply_es6_file(ctx, root_path, part_name)
filename = find_file(root_path, part_name)
if filename
source = File.read("#{root_path}#{filename}")
if filename =~ /\.erb$/
source = ERB.new(source).result(binding)
end
template = Tilt::ES6ModuleTranspilerTemplate.new {}
transpiled = template.module_transpile(source, "#{Rails.root}/app/assets/javascripts/", part_name)
ctx.eval(transpiled)
else
# Look for vendored stuff
vendor_root = "#{Rails.root}/vendor/assets/javascripts/"
filename = find_file(vendor_root, part_name)
if filename
ctx.eval(File.read("#{vendor_root}#{filename}"))
end
end
end
def self.create_es6_context
ctx = MiniRacer::Context.new(timeout: 15000)
ctx.eval("window = {}; window.devicePixelRatio = 2;") # hack to make code think stuff is retina
if Rails.env.development? || Rails.env.test?
ctx.attach("console.log", proc{|l| p l })
end
ctx_load(ctx, "vendor/assets/javascripts/loader.js")
ctx_load(ctx, "vendor/assets/javascripts/lodash.js")
manifest = File.read("#{Rails.root}/app/assets/javascripts/pretty-text-bundle.js")
root_path = "#{Rails.root}/app/assets/javascripts/"
manifest.each_line do |l|
if l =~ /\/\/= require (\.\/)?(.*)$/
apply_es6_file(ctx, root_path, Regexp.last_match[2])
elsif l =~ /\/\/= require_tree (\.\/)?(.*)$/
path = Regexp.last_match[2]
Dir["#{root_path}/#{path}/**"].each do |f|
apply_es6_file(ctx, root_path, f.sub(root_path, '')[1..-1].sub(/\.js.es6$/, ''))
end
end
end
apply_es6_file(ctx, root_path, "discourse/lib/utilities")
PrettyText::Helpers.instance_methods.each do |method|
ctx.attach("__helpers.#{method}", PrettyText::Helpers.method(method))
end
ctx.load("#{Rails.root}/lib/pretty_text/shims.js")
ctx.eval("__setUnicode(#{Emoji.unicode_replacements_json})")
to_load = []
DiscoursePluginRegistry.each_globbed_asset do |a|
to_load << a if File.file?(a) && a =~ /discourse-markdown/
end
to_load.uniq.each do |f|
if f =~ /^.+assets\/javascripts\//
root = Regexp.last_match[0]
apply_es6_file(ctx, root, f.sub(root, '').sub(/\.js\.es6$/, ''))
end
end
ctx
end
def self.v8
return @ctx if @ctx
# ensure we only init one of these
@ctx_init.synchronize do
return @ctx if @ctx
@ctx = create_es6_context
end
@ctx
end
def self.reset_context
@ctx_init.synchronize do
@ctx = nil
end
end
def self.markdown(text, opts=nil)
# we use the exact same markdown converter as the client
# TODO: use the same extensions on both client and server (in particular the template for mentions)
baked = nil
text = text || ""
protect do
context = v8
paths = {
baseUri: Discourse::base_uri,
CDN: Rails.configuration.action_controller.asset_host,
}
if SiteSetting.enable_s3_uploads?
if SiteSetting.s3_cdn_url.present?
paths[:S3CDN] = SiteSetting.s3_cdn_url
end
paths[:S3BaseUrl] = Discourse.store.absolute_base_url
end
context.eval("__optInput = {};")
context.eval("__optInput.siteSettings = #{SiteSetting.client_settings_json};")
context.eval("__paths = #{paths.to_json};")
if opts[:topicId]
context.eval("__optInput.topicId = #{opts[:topicId].to_i};")
end
context.eval("__optInput.getURL = __getURL;")
context.eval("__optInput.lookupAvatar = __lookupAvatar;")
context.eval("__optInput.getTopicInfo = __getTopicInfo;")
context.eval("__optInput.categoryHashtagLookup = __categoryLookup;")
context.eval("__optInput.mentionLookup = __mentionLookup;")
custom_emoji = {}
Emoji.custom.map {|e| custom_emoji[e.name] = e.url}
context.eval("__optInput.customEmoji = #{custom_emoji.to_json};")
opts = context.eval("__pt = new __PrettyText(__buildOptions(__optInput));")
DiscourseEvent.trigger(:markdown_context, context)
baked = context.eval("__pt.cook(#{text.inspect})")
end
if baked.blank? && !(opts || {})[:skip_blank_test]
# we may have a js engine issue
test = markdown("a", skip_blank_test: true)
if test.blank?
Rails.logger.warn("Markdown engine appears to have crashed, resetting context")
reset_context
opts ||= {}
opts = opts.dup
opts[:skip_blank_test] = true
baked = markdown(text, opts)
end
end
baked
end
# leaving this here, cause it invokes v8, don't want to implement twice
def self.avatar_img(avatar_template, size)
protect do
v8.eval("__utils.avatarImg({size: #{size.inspect}, avatarTemplate: #{avatar_template.inspect}}, __getURL);")
end
end
def self.unescape_emoji(title)
return title unless SiteSetting.enable_emoji?
set = SiteSetting.emoji_set.inspect
protect do
v8.eval("__performEmojiUnescape(#{title.inspect}, { getURL: __getURL, emojiSet: #{set} })")
end
end
def self.cook(text, opts={})
options = opts.dup
# we have a minor inconsistency
options[:topicId] = opts[:topic_id]
working_text = text.dup
sanitized = markdown(working_text, options)
doc = Nokogiri::HTML.fragment(sanitized)
if !options[:omit_nofollow] && SiteSetting.add_rel_nofollow_to_user_content
add_rel_nofollow_to_user_content(doc)
end
if SiteSetting.enable_s3_uploads && SiteSetting.s3_cdn_url.present?
add_s3_cdn(doc)
end
doc.to_html
end
def self.add_s3_cdn(doc)
doc.css("img").each do |img|
next unless img["src"]
img["src"] = Discourse.store.cdn_url(img["src"])
end
end
def self.add_rel_nofollow_to_user_content(doc)
whitelist = []
domains = SiteSetting.exclude_rel_nofollow_domains
whitelist = domains.split('|') if domains.present?
site_uri = nil
doc.css("a").each do |l|
href = l["href"].to_s
begin
uri = URI(href)
site_uri ||= URI(Discourse.base_url)
if !uri.host.present? ||
uri.host == site_uri.host ||
uri.host.ends_with?("." << site_uri.host) ||
whitelist.any?{|u| uri.host == u || uri.host.ends_with?("." << u)}
# we are good no need for nofollow
else
l["rel"] = "nofollow"
end
rescue URI::InvalidURIError, URI::InvalidComponentError
# add a nofollow anyway
l["rel"] = "nofollow"
end
end
end
class DetectedLink
attr_accessor :is_quote, :url
def initialize(url, is_quote=false)
@url = url
@is_quote = is_quote
end
end
def self.extract_links(html)
links = []
doc = Nokogiri::HTML.fragment(html)
# remove href inside quotes & elided part
doc.css("aside.quote a, .elided a").each { |l| l["href"] = "" }
# extract all links from the post
doc.css("a").each { |l|
unless l["href"].blank? || "#".freeze == l["href"][0]
links << DetectedLink.new(l["href"])
end
}
# extract links to quotes
doc.css("aside.quote[data-topic]").each do |a|
topic_id = a['data-topic']
url = "/t/topic/#{topic_id}"
if post_number = a['data-post']
url << "/#{post_number}"
end
links << DetectedLink.new(url, true)
end
links
end
def self.excerpt(html, max_length, options={})
# TODO: properly fix this HACK in ExcerptParser without introducing XSS
doc = Nokogiri::HTML.fragment(html)
strip_image_wrapping(doc)
html = doc.to_html
ExcerptParser.get_excerpt(html, max_length, options)
end
def self.strip_links(string)
return string if string.blank?
# If the user is not basic, strip links from their bio
fragment = Nokogiri::HTML.fragment(string)
fragment.css('a').each {|a| a.replace(a.inner_html) }
fragment.to_html
end
# Given a Nokogiri doc, convert all links to absolute
def self.make_all_links_absolute(doc)
site_uri = nil
doc.css("a").each do |link|
href = link["href"].to_s
begin
uri = URI(href)
site_uri ||= URI(Discourse.base_url)
link["href"] = "#{site_uri}#{link['href']}" unless uri.host.present?
rescue URI::InvalidURIError, URI::InvalidComponentError
# leave it
end
end
end
def self.strip_image_wrapping(doc)
doc.css(".lightbox-wrapper .meta").remove
end
def self.format_for_email(html, post = nil)
doc = Nokogiri::HTML.fragment(html)
DiscourseEvent.trigger(:reduce_cooked, doc, post)
strip_image_wrapping(doc)
make_all_links_absolute(doc)
doc.to_html
end
protected
class JavaScriptError < StandardError
attr_accessor :message, :backtrace
def initialize(message, backtrace)
@message = message
@backtrace = backtrace
end
end
def self.protect
rval = nil
@mutex.synchronize do
rval = yield
end
rval
end
def self.ctx_load(ctx, *files)
files.each do |file|
ctx.load(app_root + file)
end
end
end
| gpl-2.0 |
rapidwebdev/careerbridge | wp-content/themes/career/functions.php | 1771 | <?php
// Theme support options
require_once(get_template_directory().'/assets/functions/theme-support.php');
// WP Head and other cleanup functions
require_once(get_template_directory().'/assets/functions/cleanup.php');
// Register scripts and stylesheets
require_once(get_template_directory().'/assets/functions/enqueue-scripts.php');
// Register custom menus and menu walkers
require_once(get_template_directory().'/assets/functions/menu.php');
require_once(get_template_directory().'/assets/functions/menu-walkers.php');
// Register sidebars/widget areas
require_once(get_template_directory().'/assets/functions/sidebar.php');
// Makes WordPress comments suck less
require_once(get_template_directory().'/assets/functions/comments.php');
// Replace 'older/newer' post links with numbered navigation
require_once(get_template_directory().'/assets/functions/page-navi.php');
// Adds support for multiple languages
require_once(get_template_directory().'/assets/translation/translation.php');
// Adds site styles to the WordPress editor
//require_once(get_template_directory().'/assets/functions/editor-styles.php');
// Related post function - no need to rely on plugins
// require_once(get_template_directory().'/assets/functions/related-posts.php');
// Use this as a template for custom post types
// require_once(get_template_directory().'/assets/functions/custom-post-type.php');
// Customize the WordPress login menu
// require_once(get_template_directory().'/assets/functions/login.php');
// Customize the WordPress admin
// require_once(get_template_directory().'/assets/functions/admin.php');
add_action( 'after_setup_theme', 'wpdocs_theme_setup' );
function wpdocs_theme_setup() {
add_image_size( 'article-image', 500, 275, true );
} | gpl-2.0 |
eurra/flexbuilders | src/flexbuilders/basic/ObjectBuilderImpl.java | 2691 |
package flexbuilders.basic;
import java.util.ArrayList;
import java.util.List;
import flexbuilders.core.BuildException;
import flexbuilders.core.BuildStateInfo;
import flexbuilders.core.DefaultStateInfo;
import flexbuilders.core.Buildable;
import flexbuilders.core.Delegate;
import flexbuilders.core.StackBuildable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
*
* @author Enrique Urra C.
*/
class ObjectBuilderImpl<T> extends StackBuildable<T> implements Delegate, ObjectBuilder<T>
{
private Class<T> type;
private List<Buildable> args;
private T object;
public ObjectBuilderImpl(Class<T> type)
{
if(type == null)
throw new NullPointerException("Null type");
this.type = type;
this.args = new ArrayList<>();
}
@Override
public ObjectBuilderImpl<T> nextArgument(Buildable arg) throws BuildException
{
if(arg == null)
throw new BuildException("The provided buildable cannot be null");
args.add(arg);
return this;
}
@Override
public void buildInstance() throws BuildException
{
Object[] argsArr = new Object[args.size()];
int index = 0;
for(Buildable arg : args)
argsArr[index++] = arg.build();
Constructor[] constructors = type.getDeclaredConstructors();
object = null;
for(int i = 0; object == null && i < constructors.length; i++)
{
try
{
if(!constructors[i].isAccessible())
constructors[i].setAccessible(true);
object = (T)constructors[i].newInstance(argsArr);
}
catch(ClassCastException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex)
{
continue;
}
}
if(object == null)
{
String argsStr = "";
for(int i = 0; i < argsArr.length; i++)
argsStr += argsArr[i].getClass() + (i == argsArr.length - 1 ? "" : ", ");
throw new BuildException("No constructor has been found in the '" + type.getName() + "' class " + (argsStr.isEmpty() ? "with no arguments" : "with the following arguments: " + argsStr));
}
}
@Override
public T getInstance() throws BuildException
{
return object;
}
@Override
public BuildStateInfo getStateInfo()
{
return new DefaultStateInfo().
setName("Object").
addStateData("type", type.getSimpleName());
}
} | gpl-2.0 |
mobile-event-processing/Asper | source/src/com/espertech/esper/epl/agg/service/AggSvcGroupAllAccessOnlyImpl.java | 3189 | /*
* *************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
* *************************************************************************************
*/
package com.espertech.esper.epl.agg.service;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.epl.agg.access.AggregationAccess;
import com.espertech.esper.epl.agg.access.AggregationAccessorSlotPair;
import com.espertech.esper.epl.expression.ExprEvaluatorContext;
import java.util.Collection;
/**
* Aggregation service for use when only first/last/window aggregation functions are used an none other.
*/
public class AggSvcGroupAllAccessOnlyImpl implements AggregationService, AggregationResultFuture
{
private final AggregationAccessorSlotPair[] accessors;
protected final AggregationAccess[] accesses;
public AggSvcGroupAllAccessOnlyImpl(AggregationAccessorSlotPair[] accessors, AggregationAccess[] accesses) {
this.accessors = accessors;
this.accesses = accesses;
}
public void applyEnter(EventBean[] eventsPerStream, Object groupKey, ExprEvaluatorContext exprEvaluatorContext)
{
for (AggregationAccess access : accesses) {
access.applyEnter(eventsPerStream);
}
}
public void applyLeave(EventBean[] eventsPerStream, Object groupKey, ExprEvaluatorContext exprEvaluatorContext)
{
for (AggregationAccess access : accesses) {
access.applyLeave(eventsPerStream);
}
}
public void setCurrentAccess(Object groupKey, int agentInstanceId)
{
// no implementation required
}
public Object getValue(int column, int agentInstanceId)
{
AggregationAccessorSlotPair pair = accessors[column];
return pair.getAccessor().getValue(accesses[pair.getSlot()]);
}
public EventBean getEventBean(int column, ExprEvaluatorContext context) {
AggregationAccessorSlotPair pair = accessors[column];
return pair.getAccessor().getEventBean(accesses[pair.getSlot()]);
}
public Collection<EventBean> getCollection(int column, ExprEvaluatorContext context)
{
AggregationAccessorSlotPair pair = accessors[column];
return pair.getAccessor().getCollectionReadOnly(accesses[pair.getSlot()]);
}
public void clearResults(ExprEvaluatorContext exprEvaluatorContext)
{
for (AggregationAccess access : accesses) {
access.clear();
}
}
public void setRemovedCallback(AggregationRowRemovedCallback callback) {
// not applicable
}
} | gpl-2.0 |
freevo/kaa-metadata | src/disc/vcd.py | 3928 | # -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------------
# vcd.py - parse vcd track informations
# -----------------------------------------------------------------------------
# $Id$
#
# -----------------------------------------------------------------------------
# kaa-Metadata - Media Metadata for Python
# Copyright (C) 2003-2006 Thomas Schueppel, Dirk Meyer
#
# First Edition: Dirk Meyer <https://github.com/Dischi>
# Maintainer: Dirk Meyer <https://github.com/Dischi>
#
# Please see the file AUTHORS for a complete list of authors.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MER-
# CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# -----------------------------------------------------------------------------
__all__ = ['Parser']
# kaa.metadata.disc imports
from . import core
from . import cdrom
class VCD(core.Disc):
def __init__(self,device):
core.Disc.__init__(self)
self.offset = 0
self.mime = 'video/vcd'
self.type = 'CD'
self.subtype = 'video'
# parse disc
self.parseDisc(device)
def parseDisc(self, device):
type = None
if self.is_disc(device) != 2:
raise core.ParseError()
f = open(device)
try:
# read CD-XA001 at byte 1024 in sector 16
f.seek(2048*16 + 1024, 0)
if f.read(8) != 'CD-XA001':
raise core.ParseError()
# read VIDEO_CD at sector 150
f.seek(2048*150, 0)
typebuffer = f.read(8)
if typebuffer != 'VIDEO_CD' and typebuffer != 'SUPERVCD':
raise core.ParseError()
# Read some bytes of the ISO9660 part to better guess VCD or SVCD.
# Maybe this code is not needed and VIDEO_CD and SUPERVCD are enough.
f.seek(2048*16, 0)
iso9660 = f.read(2048*16)
if typebuffer == 'VIDEO_CD' and iso9660.find('MPEGAV') > 0:
type = 'VCD'
elif typebuffer == 'SUPERVCD' and \
(iso9660.find('SVCD') > 0 or iso9660.find('MPEG2') > 0):
type = 'SVCD'
else:
raise core.ParseError()
finally:
f.close()
# read the tracks to generate the title list
device = open(device)
(first, last) = cdrom.audiocd_toc_header(device)
lmin = 0
lsec = 0
num = 0
for i in range(first, last + 2):
if i == last + 1:
min, sec, frames = cdrom.audiocd_leadout(device)
else:
min, sec, frames = cdrom.audiocd_toc_entry(device, i)
if num:
vi = core.VideoStream()
# XXX add more static information here, it's also possible
# XXX to scan for more informations like fps
# XXX Settings to MPEG1/2 is a wild guess, maybe the track
# XXX isn't playable at all (e.g. the menu)
if type == 'VCD':
vi.codec = 'MPEG1'
else:
vi.codec = 'MPEG2'
vi.length = (min-lmin) * 60 + (sec-lsec)
self.tracks.append(vi)
num += 1
lmin, lsec = min, sec
device.close()
Parser = VCD
| gpl-2.0 |
Habbie/pdnsnonfork | pdns/unix_utility.cc | 8831 | /*
PowerDNS Versatile Database Driven Nameserver
Copyright (C) 2002 - 2011 PowerDNS.COM BV
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation
Additionally, the license of this program contains a special
exception which allows to distribute the program in binary form when
it is linked against OpenSSL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "utility.hh"
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include "pdnsexception.hh"
#include "logger.hh"
#include "misc.hh"
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/select.h>
#ifdef NEED_INET_NTOP_PROTO
extern "C" {
const char *inet_ntop(int af, const void *src, char *dst, size_t cnt);
}
#endif
#include "namespaces.hh"
// Closes a socket.
int Utility::closesocket( Utility::sock_t socket )
{
int ret=::close(socket);
if(ret < 0 && errno == ECONNRESET) // see ticket 192, odd BSD behaviour
return 0;
if(ret < 0)
throw PDNSException("Error closing socket: "+stringerror());
return ret;
}
// Connects to socket with timeout
int Utility::timed_connect( Utility::sock_t sock,
const sockaddr *addr,
Utility::socklen_t sockaddr_size,
int timeout_sec,
int timeout_usec )
{
fd_set set;
struct timeval timeout;
int ret;
timeout.tv_sec = timeout_sec;
timeout.tv_usec = timeout_usec;
FD_ZERO(&set);
FD_SET(sock, &set);
setNonBlocking(sock);
if ((ret = connect (sock, addr, sockaddr_size)) < 0) {
if (errno != EINPROGRESS)
return ret;
}
ret = select(sock + 1, NULL, &set, NULL, &timeout);
setBlocking(sock);
return ret;
}
bool Utility::setNonBlocking(sock_t sock)
{
int flags=fcntl(sock,F_GETFL,0);
if(flags<0 || fcntl(sock, F_SETFL,flags|O_NONBLOCK) <0)
return false;
return true;
}
bool Utility::setBlocking(sock_t sock)
{
int flags=fcntl(sock,F_GETFL,0);
if(flags<0 || fcntl(sock, F_SETFL,flags&(~O_NONBLOCK)) <0)
return false;
return true;
}
bool Utility::setCloseOnExec(sock_t sock)
{
int flags=fcntl(sock,F_GETFD,0);
if(flags<0 || fcntl(sock, F_SETFD,flags|FD_CLOEXEC) <0)
return false;
return true;
}
const char *Utility::inet_ntop(int af, const char *src, char *dst, size_t size)
{
return ::inet_ntop(af,src,dst,size);
}
unsigned int Utility::sleep(unsigned int sec)
{
return ::sleep(sec);
}
void Utility::usleep(unsigned long usec)
{
::usleep(usec);
}
// Drops the program's privileges.
void Utility::dropPrivs( int uid, int gid )
{
if(gid) {
if(setgid(gid)<0) {
theL()<<Logger::Critical<<"Unable to set effective group id to "<<gid<<": "<<stringerror()<<endl;
exit(1);
}
else
theL()<<Logger::Info<<"Set effective group id to "<<gid<<endl;
struct passwd *pw=getpwuid(uid);
if(!pw) {
theL()<<Logger::Warning<<"Unable to determine user name for uid "<<uid<<endl;
if (setgroups(0, NULL)<0) {
theL()<<Logger::Critical<<"Unable to drop supplementary gids: "<<stringerror()<<endl;
exit(1);
}
} else {
if (initgroups(pw->pw_name, gid)<0) {
theL()<<Logger::Critical<<"Unable to set supplementary groups: "<<stringerror()<<endl;
exit(1);
}
}
}
if(uid) {
if(setuid(uid)<0) {
theL()<<Logger::Critical<<"Unable to set effective user id to "<<uid<<": "<<stringerror()<<endl;
exit(1);
}
else
theL()<<Logger::Info<<"Set effective user id to "<<uid<<endl;
}
}
// Returns the current process id.
Utility::pid_t Utility::getpid( void )
{
return ::getpid();
}
// Returns the current time.
int Utility::gettimeofday( struct timeval *tv, void *tz )
{
return ::gettimeofday(tv,0);
}
// Converts an address from dot and numbers format to binary data.
int Utility::inet_aton( const char *cp, struct in_addr *inp )
{
return ::inet_aton(cp,inp);
}
// Converts an address from presentation format to network format.
int Utility::inet_pton( int af, const char *src, void *dst )
{
return ::inet_pton(af, src, dst);
}
// Retrieves a gid using a groupname.
int Utility::makeGidNumeric(const string &group)
{
int newgid;
if(!(newgid=atoi(group.c_str()))) {
errno=0;
struct group *gr=getgrnam(group.c_str());
if(!gr) {
theL()<<Logger::Critical<<"Unable to look up gid of group '"<<group<<"': "<< (errno ? strerror(errno) : "not found") <<endl;
exit(1);
}
newgid=gr->gr_gid;
}
return newgid;
}
// Retrieves an uid using a username.
int Utility::makeUidNumeric(const string &username)
{
int newuid;
if(!(newuid=atoi(username.c_str()))) {
struct passwd *pw=getpwnam(username.c_str());
if(!pw) {
theL()<<Logger::Critical<<"Unable to look up uid of user '"<<username<<"': "<< (errno ? strerror(errno) : "not found") <<endl;
exit(1);
}
newuid=pw->pw_uid;
}
return newuid;
}
// Returns a random number.
long int Utility::random( void )
{
return rand();
}
// Sets the random seed.
void Utility::srandom( unsigned int seed )
{
::srandom(seed);
}
// Writes a vector.
int Utility::writev(int socket, const iovec *vector, size_t count )
{
return ::writev(socket,vector,count);
}
/* this is cut and pasted from dietlibc, gratefully copied! */
static int isleap(int year) {
/* every fourth year is a leap year except for century years that are
* not divisible by 400. */
return (!(year%4) && ((year%100) || !(year%400)));
}
time_t Utility::timegm(struct tm *const t)
{
const static short spm[13] = /* days per month -- nonleap! */
{ 0,
(31),
(31+28),
(31+28+31),
(31+28+31+30),
(31+28+31+30+31),
(31+28+31+30+31+30),
(31+28+31+30+31+30+31),
(31+28+31+30+31+30+31+31),
(31+28+31+30+31+30+31+31+30),
(31+28+31+30+31+30+31+31+30+31),
(31+28+31+30+31+30+31+31+30+31+30),
(31+28+31+30+31+30+31+31+30+31+30+31),
};
time_t day;
time_t i;
time_t years = t->tm_year - 70;
if (t->tm_sec>60) { t->tm_min += t->tm_sec/60; t->tm_sec%=60; }
if (t->tm_min>60) { t->tm_hour += t->tm_min/60; t->tm_min%=60; }
if (t->tm_hour>60) { t->tm_mday += t->tm_hour/60; t->tm_hour%=60; }
if (t->tm_mon>11) { t->tm_year += t->tm_mon/12; t->tm_mon%=12; }
while (t->tm_mday>spm[1+t->tm_mon]) {
if (t->tm_mon==1 && isleap(t->tm_year+1900)) {
if (t->tm_mon==31+29) break;
--t->tm_mday;
}
t->tm_mday-=spm[t->tm_mon];
++t->tm_mon;
if (t->tm_mon>11) { t->tm_mon=0; ++t->tm_year; }
}
if (t->tm_year < 70)
return (time_t) -1;
/* Days since 1970 is 365 * number of years + number of leap years since 1970 */
day = years * 365 + (years + 1) / 4;
/* After 2100 we have to subtract 3 leap years for every 400 years
This is not intuitive. Most mktime implementations do not support
dates after 2059, anyway, so we might leave this out for its
bloat. */
if ((years -= 131) >= 0) {
years /= 100;
day -= (years >> 2) * 3 + 1;
if ((years &= 3) == 3) years--;
day -= years;
}
day += t->tm_yday = spm [t->tm_mon] + t->tm_mday-1 + ( isleap (t->tm_year+1900) & (t->tm_mon > 1) );
/* day is now the number of days since 'Jan 1 1970' */
i = 7;
t->tm_wday = (day + 4) % i; /* Sunday=0, Monday=1, ..., Saturday=6 */
i = 24;
day *= i;
i = 60;
return ((day + t->tm_hour) * i + t->tm_min) * i + t->tm_sec;
}
// we have our own gmtime_r because the one in GNU libc violates POSIX/SuS
// by supporting leap seconds when TZ=right/UTC
void Utility::gmtime_r(const time_t *timer, struct tm *tmbuf) {
int monthdays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int days = *timer / 86400;
int leapdays = (days + 671) / 1461;
int leapydays = (days + 365) / 1461;
tmbuf->tm_hour = *timer / 3600 % 24;
tmbuf->tm_min = *timer / 60 % 60;
tmbuf->tm_sec = *timer % 60;
tmbuf->tm_year = (days - leapdays) / 365 + 70;
tmbuf->tm_yday = days - leapydays - (tmbuf->tm_year - 70) * 365 + 1;
tmbuf->tm_mon = 0;
tmbuf->tm_mday = tmbuf->tm_yday;
monthdays[1] += isleap(tmbuf->tm_year + 1900);
while (monthdays[tmbuf->tm_mon] < tmbuf->tm_mday) {
tmbuf->tm_mday -= monthdays[tmbuf->tm_mon];
tmbuf->tm_mon++;
}
tmbuf->tm_wday = (days + 4) % 7; // Day 0 is magic thursday ;)
tmbuf->tm_isdst = 0;
}
| gpl-2.0 |
barbot/Cosmos | src/Simulator/SimulatorContinuousBounded.cpp | 8230 | /*******************************************************************************
* *
* Cosmos:(C)oncept et (O)utils (S)tatistique pour les (Mo)deles *
* (S)tochastiques *
* *
* Copyright (C) 2009-2012 LSV & LACL *
* Authors: Paolo Ballarini Benoît Barbot & Hilal Djafri *
* Website: http://www.lsv.ens-cachan.fr/Software/cosmos *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
* file SimulatorContinuousBounded.cpp created by Benoit Barbot on 31/01/12. *
*******************************************************************************
*/
#include <iostream>
#include "SimulatorContinuousBounded.hpp"
#include "float.h"
#include "math.h"
#include <sys/resource.h>
#include <algorithm>
//#include <boost/math/distributions/normal.hpp>
#include <boost/math/distributions/normal.hpp>
#include <boost/math/distributions/binomial.hpp>
#include <limits>
SimulatorContinuousBounded::SimulatorContinuousBounded(LHA_orig& a,int m,double e,int js):SimulatorBoundedRE(A,m){
epsilon = e;
if(js>0){
jumpsize = js;
singleIS =false;
}else{
jumpsize = -js;
singleIS = true;
}
//boost::math::normal norm;
//Normal_quantile = quantile(norm, 0.5 + 0.99 / 2.0);
}
void SimulatorContinuousBounded::initVectCo(double t){
lambda = numSolv->uniformizeMatrix();
cerr << "lambda:" << lambda<< endl;
fg = unique_ptr<FoxGlynn>(new FoxGlynn((lambda * t), DBL_EPSILON , 1/DBL_EPSILON ,epsilon));
if (fg->isValid){
cerr << "fox_glyn:" << fg->left << "," << fg->right << " Total weigts:"<< fg->total_weight<< endl;
/*for(int i = 0; i<= fg->right - fg->left; i++){
cerr << fg->left+i << " " << fg->weights[i]/ fg->total_weight << endl;
}*/
}
//fg->right = 10;
double lambda2= lambda;
initVect(fg->right+1);
lambda = lambda2;
}
BatchR SimulatorContinuousBounded::RunBatch(){
//cerr << "test(";
numSolv->reset();
//cerr << ")" << endl;
int left = (int)max(numSolv->getMinT(),fg->left);
int Nmax = (int)ceil(((double)fg->right - left)/jumpsize) ;
//cerr << "minT:\t" << numSolv->getMinT() << endl;
cerr << "Number of batch:\t" << Nmax+1 << "\tleft: " << left << "\tright: " << fg->right << "\tjumpsize:" << jumpsize << endl;
//cerr << "left:\t" << left << endl;
int n =-1;
BatchR batchResult(2*(Nmax+1),0);
//Copy and sum Poisson Weight
for(int i =0; i<= Nmax; i++)
batchResult.Min[2*i] = 0.0;
for(int i=left; i<= fg->right; i++){
int j = (int)ceil((double)( i - left)/jumpsize);
batchResult.Min[2*j] += fg->weights[i - fg->left];
}
for(int i =0; i<= Nmax; i++)
batchResult.Min[2*i] /= fg->total_weight;
list<simulationState> statevect((Nmax+1)*BatchSize);
int c =0;
if(verbose>=1)cerr << "new round:"<< n << "\tremaining trajectories: "<< statevect.size() << endl;
for (list<simulationState>::iterator it= statevect.begin(); it != statevect.end() ; it++) {
N.Origine_Rate_Table = vector<double>(N.tr,0.0);
N.Rate_Table = vector<double>(N.tr,0.0);
bool continueb = false;
//we try to find a trajectory reaching the precondition.
while(!continueb){
//we build a new trajectory from the initial state.
continueb =true;
EQ = new EventsQueue(N);
reset();
//We simulate until either the condition is satisfied or the trajectory reach a deadend.
while(!N.precondition(N.Marking) && continueb){
continueb = SimulateOneStep();
}
}
if (singleIS) {
it->maxStep = fg->right;
}else{
it->maxStep = (int)fmin(fg->right , left + (Nmax - (c/BatchSize))*jumpsize);
}
//cerr << "new path:\t" << it->maxStep << endl;
c++;
it->saveState(&N,&A,&EQ);
}
//cout << "new batch" << endl;
while (!statevect.empty()) {
numSolv->stepVect();
if(verbose>=3)cerr << numSolv->getVect() << endl;
n++;
if(verbose>=1)cerr << "new round:"<< n << "\tremaining trajectories: "<< statevect.size() << endl;
for (list<simulationState>::iterator it= statevect.begin(); it != statevect.end() ; it++) {
if(it->maxStep >= fg->right -n){
//cerr << "vect:\t" << it->maxStep;
it->loadState(&N,&A,&EQ);
//cerr << A.Likelihood << endl;
//cerr << "mu:\t" << mu() << " -> ";
if (it->maxStep == fg->right -n) {
//We first need to initialise the trajectory
Simulator::InitialEventsQueue();
if(verbose>=2)
//cerr << "new Path: " << it->maxStep << "\tmuinit: " << mu() << endl;
it->saveState(&N,&A,&EQ);
} else {
bool continueb = SimulateOneStep();
//cerr << "\t" << mu() << endl;
if((!EQ->isEmpty()) && continueb) {
it->saveState(&N,&A,&EQ);
} else {
int i = (int)ceil((double)(it->maxStep- left)/jumpsize) ;
int i2 =(int)fmax(0.0,ceil((double)(n - left)/jumpsize));
//cerr << "Successfull trajectory: "<< it->maxStep << " -> " << i << endl;
if (Result.accept ) {
if (Result.quantR[0] * (1 - Result.quantR[0]) != 0) batchResult.IsBernoulli[0] = false;
batchResult.Isucc+=1;
if(singleIS)for(int j = i2; j<= Nmax; j++){
batchResult.Mean[2*j]+=1;
batchResult.Mean[2*j+1] += Result.quantR[0];
batchResult.M2[2*j+1] += pow(Result.quantR[0] , 2);
batchResult.M3[2*j+1] += pow(Result.quantR[0] , 3);
batchResult.M4[2*j+1] += pow(Result.quantR[0] , 4);
batchResult.Min[2*j+1] = fmin(batchResult.Min[2*j+1],Result.quantR[0]);
batchResult.Max[2*j+1] = fmax(batchResult.Max[2*j+1],Result.quantR[0]);
} else {
batchResult.Mean[2*i]+=1;
batchResult.Mean[2*i+1] += Result.quantR[0];
batchResult.M2[2*i+1] += pow(Result.quantR[0] , 2);
batchResult.M3[2*i+1] += pow(Result.quantR[0] , 3);
batchResult.M4[2*i+1] += pow(Result.quantR[0] , 4);
batchResult.Min[2*i+1] = fmin(batchResult.Min[2*i+1],Result.quantR[0]);
batchResult.Max[2*i+1] = fmax(batchResult.Max[2*i+1],Result.quantR[0]);
}
}
if(singleIS){for(int j = 0; j<= Nmax; j++)batchResult.M2[2*j]+=1;}
else batchResult.M2[2*i]+=1;
batchResult.I++;
delete EQ;
it = statevect.erase(it);
it--;
}
}
}
}
}
return (batchResult);
}
| gpl-2.0 |
iffyio/mouse-drag-gestures | contentscript.js | 397 |
/*Listen for events* and relay to background.js */
addEventListener("dragend", function(event){
var selectedText = getSelection().toString();
if(selectedText.length > 1){
chrome.runtime.sendMessage({searchQuery:selectedText});
}
});
addEventListener("dragend", function(event){
var link = event.target;
if(link.tagName === 'A'){
chrome.runtime.sendMessage({openLink: link.href});
}
}); | gpl-2.0 |
mmaroti/shared | mmaroti/ua/symbol/InfixBinaryAssocSymbol.java | 1044 | package mmaroti.ua.symbol;
/**
* Copyright (C) 2000 Miklos Maroti
*/
import java.util.*;
public class InfixBinaryAssocSymbol extends OperatorSymbol
{
public int arity() { return 2; }
public int maxArity() { return Integer.MAX_VALUE; }
public void parse(LinkedList<Object> list)
{
ListIterator<Object> iter = list.listIterator();
if( !findFirstMatch(iter) )
return;
iter.previous();
if( !iter.hasPrevious() )
throw new IllegalArgumentException("no left argument for operator " + name);
LinkedList<Expression> args = new LinkedList<Expression>();
Object obj = iter.previous();
for(;;)
{
args.add(getExpression(obj));
iter.remove();
if( !removeNextMatch(iter) )
break;
if( !iter.hasNext() )
throw new IllegalArgumentException("no right argument for operator " + name);
obj = iter.next();
}
iter.add(new ExpressionNode(this, args.toArray(new Expression[args.size()])));
}
public InfixBinaryAssocSymbol(String name, int precedence)
{
super(name, precedence);
}
}
| gpl-2.0 |
olek1984/dremboard | wp-content/plugins/trend_drems/js/trend_drems.js | 1100 | /*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
/*
Created on : Jan 14, 2015, 2:47:46 PM
Author : jinxinzhi
*/
jQuery(".gk-bp-trend-drems .see-more").click(function(){
var page_input = jQuery(".gk-bp-trend-drems #trend-drem-page");
var page = parseInt(page_input.val());
jQuery.post(ajaxurl, {
action: 'see_more_trend',
'cookie': bp_get_cookies(),
data: {page : page}
},
function(response) {
if (response == "false"){
jQuery(".gk-bp-trend-drems .see-more").css("display", "none");
}else{
var more_flag = response.more_flag;
var trend_html = response.trend_html;
jQuery(".gk-bp-trend-drems .trend-container").append(trend_html);
if (more_flag == false){
jQuery(".gk-bp-trend-drems .see-more").css("display", "none");
}
page_input.val(page + 1);
}
}, 'json');
}); | gpl-2.0 |
hendersa/bes | src/nes/win32/NstManager.cpp | 1496 | ////////////////////////////////////////////////////////////////////////////////////////
//
// Nestopia - NES/Famicom emulator written in C++
//
// Copyright (C) 2003-2008 Martin Freij
//
// This file is part of Nestopia.
//
// Nestopia is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// Nestopia 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 Nestopia; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////////////
#include "NstApplicationInstance.hpp"
#include "NstManager.hpp"
namespace Nestopia
{
namespace Managers
{
Manager::~Manager()
{
emulator.Events().Remove( this );
menu.Commands().RemoveAll( this );
menu.Popups().Remove( this );
Application::Instance::Events::Remove( this );
}
void Manager::Resume()
{
Application::Instance::GetMainWindow().Post( Application::Instance::WM_NST_COMMAND_RESUME );
}
}
}
| gpl-2.0 |
fhuberts/osgiComponents | nl.pelagic.service.log.syslog/test/nl/pelagic/service/log/syslog/MockSysLogLogger.java | 630 | package nl.pelagic.service.log.syslog;
import java.util.EventObject;
import java.util.LinkedList;
import java.util.List;
import org.junit.Ignore;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
@Ignore
class MockSysLogLogger implements SysLogLogger {
List<LogEntryImpl> logs = new LinkedList<>();
@Override
public void log(final Bundle bundle, final ServiceReference<?> sr, final int level, final String message,
final Throwable exception, final EventObject event) {
this.logs.add(new LogEntryImpl(System.currentTimeMillis(), bundle, sr, level, message, exception, event));
}
} | gpl-2.0 |
hijoy/VSL_ERS | WebUI/UserControls/YearAndMonthUserControl.ascx.cs | 3061 | using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BusinessObjects;
using System.Text.RegularExpressions;
public delegate void DateTextChanged(object sender, EventArgs e);
public partial class UserControls_YearAndMonthUserControl : System.Web.UI.UserControl {
public event DateTextChanged DateTextChanged;
/// <summary>
/// ÈÕÆÚÖµ
/// </summary>
/// <remarks></remarks>
public string SelectedDate {
get { return this.txtDate.Text; }
set {
if ((!(value == string.Empty) && (!object.ReferenceEquals(value, DBNull.Value)))) {
if (this.IsExpensePeriod) {
this.txtDate.Text = DBNullConverter.ToDateTime(value).ToString("yyyyMM");
} else {
this.txtDate.Text = DBNullConverter.ToDateTime(value).ToString("yyyy-MM-dd");
}
} else {
this.txtDate.Text = string.Empty;
}
}
}
public System.Drawing.Color BackColor {
get { return this.txtDate.BackColor; }
set { this.txtDate.BackColor = value; }
}
/// <summary>
/// ÊÇ·ñÊÇÔ¤ËãÑ¡ÔñµÄ¿Ø¼þ
/// </summary>
/// <remarks></remarks>
private bool _expensePeriod = false;
[System.ComponentModel.Description("ÊÇ·ñÓÃÓÚÔ¤ËãÑ¡ÔñµÄ¿Ø¼þ"), System.ComponentModel.DefaultValue(false)]
public bool IsExpensePeriod {
get { return this._expensePeriod; }
set { this._expensePeriod = value; }
}
private bool _readonly;
public bool IsReadOnly {
get { return this._readonly; }
set { this._readonly = value; }
}
public string CssClass {
get { return this.txtDate.CssClass; }
set { this.txtDate.CssClass = value; }
}
protected override void OnLoad(EventArgs e) {
if ((!this.IsReadOnly)) {
this.ibtDate.Attributes.Add("onclick", "javascript:DateSelection('" + this.txtDate.ClientID + string.Format("',{0}); return false;", IsExpensePeriod.ToString().ToLower()));
}
if (this.IsReadOnly) {
this.txtDate.Attributes.Add("readonly", "readonly");
}
this.txtDate.Attributes.Add("onkeypress", "javascript:return CheckInputIsDate(this);");
this.txtDate.Attributes.Add("onblur", "javascript:return CheckExpensePeriodDatePicker(this);");
base.OnLoad(e);
}
public bool AutoPostBack {
get {
return this.txtDate.AutoPostBack;
}
set {
this.txtDate.AutoPostBack = value;
}
}
protected void txtDate_TextChanged(object sender, EventArgs e) {
if (DateTextChanged != null && this.txtDate.Text != string.Empty && Regex.IsMatch(this.txtDate.Text.ToString(), @"^\d{4}?(?:0[1-9]|1[0-2])$")) {
DateTextChanged(sender, e);
}
}
}
| gpl-2.0 |
01J/bealtine | administrator/components/com_sef/tables/word.php | 1501 | <?php
/**
* SEF component for Joomla!
*
* @package JoomSEF
* @version 4.6.2
* @author ARTIO s.r.o., http://www.artio.net
* @copyright Copyright (C) 2015 ARTIO s.r.o.
* @license GNU/GPLv3 http://www.artio.net/license/gnu-general-public-license
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
class TableWord extends JTable
{
/** @var int */
var $id = null;
/** @var string */
var $word = null;
/**
* Constructor
*
* @param object Database connector object
*/
function TableWord(& $db)
{
parent::__construct('#__sefwords', 'id', $db);
}
function check()
{
//initialize
$this->_error = null;
$this->word = trim($this->word);
// check for valid word
if ($this->word == '') {
$this->_error .= JText::_('COM_SEF_ERROR_EMPTY_WORD');
return false;
}
if (is_null($this->_error)) {
// check for existing words
$this->_db->setQuery("SELECT id FROM #__sefwords WHERE `word` LIKE " . $this->_db->Quote($this->word));
$xid = intval($this->_db->loadResult());
if ($xid && $xid != intval($this->id)) {
$this->_error = JText::_('COM_SEF_ERROR_WORD_EXISTS');
return false;
}
return true;
} else {
return false;
}
}
}
?> | gpl-2.0 |
DaniUPC/near-image-replica-detection | src/main/java/org/twitterReplica/core/FilteringParams.java | 1013 | package org.twitterReplica.core;
import org.twitterReplica.model.FilteringType;
import scala.Serializable;
public class FilteringParams implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private FilteringType filteringType;
private double thresh;
private boolean logScaleEnabled;
public FilteringParams(FilteringType filteringType, double thresh,
boolean logScaleEnabled) {
super();
this.filteringType = filteringType;
this.thresh = thresh;
this.logScaleEnabled = logScaleEnabled;
}
public FilteringType getFilteringType() {
return filteringType;
}
public void setFilteringType(FilteringType filteringType) {
this.filteringType = filteringType;
}
public double getThresh() {
return thresh;
}
public void setThresh(double thresh) {
this.thresh = thresh;
}
public boolean isLogScaleEnabled() {
return logScaleEnabled;
}
public void setLogScaleEnabled(boolean logScaleEnabled) {
this.logScaleEnabled = logScaleEnabled;
}
}
| gpl-2.0 |
GoogleFrog/Zero-K | units/armstiletto_laser.lua | 5911 | unitDef = {
unitname = [[armstiletto_laser]],
name = [[Thunderbird]],
description = [[Disarming Lightning Bomber]],
amphibious = true,
buildCostEnergy = 550,
buildCostMetal = 550,
buildPic = [[armstiletto_laser.png]],
buildTime = 550,
canAttack = true,
canDropFlare = false,
canFly = true,
canMove = true,
canSubmerge = false,
category = [[FIXEDWING]],
collide = false,
collisionVolumeOffsets = [[0 0 4]],
collisionVolumeScales = [[45 20 50]],
collisionVolumeTest = 1,
collisionVolumeType = [[box]],
corpse = [[DEAD]],
cruiseAlt = 180,
customParams = {
description_bp = [[Bombardeiro de desarmar]],
description_de = [[Entwaffnungbomber]],
description_fr = [[Bombardier desarmant]],
description_pl = [[Bombowiec rozbrajajacy]],
helptext = [[Fast bomber armed with a lightning generator that disarms units in a wide area under it.]],
helptext_bp = [[Bombardeiro rapido, que dispara raios de desarmar.]],
helptext_de = [[Schneller Entwaffnungbomber, der mit einem Stossspannungsgenerator zum Entwaffnen großflächiger Gebiete bewaffnet ist.]],
helptext_fr = [[Rapide, armé de canons desarmant pouvant désarmer les unités dans une large bande.]],
helptext_pl = [[Szybki bombowiec, ktory jest w stanie rozbroic jednostki w szerokim obszarze.]],
modelradius = [[10]],
},
explodeAs = [[GUNSHIPEX]],
floater = true,
footprintX = 3,
footprintZ = 3,
iconType = [[bomberriot]],
idleAutoHeal = 5,
idleTime = 1800,
maxAcc = 0.5,
maxDamage = 1000,
maxFuel = 1000000,
maxVelocity = 9,
minCloakDistance = 75,
noChaseCategory = [[TERRAFORM FIXEDWING LAND SHIP SWIM GUNSHIP SUB HOVER]],
objectName = [[stiletto.s3o]],
script = [[armstiletto_laser.lua]],
seismicSignature = 0,
selfDestructAs = [[GUNSHIPEX]],
sightDistance = 660,
stealth = false,
turnRadius = 130,
weapons = {
{
def = [[BOGUS_BOMB]],
badTargetCategory = [[SWIM LAND SHIP HOVER]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP]],
},
{
def = [[ARMBOMBLIGHTNING]],
mainDir = [[0 -1 0]],
maxAngleDif = 0,
onlyTargetCategory = [[NONE]],
},
},
weaponDefs = {
ARMBOMBLIGHTNING = {
name = [[Lightning]],
areaOfEffect = 192,
avoidFeature = false,
avoidFriendly = false,
beamTime = 0.01,
burst = 80,
burstRate = 0.3,
canattackground = false,
collideFriendly = false,
coreThickness = 0.6,
craterBoost = 0,
craterMult = 0,
customParams = {
disarmDamageMult = 1,
disarmDamageOnly = 1,
disarmTimer = 16, -- seconds
},
damage = {
default = 675,
},
edgeEffectiveness = 0.4,
explosionGenerator = [[custom:WHITE_LIGHTNING_BOMB]],
fireStarter = 90,
impulseBoost = 0,
impulseFactor = 0,
intensity = 12,
interceptedByShieldType = 1,
largeBeamLaser = true,
laserFlareSize = 5,
minIntensity = 1,
range = 730,
reloadtime = 10,
rgbColor = [[1 1 1]],
sprayAngle = 6000,
texture1 = [[lightning]],
texture2 = [[flare]],
texture3 = [[flare]],
texture4 = [[smallflare]],
thickness = 10,
tileLength = 50,
tolerance = 32767,
turret = true,
weaponType = [[BeamLaser]],
weaponVelocity = 2250,
},
BOGUS_BOMB = {
name = [[Fake Bomb]],
avoidFeature = false,
avoidFriendly = false,
burst = 2,
burstrate = 1,
collideFriendly = false,
damage = {
default = 0,
},
explosionGenerator = [[custom:NONE]],
interceptedByShieldType = 1,
intensity = 0,
manualBombSettings = true,
myGravity = 0.8,
noSelfDamage = true,
range = 500,
reloadtime = 10,
sprayangle = 64000,
weaponType = [[AircraftBomb]],
},
},
featureDefs = {
DEAD = {
description = [[Wreckage - Thunderbird]],
blocking = true,
damage = 1000,
energy = 0,
featureDead = [[HEAP]],
footprintX = 3,
footprintZ = 3,
metal = 220,
object = [[Stiletto_dead.s3o]],
reclaimable = true,
reclaimTime = 220,
},
HEAP = {
description = [[Debris - Thunderbird]],
blocking = false,
damage = 1000,
energy = 0,
footprintX = 3,
footprintZ = 3,
metal = 110,
object = [[debris2x2c.s3o]],
reclaimable = true,
reclaimTime = 110,
},
},
}
return lowerkeys({ armstiletto_laser = unitDef })
| gpl-2.0 |
magpie42/wp444 | wp-includes/comment-template.php | 82396 | <?php
/**
* Comment template functions
*
* These functions are meant to live inside of the WordPress loop.
*
* @package WordPress
* @subpackage Template
*/
/**
* Retrieve the author of the current comment.
*
* If the comment has an empty comment_author field, then 'Anonymous' person is
* assumed.
*
* @since 1.5.0
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param int|WP_Comment $comment_ID Optional. WP_Comment or the ID of the comment for which to retrieve the author.
* Default current comment.
* @return string The comment author
*/
function get_comment_author( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
if ( empty( $comment->comment_author ) ) {
if ( $comment->user_id && $user = get_userdata( $comment->user_id ) )
$author = $user->display_name;
else
$author = __('Anonymous');
} else {
$author = $comment->comment_author;
}
/**
* Filter the returned comment author name.
*
* @since 1.5.0
* @since 4.1.0 The `$comment_ID` and `$comment` parameters were added.
*
* @param string $author The comment author's username.
* @param int $comment_ID The comment ID.
* @param WP_Comment $comment The comment object.
*/
return apply_filters( 'get_comment_author', $author, $comment->comment_ID, $comment );
}
/**
* Displays the author of the current comment.
*
* @since 0.71
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param int|WP_Comment $comment_ID Optional. WP_Comment or the ID of the comment for which to print the author.
* Default current comment.
*/
function comment_author( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
$author = get_comment_author( $comment );
/**
* Filter the comment author's name for display.
*
* @since 1.2.0
* @since 4.1.0 The `$comment_ID` parameter was added.
*
* @param string $author The comment author's username.
* @param int $comment_ID The comment ID.
*/
echo apply_filters( 'comment_author', $author, $comment->comment_ID );
}
/**
* Retrieve the email of the author of the current comment.
*
* @since 1.5.0
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param int|WP_Comment $comment_ID Optional. WP_Comment or the ID of the comment for which to get the author's email.
* Default current comment.
* @return string The current comment author's email
*/
function get_comment_author_email( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
/**
* Filter the comment author's returned email address.
*
* @since 1.5.0
* @since 4.1.0 The `$comment_ID` and `$comment` parameters were added.
*
* @param string $comment_author_email The comment author's email address.
* @param int $comment_ID The comment ID.
* @param WP_Comment $comment The comment object.
*/
return apply_filters( 'get_comment_author_email', $comment->comment_author_email, $comment->comment_ID, $comment );
}
/**
* Display the email of the author of the current global $comment.
*
* Care should be taken to protect the email address and assure that email
* harvesters do not capture your commentors' email address. Most assume that
* their email address will not appear in raw form on the blog. Doing so will
* enable anyone, including those that people don't want to get the email
* address and use it for their own means good and bad.
*
* @since 0.71
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param int|WP_Comment $comment_ID Optional. WP_Comment or the ID of the comment for which to print the author's email.
* Default current comment.
*/
function comment_author_email( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
$author_email = get_comment_author_email( $comment );
/**
* Filter the comment author's email for display.
*
* @since 1.2.0
* @since 4.1.0 The `$comment_ID` parameter was added.
*
* @param string $author_email The comment author's email address.
* @param int $comment_ID The comment ID.
*/
echo apply_filters( 'author_email', $author_email, $comment->comment_ID );
}
/**
* Display the html email link to the author of the current comment.
*
* Care should be taken to protect the email address and assure that email
* harvesters do not capture your commentors' email address. Most assume that
* their email address will not appear in raw form on the blog. Doing so will
* enable anyone, including those that people don't want to get the email
* address and use it for their own means good and bad.
*
* @since 0.71
*
* @param string $linktext Optional. Text to display instead of the comment author's email address.
* Default empty.
* @param string $before Optional. Text or HTML to display before the email link. Default empty.
* @param string $after Optional. Text or HTML to display after the email link. Default empty.
*/
function comment_author_email_link( $linktext = '', $before = '', $after = '' ) {
if ( $link = get_comment_author_email_link( $linktext, $before, $after ) )
echo $link;
}
/**
* Return the html email link to the author of the current comment.
*
* Care should be taken to protect the email address and assure that email
* harvesters do not capture your commentors' email address. Most assume that
* their email address will not appear in raw form on the blog. Doing so will
* enable anyone, including those that people don't want to get the email
* address and use it for their own means good and bad.
*
* @since 2.7.0
*
* @param string $linktext Optional. Text to display instead of the comment author's email address.
* Default empty.
* @param string $before Optional. Text or HTML to display before the email link. Default empty.
* @param string $after Optional. Text or HTML to display after the email link. Default empty.
* @return string
*/
function get_comment_author_email_link( $linktext = '', $before = '', $after = '' ) {
$comment = get_comment();
/**
* Filter the comment author's email for display.
*
* Care should be taken to protect the email address and assure that email
* harvesters do not capture your commenter's email address.
*
* @since 1.2.0
* @since 4.1.0 The `$comment` parameter was added.
*
* @param string $comment_author_email The comment author's email address.
* @param WP_Comment $comment The comment object.
*/
$email = apply_filters( 'comment_email', $comment->comment_author_email, $comment );
if ((!empty($email)) && ($email != '@')) {
$display = ($linktext != '') ? $linktext : $email;
$return = $before;
$return .= "<a href='mailto:$email'>$display</a>";
$return .= $after;
return $return;
} else {
return '';
}
}
/**
* Retrieve the HTML link to the URL of the author of the current comment.
*
* Both get_comment_author_url() and get_comment_author() rely on get_comment(),
* which falls back to the global comment variable if the $comment_ID argument is empty.
*
* @since 1.5.0
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param int|WP_Comment $comment_ID Optional. WP_Comment or the ID of the comment for which to get the author's link.
* Default current comment.
* @return string The comment author name or HTML link for author's URL.
*/
function get_comment_author_link( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
$url = get_comment_author_url( $comment );
$author = get_comment_author( $comment );
if ( empty( $url ) || 'http://' == $url )
$return = $author;
else
$return = "<a href='$url' rel='external nofollow' class='url'>$author</a>";
/**
* Filter the comment author's link for display.
*
* @since 1.5.0
* @since 4.1.0 The `$author` and `$comment_ID` parameters were added.
*
* @param string $return The HTML-formatted comment author link.
* Empty for an invalid URL.
* @param string $author The comment author's username.
* @param int $comment_ID The comment ID.
*/
return apply_filters( 'get_comment_author_link', $return, $author, $comment->comment_ID );
}
/**
* Display the html link to the url of the author of the current comment.
*
* @since 0.71
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param int|WP_Comment $comment_ID Optional. WP_Comment or the ID of the comment for which to print the author's link.
* Default current comment.
*/
function comment_author_link( $comment_ID = 0 ) {
echo get_comment_author_link( $comment_ID );
}
/**
* Retrieve the IP address of the author of the current comment.
*
* @since 1.5.0
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param int|WP_Comment $comment_ID Optional. WP_Comment or the ID of the comment for which to get the author's IP address.
* Default current comment.
* @return string Comment author's IP address.
*/
function get_comment_author_IP( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
/**
* Filter the comment author's returned IP address.
*
* @since 1.5.0
* @since 4.1.0 The `$comment_ID` and `$comment` parameters were added.
*
* @param string $comment_author_IP The comment author's IP address.
* @param int $comment_ID The comment ID.
* @param WP_Comment $comment The comment object.
*/
return apply_filters( 'get_comment_author_IP', $comment->comment_author_IP, $comment->comment_ID, $comment );
}
/**
* Display the IP address of the author of the current comment.
*
* @since 0.71
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param int|WP_Comment $comment_ID Optional. WP_Comment or the ID of the comment for which to print the author's IP address.
* Default current comment.
*/
function comment_author_IP( $comment_ID = 0 ) {
echo get_comment_author_IP( $comment_ID );
}
/**
* Retrieve the url of the author of the current comment.
*
* @since 1.5.0
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param int|WP_Comment $comment_ID Optional. WP_Comment or the ID of the comment for which to get the author's URL.
* Default current comment.
* @return string Comment author URL.
*/
function get_comment_author_url( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
$url = ('http://' == $comment->comment_author_url) ? '' : $comment->comment_author_url;
$url = esc_url( $url, array('http', 'https') );
/**
* Filter the comment author's URL.
*
* @since 1.5.0
* @since 4.1.0 The `$comment_ID` and `$comment` parameters were added.
*
* @param string $url The comment author's URL.
* @param int $comment_ID The comment ID.
* @param WP_Comment $comment The comment object.
*/
return apply_filters( 'get_comment_author_url', $url, $comment->comment_ID, $comment );
}
/**
* Display the url of the author of the current comment.
*
* @since 0.71
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param int|WP_Comment $comment_ID Optional. WP_Comment or the ID of the comment for which to print the author's URL.
* Default current comment.
*/
function comment_author_url( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
$author_url = get_comment_author_url( $comment );
/**
* Filter the comment author's URL for display.
*
* @since 1.2.0
* @since 4.1.0 The `$comment_ID` parameter was added.
*
* @param string $author_url The comment author's URL.
* @param int $comment_ID The comment ID.
*/
echo apply_filters( 'comment_url', $author_url, $comment->comment_ID );
}
/**
* Retrieves the HTML link of the url of the author of the current comment.
*
* $linktext parameter is only used if the URL does not exist for the comment
* author. If the URL does exist then the URL will be used and the $linktext
* will be ignored.
*
* Encapsulate the HTML link between the $before and $after. So it will appear
* in the order of $before, link, and finally $after.
*
* @since 1.5.0
*
* @param string $linktext Optional. The text to display instead of the comment
* author's email address. Default empty.
* @param string $before Optional. The text or HTML to display before the email link.
* Default empty.
* @param string $after Optional. The text or HTML to display after the email link.
* Default empty.
* @return string The HTML link between the $before and $after parameters.
*/
function get_comment_author_url_link( $linktext = '', $before = '', $after = '' ) {
$url = get_comment_author_url();
$display = ($linktext != '') ? $linktext : $url;
$display = str_replace( 'http://www.', '', $display );
$display = str_replace( 'http://', '', $display );
if ( '/' == substr($display, -1) ) {
$display = substr($display, 0, -1);
}
$return = "$before<a href='$url' rel='external'>$display</a>$after";
/**
* Filter the comment author's returned URL link.
*
* @since 1.5.0
*
* @param string $return The HTML-formatted comment author URL link.
*/
return apply_filters( 'get_comment_author_url_link', $return );
}
/**
* Displays the HTML link of the url of the author of the current comment.
*
* @since 0.71
*
* @param string $linktext Optional. Text to display instead of the comment author's
* email address. Default empty.
* @param string $before Optional. Text or HTML to display before the email link.
* Default empty.
* @param string $after Optional. Text or HTML to display after the email link.
* Default empty.
*/
function comment_author_url_link( $linktext = '', $before = '', $after = '' ) {
echo get_comment_author_url_link( $linktext, $before, $after );
}
/**
* Generates semantic classes for each comment element.
*
* @since 2.7.0
* @since 4.4.0 Added the ability for `$comment` to also accept a WP_Comment object.
*
* @param string|array $class Optional. One or more classes to add to the class list.
* Default empty.
* @param int|WP_Comment $comment Comment ID or WP_Comment object. Default current comment.
* @param int|WP_Post $post_id Post ID or WP_Post object. Default current post.
* @param bool $echo Optional. Whether to cho or return the output.
* Default true.
* @return string If `$echo` is false, the class will be returned. Void otherwise.
*/
function comment_class( $class = '', $comment = null, $post_id = null, $echo = true ) {
// Separates classes with a single space, collates classes for comment DIV
$class = 'class="' . join( ' ', get_comment_class( $class, $comment, $post_id ) ) . '"';
if ( $echo)
echo $class;
else
return $class;
}
/**
* Returns the classes for the comment div as an array.
*
* @since 2.7.0
* @since 4.4.0 Added the ability for `$comment_id` to also accept a WP_Comment object.
*
* @global int $comment_alt
* @global int $comment_depth
* @global int $comment_thread_alt
*
* @param string|array $class Optional. One or more classes to add to the class list. Default empty.
* @param int|WP_Comment $comment_id Comment ID or WP_Comment object. Default current comment.
* @param int|WP_Post $post_id Post ID or WP_Post object. Default current post.
* @return array An array of classes.
*/
function get_comment_class( $class = '', $comment_id = null, $post_id = null ) {
global $comment_alt, $comment_depth, $comment_thread_alt;
$classes = array();
$comment = get_comment( $comment_id );
if ( ! $comment ) {
return $classes;
}
// Get the comment type (comment, trackback),
$classes[] = ( empty( $comment->comment_type ) ) ? 'comment' : $comment->comment_type;
// Add classes for comment authors that are registered users.
if ( $comment->user_id > 0 && $user = get_userdata( $comment->user_id ) ) {
$classes[] = 'byuser';
$classes[] = 'comment-author-' . sanitize_html_class( $user->user_nicename, $comment->user_id );
// For comment authors who are the author of the post
if ( $post = get_post($post_id) ) {
if ( $comment->user_id === $post->post_author ) {
$classes[] = 'bypostauthor';
}
}
}
if ( empty($comment_alt) )
$comment_alt = 0;
if ( empty($comment_depth) )
$comment_depth = 1;
if ( empty($comment_thread_alt) )
$comment_thread_alt = 0;
if ( $comment_alt % 2 ) {
$classes[] = 'odd';
$classes[] = 'alt';
} else {
$classes[] = 'even';
}
$comment_alt++;
// Alt for top-level comments
if ( 1 == $comment_depth ) {
if ( $comment_thread_alt % 2 ) {
$classes[] = 'thread-odd';
$classes[] = 'thread-alt';
} else {
$classes[] = 'thread-even';
}
$comment_thread_alt++;
}
$classes[] = "depth-$comment_depth";
if ( !empty($class) ) {
if ( !is_array( $class ) )
$class = preg_split('#\s+#', $class);
$classes = array_merge($classes, $class);
}
$classes = array_map('esc_attr', $classes);
/**
* Filter the returned CSS classes for the current comment.
*
* @since 2.7.0
*
* @param array $classes An array of comment classes.
* @param string $class A comma-separated list of additional classes added to the list.
* @param int $comment_id The comment id.
* @param WP_Comment $comment The comment object.
* @param int|WP_Post $post_id The post ID or WP_Post object.
*/
return apply_filters( 'comment_class', $classes, $class, $comment->comment_ID, $comment, $post_id );
}
/**
* Retrieve the comment date of the current comment.
*
* @since 1.5.0
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param string $d Optional. The format of the date. Default user's setting.
* @param int|WP_Comment $comment_ID WP_Comment or ID of the comment for which to get the date.
* Default current comment.
* @return string The comment's date.
*/
function get_comment_date( $d = '', $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
if ( '' == $d )
$date = mysql2date(get_option('date_format'), $comment->comment_date);
else
$date = mysql2date($d, $comment->comment_date);
/**
* Filter the returned comment date.
*
* @since 1.5.0
*
* @param string|int $date Formatted date string or Unix timestamp.
* @param string $d The format of the date.
* @param WP_Comment $comment The comment object.
*/
return apply_filters( 'get_comment_date', $date, $d, $comment );
}
/**
* Display the comment date of the current comment.
*
* @since 0.71
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param string $d Optional. The format of the date. Default user's settings.
* @param int|WP_Comment $comment_ID WP_Comment or ID of the comment for which to print the date.
* Default current comment.
*/
function comment_date( $d = '', $comment_ID = 0 ) {
echo get_comment_date( $d, $comment_ID );
}
/**
* Retrieve the excerpt of the current comment.
*
* Will cut each word and only output the first 20 words with '…' at the end.
* If the word count is less than 20, then no truncating is done and no '…'
* will appear.
*
* @since 1.5.0
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param int|WP_Comment $comment_ID WP_Comment or ID of the comment for which to get the excerpt.
* Default current comment.
* @return string The maybe truncated comment with 20 words or less.
*/
function get_comment_excerpt( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
$comment_text = strip_tags( str_replace( array( "\n", "\r" ), ' ', $comment->comment_content ) );
$words = explode( ' ', $comment_text );
/**
* Filter the amount of words used in the comment excerpt.
*
* @since 4.4.0
*
* @param int $comment_excerpt_length The amount of words you want to display in the comment excerpt.
*/
$comment_excerpt_length = apply_filters( 'comment_excerpt_length', 20 );
$use_ellipsis = count( $words ) > $comment_excerpt_length;
if ( $use_ellipsis ) {
$words = array_slice( $words, 0, $comment_excerpt_length );
}
$excerpt = trim( join( ' ', $words ) );
if ( $use_ellipsis ) {
$excerpt .= '…';
}
/**
* Filter the retrieved comment excerpt.
*
* @since 1.5.0
* @since 4.1.0 The `$comment_ID` and `$comment` parameters were added.
*
* @param string $excerpt The comment excerpt text.
* @param int $comment_ID The comment ID.
* @param WP_Comment $comment The comment object.
*/
return apply_filters( 'get_comment_excerpt', $excerpt, $comment->comment_ID, $comment );
}
/**
* Display the excerpt of the current comment.
*
* @since 1.2.0
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param int|WP_Comment $comment_ID WP_Comment or ID of the comment for which to print the excerpt.
* Default current comment.
*/
function comment_excerpt( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
$comment_excerpt = get_comment_excerpt( $comment );
/**
* Filter the comment excerpt for display.
*
* @since 1.2.0
* @since 4.1.0 The `$comment_ID` parameter was added.
*
* @param string $comment_excerpt The comment excerpt text.
* @param int $comment_ID The comment ID.
*/
echo apply_filters( 'comment_excerpt', $comment_excerpt, $comment->comment_ID );
}
/**
* Retrieve the comment id of the current comment.
*
* @since 1.5.0
*
* @return int The comment ID.
*/
function get_comment_ID() {
$comment = get_comment();
/**
* Filter the returned comment ID.
*
* @since 1.5.0
* @since 4.1.0 The `$comment_ID` parameter was added.
*
* @param int $comment_ID The current comment ID.
* @param WP_Comment $comment The comment object.
*/
return apply_filters( 'get_comment_ID', $comment->comment_ID, $comment );
}
/**
* Display the comment id of the current comment.
*
* @since 0.71
*/
function comment_ID() {
echo get_comment_ID();
}
/**
* Retrieve the link to a given comment.
*
* @since 1.5.0
* @since 4.4.0 Added the ability for `$comment` to also accept a WP_Comment object. Added `$cpage` argument.
*
* @see get_page_of_comment()
*
* @global WP_Rewrite $wp_rewrite
* @global bool $in_comment_loop
*
* @param WP_Comment|int|null $comment Comment to retrieve. Default current comment.
* @param array $args {
* An array of optional arguments to override the defaults.
*
* @type string $type Passed to {@see get_page_of_comment()}.
* @type int $page Current page of comments, for calculating comment pagination.
* @type int $per_page Per-page value for comment pagination.
* @type int $max_depth Passed to {@see get_page_of_comment()}.
* @type int|string $cpage Value to use for the comment's "comment-page" or "cpage" value. If provided, this
* value overrides any value calculated from `$page` and `$per_page`.
* }
* @return string The permalink to the given comment.
*/
function get_comment_link( $comment = null, $args = array() ) {
global $wp_rewrite, $in_comment_loop;
$comment = get_comment($comment);
// Backwards compat
if ( ! is_array( $args ) ) {
$args = array( 'page' => $args );
}
$defaults = array(
'type' => 'all',
'page' => '',
'per_page' => '',
'max_depth' => '',
'cpage' => null,
);
$args = wp_parse_args( $args, $defaults );
$link = get_permalink( $comment->comment_post_ID );
// The 'cpage' param takes precedence.
if ( ! is_null( $args['cpage'] ) ) {
$cpage = $args['cpage'];
// No 'cpage' is provided, so we calculate one.
} else {
if ( '' === $args['per_page'] && get_option( 'page_comments' ) ) {
$args['per_page'] = get_option('comments_per_page');
}
if ( empty( $args['per_page'] ) ) {
$args['per_page'] = 0;
$args['page'] = 0;
}
$cpage = $args['page'];
if ( '' == $cpage ) {
if ( ! empty( $in_comment_loop ) ) {
$cpage = get_query_var( 'cpage' );
} else {
// Requires a database hit, so we only do it when we can't figure out from context.
$cpage = get_page_of_comment( $comment->comment_ID, $args );
}
}
/*
* If the default page displays the oldest comments, the permalinks for comments on the default page
* do not need a 'cpage' query var.
*/
$default_comments_page = get_option( 'default_comments_page' );
if ( 'oldest' === get_option( 'default_comments_page' ) && 1 === $cpage ) {
$cpage = '';
}
}
if ( $cpage ) {
if ( $wp_rewrite->using_permalinks() ) {
if ( $cpage ) {
$link = trailingslashit( $link ) . $wp_rewrite->comments_pagination_base . '-' . $cpage;
}
$link = user_trailingslashit( $link, 'comment' );
} elseif ( $cpage ) {
$link = add_query_arg( 'cpage', $cpage, $link );
}
}
if ( $wp_rewrite->using_permalinks() ) {
$link = user_trailingslashit( $link, 'comment' );
}
$link = $link . '#comment-' . $comment->comment_ID;
/**
* Filter the returned single comment permalink.
*
* @since 2.8.0
* @since 4.4.0 Added the `$cpage` parameter.
*
* @see get_page_of_comment()
*
* @param string $link The comment permalink with '#comment-$id' appended.
* @param WP_Comment $comment The current comment object.
* @param array $args An array of arguments to override the defaults.
* @param int $cpage The calculated 'cpage' value.
*/
return apply_filters( 'get_comment_link', $link, $comment, $args, $cpage );
}
/**
* Retrieves the link to the current post comments.
*
* @since 1.5.0
*
* @param int|WP_Post $post_id Optional. Post ID or WP_Post object. Default is global $post.
* @return string The link to the comments.
*/
function get_comments_link( $post_id = 0 ) {
$hash = get_comments_number( $post_id ) ? '#comments' : '#respond';
$comments_link = get_permalink( $post_id ) . $hash;
/**
* Filter the returned post comments permalink.
*
* @since 3.6.0
*
* @param string $comments_link Post comments permalink with '#comments' appended.
* @param int|WP_Post $post_id Post ID or WP_Post object.
*/
return apply_filters( 'get_comments_link', $comments_link, $post_id );
}
/**
* Display the link to the current post comments.
*
* @since 0.71
*
* @param string $deprecated Not Used.
* @param string $deprecated_2 Not Used.
*/
function comments_link( $deprecated = '', $deprecated_2 = '' ) {
if ( !empty( $deprecated ) )
_deprecated_argument( __FUNCTION__, '0.72' );
if ( !empty( $deprecated_2 ) )
_deprecated_argument( __FUNCTION__, '1.3' );
echo esc_url( get_comments_link() );
}
/**
* Retrieve the amount of comments a post has.
*
* @since 1.5.0
*
* @param int|WP_Post $post_id Optional. Post ID or WP_Post object. Default is global $post.
* @return int The number of comments a post has.
*/
function get_comments_number( $post_id = 0 ) {
$post = get_post( $post_id );
if ( ! $post ) {
$count = 0;
} else {
$count = $post->comment_count;
$post_id = $post->ID;
}
/**
* Filter the returned comment count for a post.
*
* @since 1.5.0
*
* @param int $count Number of comments a post has.
* @param int $post_id Post ID.
*/
return apply_filters( 'get_comments_number', $count, $post_id );
}
/**
* Display the language string for the number of comments the current post has.
*
* @since 0.71
*
* @param string $zero Optional. Text for no comments. Default false.
* @param string $one Optional. Text for one comment. Default false.
* @param string $more Optional. Text for more than one comment. Default false.
* @param string $deprecated Not used.
*/
function comments_number( $zero = false, $one = false, $more = false, $deprecated = '' ) {
if ( ! empty( $deprecated ) ) {
_deprecated_argument( __FUNCTION__, '1.3' );
}
echo get_comments_number_text( $zero, $one, $more );
}
/**
* Display the language string for the number of comments the current post has.
*
* @since 4.0.0
*
* @param string $zero Optional. Text for no comments. Default false.
* @param string $one Optional. Text for one comment. Default false.
* @param string $more Optional. Text for more than one comment. Default false.
*/
function get_comments_number_text( $zero = false, $one = false, $more = false ) {
$number = get_comments_number();
if ( $number > 1 ) {
if ( false === $more ) {
/* translators: %s: number of comments */
$output = sprintf( _n( '%s Comment', '%s Comments', $number ), number_format_i18n( $number ) );
} else {
// % Comments
$output = str_replace( '%', number_format_i18n( $number ), $more );
}
} elseif ( $number == 0 ) {
$output = ( false === $zero ) ? __( 'No Comments' ) : $zero;
} else { // must be one
$output = ( false === $one ) ? __( '1 Comment' ) : $one;
}
/**
* Filter the comments count for display.
*
* @since 1.5.0
*
* @see _n()
*
* @param string $output A translatable string formatted based on whether the count
* is equal to 0, 1, or 1+.
* @param int $number The number of post comments.
*/
return apply_filters( 'comments_number', $output, $number );
}
/**
* Retrieve the text of the current comment.
*
* @since 1.5.0
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @see Walker_Comment::comment()
*
* @param int|WP_Comment $comment_ID WP_Comment or ID of the comment for which to get the text.
* Default current comment.
* @param array $args Optional. An array of arguments. Default empty.
* @return string The comment content.
*/
function get_comment_text( $comment_ID = 0, $args = array() ) {
$comment = get_comment( $comment_ID );
/**
* Filter the text of a comment.
*
* @since 1.5.0
*
* @see Walker_Comment::comment()
*
* @param string $comment_content Text of the comment.
* @param WP_Comment $comment The comment object.
* @param array $args An array of arguments.
*/
return apply_filters( 'get_comment_text', $comment->comment_content, $comment, $args );
}
/**
* Display the text of the current comment.
*
* @since 0.71
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @see Walker_Comment::comment()
*
* @param int|WP_Comment $comment_ID WP_Comment or ID of the comment for which to print the text.
* Default current comment.
* @param array $args Optional. An array of arguments. Default empty array. Default empty.
*/
function comment_text( $comment_ID = 0, $args = array() ) {
$comment = get_comment( $comment_ID );
$comment_text = get_comment_text( $comment, $args );
/**
* Filter the text of a comment to be displayed.
*
* @since 1.2.0
*
* @see Walker_Comment::comment()
*
* @param string $comment_text Text of the current comment.
* @param WP_Comment $comment The comment object.
* @param array $args An array of arguments.
*/
echo apply_filters( 'comment_text', $comment_text, $comment, $args );
}
/**
* Retrieve the comment time of the current comment.
*
* @since 1.5.0
*
* @param string $d Optional. The format of the time. Default user's settings.
* @param bool $gmt Optional. Whether to use the GMT date. Default false.
* @param bool $translate Optional. Whether to translate the time (for use in feeds).
* Default true.
* @return string The formatted time.
*/
function get_comment_time( $d = '', $gmt = false, $translate = true ) {
$comment = get_comment();
$comment_date = $gmt ? $comment->comment_date_gmt : $comment->comment_date;
if ( '' == $d )
$date = mysql2date(get_option('time_format'), $comment_date, $translate);
else
$date = mysql2date($d, $comment_date, $translate);
/**
* Filter the returned comment time.
*
* @since 1.5.0
*
* @param string|int $date The comment time, formatted as a date string or Unix timestamp.
* @param string $d Date format.
* @param bool $gmt Whether the GMT date is in use.
* @param bool $translate Whether the time is translated.
* @param WP_Comment $comment The comment object.
*/
return apply_filters( 'get_comment_time', $date, $d, $gmt, $translate, $comment );
}
/**
* Display the comment time of the current comment.
*
* @since 0.71
*
* @param string $d Optional. The format of the time. Default user's settings.
*/
function comment_time( $d = '' ) {
echo get_comment_time($d);
}
/**
* Retrieve the comment type of the current comment.
*
* @since 1.5.0
* @since 4.4.0 Added the ability for `$comment_ID` to also accept a WP_Comment object.
*
* @param int|WP_Comment $comment_ID Optional. WP_Comment or ID of the comment for which to get the type.
* Default current comment.
* @return string The comment type.
*/
function get_comment_type( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
if ( '' == $comment->comment_type )
$comment->comment_type = 'comment';
/**
* Filter the returned comment type.
*
* @since 1.5.0
* @since 4.1.0 The `$comment_ID` and `$comment` parameters were added.
*
* @param string $comment_type The type of comment, such as 'comment', 'pingback', or 'trackback'.
* @param int $comment_ID The comment ID.
* @param WP_Comment $comment The comment object.
*/
return apply_filters( 'get_comment_type', $comment->comment_type, $comment->comment_ID, $comment );
}
/**
* Display the comment type of the current comment.
*
* @since 0.71
*
* @param string $commenttxt Optional. String to display for comment type. Default false.
* @param string $trackbacktxt Optional. String to display for trackback type. Default false.
* @param string $pingbacktxt Optional. String to display for pingback type. Default false.
*/
function comment_type( $commenttxt = false, $trackbacktxt = false, $pingbacktxt = false ) {
if ( false === $commenttxt ) $commenttxt = _x( 'Comment', 'noun' );
if ( false === $trackbacktxt ) $trackbacktxt = __( 'Trackback' );
if ( false === $pingbacktxt ) $pingbacktxt = __( 'Pingback' );
$type = get_comment_type();
switch( $type ) {
case 'trackback' :
echo $trackbacktxt;
break;
case 'pingback' :
echo $pingbacktxt;
break;
default :
echo $commenttxt;
}
}
/**
* Retrieve The current post's trackback URL.
*
* There is a check to see if permalink's have been enabled and if so, will
* retrieve the pretty path. If permalinks weren't enabled, the ID of the
* current post is used and appended to the correct page to go to.
*
* @since 1.5.0
*
* @return string The trackback URL after being filtered.
*/
function get_trackback_url() {
if ( '' != get_option('permalink_structure') )
$tb_url = trailingslashit(get_permalink()) . user_trailingslashit('trackback', 'single_trackback');
else
$tb_url = get_option('siteurl') . '/wp-trackback.php?p=' . get_the_ID();
/**
* Filter the returned trackback URL.
*
* @since 2.2.0
*
* @param string $tb_url The trackback URL.
*/
return apply_filters( 'trackback_url', $tb_url );
}
/**
* Display the current post's trackback URL.
*
* @since 0.71
*
* @param bool $deprecated_echo Not used.
* @return void|string Should only be used to echo the trackback URL, use get_trackback_url()
* for the result instead.
*/
function trackback_url( $deprecated_echo = true ) {
if ( true !== $deprecated_echo ) {
_deprecated_argument( __FUNCTION__, '2.5',
/* translators: %s: get_trackback_url() */
sprintf( __( 'Use %s instead if you do not want the value echoed.' ),
'<code>get_trackback_url()</code>'
)
);
}
if ( $deprecated_echo ) {
echo get_trackback_url();
} else {
return get_trackback_url();
}
}
/**
* Generate and display the RDF for the trackback information of current post.
*
* Deprecated in 3.0.0, and restored in 3.0.1.
*
* @since 0.71
*
* @param int $deprecated Not used (Was $timezone = 0).
*/
function trackback_rdf( $deprecated = '' ) {
if ( ! empty( $deprecated ) ) {
_deprecated_argument( __FUNCTION__, '2.5' );
}
if ( isset( $_SERVER['HTTP_USER_AGENT'] ) && false !== stripos( $_SERVER['HTTP_USER_AGENT'], 'W3C_Validator' ) ) {
return;
}
echo '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
<rdf:Description rdf:about="';
the_permalink();
echo '"'."\n";
echo ' dc:identifier="';
the_permalink();
echo '"'."\n";
echo ' dc:title="'.str_replace('--', '--', wptexturize(strip_tags(get_the_title()))).'"'."\n";
echo ' trackback:ping="'.get_trackback_url().'"'." />\n";
echo '</rdf:RDF>';
}
/**
* Whether the current post is open for comments.
*
* @since 1.5.0
*
* @param int|WP_Post $post_id Post ID or WP_Post object. Default current post.
* @return bool True if the comments are open.
*/
function comments_open( $post_id = null ) {
$_post = get_post($post_id);
$open = ( 'open' == $_post->comment_status );
/**
* Filter whether the current post is open for comments.
*
* @since 2.5.0
*
* @param bool $open Whether the current post is open for comments.
* @param int|WP_Post $post_id The post ID or WP_Post object.
*/
return apply_filters( 'comments_open', $open, $post_id );
}
/**
* Whether the current post is open for pings.
*
* @since 1.5.0
*
* @param int|WP_Post $post_id Post ID or WP_Post object. Default current post.
* @return bool True if pings are accepted
*/
function pings_open( $post_id = null ) {
$_post = get_post($post_id);
$open = ( 'open' == $_post->ping_status );
/**
* Filter whether the current post is open for pings.
*
* @since 2.5.0
*
* @param bool $open Whether the current post is open for pings.
* @param int|WP_Post $post_id The post ID or WP_Post object.
*/
return apply_filters( 'pings_open', $open, $post_id );
}
/**
* Display form token for unfiltered comments.
*
* Will only display nonce token if the current user has permissions for
* unfiltered html. Won't display the token for other users.
*
* The function was backported to 2.0.10 and was added to versions 2.1.3 and
* above. Does not exist in versions prior to 2.0.10 in the 2.0 branch and in
* the 2.1 branch, prior to 2.1.3. Technically added in 2.2.0.
*
* Backported to 2.0.10.
*
* @since 2.1.3
*/
function wp_comment_form_unfiltered_html_nonce() {
$post = get_post();
$post_id = $post ? $post->ID : 0;
if ( current_user_can( 'unfiltered_html' ) ) {
wp_nonce_field( 'unfiltered-html-comment_' . $post_id, '_wp_unfiltered_html_comment_disabled', false );
echo "<script>(function(){if(window===window.parent){document.getElementById('_wp_unfiltered_html_comment_disabled').name='_wp_unfiltered_html_comment';}})();</script>\n";
}
}
/**
* Load the comment template specified in $file.
*
* Will not display the comments template if not on single post or page, or if
* the post does not have comments.
*
* Uses the WordPress database object to query for the comments. The comments
* are passed through the 'comments_array' filter hook with the list of comments
* and the post ID respectively.
*
* The $file path is passed through a filter hook called, 'comments_template'
* which includes the TEMPLATEPATH and $file combined. Tries the $filtered path
* first and if it fails it will require the default comment template from the
* default theme. If either does not exist, then the WordPress process will be
* halted. It is advised for that reason, that the default theme is not deleted.
*
* @uses $withcomments Will not try to get the comments if the post has none.
*
* @since 1.5.0
*
* @global WP_Query $wp_query
* @global WP_Post $post
* @global wpdb $wpdb
* @global int $id
* @global WP_Comment $comment
* @global string $user_login
* @global int $user_ID
* @global string $user_identity
* @global bool $overridden_cpage
*
* @param string $file Optional. The file to load. Default '/comments.php'.
* @param bool $separate_comments Optional. Whether to separate the comments by comment type.
* Default false.
*/
function comments_template( $file = '/comments.php', $separate_comments = false ) {
global $wp_query, $withcomments, $post, $wpdb, $id, $comment, $user_login, $user_ID, $user_identity, $overridden_cpage;
if ( !(is_single() || is_page() || $withcomments) || empty($post) )
return;
if ( empty($file) )
$file = '/comments.php';
$req = get_option('require_name_email');
/*
* Comment author information fetched from the comment cookies.
*/
$commenter = wp_get_current_commenter();
/*
* The name of the current comment author escaped for use in attributes.
* Escaped by sanitize_comment_cookies().
*/
$comment_author = $commenter['comment_author'];
/*
* The email address of the current comment author escaped for use in attributes.
* Escaped by sanitize_comment_cookies().
*/
$comment_author_email = $commenter['comment_author_email'];
/*
* The url of the current comment author escaped for use in attributes.
*/
$comment_author_url = esc_url($commenter['comment_author_url']);
$comment_args = array(
'orderby' => 'comment_date_gmt',
'order' => 'ASC',
'status' => 'approve',
'post_id' => $post->ID,
'hierarchical' => 'threaded',
'no_found_rows' => false,
'update_comment_meta_cache' => false, // We lazy-load comment meta for performance.
);
if ( $user_ID ) {
$comment_args['include_unapproved'] = array( $user_ID );
} elseif ( ! empty( $comment_author_email ) ) {
$comment_args['include_unapproved'] = array( $comment_author_email );
}
$per_page = 0;
if ( get_option( 'page_comments' ) ) {
$per_page = (int) get_query_var( 'comments_per_page' );
if ( 0 === $per_page ) {
$per_page = (int) get_option( 'comments_per_page' );
}
$comment_args['number'] = $per_page;
$page = (int) get_query_var( 'cpage' );
if ( $page ) {
$comment_args['offset'] = ( $page - 1 ) * $per_page;
} elseif ( 'oldest' === get_option( 'default_comments_page' ) ) {
$comment_args['offset'] = 0;
} else {
// If fetching the first page of 'newest', we need a top-level comment count.
$top_level_query = new WP_Comment_Query();
$top_level_count = $top_level_query->query( array(
'count' => true,
'orderby' => false,
'post_id' => $post->ID,
'parent' => 0,
) );
$comment_args['offset'] = ( ceil( $top_level_count / $per_page ) - 1 ) * $per_page;
}
}
$comment_query = new WP_Comment_Query( $comment_args );
$_comments = $comment_query->comments;
// Trees must be flattened before they're passed to the walker.
$comments_flat = array();
foreach ( $_comments as $_comment ) {
$comments_flat = array_merge( $comments_flat, array( $_comment ), $_comment->get_children( array(
'format' => 'flat',
'status' => $comment_args['status'],
'orderby' => $comment_args['orderby']
) ) );
}
/**
* Filter the comments array.
*
* @since 2.1.0
*
* @param array $comments Array of comments supplied to the comments template.
* @param int $post_ID Post ID.
*/
$wp_query->comments = apply_filters( 'comments_array', $comments_flat, $post->ID );
// Set up lazy-loading for comment metadata.
add_action( 'get_comment_metadata', array( $wp_query, 'lazyload_comment_meta' ), 10, 2 );
$comments = &$wp_query->comments;
$wp_query->comment_count = count($wp_query->comments);
$wp_query->max_num_comment_pages = $comment_query->max_num_pages;
if ( $separate_comments ) {
$wp_query->comments_by_type = separate_comments($comments);
$comments_by_type = &$wp_query->comments_by_type;
} else {
$wp_query->comments_by_type = array();
}
$overridden_cpage = false;
if ( '' == get_query_var( 'cpage' ) && $wp_query->max_num_comment_pages > 1 ) {
set_query_var( 'cpage', 'newest' == get_option('default_comments_page') ? get_comment_pages_count() : 1 );
$overridden_cpage = true;
}
if ( !defined('COMMENTS_TEMPLATE') )
define('COMMENTS_TEMPLATE', true);
$theme_template = STYLESHEETPATH . $file;
/**
* Filter the path to the theme template file used for the comments template.
*
* @since 1.5.1
*
* @param string $theme_template The path to the theme template file.
*/
$include = apply_filters( 'comments_template', $theme_template );
if ( file_exists( $include ) )
require( $include );
elseif ( file_exists( TEMPLATEPATH . $file ) )
require( TEMPLATEPATH . $file );
else // Backward compat code will be removed in a future release
require( ABSPATH . WPINC . '/theme-compat/comments.php');
}
/**
* Display the JS popup script to show a comment.
*
* If the $file parameter is empty, then the home page is assumed. The defaults
* for the window are 400px by 400px.
*
* For the comment link popup to work, this function has to be called or the
* normal comment link will be assumed.
*
* @global string $wpcommentspopupfile The URL to use for the popup window.
* @global int $wpcommentsjavascript Whether to use JavaScript. Set when function is called.
*
* @since 0.71
*
* @param int $width Optional. The width of the popup window. Default 400.
* @param int $height Optional. The height of the popup window. Default 400.
* @param string $file Optional. Sets the location of the popup window.
*/
function comments_popup_script( $width = 400, $height = 400, $file = '' ) {
global $wpcommentspopupfile, $wpcommentsjavascript;
if (empty ($file)) {
$wpcommentspopupfile = ''; // Use the index.
} else {
$wpcommentspopupfile = $file;
}
$wpcommentsjavascript = 1;
$javascript = "<script type='text/javascript'>\nfunction wpopen (macagna) {\n window.open(macagna, '_blank', 'width=$width,height=$height,scrollbars=yes,status=yes');\n}\n</script>\n";
echo $javascript;
}
/**
* Displays the link to the comments popup window for the current post ID.
*
* Is not meant to be displayed on single posts and pages. Should be used
* on the lists of posts
*
* @global string $wpcommentspopupfile The URL to use for the popup window.
* @global int $wpcommentsjavascript Whether to use JavaScript. Set when function is called.
*
* @since 0.71
*
* @param string $zero Optional. String to display when no comments. Default false.
* @param string $one Optional. String to display when only one comment is available.
* Default false.
* @param string $more Optional. String to display when there are more than one comment.
* Default false.
* @param string $css_class Optional. CSS class to use for comments. Default empty.
* @param string $none Optional. String to display when comments have been turned off.
* Default false.
*/
function comments_popup_link( $zero = false, $one = false, $more = false, $css_class = '', $none = false ) {
global $wpcommentspopupfile, $wpcommentsjavascript;
$id = get_the_ID();
$title = get_the_title();
$number = get_comments_number( $id );
if ( false === $zero ) {
/* translators: %s: post title */
$zero = sprintf( __( 'No Comments<span class="screen-reader-text"> on %s</span>' ), $title );
}
if ( false === $one ) {
/* translators: %s: post title */
$one = sprintf( __( '1 Comment<span class="screen-reader-text"> on %s</span>' ), $title );
}
if ( false === $more ) {
/* translators: 1: Number of comments 2: post title */
$more = _n( '%1$s Comment<span class="screen-reader-text"> on %2$s</span>', '%1$s Comments<span class="screen-reader-text"> on %2$s</span>', $number );
$more = sprintf( $more, number_format_i18n( $number ), $title );
}
if ( false === $none ) {
/* translators: %s: post title */
$none = sprintf( __( 'Comments Off<span class="screen-reader-text"> on %s</span>' ), $title );
}
if ( 0 == $number && !comments_open() && !pings_open() ) {
echo '<span' . ((!empty($css_class)) ? ' class="' . esc_attr( $css_class ) . '"' : '') . '>' . $none . '</span>';
return;
}
if ( post_password_required() ) {
_e( 'Enter your password to view comments.' );
return;
}
echo '<a href="';
if ( $wpcommentsjavascript ) {
if ( empty( $wpcommentspopupfile ) )
$home = home_url();
else
$home = get_option('siteurl');
echo $home . '/' . $wpcommentspopupfile . '?comments_popup=' . $id;
echo '" onclick="wpopen(this.href); return false"';
} else {
// if comments_popup_script() is not in the template, display simple comment link
if ( 0 == $number ) {
$respond_link = get_permalink() . '#respond';
/**
* Filter the respond link when a post has no comments.
*
* @since 4.4.0
*
* @param string $respond_link The default response link.
* @param integer $id The post ID.
*/
echo apply_filters( 'respond_link', $respond_link, $id );
} else {
comments_link();
}
echo '"';
}
if ( !empty( $css_class ) ) {
echo ' class="'.$css_class.'" ';
}
$attributes = '';
/**
* Filter the comments popup link attributes for display.
*
* @since 2.5.0
*
* @param string $attributes The comments popup link attributes. Default empty.
*/
echo apply_filters( 'comments_popup_link_attributes', $attributes );
echo '>';
comments_number( $zero, $one, $more );
echo '</a>';
}
/**
* Retrieve HTML content for reply to comment link.
*
* @since 2.7.0
* @since 4.4.0 Added the ability for `$comment` to also accept a WP_Comment object.
*
* @param array $args {
* Optional. Override default arguments.
*
* @type string $add_below The first part of the selector used to identify the comment to respond below.
* The resulting value is passed as the first parameter to addComment.moveForm(),
* concatenated as $add_below-$comment->comment_ID. Default 'comment'.
* @type string $respond_id The selector identifying the responding comment. Passed as the third parameter
* to addComment.moveForm(), and appended to the link URL as a hash value.
* Default 'respond'.
* @type string $reply_text The text of the Reply link. Default 'Reply'.
* @type string $login_text The text of the link to reply if logged out. Default 'Log in to Reply'.
* @type int $depth' The depth of the new comment. Must be greater than 0 and less than the value
* of the 'thread_comments_depth' option set in Settings > Discussion. Default 0.
* @type string $before The text or HTML to add before the reply link. Default empty.
* @type string $after The text or HTML to add after the reply link. Default empty.
* }
* @param int|WP_Comment $comment Comment being replied to. Default current comment.
* @param int|WP_Post $post Post ID or WP_Post object the comment is going to be displayed on.
* Default current post.
* @return void|false|string Link to show comment form, if successful. False, if comments are closed.
*/
function get_comment_reply_link( $args = array(), $comment = null, $post = null ) {
$defaults = array(
'add_below' => 'comment',
'respond_id' => 'respond',
'reply_text' => __( 'Reply' ),
'reply_to_text' => __( 'Reply to %s' ),
'login_text' => __( 'Log in to Reply' ),
'depth' => 0,
'before' => '',
'after' => ''
);
$args = wp_parse_args( $args, $defaults );
if ( 0 == $args['depth'] || $args['max_depth'] <= $args['depth'] ) {
return;
}
$comment = get_comment( $comment );
if ( empty( $post ) ) {
$post = $comment->comment_post_ID;
}
$post = get_post( $post );
if ( ! comments_open( $post->ID ) ) {
return false;
}
/**
* Filter the comment reply link arguments.
*
* @since 4.1.0
*
* @param array $args Comment reply link arguments. See get_comment_reply_link()
* for more information on accepted arguments.
* @param WP_Comment $comment The object of the comment being replied to.
* @param WP_Post $post The WP_Post object.
*/
$args = apply_filters( 'comment_reply_link_args', $args, $comment, $post );
if ( get_option( 'comment_registration' ) && ! is_user_logged_in() ) {
$link = sprintf( '<a rel="nofollow" class="comment-reply-login" href="%s">%s</a>',
esc_url( wp_login_url( get_permalink() ) ),
$args['login_text']
);
} else {
$onclick = sprintf( 'return addComment.moveForm( "%1$s-%2$s", "%2$s", "%3$s", "%4$s" )',
$args['add_below'], $comment->comment_ID, $args['respond_id'], $post->ID
);
$link = sprintf( "<a rel='nofollow' class='comment-reply-link' href='%s' onclick='%s' aria-label='%s'>%s</a>",
esc_url( add_query_arg( 'replytocom', $comment->comment_ID, get_permalink( $post->ID ) ) ) . "#" . $args['respond_id'],
$onclick,
esc_attr( sprintf( $args['reply_to_text'], $comment->comment_author ) ),
$args['reply_text']
);
}
/**
* Filter the comment reply link.
*
* @since 2.7.0
*
* @param string $link The HTML markup for the comment reply link.
* @param array $args An array of arguments overriding the defaults.
* @param object $comment The object of the comment being replied.
* @param WP_Post $post The WP_Post object.
*/
return apply_filters( 'comment_reply_link', $args['before'] . $link . $args['after'], $args, $comment, $post );
}
/**
* Displays the HTML content for reply to comment link.
*
* @since 2.7.0
*
* @see get_comment_reply_link()
*
* @param array $args Optional. Override default options.
* @param int $comment Comment being replied to. Default current comment.
* @param int|WP_Post $post Post ID or WP_Post object the comment is going to be displayed on.
* Default current post.
* @return mixed Link to show comment form, if successful. False, if comments are closed.
*/
function comment_reply_link($args = array(), $comment = null, $post = null) {
echo get_comment_reply_link($args, $comment, $post);
}
/**
* Retrieve HTML content for reply to post link.
*
* @since 2.7.0
*
* @param array $args {
* Optional. Override default arguments.
*
* @type string $add_below The first part of the selector used to identify the comment to respond below.
* The resulting value is passed as the first parameter to addComment.moveForm(),
* concatenated as $add_below-$comment->comment_ID. Default is 'post'.
* @type string $respond_id The selector identifying the responding comment. Passed as the third parameter
* to addComment.moveForm(), and appended to the link URL as a hash value.
* Default 'respond'.
* @type string $reply_text Text of the Reply link. Default is 'Leave a Comment'.
* @type string $login_text Text of the link to reply if logged out. Default is 'Log in to leave a Comment'.
* @type string $before Text or HTML to add before the reply link. Default empty.
* @type string $after Text or HTML to add after the reply link. Default empty.
* }
* @param int|WP_Post $post Optional. Post ID or WP_Post object the comment is going to be displayed on.
* Default current post.
* @return false|null|string Link to show comment form, if successful. False, if comments are closed.
*/
function get_post_reply_link($args = array(), $post = null) {
$defaults = array(
'add_below' => 'post',
'respond_id' => 'respond',
'reply_text' => __('Leave a Comment'),
'login_text' => __('Log in to leave a Comment'),
'before' => '',
'after' => '',
);
$args = wp_parse_args($args, $defaults);
$post = get_post($post);
if ( ! comments_open( $post->ID ) ) {
return false;
}
if ( get_option('comment_registration') && ! is_user_logged_in() ) {
$link = sprintf( '<a rel="nofollow" class="comment-reply-login" href="%s">%s</a>',
wp_login_url( get_permalink() ),
$args['login_text']
);
} else {
$onclick = sprintf( 'return addComment.moveForm( "%1$s-%2$s", "0", "%3$s", "%2$s" )',
$args['add_below'], $post->ID, $args['respond_id']
);
$link = sprintf( "<a rel='nofollow' class='comment-reply-link' href='%s' onclick='%s'>%s</a>",
get_permalink( $post->ID ) . '#' . $args['respond_id'],
$onclick,
$args['reply_text']
);
}
$formatted_link = $args['before'] . $link . $args['after'];
/**
* Filter the formatted post comments link HTML.
*
* @since 2.7.0
*
* @param string $formatted The HTML-formatted post comments link.
* @param int|WP_Post $post The post ID or WP_Post object.
*/
return apply_filters( 'post_comments_link', $formatted_link, $post );
}
/**
* Displays the HTML content for reply to post link.
*
* @since 2.7.0
*
* @see get_post_reply_link()
*
* @param array $args Optional. Override default options,
* @param int|WP_Post $post Post ID or WP_Post object the comment is going to be displayed on.
* Default current post.
* @return string|bool|null Link to show comment form, if successful. False, if comments are closed.
*/
function post_reply_link($args = array(), $post = null) {
echo get_post_reply_link($args, $post);
}
/**
* Retrieve HTML content for cancel comment reply link.
*
* @since 2.7.0
*
* @param string $text Optional. Text to display for cancel reply link. Default empty.
* @return string
*/
function get_cancel_comment_reply_link( $text = '' ) {
if ( empty($text) )
$text = __('Click here to cancel reply.');
$style = isset($_GET['replytocom']) ? '' : ' style="display:none;"';
$link = esc_html( remove_query_arg('replytocom') ) . '#respond';
$formatted_link = '<a rel="nofollow" id="cancel-comment-reply-link" href="' . $link . '"' . $style . '>' . $text . '</a>';
/**
* Filter the cancel comment reply link HTML.
*
* @since 2.7.0
*
* @param string $formatted_link The HTML-formatted cancel comment reply link.
* @param string $link Cancel comment reply link URL.
* @param string $text Cancel comment reply link text.
*/
return apply_filters( 'cancel_comment_reply_link', $formatted_link, $link, $text );
}
/**
* Display HTML content for cancel comment reply link.
*
* @since 2.7.0
*
* @param string $text Optional. Text to display for cancel reply link. Default empty.
*/
function cancel_comment_reply_link( $text = '' ) {
echo get_cancel_comment_reply_link($text);
}
/**
* Retrieve hidden input HTML for replying to comments.
*
* @since 3.0.0
*
* @param int $id Optional. Post ID. Default current post ID.
* @return string Hidden input HTML for replying to comments
*/
function get_comment_id_fields( $id = 0 ) {
if ( empty( $id ) )
$id = get_the_ID();
$replytoid = isset($_GET['replytocom']) ? (int) $_GET['replytocom'] : 0;
$result = "<input type='hidden' name='comment_post_ID' value='$id' id='comment_post_ID' />\n";
$result .= "<input type='hidden' name='comment_parent' id='comment_parent' value='$replytoid' />\n";
/**
* Filter the returned comment id fields.
*
* @since 3.0.0
*
* @param string $result The HTML-formatted hidden id field comment elements.
* @param int $id The post ID.
* @param int $replytoid The id of the comment being replied to.
*/
return apply_filters( 'comment_id_fields', $result, $id, $replytoid );
}
/**
* Output hidden input HTML for replying to comments.
*
* @since 2.7.0
*
* @param int $id Optional. Post ID. Default current post ID.
*/
function comment_id_fields( $id = 0 ) {
echo get_comment_id_fields( $id );
}
/**
* Display text based on comment reply status.
*
* Only affects users with JavaScript disabled.
*
* @since 2.7.0
*
* @param string $noreplytext Optional. Text to display when not replying to a comment.
* Default false.
* @param string $replytext Optional. Text to display when replying to a comment.
* Default false. Accepts "%s" for the author of the comment
* being replied to.
* @param string $linktoparent Optional. Boolean to control making the author's name a link
* to their comment. Default true.
*/
function comment_form_title( $noreplytext = false, $replytext = false, $linktoparent = true ) {
$comment = get_comment();
if ( false === $noreplytext ) $noreplytext = __( 'Leave a Reply' );
if ( false === $replytext ) $replytext = __( 'Leave a Reply to %s' );
$replytoid = isset($_GET['replytocom']) ? (int) $_GET['replytocom'] : 0;
if ( 0 == $replytoid )
echo $noreplytext;
else {
$comment = get_comment($replytoid);
$author = ( $linktoparent ) ? '<a href="#comment-' . get_comment_ID() . '">' . get_comment_author( $comment ) . '</a>' : get_comment_author( $comment );
printf( $replytext, $author );
}
}
/**
* List comments.
*
* Used in the comments.php template to list comments for a particular post.
*
* @since 2.7.0
*
* @see WP_Query->comments
*
* @global WP_Query $wp_query
* @global int $comment_alt
* @global int $comment_depth
* @global int $comment_thread_alt
* @global bool $overridden_cpage
* @global bool $in_comment_loop
*
* @param string|array $args {
* Optional. Formatting options.
*
* @type object $walker Instance of a Walker class to list comments. Default null.
* @type int $max_depth The maximum comments depth. Default empty.
* @type string $style The style of list ordering. Default 'ul'. Accepts 'ul', 'ol'.
* @type string $callback Callback function to use. Default null.
* @type string $end-callback Callback function to use at the end. Default null.
* @type string $type Type of comments to list.
* Default 'all'. Accepts 'all', 'comment', 'pingback', 'trackback', 'pings'.
* @type int $page Page ID to list comments for. Default empty.
* @type int $per_page Number of comments to list per page. Default empty.
* @type int $avatar_size Height and width dimensions of the avatar size. Default 32.
* @type string $reverse_top_level Ordering of the listed comments. Default null. Accepts 'desc', 'asc'.
* @type bool $reverse_children Whether to reverse child comments in the list. Default null.
* @type string $format How to format the comments list.
* Default 'html5' if the theme supports it. Accepts 'html5', 'xhtml'.
* @type bool $short_ping Whether to output short pings. Default false.
* @type bool $echo Whether to echo the output or return it. Default true.
* }
* @param array $comments Optional. Array of WP_Comment objects.
*/
function wp_list_comments( $args = array(), $comments = null ) {
global $wp_query, $comment_alt, $comment_depth, $comment_thread_alt, $overridden_cpage, $in_comment_loop;
$in_comment_loop = true;
$comment_alt = $comment_thread_alt = 0;
$comment_depth = 1;
$defaults = array(
'walker' => null,
'max_depth' => '',
'style' => 'ul',
'callback' => null,
'end-callback' => null,
'type' => 'all',
'page' => '',
'per_page' => '',
'avatar_size' => 32,
'reverse_top_level' => null,
'reverse_children' => '',
'format' => current_theme_supports( 'html5', 'comment-list' ) ? 'html5' : 'xhtml',
'short_ping' => false,
'echo' => true,
);
$r = wp_parse_args( $args, $defaults );
/**
* Filter the arguments used in retrieving the comment list.
*
* @since 4.0.0
*
* @see wp_list_comments()
*
* @param array $r An array of arguments for displaying comments.
*/
$r = apply_filters( 'wp_list_comments_args', $r );
// Figure out what comments we'll be looping through ($_comments)
if ( null !== $comments ) {
$comments = (array) $comments;
if ( empty($comments) )
return;
if ( 'all' != $r['type'] ) {
$comments_by_type = separate_comments($comments);
if ( empty($comments_by_type[$r['type']]) )
return;
$_comments = $comments_by_type[$r['type']];
} else {
$_comments = $comments;
}
} else {
if ( empty($wp_query->comments) )
return;
if ( 'all' != $r['type'] ) {
if ( empty($wp_query->comments_by_type) )
$wp_query->comments_by_type = separate_comments($wp_query->comments);
if ( empty($wp_query->comments_by_type[$r['type']]) )
return;
$_comments = $wp_query->comments_by_type[$r['type']];
} else {
$_comments = $wp_query->comments;
}
// Pagination is already handled by `WP_Comment_Query`, so we tell Walker not to bother.
if ( $wp_query->max_num_comment_pages ) {
$default_comments_page = get_option( 'default_comments_page' );
$cpage = get_query_var( 'cpage' );
if ( 'newest' === $default_comments_page ) {
$r['cpage'] = $cpage;
// When first page shows oldest comments, post permalink is the same as the comment permalink.
} elseif ( $cpage == 1 ) {
$r['cpage'] = '';
} else {
$r['cpage'] = $cpage;
}
$r['page'] = 0;
$r['per_page'] = 0;
}
}
if ( '' === $r['per_page'] && get_option( 'page_comments' ) ) {
$r['per_page'] = get_query_var('comments_per_page');
}
if ( empty($r['per_page']) ) {
$r['per_page'] = 0;
$r['page'] = 0;
}
if ( '' === $r['max_depth'] ) {
if ( get_option('thread_comments') )
$r['max_depth'] = get_option('thread_comments_depth');
else
$r['max_depth'] = -1;
}
if ( '' === $r['page'] ) {
if ( empty($overridden_cpage) ) {
$r['page'] = get_query_var('cpage');
} else {
$threaded = ( -1 != $r['max_depth'] );
$r['page'] = ( 'newest' == get_option('default_comments_page') ) ? get_comment_pages_count($_comments, $r['per_page'], $threaded) : 1;
set_query_var( 'cpage', $r['page'] );
}
}
// Validation check
$r['page'] = intval($r['page']);
if ( 0 == $r['page'] && 0 != $r['per_page'] )
$r['page'] = 1;
if ( null === $r['reverse_top_level'] )
$r['reverse_top_level'] = ( 'desc' == get_option('comment_order') );
if ( empty( $r['walker'] ) ) {
$walker = new Walker_Comment;
} else {
$walker = $r['walker'];
}
$output = $walker->paged_walk( $_comments, $r['max_depth'], $r['page'], $r['per_page'], $r );
$in_comment_loop = false;
if ( $r['echo'] ) {
echo $output;
} else {
return $output;
}
}
/**
* Output a complete commenting form for use within a template.
*
* Most strings and form fields may be controlled through the $args array passed
* into the function, while you may also choose to use the comment_form_default_fields
* filter to modify the array of default fields if you'd just like to add a new
* one or remove a single field. All fields are also individually passed through
* a filter of the form comment_form_field_$name where $name is the key used
* in the array of fields.
*
* @since 3.0.0
* @since 4.1.0 Introduced the 'class_submit' argument.
* @since 4.2.0 Introduced the 'submit_button' and 'submit_fields' arguments.
* @since 4.4.0 Introduced the 'class_form', 'title_reply_before', 'title_reply_after',
* 'cancel_reply_before', and 'cancel_reply_after' arguments.
*
* @param array $args {
* Optional. Default arguments and form fields to override.
*
* @type array $fields {
* Default comment fields, filterable by default via the 'comment_form_default_fields' hook.
*
* @type string $author Comment author field HTML.
* @type string $email Comment author email field HTML.
* @type string $url Comment author URL field HTML.
* }
* @type string $comment_field The comment textarea field HTML.
* @type string $must_log_in HTML element for a 'must be logged in to comment' message.
* @type string $logged_in_as HTML element for a 'logged in as [user]' message.
* @type string $comment_notes_before HTML element for a message displayed before the comment fields
* if the user is not logged in.
* Default 'Your email address will not be published.'.
* @type string $comment_notes_after HTML element for a message displayed after the textarea field.
* @type string $id_form The comment form element id attribute. Default 'commentform'.
* @type string $id_submit The comment submit element id attribute. Default 'submit'.
* @type string $class_form The comment form element class attribute. Default 'comment-form'.
* @type string $class_submit The comment submit element class attribute. Default 'submit'.
* @type string $name_submit The comment submit element name attribute. Default 'submit'.
* @type string $title_reply The translatable 'reply' button label. Default 'Leave a Reply'.
* @type string $title_reply_to The translatable 'reply-to' button label. Default 'Leave a Reply to %s',
* where %s is the author of the comment being replied to.
* @type string $title_reply_before HTML displayed before the comment form title.
* Default: '<h3 id="reply-title" class="comment-reply-title">'.
* @type string $title_reply_after HTML displayed after the comment form title.
* Default: '</h3>'.
* @type string $cancel_reply_before HTML displayed before the cancel reply link.
* @type string $cancel_reply_after HTML displayed after the cancel reply link.
* @type string $cancel_reply_link The translatable 'cancel reply' button label. Default 'Cancel reply'.
* @type string $label_submit The translatable 'submit' button label. Default 'Post a comment'.
* @type string $submit_button HTML format for the Submit button.
* Default: '<input name="%1$s" type="submit" id="%2$s" class="%3$s" value="%4$s" />'.
* @type string $submit_field HTML format for the markup surrounding the Submit button and comment hidden
* fields. Default: '<p class="form-submit">%1$s %2$s</a>', where %1$s is the
* submit button markup and %2$s is the comment hidden fields.
* @type string $format The comment form format. Default 'xhtml'. Accepts 'xhtml', 'html5'.
* }
* @param int|WP_Post $post_id Post ID or WP_Post object to generate the form for. Default current post.
*/
function comment_form( $args = array(), $post_id = null ) {
if ( null === $post_id )
$post_id = get_the_ID();
$commenter = wp_get_current_commenter();
$user = wp_get_current_user();
$user_identity = $user->exists() ? $user->display_name : '';
$args = wp_parse_args( $args );
if ( ! isset( $args['format'] ) )
$args['format'] = current_theme_supports( 'html5', 'comment-form' ) ? 'html5' : 'xhtml';
$req = get_option( 'require_name_email' );
$aria_req = ( $req ? " aria-required='true'" : '' );
$html_req = ( $req ? " required='required'" : '' );
$html5 = 'html5' === $args['format'];
$fields = array(
'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Name' ) . ( $req ? ' <span class="required">*</span>' : '' ) . '</label> ' .
'<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . $html_req . ' /></p>',
'email' => '<p class="comment-form-email"><label for="email">' . __( 'Email' ) . ( $req ? ' <span class="required">*</span>' : '' ) . '</label> ' .
'<input id="email" name="email" ' . ( $html5 ? 'type="email"' : 'type="text"' ) . ' value="' . esc_attr( $commenter['comment_author_email'] ) . '" size="30" aria-describedby="email-notes"' . $aria_req . $html_req . ' /></p>',
'url' => '<p class="comment-form-url"><label for="url">' . __( 'Website' ) . '</label> ' .
'<input id="url" name="url" ' . ( $html5 ? 'type="url"' : 'type="text"' ) . ' value="' . esc_attr( $commenter['comment_author_url'] ) . '" size="30" /></p>',
);
$required_text = sprintf( ' ' . __('Required fields are marked %s'), '<span class="required">*</span>' );
/**
* Filter the default comment form fields.
*
* @since 3.0.0
*
* @param array $fields The default comment fields.
*/
$fields = apply_filters( 'comment_form_default_fields', $fields );
$defaults = array(
'fields' => $fields,
'comment_field' => '<p class="comment-form-comment"><label for="comment">' . _x( 'Comment', 'noun' ) . '</label> <textarea id="comment" name="comment" cols="45" rows="8" aria-required="true" required="required"></textarea></p>',
/** This filter is documented in wp-includes/link-template.php */
'must_log_in' => '<p class="must-log-in">' . sprintf( __( 'You must be <a href="%s">logged in</a> to post a comment.' ), wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
/** This filter is documented in wp-includes/link-template.php */
'logged_in_as' => '<p class="logged-in-as">' . sprintf( __( '<a href="%1$s" aria-label="Logged in as %2$s. Edit your profile.">Logged in as %2$s</a>. <a href="%3$s">Log out?</a>' ), get_edit_user_link(), $user_identity, wp_logout_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
'comment_notes_before' => '<p class="comment-notes"><span id="email-notes">' . __( 'Your email address will not be published.' ) . '</span>'. ( $req ? $required_text : '' ) . '</p>',
'comment_notes_after' => '',
'id_form' => 'commentform',
'id_submit' => 'submit',
'class_form' => 'comment-form',
'class_submit' => 'submit',
'name_submit' => 'submit',
'title_reply' => __( 'Leave a Reply' ),
'title_reply_to' => __( 'Leave a Reply to %s' ),
'title_reply_before' => '<h3 id="reply-title" class="comment-reply-title">',
'title_reply_after' => '</h3>',
'cancel_reply_before' => ' <small>',
'cancel_reply_after' => '</small>',
'cancel_reply_link' => __( 'Cancel reply' ),
'label_submit' => __( 'Post Comment' ),
'submit_button' => '<input name="%1$s" type="submit" id="%2$s" class="%3$s" value="%4$s" />',
'submit_field' => '<p class="form-submit">%1$s %2$s</p>',
'format' => 'xhtml',
);
/**
* Filter the comment form default arguments.
*
* Use 'comment_form_default_fields' to filter the comment fields.
*
* @since 3.0.0
*
* @param array $defaults The default comment form arguments.
*/
$args = wp_parse_args( $args, apply_filters( 'comment_form_defaults', $defaults ) );
// Ensure that the filtered args contain all required default values.
$args = array_merge( $defaults, $args );
if ( comments_open( $post_id ) ) : ?>
<?php
/**
* Fires before the comment form.
*
* @since 3.0.0
*/
do_action( 'comment_form_before' );
?>
<div id="respond" class="comment-respond">
<?php
echo $args['title_reply_before'];
comment_form_title( $args['title_reply'], $args['title_reply_to'] );
echo $args['cancel_reply_before'];
cancel_comment_reply_link( $args['cancel_reply_link'] );
echo $args['cancel_reply_after'];
echo $args['title_reply_after'];
if ( get_option( 'comment_registration' ) && !is_user_logged_in() ) :
echo $args['must_log_in'];
/**
* Fires after the HTML-formatted 'must log in after' message in the comment form.
*
* @since 3.0.0
*/
do_action( 'comment_form_must_log_in_after' );
else : ?>
<form action="<?php echo site_url( '/wp-comments-post.php' ); ?>" method="post" id="<?php echo esc_attr( $args['id_form'] ); ?>" class="<?php echo esc_attr( $args['class_form'] ); ?>"<?php echo $html5 ? ' novalidate' : ''; ?>>
<?php
/**
* Fires at the top of the comment form, inside the form tag.
*
* @since 3.0.0
*/
do_action( 'comment_form_top' );
if ( is_user_logged_in() ) :
/**
* Filter the 'logged in' message for the comment form for display.
*
* @since 3.0.0
*
* @param string $args_logged_in The logged-in-as HTML-formatted message.
* @param array $commenter An array containing the comment author's
* username, email, and URL.
* @param string $user_identity If the commenter is a registered user,
* the display name, blank otherwise.
*/
echo apply_filters( 'comment_form_logged_in', $args['logged_in_as'], $commenter, $user_identity );
/**
* Fires after the is_user_logged_in() check in the comment form.
*
* @since 3.0.0
*
* @param array $commenter An array containing the comment author's
* username, email, and URL.
* @param string $user_identity If the commenter is a registered user,
* the display name, blank otherwise.
*/
do_action( 'comment_form_logged_in_after', $commenter, $user_identity );
else :
echo $args['comment_notes_before'];
endif;
// Prepare an array of all fields, including the textarea
$comment_fields = array( 'comment' => $args['comment_field'] ) + (array) $args['fields'];
/**
* Filter the comment form fields.
*
* @since 4.4.0
*
* @param array $comment_fields The comment fields.
*/
$comment_fields = apply_filters( 'comment_form_fields', $comment_fields );
// Get an array of field names, excluding the textarea
$comment_field_keys = array_diff( array_keys( $comment_fields ), array( 'comment' ) );
// Get the first and the last field name, excluding the textarea
$first_field = reset( $comment_field_keys );
$last_field = end( $comment_field_keys );
foreach ( $comment_fields as $name => $field ) {
if ( 'comment' === $name ) {
/**
* Filter the content of the comment textarea field for display.
*
* @since 3.0.0
*
* @param string $args_comment_field The content of the comment textarea field.
*/
echo apply_filters( 'comment_form_field_comment', $field );
echo $args['comment_notes_after'];
} elseif ( ! is_user_logged_in() ) {
if ( $first_field === $name ) {
/**
* Fires before the comment fields in the comment form, excluding the textarea.
*
* @since 3.0.0
*/
do_action( 'comment_form_before_fields' );
}
/**
* Filter a comment form field for display.
*
* The dynamic portion of the filter hook, `$name`, refers to the name
* of the comment form field. Such as 'author', 'email', or 'url'.
*
* @since 3.0.0
*
* @param string $field The HTML-formatted output of the comment form field.
*/
echo apply_filters( "comment_form_field_{$name}", $field ) . "\n";
if ( $last_field === $name ) {
/**
* Fires after the comment fields in the comment form, excluding the textarea.
*
* @since 3.0.0
*/
do_action( 'comment_form_after_fields' );
}
}
}
$submit_button = sprintf(
$args['submit_button'],
esc_attr( $args['name_submit'] ),
esc_attr( $args['id_submit'] ),
esc_attr( $args['class_submit'] ),
esc_attr( $args['label_submit'] )
);
/**
* Filter the submit button for the comment form to display.
*
* @since 4.2.0
*
* @param string $submit_button HTML markup for the submit button.
* @param array $args Arguments passed to `comment_form()`.
*/
$submit_button = apply_filters( 'comment_form_submit_button', $submit_button, $args );
$submit_field = sprintf(
$args['submit_field'],
$submit_button,
get_comment_id_fields( $post_id )
);
/**
* Filter the submit field for the comment form to display.
*
* The submit field includes the submit button, hidden fields for the
* comment form, and any wrapper markup.
*
* @since 4.2.0
*
* @param string $submit_field HTML markup for the submit field.
* @param array $args Arguments passed to comment_form().
*/
echo apply_filters( 'comment_form_submit_field', $submit_field, $args );
/**
* Fires at the bottom of the comment form, inside the closing </form> tag.
*
* @since 1.5.0
*
* @param int $post_id The post ID.
*/
do_action( 'comment_form', $post_id );
?>
</form>
<?php endif; ?>
</div><!-- #respond -->
<?php
/**
* Fires after the comment form.
*
* @since 3.0.0
*/
do_action( 'comment_form_after' );
else :
/**
* Fires after the comment form if comments are closed.
*
* @since 3.0.0
*/
do_action( 'comment_form_comments_closed' );
endif;
}
| gpl-2.0 |
ambilight-4-mediaportal/AtmoWin | AtmoRes.cpp | 585 | #include <windows.h>
#include "AtmoRes.h"
HINSTANCE hAtmo_ResInstance;
HINSTANCE hAtmo_Instance;
char *getResStr(UINT uID,char *psz_default)
{
char *buffer = new char[1026];
char *temp;
if(hAtmo_ResInstance) {
if(LoadString(hAtmo_ResInstance,uID,buffer,sizeof(char)*1024)) {
temp = strdup(buffer);
delete []buffer;
return(temp);
}
}
if(LoadString(hAtmo_Instance,uID,buffer,sizeof(char)*1024)) {
temp = strdup(buffer);
delete []buffer;
return(temp);
}
delete []buffer;
return strdup(psz_default);
}
| gpl-2.0 |
dermatologist/openmrs-module-skinhelpdesk | api/src/test/java/org/openmrs/module/skinhelpdesk/api/SkinHelpDeskServiceTest.java | 2949 | /**
* 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/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs.module.skinhelpdesk.api;
import static org.junit.Assert.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openmrs.Patient;
import org.openmrs.User;
import org.openmrs.api.PatientService;
import org.openmrs.api.UserService;
import org.openmrs.api.context.Context;
import org.openmrs.module.skinhelpdesk.SkinHelpDesk;
import org.openmrs.module.skinhelpdesk.api.impl.SkinHelpDeskServiceImpl;
import org.openmrs.test.BaseModuleContextSensitiveTest;
import static org.mockito.Mockito.*;
/**
* Tests {@link ${${module-name-no-spaces}Service}}.
*/
public class SkinHelpDeskServiceTest extends BaseModuleContextSensitiveTest {
private SkinHelpDeskService service;
private PatientService patientService;
private SkinHelpDesk lesionmap;
private Patient patient;
@Before
public void setUp(){
service = Context.getService(SkinHelpDeskService.class);
patientService = Context.getPatientService();
patient = patientService.getPatient(2); // Dataset
try {
executeDataSet("SkinHelpDeskTestDataSet.xml");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @verifies return the lesionmap for the patient
* @see SkinHelpDeskService#getLesionmap(Patient)
*/
@Test
public void getLesionmap_shouldReturnTheLesionmapForThePatient() throws Exception {
//TODO auto-generated
lesionmap = service.getLesionmap(patient);
Assert.assertNotNull(lesionmap);
}
/**
* @verifies return saved lesionmap
* @see SkinHelpDeskService#saveLesionmap(SkinHelpDesk)
*/
@Test
public void saveLesionmap_shouldReturnSavedLesionmap() throws Exception {
//TODO auto-generated
String imagemap = "Test Map";
lesionmap = service.getLesionmap(patient);
lesionmap.setLesionMap(imagemap);
SkinHelpDesk testMap = service.saveLesionmap(lesionmap);
Assert.assertNotNull(testMap);
Assert.assertNotEquals(0,testMap.getLesionMap().length());
}
/**
* @verifies delete the lesionmap
* @see SkinHelpDeskService#purgeLesionmap(SkinHelpDesk)
*/
@Test
public void purgeLesionmap_shouldDeleteTheLesionmap() throws Exception {
//TODO auto-generated
lesionmap = service.getLesionmap(patient);
service.purgeLesionmap(lesionmap);
Assert.assertNull(service.getLesionmap(patient));
}
}
| gpl-2.0 |
Yammy/ec-cube | src/Eccube/Repository/PageLayoutRepository.php | 9101 | <?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
*
* http://www.lockon.co.jp/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
namespace Eccube\Repository;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Finder\Finder;
/**
* PageLayoutRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class PageLayoutRepository extends EntityRepository
{
public function setApp($app)
{
$this->app = $app;
}
public function get($deviceTypeId, $pageId)
{
$qb = $this->createQueryBuilder('p')
->select('p, bp, b')
->leftJoin('p.BlocPositions', 'bp', 'WITH', 'p.page_id = bp.page_id OR bp.anywhere = 1')
->innerJoin('bp.Bloc', 'b')
->andWhere('p.device_type_id = :deviceTypeId AND p.page_id = :pageId')
->addOrderBy('bp.target_id', 'ASC')
->addOrderBy('bp.bloc_row', 'ASC');
return $qb
->getQuery()
->setParameters(array(
'deviceTypeId' => $deviceTypeId,
'pageId' => $pageId,
))
->getSingleResult();
}
public function getByUrl($deviceTypeId, $url)
{
$qb = $this->createQueryBuilder('p')
->select('p, bp, b')
->leftJoin('p.BlocPositions', 'bp', 'WITH', 'p.page_id = bp.page_id OR bp.anywhere = 1')
->innerJoin('bp.Bloc', 'b')
->andWhere('p.device_type_id = :deviceTypeId AND p.url = :url')
->addOrderBy('bp.target_id', 'ASC')
->addOrderBy('bp.bloc_row', 'ASC');
return $qb
->getQuery()
->setParameters(array(
'deviceTypeId' => $deviceTypeId,
'url' => $url,
))
->getSingleResult();
}
public function getByRoutingName($deviceTypeId, $routingName)
{
$legacyUrls = array(
'preview' => 'preview',
'homepage' => 'index.php',
'product_list' => 'products/list.php',
'product_detail' => 'products/detail.php',
'mypage' => 'mypage/index.php',
'mypage_change' => 'mypage/change.php',
'mypage_change_complete' => 'mypage/change_complete.php',
'mypage_delivery' => 'mypage/delivery.php',
'mypage_favorite' => 'mypage/favorite.php',
'mypage_history' => 'mypage/history.php',
'mypage_login' => 'mypage/login.php',
'mypage_refusal' => 'mypage/refusal.php',
'mypage_refusal_complete' => 'mypage/refusal_complete.php',
'help_about' => 'abouts/index.php',
'cart' => 'cart/index.php',
'contact' => 'contact/index.php',
'contact_complete' => 'contact/complete.php',
'entry' => 'entry/index.php',
// 'entry_kiyaku' => 'entry/kiyaku.php',
'entry_complete' => 'entry/complete.php',
'help_tradelaw' => 'order/index.php',
'regist_complete' => 'regist/complete.php',
'shopping' => 'shopping/index.php',
'shopping_delivery' => 'shopping/deliv.php',
'shopping_shipping_multiple' => 'shopping/multiple.php',
'shopping_payment' => 'shopping/payment.php',
'shopping_confirm' => 'shopping/confirm.php',
'shopping_complete' => 'shopping/complete.php',
'help_privacy' => 'guide/privacy.php',
);
if (!array_key_exists($routingName, $legacyUrls)) {
throw new \Doctrine\ORM\NoResultException();
}
return $this->getByUrl($deviceTypeId, $routingName);
}
public function newPageLayout($deviceTypeId)
{
$PageLayout = new \Eccube\Entity\PageLayout();
$PageLayout
->setDeviceTypeId($deviceTypeId);
return $PageLayout;
}
public function findOrCreate($page_id, $deviceTypeId)
{
if ($page_id == null) {
$PageLayout = $this->newPageLayout($deviceTypeId);
$page_id = $this->getNewPageId($deviceTypeId);
$PageLayout->setPageId($page_id);
return $PageLayout;
} else {
return $this->get($deviceTypeId, $page_id);
}
}
private function getNewPageId($deviceTypeId)
{
$qb = $this->createQueryBuilder('l')
->select('max(l.page_id) +1 as page_id')
->where('l.device_type_id = :device_type_id')
->setParameter('device_type_id', $deviceTypeId);
$result = $qb->getQuery()->getSingleResult();
return $result['page_id'];
}
/**
* ページの属性を取得する.
*
* この関数は, dtb_pagelayout の情報を検索する.
* $deviceTypeId は必須. デフォルト値は DEVICE_TYPE_PC.
*
* @access public
* @param integer $deviceTypeId 端末種別ID
* @param string $where 追加の検索条件
* @param string[] $parameters 追加の検索パラメーター
* @return array ページ属性の配列
*/
public function getPageList($deviceTypeId, $where = '', $parameters = array())
{
$qb = $this->createQueryBuilder('l')
->orderBy('l.page_id', 'DESC')
->where('l.device_type_id = :device_type_id')
->setParameter('device_type_id', $deviceTypeId)
->andWhere('l.page_id <> 0');
if ($where != '') {
$qb->andWhere($where);
foreach ($parameters as $key => $val) {
$qb->setParameter($key, $val);
}
}
$PageLayouts = $qb
->getQuery()
->getResult();
return $PageLayouts;
}
/**
* テンプレートのパスを取得する.
*
* @access public
* @param integer $deviceTypeId 端末種別ID
* @param boolean $isUser USER_REALDIR 以下のパスを返す場合 true
* @return string テンプレートのパス
*/
public function getTemplatePath($deviceTypeId, $isUser = false)
{
$app = $this->app;
$templateName = '';
switch ($deviceTypeId) {
case $app['config']['device_type_mobile']:
$dir = $app['config']['mobile_template_realdir'];
$templateName = $app['config']['mobile_template_name'];
break;
case $app['config']['device_type_smartphone']:
$dir = $app['config']['smartphone_template_realdir'];
$templateName = $app['config']['smartphone_template_name'];
break;
case $app['config']['device_type_pc'];
$dir = $app['config']['template_realdir'];
$templateName = $app['config']['template_name'];
break;
}
$userPath = $app['config']['user_realdir'];
if ($isUser) {
$dir = $userPath . $app['config']['user_package_dir'] . $templateName . '/';
}
return $dir;
}
/**
* ページデータを取得する.
* @param integer $filename ファイル名
* @param integer $deviceTypeId 端末種別ID
* @param boolean $isUser
* @return mixed
*/
public function getTemplateFile($filename, $deviceTypeId, $isUser = false)
{
$templatePath = $this->getTemplatePath($deviceTypeId, $isUser);
$finder = Finder::create();
$finder->followLinks();
// TODO: ファイル名にディレクトリのパスが一部含まれるので/ディレクトと分ける処理。イケてない・・・
$arrDir = explode('/', $filename);
for ($index =0; $index < count($arrDir)-1; $index++) {
$templatePath .= $arrDir[$index] . '/';
}
// TODO: .tpl, .twig が混在するためひとまず*。元の$filenameから拡張子込で持ちたい。
$finder->in($templatePath)->name($arrDir[$index].'.*');
$data = null;
if ($finder->count() === 1) {
foreach ($finder as $file) {
$data = array(
'file_name' => $file->getFileName(),
'tpl_data' => file_get_contents($file->getPathName())
);
}
}
return $data;
}
}
| gpl-2.0 |
gnuedcl/dcl | dcl/inc/controllers/AttributeSetMapController.php | 2552 | <?php
/*
* This file is part of Double Choco Latte.
* Copyright (C) 1999-2011 Free Software Foundation
*
* Double Choco Latte is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* Double Choco Latte is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Select License Info from the Help menu to view the terms and conditions of this license.
*/
LoadStringResource('bo');
class AttributeSetMapController
{
public function Index()
{
if (($id = @Filter::ToInt($_REQUEST['id'])) === null)
throw new InvalidDataException();
$model = new AttributeSetModel();
if ($model->Load(array('id' => $id)) == -1)
throw new InvalidEntityException();
$presenter = new AttributeSetMapPresenter();
$presenter->Index($model);
}
public function Edit()
{
if (($setId = @Filter::ToInt($_REQUEST['setid'])) === null)
throw new InvalidDataException();
if (($typeId = @Filter::ToInt($_REQUEST['typeid'])) === null)
throw new InvalidDataException();
$presenter = new AttributeSetMapPresenter();
$presenter->Edit($setId, $typeId);
}
public function Update()
{
global $g_oSec;
if (!$g_oSec->HasPerm(DCL_ENTITY_ATTRIBUTESETS, DCL_PERM_MODIFY))
throw new PermissionDeniedException();
if (($setId = @Filter::ToInt($_REQUEST['setid'])) === null)
throw new InvalidDataException();
if (($typeId = @Filter::ToInt($_REQUEST['typeid'])) === null)
throw new InvalidDataException();
$model = new AttributeSetMapModel();
$model->setid = $setId;
$model->typeid = $typeId;
$model->BeginTransaction();
$model->DeleteBySetType($setId, $typeId);
if (($aKeyID = @Filter::ToIntArray($_REQUEST['keyidset'])) !== null)
{
$i = 1;
foreach ($aKeyID as $id)
{
$model->weight = $i;
$model->keyid = $id;
$model->Add();
$i++;
}
}
$model->EndTransaction();
SetRedirectMessage('Success', 'Attribute set mapping updated successfully.');
RedirectToAction('AttributeSetMap', 'Index', 'id=' . $setId);
}
} | gpl-2.0 |
byronmisiva/mrkpln-dev | wp-content/plugins/expo/loop.php | 241 | <?php do_action("before_loop"); ?>
<?php while (have_posts()): the_post(); ?>
<?php get_template_part("content", get_post_format()); ?>
<?php endwhile; ?>
<?php get_template_part("pagination"); ?>
<?php do_action("after_loop"); ?>
| gpl-2.0 |
boneclock/TestWordpress | wp-content/themes/Test/single.php | 784 | <?php
/**
* Template for single post
*
* @package Mega Test
* @since Mega Test 0.1
*/
?>
<?php get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php while(have_posts()):the_post(); ?>
<?php mega_test_content_nav('nav-above'); ?>
<?php get_template_part('content','single') ?>
<?php mega_test_content_nav('nav-below'); ?>
<?php
//If comments are open or we have at least one comment, load up the comment template
if(comments_open() || get_comments_number() != '0')
comments_template('',true);
?>
<?php endwhile; ?>
</div>
</div>
<?php get_sidebar() ?>
<?php get_footer() ?>
| gpl-2.0 |
parmindersingh1/rollingtiger | wp-content/plugins/the-events-calendar/views/list/single-event.php | 2526 | <?php
/**
* List View Single Event
* This file contains one event in the list view
*
* Override this template in your own theme by creating a file at [your-theme]/tribe-events/list/single-event.php
*
* @package TribeEventsCalendar
* @since 3.0
* @author Modern Tribe Inc.
*
*/
if ( !defined('ABSPATH') ) { die('-1'); } ?>
<?php
// Setup an array of venue details for use later in the template
$venue_details = array();
if ($venue_name = tribe_get_meta( 'tribe_event_venue_name' ) ) {
$venue_details[] = $venue_name;
}
if ($venue_address = tribe_get_meta( 'tribe_event_venue_address' ) ) {
$venue_details[] = $venue_address;
}
// Venue microformats
$has_venue = ( $venue_details ) ? ' vcard': '';
$has_venue_address = ( $venue_address ) ? ' location': '';
?>
<!-- Event Cost -->
<?php if ( tribe_get_cost() ) : ?>
<div class="tribe-events-event-cost">
<span><?php echo tribe_get_cost( null, true ); ?></span>
</div>
<?php endif; ?>
<!-- Event Title -->
<?php do_action( 'tribe_events_before_the_event_title' ) ?>
<h2 class="tribe-events-list-event-title summary ">
<a class="url" href="<?php echo tribe_get_event_link() ?>" title="<?php the_title() ?>" rel="bookmark">
<?php the_title() ?>
</a>
</h2>
<?php do_action( 'tribe_events_after_the_event_title' ) ?>
<!-- Event Meta -->
<?php do_action( 'tribe_events_before_the_meta' ) ?>
<div class="tribe-events-event-meta <?php echo $has_venue . $has_venue_address; ?>">
<!-- Schedule & Recurrence Details -->
<div class="updated published time-details">
<?php echo tribe_events_event_schedule_details() ?>
<?php echo tribe_events_event_recurring_info_tooltip() ?>
</div>
<?php if ( $venue_details ) : ?>
<!-- Venue Display Info -->
<div class="tribe-events-venue-details">
<?php echo implode( ', ', $venue_details) ; ?>
</div> <!-- .tribe-events-venue-details -->
<?php endif; ?>
</div><!-- .tribe-events-event-meta -->
<?php do_action( 'tribe_events_after_the_meta' ) ?>
<!-- Event Image -->
<?php echo tribe_event_featured_image( null, 'medium' ) ?>
<!-- Event Content -->
<?php do_action( 'tribe_events_before_the_content' ) ?>
<div class="tribe-events-list-event-description tribe-events-content description entry-summary">
<?php the_excerpt() ?>
<a href="<?php echo tribe_get_event_link() ?>" class="tribe-events-read-more" rel="bookmark"><?php _e( 'Find out more', 'tribe-events-calendar' ) ?> »</a>
</div><!-- .tribe-events-list-event-description -->
<?php do_action( 'tribe_events_after_the_content' ) ?>
| gpl-2.0 |
pixocode/seedbox | www/js/services/alert.js | 2992 | app.services.service('AlertService', ['states', '$ionicPopup', function(states, $ionicPopup){
var self = this;
this.addMessages = function(messages){
var text = '';
var type = '';
for(var i in messages) {
var message = messages[i];
if(message.field && message.text.toLowerCase().indexOf(message.field.toLowerCase()) == -1) {
message.text = message.field + ' : ' + message.text;
}
type = messages[i].type;
text += messages[i].text + '<br/>';
}
text = text.substr(0, text.length - 5);
self.addMessage(text, messages.length == 1 ? type : 'warning');
};
this.addMessage = function(text, type, field){
var obj = {
text : text,
type : type,
field : field
};
self.addMessageObject(obj);
};
this.addMessageObject = function(obj){
if(typeof obj.field == 'undefined') obj.field = '';
else if(obj.text.indexOf(obj.field.toLowerCase()) > -1) obj.field = '';
if(typeof obj.type === 'undefined' || !obj.type || obj.type == 'error') obj.type = 'danger';
if(obj.field) {
if(obj.text.toLowerCase().indexOf(obj.field.toLowerCase()) == -1) obj.text = obj.field + ' : ' + obj.text;
obj.field = '';
}
if(states.debug) {
console.info('--- MESSAGE ---');
console.info(obj);
}
switch(obj.type){
case 'success': var type = 'balanced';break;
case 'info': var type = 'calm';break;
case 'warning': var type = 'energized';break;
case 'danger': var type = 'assertive';break;
}
if(states.popup === false) {
states.message = obj;
states.popup = $ionicPopup.alert({
title: obj.text,
template: '',//states.message.text,
buttons: [{
text: 'OK',
type: 'btn-action button-' + type
}]
});
states.popup.then(function (res) {
states.popup = false;
states.message = false;
});
}
else if(states.message && (states.message.text.indexOf(obj.text) === false || states.message.text.indexOf(obj.text) === -1)){
states.popup.close();
states.popup = false;
states.message.text += '<br/>' + obj.text;
self.addMessage(states.message.text, 'warning');
}
};
this.confirm = function(message, button, callbackOk, callbackCancel, callbackContinue){
if(typeof button == 'undefined') button = 'assertive';
if(typeof callbackCancel == 'undefined') callbackCancel = function(){};
if(typeof callbackContinue == 'undefined') callbackContinue = function(){};
$ionicPopup.show({
title: message,
template: '',
buttons: [
{
text: Translator.trans('actions.common.no'),
type: 'btn-action button-default',
onTap: callbackCancel
},
{
text: Translator.trans('actions.common.yes'),
type: 'btn-action button-' + button,
onTap: callbackOk
}
]
}).then(callbackContinue);
}
}]); | gpl-2.0 |
alsmadi/Malware_Analysis | Properties/AssemblyInfo.cs | 1406 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Malware Scanner")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Malware Scanner")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f48200a6-fc62-4617-b923-fca7a7160eba")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| gpl-2.0 |
rbberger/lammps | src/USER-OMP/pair_born_coul_msm_omp.cpp | 5859 | /* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
https://lammps.sandia.gov/, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
This software is distributed under the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing author: Axel Kohlmeyer (Temple U)
------------------------------------------------------------------------- */
#include "pair_born_coul_msm_omp.h"
#include "atom.h"
#include "comm.h"
#include "error.h"
#include "force.h"
#include "kspace.h"
#include "neigh_list.h"
#include "suffix.h"
#include <cmath>
#include "omp_compat.h"
using namespace LAMMPS_NS;
/* ---------------------------------------------------------------------- */
PairBornCoulMSMOMP::PairBornCoulMSMOMP(LAMMPS *lmp) :
PairBornCoulMSM(lmp), ThrOMP(lmp, THR_PAIR)
{
suffix_flag |= Suffix::OMP;
respa_enable = 0;
}
/* ---------------------------------------------------------------------- */
void PairBornCoulMSMOMP::compute(int eflag, int vflag)
{
if (force->kspace->scalar_pressure_flag)
error->all(FLERR,"Must use 'kspace_modify pressure/scalar no' "
"with OMP MSM Pair styles");
ev_init(eflag,vflag);
const int nall = atom->nlocal + atom->nghost;
const int nthreads = comm->nthreads;
const int inum = list->inum;
#if defined(_OPENMP)
#pragma omp parallel LMP_DEFAULT_NONE LMP_SHARED(eflag,vflag)
#endif
{
int ifrom, ito, tid;
loop_setup_thr(ifrom, ito, tid, inum, nthreads);
ThrData *thr = fix->get_thr(tid);
thr->timer(Timer::START);
ev_setup_thr(eflag, vflag, nall, eatom, vatom, nullptr, thr);
if (evflag) {
if (eflag) {
if (force->newton_pair) eval<1,1,1>(ifrom, ito, thr);
else eval<1,1,0>(ifrom, ito, thr);
} else {
if (force->newton_pair) eval<1,0,1>(ifrom, ito, thr);
else eval<1,0,0>(ifrom, ito, thr);
}
} else {
if (force->newton_pair) eval<0,0,1>(ifrom, ito, thr);
else eval<0,0,0>(ifrom, ito, thr);
}
thr->timer(Timer::PAIR);
reduce_thr(this, eflag, vflag, thr);
} // end of omp parallel region
}
/* ---------------------------------------------------------------------- */
template <int EVFLAG, int EFLAG, int NEWTON_PAIR>
void PairBornCoulMSMOMP::eval(int iifrom, int iito, ThrData * const thr)
{
int i,j,ii,jj,jnum,itype,jtype;
double qtmp,xtmp,ytmp,ztmp,delx,dely,delz,evdwl,ecoul,fpair;
double rsq,r2inv,r6inv,r,rexp,forcecoul,forceborn,factor_coul,factor_lj;
double egamma,fgamma,prefactor;
int *ilist,*jlist,*numneigh,**firstneigh;
evdwl = ecoul = 0.0;
const dbl3_t * _noalias const x = (dbl3_t *) atom->x[0];
dbl3_t * _noalias const f = (dbl3_t *) thr->get_f()[0];
const double * _noalias const q = atom->q;
const int * _noalias const type = atom->type;
int nlocal = atom->nlocal;
double *special_coul = force->special_coul;
double *special_lj = force->special_lj;
double qqrd2e = force->qqrd2e;
double fxtmp,fytmp,fztmp;
ilist = list->ilist;
numneigh = list->numneigh;
firstneigh = list->firstneigh;
// loop over neighbors of my atoms
for (ii = iifrom; ii < iito; ++ii) {
i = ilist[ii];
qtmp = q[i];
xtmp = x[i].x;
ytmp = x[i].y;
ztmp = x[i].z;
itype = type[i];
jlist = firstneigh[i];
jnum = numneigh[i];
fxtmp=fytmp=fztmp=0.0;
for (jj = 0; jj < jnum; jj++) {
j = jlist[jj];
factor_lj = special_lj[sbmask(j)];
factor_coul = special_coul[sbmask(j)];
j &= NEIGHMASK;
delx = xtmp - x[j].x;
dely = ytmp - x[j].y;
delz = ztmp - x[j].z;
rsq = delx*delx + dely*dely + delz*delz;
jtype = type[j];
if (rsq < cutsq[itype][jtype]) {
r2inv = 1.0/rsq;
r = sqrt(rsq);
if (rsq < cut_coulsq) {
prefactor = qqrd2e * qtmp*q[j]/r;
egamma = 1.0 - (r/cut_coul)*force->kspace->gamma(r/cut_coul);
fgamma = 1.0 + (rsq/cut_coulsq)*force->kspace->dgamma(r/cut_coul);
forcecoul = prefactor * fgamma;
if (factor_coul < 1.0) forcecoul -= (1.0-factor_coul)*prefactor;
} else forcecoul = 0.0;
if (rsq < cut_ljsq[itype][jtype]) {
r6inv = r2inv*r2inv*r2inv;
rexp = exp((sigma[itype][jtype]-r)*rhoinv[itype][jtype]);
forceborn = born1[itype][jtype]*r*rexp - born2[itype][jtype]*r6inv
+ born3[itype][jtype]*r2inv*r6inv;
} else forceborn = 0.0;
fpair = (forcecoul + factor_lj*forceborn)*r2inv;
fxtmp += delx*fpair;
fytmp += dely*fpair;
fztmp += delz*fpair;
if (NEWTON_PAIR || j < nlocal) {
f[j].x -= delx*fpair;
f[j].y -= dely*fpair;
f[j].z -= delz*fpair;
}
if (EFLAG) {
if (rsq < cut_coulsq) {
ecoul = prefactor*egamma;
if (factor_coul < 1.0) ecoul -= (1.0-factor_coul)*prefactor;
} else ecoul = 0.0;
if (rsq < cut_ljsq[itype][jtype]) {
evdwl = a[itype][jtype]*rexp - c[itype][jtype]*r6inv
+ d[itype][jtype]*r6inv*r2inv - offset[itype][jtype];
evdwl *= factor_lj;
} else evdwl = 0.0;
}
if (EVFLAG) ev_tally_thr(this, i,j,nlocal,NEWTON_PAIR,
evdwl,ecoul,fpair,delx,dely,delz,thr);
}
}
f[i].x += fxtmp;
f[i].y += fytmp;
f[i].z += fztmp;
}
}
/* ---------------------------------------------------------------------- */
double PairBornCoulMSMOMP::memory_usage()
{
double bytes = memory_usage_thr();
bytes += PairBornCoulMSM::memory_usage();
return bytes;
}
| gpl-2.0 |
AceXIE/lintcode | src/main/java/SortList.java | 1602 | /**
* Created by Administrator on 2016/5/13.
* O(nlogn) 归并排序
*/
public class SortList {
public static void main(String[] args) {
ListNode root = new ListNode(1);
ListNode l1 = new ListNode(3);
ListNode l2 = new ListNode(2);
ListNode p = root;
p.next = l1;
l1.next = l2;
print(sortList(root));
}
public static ListNode sortList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode middle = getMiddle(head);
ListNode nextListNode = middle.next;
middle.next = null;//断开
return mergeList(sortList(head), sortList(nextListNode));
}
public static ListNode getMiddle(ListNode head) {
ListNode slow = head, fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public static ListNode mergeList(ListNode a, ListNode b) {
ListNode listNode = new ListNode(0);
ListNode curr = listNode;
while (a != null && b != null) {
if (a.val <= b.val) {
curr.next = a;
a = a.next;
} else {
curr.next = b;
b = b.next;
}
curr = curr.next;
}
curr.next = (a!=null?a:b);
return listNode.next;
}
public static void print(ListNode root) {
ListNode p = root;
while (p != null) {
System.out.print(p.val);
p = p.next;
}
}
}
| gpl-2.0 |
mvcaaa/ssur | bin/php/clusterize.php | 6393 | #!/usr/bin/env php
<?php
//
// Created on: <30-Mar-2006 06:30:00 vs>
//
// SOFTWARE NAME: eZ Publish
// SOFTWARE RELEASE: 4.0.1
// BUILD VERSION: 22260
// COPYRIGHT NOTICE: Copyright (C) 1999-2008 eZ Systems AS
// SOFTWARE LICENSE: GNU General Public License v2.0
// NOTICE: >
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2.0 of the GNU General
// Public License as published by the Free Software Foundation.
//
// 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 version 2.0 of the GNU General
// Public License along with this program; if not, write to the Free
// Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
//
//
/*
NOTE:
Please read doc/features/3.8/clustering.txt and set up clustering
before runnning this script.
*/
error_reporting( E_ALL | E_NOTICE );
// require_once( 'lib/ezdb/classes/ezdb.php' );
// require_once( 'lib/ezutils/classes/ezcli.php' );
// require_once( 'lib/ezutils/classes/ezsys.php' );
// require_once( 'kernel/classes/ezscript.php' );
// require_once( 'kernel/classes/ezclusterfilehandler.php' );
require 'autoload.php';
// This code is taken from eZBinaryFile::storedFileInfo()
function filePathForBinaryFile($fileName, $mimeType )
{
$storageDir = eZSys::storageDirectory();
list( $group, $type ) = explode( '/', $mimeType );
$filePath = $storageDir . '/original/' . $group . '/' . $fileName;
return $filePath;
}
function copyBinaryfilesToDB( $remove )
{
global $cli, $dbFileHandler;
$db = eZDB::instance();
$cli->output( "Importing binary files to database:");
$rows = $db->arrayQuery('select filename, mime_type from ezbinaryfile' );
foreach( $rows as $row )
{
$filePath = filePathForBinaryFile( $row['filename'] , $row['mime_type'] );
$cli->output( "- " . $filePath);
$dbFileHandler->fileStore( $filePath, 'binaryfile', $remove );
}
$cli->output();
}
function copyMediafilesToDB( $remove )
{
global $cli, $dbFileHandler;
$db = eZDB::instance();
$cli->output( "Importing media files to database:");
$rows = $db->arrayQuery('select filename, mime_type from ezmedia' );
foreach( $rows as $row )
{
$filePath = filePathForBinaryFile( $row['filename'] , $row['mime_type'] );
$cli->output( "- " . $filePath);
$dbFileHandler->fileStore( $filePath, 'mediafile', $remove );
}
$cli->output();
}
function copyImagesToDB( $remove )
{
global $cli, $dbFileHandler;
$db = eZDB::instance();
$cli->output( "Importing images and imagealiases files to database:");
$rows = $db->arrayQuery('select filepath from ezimagefile' );
//include_once( 'lib/ezutils/classes/ezmimetype.php' );
foreach( $rows as $row )
{
$filePath = $row['filepath'];
$cli->output( "- " . $filePath);
$mimeData = eZMimeType::findByFileContents( $filePath );
$dbFileHandler->fileStore( $filePath, 'image', $remove, $mimeData['name'] );
}
}
function copyFilesFromDB( $copyFiles, $copyImages, $remove )
{
global $cli, $dbFileHandler;
$cli->output( "Exporting files from database:");
$filePathList = $dbFileHandler->getFileList( !$copyFiles, !$copyImages );
foreach ( $filePathList as $filePath )
{
$cli->output( "- " . $filePath );
eZDir::mkdir( dirname( $filePath ), false, true );
$dbFileHandler->fileFetch( $filePath );
if ( $remove )
$dbFileHandler->fileDelete( $filePath );
}
$cli->output();
}
$cli = eZCLI::instance();
$script = eZScript::instance( array( 'description' => ( "eZ Publish (un)clusterize\n" .
"Script for moving var_dir files from " .
"filesystem to database and vice versa\n" .
"\n" .
"./bin/php/clusterize.php" ),
'use-session' => false,
'use-modules' => false,
'use-extensions' => true ) );
$script->startup();
$options = $script->getOptions( "[u][skip-binary-files][skip-media-files][skip-images][r][n]",
"",
array( 'u' => 'Unclusterize',
'skip-binary-files' => 'Skip copying binary files',
'skip-media-files' => 'Skip copying media files',
'skip-images' => 'Skip copying images',
'r' => 'Remove files after copying',
'n' => 'Do not wait' ) );
$script->initialize();
$clusterize = !isset( $options['u'] );
$remove = isset( $options['r'] );
$copyFiles = !isset( $options['skip-binary-files'] );
$copyMedia = !isset( $options['skip-media-files'] );
$copyImages = !isset( $options['skip-images'] );
$wait = !isset( $options['n'] );
if ( $wait )
{
$warningMsg = sprintf( "This script will now %s your files and/or images %s database.",
( $remove ? "move" : "copy" ),
( $clusterize ? 'to' : 'from' ) );
$cli->warning( $warningMsg );
$cli->warning( "You have 10 seconds to break the script (press Ctrl-C)." );
sleep( 10 );
}
$dbFileHandler = eZClusterFileHandler::instance();
if ( !is_object( $dbFileHandler ) || !( $dbFileHandler instanceof eZDBFileHandler ) )
{
$cli->error( "Clustering settings specified incorrectly or the chosen file handler is ezfs." );
$script->shutdown( 1 );
}
if ( $clusterize )
{
if ( $copyFiles )
copyBinaryfilesToDB( $remove );
if ( $copyImages )
copyImagesToDB( $remove );
if ( $copyMedia )
copyMediafilesToDB( $remove );
}
else
{
copyFilesFromDB( $copyFiles, $copyImages, $remove );
}
$script->shutdown();
?>
| gpl-2.0 |
tonglin/pdPm | public_html/typo3_src-6.1.7/typo3/sysext/recordlist/ext_autoload.php | 311 | <?php
// DO NOT CHANGE THIS FILE! It is automatically generated by extdeveval::buildAutoloadRegistry.
// This file was generated on 2009-10-26 22:04
$extensionPath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('recordlist');
return array(
'sc_db_list' => $extensionPath . 'mod1/index.php'
);
?> | gpl-2.0 |
ligenzatomas/firebird-vizualization-tool | src/main/java/org/tinyuml/ui/model/IndexColsTableModel.java | 4004 | /**
* Copyright 2014 Tomáš Ligenza
*
* This file is part of Firebird Visualization Tool.
*
* Firebird Visualization Tool is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* TinyUML 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 Firebird Visualization Tool; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.tinyuml.ui.model;
import org.tinyuml.model.IndexColumn;
import java.util.LinkedList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import org.firebirdvisualizationtool.database.firebird.IndexOrders;
import org.tinyuml.util.ApplicationResources;
/**
*
* @author Tomáš Ligenza
*/
public class IndexColsTableModel extends AbstractTableModel {
private static final long serialVersionUID = -3694142998063548137L;
private final String[] columnNames = {
""
, ApplicationResources.getInstance().getString("database.model.indexcol.column")
, ApplicationResources.getInstance().getString("database.model.indexcol.way")};
private final List<IndexColumn> entries = new LinkedList<IndexColumn>();
@Override
public String getColumnName(int index) {
return columnNames[index];
}
public void clearEntries() {
entries.clear();
fireTableDataChanged();
}
public void addEntry(Boolean check, String col, IndexOrders order) {
int size = entries.size();
entries.add(new IndexColumn(check, col, order));
fireTableRowsInserted(size, size);
}
public List<IndexColumn> getEntries() {
return entries;
}
public boolean isIndexColByName(String name) {
for(IndexColumn col : entries) {
if(col.getName() == name)
return true;
}
return false;
}
public void moveUpEntry(int index) {
if(index < getRowCount()) {
IndexColumn entryDown = entries.remove(index);
IndexColumn entryUp = entries.remove(index - 1);
entries.add(index - 1, entryDown);
entries.add(index, entryUp);
fireTableDataChanged();
}
}
public void moveDownEntry(int index) {
if(index < (getRowCount() - 1)) {
IndexColumn entryDown = entries.remove(index);
entries.add(index + 1, entryDown);
fireTableDataChanged();
}
}
public void removeEntryAt(int index) {
entries.remove(index);
fireTableRowsDeleted(index, index);
}
@Override
public int getRowCount() {
return entries.size();
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object ret;
switch(columnIndex) {
case 0:
ret = entries.get(rowIndex).getChecked();
break;
case 1:
ret = entries.get(rowIndex).getName();
break;
case 2:
ret = entries.get(rowIndex).getoOrder();
break;
default:
ret = new Object();
break;
}
return ret;
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
switch(columnIndex) {
case 0:
entries.get(rowIndex).setChecked((Boolean) value);
break;
case 1:
entries.get(rowIndex).setName((String) value);
break;
case 2:
entries.get(rowIndex).setoOrder((IndexOrders) value);
break;
}
fireTableCellUpdated(rowIndex, columnIndex);
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
if(columnIndex == 0 || columnIndex == 2)
return true;
else
return false;
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
}
| gpl-2.0 |