<commit_before>
/**
 *  Replace strings grunt task for CartoDB.js
 *
 */

module.exports = {
  task: function(grunt, config) {
    return {

      cdb: {
        options: {
          patterns: [{
            match: '/cdb.VERSION = "<%= config.version.bugfixing %>"/g',
            replacement: 'cdb.VERSION = "<%= grunt.config(\'bump.version\') %>"',
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['src/cartodb.js'],
          dest: 'src/'
        }]
      },

      pkg: {
        options: {
          patterns: [{
            match: '/"version": "<%= config.version.bugfixing %>"/g',
            replacement: '"version": "<%= grunt.config(\'bump.version\') %>"',
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['package.json'],
          dest: ''
        }]
      },

      readme: {
        options: {
          patterns: [{
            match: '/<%= config.version.minor %>/gi',
            replacement: "<%= grunt.config('bump.minor') %>",
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['README.md'],
          dest: ''
        }]
      },

      api: {
        options: {
          patterns: [{
            match: '/\/<%= config.version.minor %>\//gi',
            replacement: "/<%= grunt.config('bump.minor') %>/",
            expression: true
          },{
            match: '/<%= config.version.bugfixing %>/gi',
            replacement: "<%= grunt.config('bump.version') %>",
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['doc/API.md'],
          dest: 'doc/'
        }]
      },

      examples: {
        options: {
          patterns: [{
            match: '/\/<%= config.version.minor %>\//gi',
            replacement: "/<%= grunt.config('bump.minor') %>/",
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['examples/**/*.html'],
          dest: 'examples/'
        }]
      },

      releasing: {
        options: {
          patterns: [{
            match: '/\/<%= config.version.minor %>\//gi',
            replacement: "/<%= grunt.config('bump.minor') %>/",
            expression: true
          },{
            match: '/<%= config.version.bugfixing %>/gi',
            replacement: "<%= grunt.config('bump.version') %>",
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['RELEASING.md'],
          dest: ''
        }]
      },

      bower: {
        options: {
          patterns: [{
            match: '/"version": "<%= config.version.bugfixing %>"/g',
            replacement: '"version": "<%= grunt.config(\'bump.version\') %>"',
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['bower.json'],
          dest: ''
        }]
      },
    }
  }
}
<commit_msg>Update the cdb.VERSION of the new cdb.js file<commit_after>
/**
 *  Replace strings grunt task for CartoDB.js
 *
 */

module.exports = {
  task: function(grunt, config) {
    return {

      cdb: {
        options: {
          patterns: [{
            match: '/cdb.VERSION = "<%= config.version.bugfixing %>"/g',
            replacement: 'cdb.VERSION = "<%= grunt.config(\'bump.version\') %>"',
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['src-browserify/cdb.js'],
          dest: 'src-browserify/'
        }]
      },

      'cdb-old': {
        options: {
          patterns: [{
            match: '/cdb.VERSION = "<%= config.version.bugfixing %>"/g',
            replacement: 'cdb.VERSION = "<%= grunt.config(\'bump.version\') %>"',
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['src/cartodb.js'],
          dest: 'src/'
        }]
      },

      pkg: {
        options: {
          patterns: [{
            match: '/"version": "<%= config.version.bugfixing %>"/g',
            replacement: '"version": "<%= grunt.config(\'bump.version\') %>"',
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['package.json'],
          dest: ''
        }]
      },

      readme: {
        options: {
          patterns: [{
            match: '/<%= config.version.minor %>/gi',
            replacement: "<%= grunt.config('bump.minor') %>",
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['README.md'],
          dest: ''
        }]
      },

      api: {
        options: {
          patterns: [{
            match: '/\/<%= config.version.minor %>\//gi',
            replacement: "/<%= grunt.config('bump.minor') %>/",
            expression: true
          },{
            match: '/<%= config.version.bugfixing %>/gi',
            replacement: "<%= grunt.config('bump.version') %>",
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['doc/API.md'],
          dest: 'doc/'
        }]
      },

      examples: {
        options: {
          patterns: [{
            match: '/\/<%= config.version.minor %>\//gi',
            replacement: "/<%= grunt.config('bump.minor') %>/",
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['examples/**/*.html'],
          dest: 'examples/'
        }]
      },

      releasing: {
        options: {
          patterns: [{
            match: '/\/<%= config.version.minor %>\//gi',
            replacement: "/<%= grunt.config('bump.minor') %>/",
            expression: true
          },{
            match: '/<%= config.version.bugfixing %>/gi',
            replacement: "<%= grunt.config('bump.version') %>",
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['RELEASING.md'],
          dest: ''
        }]
      },

      bower: {
        options: {
          patterns: [{
            match: '/"version": "<%= config.version.bugfixing %>"/g',
            replacement: '"version": "<%= grunt.config(\'bump.version\') %>"',
            expression: true
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['bower.json'],
          dest: ''
        }]
      },
    }
  }
}
<|endoftext|>


<commit_before>function Array$(elems,$$targs$$) {
    var e=[];
    if (!(elems === null || elems === undefined)) {
        var iter=elems.iterator();
        var item;while((item=iter.next())!==getFinished()) {
            e.push(item);
        }
    }
    e.$$targs$$=$$targs$$;
    List({Element$List:$$targs$$.Element$Array}, e);
    return e;
}
Array$.$crtmm$={$ps:[{$nm:'elements',$mt:'prm',$t:{t:Iterable,a:{Absent$Iterable:{t:Null},Element$Iterable:'Element$Array'}}}],$an:function(){return[shared(),final(),native()];},mod:$CCMM$,d:['ceylon.language','Array'],
  'super':{t:Object$}, $tp:{Element$Array:{}}, satisfies:[{t:List,a:{Element$List:'Element$Array'}},
    {t:Ranged,a:{Index$Ranged:{t:Integer},Span$Ranged:{t:Array$,a:{Element$Array:'Element$Array'}}}}]};

initExistingType(Array$, Array, 'ceylon.language::Array', Object$,
        Ranged, $init$List());
var Array$proto = Array.prototype;
var origArrToString = Array$proto.toString;
inheritProto(Array$, Object$, Ranged, $init$List());
Array$proto.toString = origArrToString;
Array$proto.reifyCeylonType = function(typeParameters) {
    this.$$targs$$ = typeParameters;
    return this;
}
exports.$Array=Array$;

function ArraySequence(/* js array */value, $$targs$$) {
if (value.length===0)return getEmpty();
    value.$seq = true;
var t=$$targs$$.Element$Iterable;
if (t===undefined)t=$$targs$$.Element$ArraySequence;
if (t===undefined)t=$$targs$$.Element$Array;
if (t===undefined)t=$$targs$$.Element$Sequence;
if (t===undefined)t=$$targs$$.Element$Sequential;
if (t===undefined)t=$$targs$$.Element$List;
if (t===undefined)throw new Error("Invalid type arguments for ArraySequence: "+require('util').inspect($$targs$$));
    value.$$targs$$={Element$Iterable:t, Element$ArraySequence:t, Element$Sequence:t, Element$Sequential:t, Element$List:t, Element$Collection:t, Item$Correspondence:t, Key$Correspondence:{t:Integer},Absent$Iterable:{t:Nothing}, Element$Array:t};
    return value;
}
ArraySequence.$crtmm$=function(){return{mod:$CCMM$,d:['ceylon.language','ArraySequence'],$ps:[{$nm:'elements',$t:{t:Sequence,a:{Element$Sequence:'Element$ArraySequence'}}}],$tp:{Element$ArraySequence:{'var':'out'}},satisfies:[{t:Sequence,a:{Element$Sequence:'Element$ArraySequence'}}]};};
initTypeProto(ArraySequence, 'ceylon.language::ArraySequence', $init$Basic(), $init$Sequence());
Array$proto.getT$name = function() {
    return (this.$seq ? ArraySequence : Array$).$$.T$name;
}
Array$proto.getT$all = function() {
    return (this.$seq ? ArraySequence : Array$).$$.T$all;
}

$defat(Array$proto, 'size', function(){ return this.length; },undefined,function(){return{mod:$CCMM$,d:['ceylon.language','Iterable','$at','size'],$cont:Array$proto,$t:{t:Integer}};});
$defat(Array$proto,'string',function(){
    return (opt$181=(this.empty?String$("[]",2):null),opt$181!==null?opt$181:StringBuilder().appendAll([String$("[",1),commaList(this).string,String$("]",1)]).string);
},undefined,function(){return{mod:$CCMM$,d:['ceylon.language','Object','$at','string'],$t:{t:String},$cont:Array$proto};});
Array$proto.set = function(idx,elem) {
    if (idx >= 0 && idx < this.length) {
        this[idx] = elem;
    }
}
Array$proto.set.$crtmm$=function(){return{mod:$CCMM$,d:['ceylon.language','Array','$m','set'],$t:{t:Anything},$ps:[{$nm:'index',$t:{t:Integer},$mt:'prm'},{$nm:'element',$mt:'prm',$t:'Element$Array'}]};}
Array$proto.$get = function(idx) {
    var result = this[idx];
    return result!==undefined ? result:null;
}
Array$proto.$get.$crtmm$=function(){
  return{mod:$CCMM$,d:['ceylon.language','List','$m','get'],$t:{t:'u',l:[{t:Null},'Element$Array']},$ps:[{$nm:'index',$t:{t:Integer},$mt:'prm'}]};
}
$defat(Array$proto, 'lastIndex', function() {
    return this.length>0 ? (this.length-1) : null;
},undefined,function(){return{mod:$CCMM$,d:['ceylon.language','List','$at','lastIndex'],$t:{t:'u',l:[{t:Null},{t:Integer}]}};});
$defat(Array$proto, 'reversed', function() {
    if (this.length === 0) { return this; }
    var arr = this.slice(0);
    arr.reverse();
    return this.$seq ? ArraySequence(arr,this.$$targs$$||{Element$Iterable:{t:Anything}}) : arr.reifyCeylonType(this.$$targs$$);
},undefined,function(){return{mod:$CCMM$,d:['ceylon.language','List','$at','reversed'],$t:{t:List,a:{Element$List:'Element$Array'}}};});
Array$proto.chain = function(other, $$$mptypes) {
    if (this.length === 0) { return other; }
    return Iterable.$$.prototype.chain.call(this, other, $$$mptypes);
}
$defat(Array$proto, 'first', function(){ return this.length>0 ? this[0] : null; },
  undefined,function(){return{mod:$CCMM$,d:['ceylon.language','Iterable','$at','first'],$t:{t:'u',l:[{t:Null},'Element$Array']}};});
$defat(Array$proto, 'last', function() { return this.length>0 ? this[this.length-1] : null; },
  undefined,function(){return{mod:$CCMM$,d:['ceylon.language','List','$at','last'],$t:{t:'u',l:[{t:Null},'Element$Array']}};});
Array$proto.segment = function(from, len) {
    if (len <= 0) { return getEmpty(); }
    var stop = from + len;
    var seq = this.slice((from>=0)?from:0, (stop>=0)?stop:0);
    return (seq.length > 0) ? ArraySequence(seq,this.$$targs$$||{Element$Iterable:{t:Anything}}) : getEmpty();
}
Array$proto.span = function(from, to) {
    if (from > to) {
        var arr = this.segment(to, from-to+1);
        arr.reverse();
        return arr.reifyCeylonType(this.$$targs$$);
    }
    return this.segment(from, to-from+1);
}
Array$proto.spanTo = function(to) {
    return to < 0 ? getEmpty() : this.span(0, to);
}
Array$proto.spanFrom = function(from) {
    return this.span(from, 0x7fffffff);
}
$defat(Array$proto, 'rest', function() {
    return this.length<=1 ? getEmpty() : ArraySequence(this.slice(1),this.$$targs$$||{Element$Iterable:{t:Anything}});
});
Array$proto.items = function(keys) {
    if (keys === undefined) return getEmpty();
    var seq = [];
    for (var i = 0; i < keys.size; i++) {
        var key = keys.$get(i);
        seq.push(this.$get(key));
    }
    return ArraySequence(seq,this.$$targs$$||{Element$Iterable:{t:Anything}});
}
$defat(Array$proto, 'keys', function(){ return TypeCategory(this, {t:Integer}); });
Array$proto.contains = function(elem) {
    for (var i=0; i<this.length; i++) {
        if (elem.equals(this[i])) {
            return true;
        }
    }
    return false;
}
Array$proto.iterator = function() {
    var $$$index$$$ = 0;
    var $$$arr$$$ = this;
    return new ComprehensionIterator(function() {
        return ($$$index$$$ === $$$arr$$$.length) ? getFinished() : $$$arr$$$[$$$index$$$++];
    }, this.$$targs$$);
}
Array$proto.copyTo = function(other, srcpos, dstpos, length) {
    if (length === undefined) length = this.size;
    if (srcpos === undefined) srcpos = 0;
    if (dstpos === undefined) dstpos = 0;
    var endpos = srcpos+length;
    //TODO validate range?
    for (var i=srcpos; i<endpos; i++) {
        other[dstpos]=this[i];
        dstpos++;
    }
}
Array$proto.shorterThan = function(len) {
  return this.size < len;
}
Array$proto.shorterThan.$crtmm$={mod:$CCMM$,d:['ceylon.language','Iterable','$m','shorterThan']};
Array$proto.longerThan = function(len) {
  return this.size > len;
}
Array$proto.longerThan.$crtmm$={mod:$CCMM$,d:['ceylon.language','Iterable','$m','longerThan']};

exports.arrayOfSize=function(size, elem, $$$mptypes) {
    if (size > 0) {
        var elems = [];
        for (var i = 0; i < size; i++) {
            elems.push(elem);
        }
        elems.$$targs$$=$$$mptypes;
        return elems;
    } else return [];
}
exports.arrayOfSize.$crtmm$={$an:function(){return[shared()];},mod:$CCMM$,d:['ceylon.language','arrayOfSize']};

function TypeCategory(seq, type) {
    var that = new TypeCategory.$$;
    that.type = type;
    that.seq = seq;
    return that;
}
initTypeProto(TypeCategory, 'ceylon.language::TypeCategory', $init$Basic(), Category);
var TypeCategory$proto = TypeCategory.$$.prototype;
TypeCategory$proto.contains = function(k) {
    return $is(k, this.type) && this.seq.defines(k);
}

function SequenceBuilder($$targs$$,that) {
    if(that===undefined)that=new SequenceBuilder.$$;
    that.seq = [];
    that.$$targs$$=$$targs$$;
    return that;
}
SequenceBuilder.$crtmm$=function(){return{$ps:[],$an:function(){return[shared()];},
  $tp:{Element$SequenceBuilder:{}}, mod:$CCMM$,d:['ceylon.language','SequenceBuilder']};}

initTypeProto(SequenceBuilder, 'ceylon.language::SequenceBuilder', $init$Basic());
var SequenceBuilder$proto = SequenceBuilder.$$.prototype;
$defat(SequenceBuilder$proto, 'sequence', function() {
    return (this.seq.length > 0) ? ArraySequence(this.seq,{Element$Iterable:this.$$targs$$.Element$SequenceBuilder}) : getEmpty();
},undefined,function(){return{
  $t:{t:Sequential,a:{Element$Sequential:'Element$SequenceBuilder'}},mod:$CCMM$,d:['ceylon.language','SequenceBuilder','$at','sequence']};});
SequenceBuilder$proto.append=function(e){
  this.seq.push(e);
  return this;
}
SequenceBuilder$proto.appendAll = function(/*Iterable*/arr) {
    if (arr === undefined) return;
    var iter = arr.iterator();
    var e; while ((e = iter.next()) !== getFinished()) {
        this.seq.push(e);
    }
    return this;
}
$defat(SequenceBuilder$proto, 'size', function(){ return this.seq.length; },undefined,function(){return{
  $t:{t:Integer},mod:$CCMM$,d:['ceylon.language','SequenceBuilder','$at','size']
};});
$defat(SequenceBuilder$proto, 'empty', function() { return this.seq.length===0 },function(){return{
  $t:{t:Boolean$},mod:$CCMM$,d:['ceylon.language','SequenceBuilder','$at','empty']
};});

function SequenceAppender(other, $$targs$$,that) {
    if (that===undefined)that=new SequenceAppender.$$;
    SequenceBuilder({Element$SequenceBuilder:$$targs$$.Element$SequenceAppender},that);
    that.appendAll(other);
    return that;
}
SequenceAppender.$crtmm$=function(){return{$ps:[{$nm:'elements',$t:{t:Sequence,a:{Element$Sequence:'Element$SequenceAppender'}},$mt:'prm'}],$an:function(){return[shared()];},
  'super':{t:SequenceBuilder,a:{Element$SequenceBuilder:'Element$SequenceAppender'}},$tp:{Element$SequenceAppender:{}},mod:$CCMM$,d:['ceylon.language','SequenceAppender']};}

initTypeProto(SequenceAppender, 'ceylon.language::SequenceAppender', SequenceBuilder);

exports.Sequence=Sequence;
exports.SequenceBuilder=SequenceBuilder;
exports.SequenceAppender=SequenceAppender;
exports.ArraySequence=ArraySequence;
<commit_msg>Lazy Iterable for ceylon/ceylon-js#334<commit_after>function Array$(elems,$$targs$$) {
    var e=[];
    if (!(elems === null || elems === undefined)) {
        var iter=elems.iterator();
        var item;while((item=iter.next())!==getFinished()) {
            e.push(item);
        }
    }
    e.$$targs$$=$$targs$$;
    List({Element$List:$$targs$$.Element$Array}, e);
    return e;
}
Array$.$crtmm$={$ps:[{$nm:'elements',$mt:'prm',$t:{t:Iterable,a:{Absent$Iterable:{t:Null},Element$Iterable:'Element$Array'}}}],$an:function(){return[shared(),final(),native()];},mod:$CCMM$,d:['ceylon.language','Array'],
  'super':{t:Object$}, $tp:{Element$Array:{}}, satisfies:[{t:List,a:{Element$List:'Element$Array'}},
    {t:Ranged,a:{Index$Ranged:{t:Integer},Span$Ranged:{t:Array$,a:{Element$Array:'Element$Array'}}}}]};

initExistingType(Array$, Array, 'ceylon.language::Array', Object$,
        Ranged, $init$List());
var Array$proto = Array.prototype;
var origArrToString = Array$proto.toString;
inheritProto(Array$, Object$, Ranged, $init$List());
Array$proto.toString = origArrToString;
Array$proto.reifyCeylonType = function(typeParameters) {
    this.$$targs$$ = typeParameters;
    return this;
}
exports.$Array=Array$;

function ArraySequence(/* js array */value, $$targs$$) {
if (value.length===0)return getEmpty();
    value.$seq = true;
var t=$$targs$$.Element$Iterable;
if (t===undefined)t=$$targs$$.Element$ArraySequence;
if (t===undefined)t=$$targs$$.Element$Array;
if (t===undefined)t=$$targs$$.Element$Sequence;
if (t===undefined)t=$$targs$$.Element$Sequential;
if (t===undefined)t=$$targs$$.Element$List;
if (t===undefined)throw new Error("Invalid type arguments for ArraySequence: "+require('util').inspect($$targs$$));
    value.$$targs$$={Element$Iterable:t, Element$ArraySequence:t, Element$Sequence:t, Element$Sequential:t, Element$List:t, Element$Collection:t, Item$Correspondence:t, Key$Correspondence:{t:Integer},Absent$Iterable:{t:Nothing}, Element$Array:t};
    return value;
}
ArraySequence.$crtmm$=function(){return{mod:$CCMM$,d:['ceylon.language','ArraySequence'],$ps:[{$nm:'elements',$t:{t:Sequence,a:{Element$Sequence:'Element$ArraySequence'}}}],$tp:{Element$ArraySequence:{'var':'out'}},satisfies:[{t:Sequence,a:{Element$Sequence:'Element$ArraySequence'}}]};};
initTypeProto(ArraySequence, 'ceylon.language::ArraySequence', $init$Basic(), $init$Sequence());
Array$proto.getT$name = function() {
    return (this.$seq ? ArraySequence : Array$).$$.T$name;
}
Array$proto.getT$all = function() {
    return (this.$seq ? ArraySequence : Array$).$$.T$all;
}

$defat(Array$proto, 'size', function(){ return this.length; },undefined,function(){return{mod:$CCMM$,d:['ceylon.language','Iterable','$at','size'],$cont:Array$proto,$t:{t:Integer}};});
$defat(Array$proto,'string',function(){
    return (opt$181=(this.empty?String$("[]",2):null),opt$181!==null?opt$181:StringBuilder().appendAll([String$("[",1),commaList(this).string,String$("]",1)]).string);
},undefined,function(){return{mod:$CCMM$,d:['ceylon.language','Object','$at','string'],$t:{t:String},$cont:Array$proto};});
Array$proto.set = function(idx,elem) {
    if (idx >= 0 && idx < this.length) {
        this[idx] = elem;
    }
}
Array$proto.set.$crtmm$=function(){return{mod:$CCMM$,d:['ceylon.language','Array','$m','set'],$t:{t:Anything},$ps:[{$nm:'index',$t:{t:Integer},$mt:'prm'},{$nm:'element',$mt:'prm',$t:'Element$Array'}]};}
Array$proto.$get = function(idx) {
    var result = this[idx];
    return result!==undefined ? result:null;
}
Array$proto.$get.$crtmm$=function(){
  return{mod:$CCMM$,d:['ceylon.language','List','$m','get'],$t:{t:'u',l:[{t:Null},'Element$Array']},$ps:[{$nm:'index',$t:{t:Integer},$mt:'prm'}]};
}
$defat(Array$proto, 'lastIndex', function() {
    return this.length>0 ? (this.length-1) : null;
},undefined,function(){return{mod:$CCMM$,d:['ceylon.language','List','$at','lastIndex'],$t:{t:'u',l:[{t:Null},{t:Integer}]}};});
$defat(Array$proto, 'reversed', function() {
    if (this.length === 0) { return this; }
    var arr = this.slice(0);
    arr.reverse();
    return this.$seq ? ArraySequence(arr,this.$$targs$$||{Element$Iterable:{t:Anything}}) : arr.reifyCeylonType(this.$$targs$$);
},undefined,function(){return{mod:$CCMM$,d:['ceylon.language','List','$at','reversed'],$t:{t:List,a:{Element$List:'Element$Array'}}};});
Array$proto.chain = function(other, $$$mptypes) {
    if (this.length === 0) { return other; }
    return Iterable.$$.prototype.chain.call(this, other, $$$mptypes);
}
$defat(Array$proto, 'first', function(){ return this.length>0 ? this[0] : null; },
  undefined,function(){return{mod:$CCMM$,d:['ceylon.language','Iterable','$at','first'],$t:{t:'u',l:[{t:Null},'Element$Array']}};});
$defat(Array$proto, 'last', function() { return this.length>0 ? this[this.length-1] : null; },
  undefined,function(){return{mod:$CCMM$,d:['ceylon.language','List','$at','last'],$t:{t:'u',l:[{t:Null},'Element$Array']}};});
Array$proto.segment = function(from, len) {
    if (len <= 0) { return getEmpty(); }
    var stop = from + len;
    var seq = this.slice((from>=0)?from:0, (stop>=0)?stop:0);
    return (seq.length > 0) ? ArraySequence(seq,this.$$targs$$||{Element$Iterable:{t:Anything}}) : getEmpty();
}
Array$proto.span = function(from, to) {
    if (from > to) {
        var arr = this.segment(to, from-to+1);
        arr.reverse();
        return arr.reifyCeylonType(this.$$targs$$);
    }
    return this.segment(from, to-from+1);
}
Array$proto.spanTo = function(to) {
    return to < 0 ? getEmpty() : this.span(0, to);
}
Array$proto.spanFrom = function(from) {
    return this.span(from, 0x7fffffff);
}
$defat(Array$proto, 'rest', function() {
    return this.length<=1 ? getEmpty() : ArraySequence(this.slice(1),this.$$targs$$||{Element$Iterable:{t:Anything}});
});
Array$proto.items = function(keys) {
    if (keys === undefined) return getEmpty();
    var seq = [];
    for (var i = 0; i < keys.size; i++) {
        var key = keys.$get(i);
        seq.push(this.$get(key));
    }
    return ArraySequence(seq,this.$$targs$$||{Element$Iterable:{t:Anything}});
}
$defat(Array$proto, 'keys', function(){ return TypeCategory(this, {t:Integer}); });
Array$proto.contains = function(elem) {
    for (var i=0; i<this.length; i++) {
        if (elem.equals(this[i])) {
            return true;
        }
    }
    return false;
}
Array$proto.iterator = function() {
    var $$$index$$$ = 0;
    var $$$arr$$$ = this;
    return new ComprehensionIterator(function() {
        return ($$$index$$$ === $$$arr$$$.length) ? getFinished() : $$$arr$$$[$$$index$$$++];
    }, this.$$targs$$);
}
Array$proto.copyTo = function(other, srcpos, dstpos, length) {
    if (length === undefined) length = this.size;
    if (srcpos === undefined) srcpos = 0;
    if (dstpos === undefined) dstpos = 0;
    var endpos = srcpos+length;
    //TODO validate range?
    for (var i=srcpos; i<endpos; i++) {
        other[dstpos]=this[i];
        dstpos++;
    }
}
Array$proto.shorterThan = function(len) {
  return this.size < len;
}
Array$proto.shorterThan.$crtmm$={mod:$CCMM$,d:['ceylon.language','Iterable','$m','shorterThan']};
Array$proto.longerThan = function(len) {
  return this.size > len;
}
Array$proto.longerThan.$crtmm$={mod:$CCMM$,d:['ceylon.language','Iterable','$m','longerThan']};

exports.arrayOfSize=function(size, elem, $$$mptypes) {
    if (size > 0) {
        var elems = [];
        for (var i = 0; i < size; i++) {
            elems.push(elem);
        }
        elems.$$targs$$=$$$mptypes;
        return elems;
    } else return [];
}
exports.arrayOfSize.$crtmm$={$an:function(){return[shared()];},mod:$CCMM$,d:['ceylon.language','arrayOfSize']};

function TypeCategory(seq, type) {
    var that = new TypeCategory.$$;
    that.type = type;
    that.seq = seq;
    return that;
}
initTypeProto(TypeCategory, 'ceylon.language::TypeCategory', $init$Basic(), Category);
var TypeCategory$proto = TypeCategory.$$.prototype;
TypeCategory$proto.contains = function(k) {
    return $is(k, this.type) && this.seq.defines(k);
}

function SequenceBuilder($$targs$$,that) {
    if(that===undefined)that=new SequenceBuilder.$$;
    that.seq = [];
    that.$$targs$$=$$targs$$;
    return that;
}
SequenceBuilder.$crtmm$=function(){return{$ps:[],$an:function(){return[shared()];},
  $tp:{Element$SequenceBuilder:{}}, mod:$CCMM$,d:['ceylon.language','SequenceBuilder']};}

initTypeProto(SequenceBuilder, 'ceylon.language::SequenceBuilder', $init$Basic());
var SequenceBuilder$proto = SequenceBuilder.$$.prototype;
$defat(SequenceBuilder$proto, 'sequence', function() {
    return (this.seq.length > 0) ? ArraySequence(this.seq,{Element$Iterable:this.$$targs$$.Element$SequenceBuilder}) : getEmpty();
},undefined,function(){return{
  $t:{t:Sequential,a:{Element$Sequential:'Element$SequenceBuilder'}},mod:$CCMM$,d:['ceylon.language','SequenceBuilder','$at','sequence']};});
SequenceBuilder$proto.append=function(e){
  this.seq.push(e);
  return this;
}
SequenceBuilder$proto.appendAll = function(/*Iterable*/arr) {
    if (arr === undefined) return;
    var iter = arr.iterator();
    var e; while ((e = iter.next()) !== getFinished()) {
        this.seq.push(e);
    }
    return this;
}
$defat(SequenceBuilder$proto, 'size', function(){ return this.seq.length; },undefined,function(){return{
  $t:{t:Integer},mod:$CCMM$,d:['ceylon.language','SequenceBuilder','$at','size']
};});
$defat(SequenceBuilder$proto, 'empty', function() { return this.seq.length===0 },function(){return{
  $t:{t:Boolean$},mod:$CCMM$,d:['ceylon.language','SequenceBuilder','$at','empty']
};});

function SequenceAppender(other, $$targs$$,that) {
    if (that===undefined)that=new SequenceAppender.$$;
    SequenceBuilder({Element$SequenceBuilder:$$targs$$.Element$SequenceAppender},that);
    that.appendAll(other);
    return that;
}
SequenceAppender.$crtmm$=function(){return{$ps:[{$nm:'elements',$t:{t:Sequence,a:{Element$Sequence:'Element$SequenceAppender'}},$mt:'prm'}],$an:function(){return[shared()];},
  'super':{t:SequenceBuilder,a:{Element$SequenceBuilder:'Element$SequenceAppender'}},$tp:{Element$SequenceAppender:{}},mod:$CCMM$,d:['ceylon.language','SequenceAppender']};}

initTypeProto(SequenceAppender, 'ceylon.language::SequenceAppender', SequenceBuilder);

exports.Sequence=Sequence;
exports.SequenceBuilder=SequenceBuilder;
exports.SequenceAppender=SequenceAppender;
exports.ArraySequence=ArraySequence;

//for sequenced enumerations
function $sarg(elems,spread,$$targs$$){
  $init$sarg();
  that=new $sarg.$$;
  set_type_args(that,$$targs$$);
  Iterable({Element$Iterable:$$targs$$.T$LazyIterable,Absent$Iterable:{t:Null}},that);
  add_type_arg(that,'Absent$Iterable',{t:Null});
  that.e=elems;
  that.s=spread;
  return that;
}
$sarg.$crtmm$=function(){return{mod:$CCMM$,'super':{t:Basic},$ps:[],$tp:{T$LazyIterable:{'var':'out'}},satisfies:[{t:Iterable,a:{Element$Iterable:'T$LazyIterable',Absent$Iterable:{t:Null}}}],$an:function(){return[shared()];},d:['$','LazyIterable']};};
exports.$sarg=$sarg;
function $init$sarg(){if($sarg.$$===undefined){
  initTypeProto($sarg,'ceylon.language::LazyIterable',Basic,Iterable);
  (function(that){
    that.iterator=function (){
      var sarg=this;
      //ObjectDef it at caca.ceylon (13:4-15:4)
      function iter($$targs$$){
        var $$4=new iter.$$;
        $$4.$$outer=sarg;
        $$4.$$targs$$=$$targs$$;
        Iterator({Element$Iterator:sarg.$$targs$$.T$LazyIterable},$$4);
        $$4.i=0;
        return $$4;
      };iter.$crtmm$=function(){return{mod:$CCMM$,'super':{t:Basic},$cont:iterator,satisfies:[{t:Iterator,a:{Element$Iterator:'T$LazyIterable'}}],d:['$','LazyIterable','$m','iterator','$o','it']};};
      if(iter.$$===undefined){
        initTypeProto(iter,'LazyIterable.it',Basic,Iterator);
        iter.$$.prototype.next=function(){
          if (this.sp)return this.sp.next();
          var e=sarg.e(this.i);
          if (e===getFinished() && sarg.s) {
            this.sp=sarg.s().iterator();
            e=this.sp.next();
          } else {
            this.i++;
          }
          return e;
        };
        iter.$$.prototype.next.$crtmm$=function(){return{mod:$CCMM$,$t:{t:'u',l:['T$LazyIterable',{t:Finished}]},$ps:[],$cont:iter,$an:function(){return[shared(),actual()];},d:['$','LazyIterable','$m','iterator','$o','it','$m','next']};};
      }
      return iter({Element$Iterator:sarg.$$targs$$.T$LazyIterable});
    };
    that.iterator.$crtmm$=function(){return{mod:$CCMM$,$t:{t:Iterator,a:{Element$Iterator:'T$LazyIterable'}},$ps:[],$cont:$sarg,$an:function(){return[shared(),actual()];},d:['$','LazyIterable','$m','iterator']};};
  })($sarg.$$.prototype);
}
return $sarg;
}
$init$sarg();
exports.$init$sarg=$init$sarg;
$init$sarg();

<|endoftext|>


<commit_before>/*
 * ext-server_opensave.js
 *
 * Licensed under the Apache License, Version 2
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */

svgEditor.addExtension("server_opensave", {
	callback: function() {

		var save_svg_action = 'extensions/filesave.php';
		var save_png_action = 'extensions/filesave.php';

		// Create upload target (hidden iframe)
		var target = $('<iframe name="output_frame" src="#"/>').hide().appendTo('body');

		svgEditor.setCustomHandlers({
			save: function(win, data) {
				var svg = "<?xml version='1.0'?>\n" + data;

				var title = svgCanvas.getDocumentTitle();
				var filename = title.replace(/[^a-z0-9\.\_\-]+/gi, '_');

				var form = $('<form>').attr({
					method: 'post',
					action: save_svg_action,
					target: 'output_frame'
				})	.append('<input type="hidden" name="output_svg" value="' + encodeURI(svg) + '">')
					.append('<input type="hidden" name="filename" value="' + filename + '">')
					.appendTo('body')
					.submit().remove();
			},
			pngsave: function(win, data) {
				var issues = data.issues;

				if(!$('#export_canvas').length) {
					$('<canvas>', {id: 'export_canvas'}).hide().appendTo('body');
				}
				var c = $('#export_canvas')[0];

				c.width = svgCanvas.contentW;
				c.height = svgCanvas.contentH;
				canvg(c, data.svg);

				// Timeout to allow canvg to run a bit
				setTimeout(function() {
					var datauri = c.toDataURL('image/png');

					var uiStrings = svgEditor.uiStrings;
					var note = '';

					// Check if there's issues
					if(issues.length) {
						var pre = "\n \u2022 ";
						note += ("\n\n" + pre + issues.join(pre));
					}

					if(note.length) {
						alert(note);
					}

					var title = svgCanvas.getDocumentTitle();
					var filename = title.replace(/[^a-z0-9\.\_\-]+/gi, '_');

					var form = $('<form>').attr({
						method: 'post',
						action: save_png_action,
						target: 'output_frame'
					})	.append('<input type="hidden" name="output_png" value="' + datauri + '">')
						.append('<input type="hidden" name="filename" value="' + filename + '">')
						.appendTo('body')
						.submit().remove();
				}, 1000);

			}
		});

		// Do nothing if client support is found
		if(window.FileReader) return;

		var cancelled = false;

		// Change these to appropriate script file
		var open_svg_action = 'extensions/fileopen.php?type=load_svg';
		var import_svg_action = 'extensions/fileopen.php?type=import_svg';
		var import_img_action = 'extensions/fileopen.php?type=import_img';

		// Set up function for PHP uploader to use
		svgEditor.processFile = function(str64, type) {
			if(cancelled) {
				cancelled = false;
				return;
			}

			$('#dialog_box').hide();

			if(type != 'import_img') {
				var xmlstr = svgCanvas.Utils.decode64(str64);
			}

			switch ( type ) {
				case 'load_svg':
					svgCanvas.clear();
					svgCanvas.setSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_svg':
					svgCanvas.importSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_img':
					svgCanvas.setGoodImage(str64);
					break;
			}
		}

		// Create upload form
		var open_svg_form = $('<form>');
		open_svg_form.attr({
			enctype: 'multipart/form-data',
			method: 'post',
			action: open_svg_action,
			target: 'output_frame'
		});

		// Create import form
		var import_svg_form = open_svg_form.clone().attr('action', import_svg_action);

		// Create image form
		var import_img_form = open_svg_form.clone().attr('action', import_img_action);

		// It appears necessory to rebuild this input every time a file is
		// selected so the same file can be picked and the change event can fire.
		function rebuildInput(form) {
			form.empty();
			var inp = $('<input type="file" name="svg_file">').appendTo(form);

			function submit() {
				// This submits the form, which returns the file data using svgEditor.uploadSVG
				form.submit();

				rebuildInput(form);
				$.process_cancel("Uploading...", function() {
					cancelled = true;
					$('#dialog_box').hide();
				});
			}

			if(form[0] == open_svg_form[0]) {
				inp.change(function() {
					// This takes care of the "are you sure" dialog box
					svgEditor.openPrep(function(ok) {
						if(!ok) {
							rebuildInput(form);
							return;
						}
						submit();
					});
				});
			} else {
				inp.change(function() {
					// This submits the form, which returns the file data using svgEditor.uploadSVG
					submit();
				});
			}
		}

		// Create the input elements
		rebuildInput(open_svg_form);
		rebuildInput(import_svg_form);
		rebuildInput(import_img_form);

		// Add forms to buttons
		$("#tool_open").show().prepend(open_svg_form);
		$("#tool_import").show().prepend(import_svg_form);
		$("#tool_image").prepend(import_img_form);
	}
});

<commit_msg>Added canvg callback to opensave extension<commit_after>/*
 * ext-server_opensave.js
 *
 * Licensed under the Apache License, Version 2
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */

svgEditor.addExtension("server_opensave", {
	callback: function() {

		var save_svg_action = 'extensions/filesave.php';
		var save_png_action = 'extensions/filesave.php';

		// Create upload target (hidden iframe)
		var target = $('<iframe name="output_frame" src="#"/>').hide().appendTo('body');

		svgEditor.setCustomHandlers({
			save: function(win, data) {
				var svg = "<?xml version='1.0'?>\n" + data;

				var title = svgCanvas.getDocumentTitle();
				var filename = title.replace(/[^a-z0-9\.\_\-]+/gi, '_');

				var form = $('<form>').attr({
					method: 'post',
					action: save_svg_action,
					target: 'output_frame'
				})	.append('<input type="hidden" name="output_svg" value="' + encodeURI(svg) + '">')
					.append('<input type="hidden" name="filename" value="' + filename + '">')
					.appendTo('body')
					.submit().remove();
			},
			pngsave: function(win, data) {
				var issues = data.issues;

				if(!$('#export_canvas').length) {
					$('<canvas>', {id: 'export_canvas'}).hide().appendTo('body');
				}
				var c = $('#export_canvas')[0];

				c.width = svgCanvas.contentW;
				c.height = svgCanvas.contentH;
				canvg(c, data.svg, {renderCallback: function() {
					var datauri = c.toDataURL('image/png');

					var uiStrings = svgEditor.uiStrings;
					var note = '';

					// Check if there's issues
					if(issues.length) {
						var pre = "\n \u2022 ";
						note += ("\n\n" + pre + issues.join(pre));
					}

					if(note.length) {
						alert(note);
					}

					var title = svgCanvas.getDocumentTitle();
					var filename = title.replace(/[^a-z0-9\.\_\-]+/gi, '_');

					var form = $('<form>').attr({
						method: 'post',
						action: save_png_action,
						target: 'output_frame'
					})	.append('<input type="hidden" name="output_png" value="' + datauri + '">')
						.append('<input type="hidden" name="filename" value="' + filename + '">')
						.appendTo('body')
						.submit().remove();
				}});

			}
		});

		// Do nothing if client support is found
		if(window.FileReader) return;

		var cancelled = false;

		// Change these to appropriate script file
		var open_svg_action = 'extensions/fileopen.php?type=load_svg';
		var import_svg_action = 'extensions/fileopen.php?type=import_svg';
		var import_img_action = 'extensions/fileopen.php?type=import_img';

		// Set up function for PHP uploader to use
		svgEditor.processFile = function(str64, type) {
			if(cancelled) {
				cancelled = false;
				return;
			}

			$('#dialog_box').hide();

			if(type != 'import_img') {
				var xmlstr = svgCanvas.Utils.decode64(str64);
			}

			switch ( type ) {
				case 'load_svg':
					svgCanvas.clear();
					svgCanvas.setSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_svg':
					svgCanvas.importSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_img':
					svgCanvas.setGoodImage(str64);
					break;
			}
		}

		// Create upload form
		var open_svg_form = $('<form>');
		open_svg_form.attr({
			enctype: 'multipart/form-data',
			method: 'post',
			action: open_svg_action,
			target: 'output_frame'
		});

		// Create import form
		var import_svg_form = open_svg_form.clone().attr('action', import_svg_action);

		// Create image form
		var import_img_form = open_svg_form.clone().attr('action', import_img_action);

		// It appears necessory to rebuild this input every time a file is
		// selected so the same file can be picked and the change event can fire.
		function rebuildInput(form) {
			form.empty();
			var inp = $('<input type="file" name="svg_file">').appendTo(form);

			function submit() {
				// This submits the form, which returns the file data using svgEditor.uploadSVG
				form.submit();

				rebuildInput(form);
				$.process_cancel("Uploading...", function() {
					cancelled = true;
					$('#dialog_box').hide();
				});
			}

			if(form[0] == open_svg_form[0]) {
				inp.change(function() {
					// This takes care of the "are you sure" dialog box
					svgEditor.openPrep(function(ok) {
						if(!ok) {
							rebuildInput(form);
							return;
						}
						submit();
					});
				});
			} else {
				inp.change(function() {
					// This submits the form, which returns the file data using svgEditor.uploadSVG
					submit();
				});
			}
		}

		// Create the input elements
		rebuildInput(open_svg_form);
		rebuildInput(import_svg_form);
		rebuildInput(import_img_form);

		// Add forms to buttons
		$("#tool_open").show().prepend(open_svg_form);
		$("#tool_import").show().prepend(import_svg_form);
		$("#tool_image").prepend(import_img_form);
	}
});

<|endoftext|>


<commit_before>/** map initialisation JS file **/

var initialLoc;
var browserSupportFlag = new Boolean();
var EventID = false;  // used as a flag for the boundary changes

var airportList = new Array();
var airportsLoaded = {};
var flightList = new Array();

function toRad (degrees) {
  radians = (2 * Math.PI * degrees)/360;
  return radians;

}

function toDeg(radians) {
   degrees = 360 * radians/(2 * Math.PI);
   return degrees;
}

function initialize() {
    // this function initialises the map to the starting position and zoom
    // to the div in the page.

    // these are the inline functions

    function noGeoHandler() {
      // this function deals with if the user either does't have or
      // doesn't allow the geolocation to fire.
      // no geolocation data so just go world view

      browserSupportFlag = false;
      var worldView = new google.maps.LatLng(0,150);
      map.setZoom(2);
      map.setCenter(worldView);
    }

    function boundaryChange() {
        // this function deals with a boundary change and will do things based
        // on that event

        //console.log("boundary_change");
       // update the data area with the boundary details:
       var bounds = map.getBounds();
       var sw = bounds.getSouthWest();
       var ne = bounds.getNorthEast()

       // hit the ajax call for the airports and we'll retrieve them:
       var airporturl = '/api/airport/list/' + sw.lat() + '/' + sw.lng() +
                                          '/' + ne.lat() + '/' + ne.lng() + "/";

        var flighturl = '/api/flight/list/' + sw.lat() + '/' + sw.lng() +
                                          '/' + ne.lat() + '/' + ne.lng() + "/";

        $("#map_data").text(airporturl);

       $.getJSON(airporturl, null, DisplayAirports);
       $.getJSON(flighturl, null, DisplayFlights);

        CleanupBounding();

    }

    function DisplayAirports(data) {
      // this function plots the airports on the map.

       for (i=0; i< data.length; i++) {
         item = data[i];

         if (! airportsLoaded[item.pk]) {

           if (item.fields["iata_code"] != null) {
              lat = item.fields["latitude"];
              lng = item.fields["longitude"];
              n = item.fields["name"];

              var marker = new google.maps.Marker({
                  position: new google.maps.LatLng(lat, lng),
                  map: map,
                  title:n,
                  icon: airportimage
              });
           }
           airportsLoaded[item.pk] = marker;
        }

       }

    }

    function DisplayFlights(data) {
      // this function plots the flights on the map

      // this is a demo to get it working for the Mel -> BNE flight.

      mel = new google.maps.LatLng(-37.67333333333333, 144.84333333333333);
      lax = new google.maps.LatLng(33.942499999999995, -118.40805555555556);

      var flightCoords = [
        // mel then syd
        mel, lax
      ];

      var flightPath = new google.maps.Polyline({
        path: flightCoords,
        geodesic: true,
        strokeColor: "#b10000",
        strokeOpacity: 0.2,
        strokeWeight: 3
      });

      flightPath.setMap(map);

      //alert(distance(mel, lax) / 2);

      midpoint = mel.midpointLocation(lax, distance(mel, lax) * 0.80);
      var marker = new google.maps.Marker({
                  position: midpoint.LatLng,
                  map: map,
                  title:"midpoint"
              });

    }

    function distance(point1, point2) {
          lat1 = point1.lat();
          lat2 = point2.lat();
          lon1 = point1.lng();
          lon2 = point2.lng();
	        var R = 6371000; // km (change this constant to get miles)
	        var dLat = (lat2-lat1) * Math.PI / 180;
	        var dLon = (lon2-lon1) * Math.PI / 180;
	        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
	            Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
	            Math.sin(dLon/2) * Math.sin(dLon/2);
	        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	        var d = R * c;
	        return d;
    }

    google.maps.LatLng.prototype.midpointLocation = function(point, distance) {
       var lat1 = toRad(this.lat());
       var lon1 = toRad(this.lng());
       var lat2 = toRad(point.lat());
       var lon2 = toRad(point.lng());
       var dLon = (toRad(point.lng()) - toRad(this.lng()));

       // Find the bearing from this point to the next.
       var brng = Math.atan2(Math.sin(dLon) * Math.cos(lat2),
                             Math.cos(lat1) * Math.sin(lat2) -
                             Math.sin(lat1) * Math.cos(lat2) *
                             Math.cos(dLon));

       var angDist = distance / 6371000;  // Earth's radius.

       // Calculate the destination point, given the source and bearing.
       lat2 = Math.asin(Math.sin(lat1) * Math.cos(angDist) +
                        Math.cos(lat1) * Math.sin(angDist) *
                        Math.cos(brng));

       lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(angDist) *
                                Math.cos(lat1),
                                Math.cos(angDist) - Math.sin(lat1) *
                                Math.sin(lat2));

       if (isNaN(lat2) || isNaN(lon2)) return null;

        midpointObject  = {};
        midpointObject.LatLng = new google.maps.LatLng(toDeg(lat2), toDeg(lon2));

       return midpointObject;
    }

    function CleanupBounding() {
      // this function removes all of the items that are outside of the bounding
      // area of the map.

      bounds = map.getBounds();

      for (k in airportsLoaded) {

        if (! bounds.contains(airportsLoaded[k].getPosition())) {
          // remove the point off the map
          airportsLoaded[k].setMap(null);

          // remove the point from the array
          delete airportsLoaded[k]; // = null
        }
      }

      /**allist=0;
       for (k in airportsLoaded){
        allist++;
      }**/
      //$("#map_data").text("Airports: " + allist + " // ");

    }

    // THIS IS WHERE WE START THE ACTUAL INIT OF THE MAP ETC

    var airportimage = "/site_media/img/airport.png";

    var mapOptions = {
        zoom: 4,
        mapTypeControl: false,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    }

    var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    // Try W3C Geolocation (Preferred)
    if(navigator.geolocation) {
        browserSupportFlag = true;
        // use the geo log and depending and if the user allows the service
        // to work and it returns properly or they choose not to or it fails
        // for whatever reason call one function or the other to set pass or
        // fail.
        navigator.geolocation.getCurrentPosition(
            function(position) {
                initialLoc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                map.setCenter(initialLoc);
            },
            function() {
                noGeoHandler();
            });
    } else {
        // if geo log W3C stylee doesn't work then we're not bothering with
        // other styles for the moment. GL W3C has enough coverage.
        noGeoHandler();

    }

    // now we set up event handlers to deal with the changes
    google.maps.event.addListener(map, 'bounds_changed',
      function() {
        if (EventID) {
          clearTimeout(EventID);
          //console.log("cleared");
        }
        EventID = setTimeout(boundaryChange, 1000);
      }
    );

}

function loadGMapScript() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
    document.body.appendChild(script);
}

<commit_msg>plane on the flight map<commit_after>/** map initialisation JS file **/

var initialLoc;
var browserSupportFlag = new Boolean();
var EventID = false;  // used as a flag for the boundary changes

var airportList = new Array();
var airportsLoaded = {};
var flightList = new Array();

function toRad (degrees) {
  radians = (2 * Math.PI * degrees)/360;
  return radians;

}

function toDeg(radians) {
   degrees = 360 * radians/(2 * Math.PI);
   return degrees;
}

function initialize() {
    // this function initialises the map to the starting position and zoom
    // to the div in the page.

    // these are the inline functions

    function noGeoHandler() {
      // this function deals with if the user either does't have or
      // doesn't allow the geolocation to fire.
      // no geolocation data so just go world view

      browserSupportFlag = false;
      var worldView = new google.maps.LatLng(0,150);
      map.setZoom(2);
      map.setCenter(worldView);
    }

    function boundaryChange() {
        // this function deals with a boundary change and will do things based
        // on that event

        //console.log("boundary_change");
       // update the data area with the boundary details:
       var bounds = map.getBounds();
       var sw = bounds.getSouthWest();
       var ne = bounds.getNorthEast()

       // hit the ajax call for the airports and we'll retrieve them:
       var airporturl = '/api/airport/list/' + sw.lat() + '/' + sw.lng() +
                                          '/' + ne.lat() + '/' + ne.lng() + "/";

        var flighturl = '/api/flight/list/' + sw.lat() + '/' + sw.lng() +
                                          '/' + ne.lat() + '/' + ne.lng() + "/";

        $("#map_data").text(airporturl);

       $.getJSON(airporturl, null, DisplayAirports);
       $.getJSON(flighturl, null, DisplayFlights);

        CleanupBounding();

    }

    function DisplayAirports(data) {
      // this function plots the airports on the map.

       for (i=0; i< data.length; i++) {
         item = data[i];

         if (! airportsLoaded[item.pk]) {

           if (item.fields["iata_code"] != null) {
              lat = item.fields["latitude"];
              lng = item.fields["longitude"];
              n = item.fields["name"];

              var marker = new google.maps.Marker({
                  position: new google.maps.LatLng(lat, lng),
                  map: map,
                  title:n,
                  icon: airportimage
              });
           }
           airportsLoaded[item.pk] = marker;
        }

       }

    }

    function DisplayFlights(data) {
      // this function plots the flights on the map

      // this is a demo to get it working for the Mel -> BNE flight.

      mel = new google.maps.LatLng(-37.67333333333333, 144.84333333333333);
      lax = new google.maps.LatLng(33.942499999999995, -118.40805555555556);

      var flightCoords = [
        // mel then syd
        mel, lax
      ];

      var flightPath = new google.maps.Polyline({
        path: flightCoords,
        geodesic: true,
        strokeColor: "#b10000",
        strokeOpacity: 0.2,
        strokeWeight: 3
      });

      flightPath.setMap(map);

      //alert(distance(mel, lax) / 2);

      midpoint = mel.midpointLocation(lax, distance(mel, lax) * 0.80);
      var marker = new google.maps.Marker({
                  position: midpoint.LatLng,
                  map: map,
                  icon: planeimage
              });

    }

    function distance(point1, point2) {
          lat1 = point1.lat();
          lat2 = point2.lat();
          lon1 = point1.lng();
          lon2 = point2.lng();
	        var R = 6371000; // km (change this constant to get miles)
	        var dLat = (lat2-lat1) * Math.PI / 180;
	        var dLon = (lon2-lon1) * Math.PI / 180;
	        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
	            Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
	            Math.sin(dLon/2) * Math.sin(dLon/2);
	        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	        var d = R * c;
	        return d;
    }

    google.maps.LatLng.prototype.midpointLocation = function(point, distance) {
       var lat1 = toRad(this.lat());
       var lon1 = toRad(this.lng());
       var lat2 = toRad(point.lat());
       var lon2 = toRad(point.lng());
       var dLon = (toRad(point.lng()) - toRad(this.lng()));

       // Find the bearing from this point to the next.
       var brng = Math.atan2(Math.sin(dLon) * Math.cos(lat2),
                             Math.cos(lat1) * Math.sin(lat2) -
                             Math.sin(lat1) * Math.cos(lat2) *
                             Math.cos(dLon));

       var angDist = distance / 6371000;  // Earth's radius.

       // Calculate the destination point, given the source and bearing.
       lat2 = Math.asin(Math.sin(lat1) * Math.cos(angDist) +
                        Math.cos(lat1) * Math.sin(angDist) *
                        Math.cos(brng));

       lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(angDist) *
                                Math.cos(lat1),
                                Math.cos(angDist) - Math.sin(lat1) *
                                Math.sin(lat2));

       if (isNaN(lat2) || isNaN(lon2)) return null;

        midpointObject  = {};
        midpointObject.LatLng = new google.maps.LatLng(toDeg(lat2), toDeg(lon2));

       return midpointObject;
    }

    function CleanupBounding() {
      // this function removes all of the items that are outside of the bounding
      // area of the map.

      bounds = map.getBounds();

      for (k in airportsLoaded) {

        if (! bounds.contains(airportsLoaded[k].getPosition())) {
          // remove the point off the map
          airportsLoaded[k].setMap(null);

          // remove the point from the array
          delete airportsLoaded[k]; // = null
        }
      }

      /**allist=0;
       for (k in airportsLoaded){
        allist++;
      }**/
      //$("#map_data").text("Airports: " + allist + " // ");

    }

    // THIS IS WHERE WE START THE ACTUAL INIT OF THE MAP ETC

    var airportimage = "/site_media/img/airport.png";
    var planeimage = "/site_media/img/plane.png";

    var mapOptions = {
        zoom: 4,
        mapTypeControl: false,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    }

    var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    // Try W3C Geolocation (Preferred)
    if(navigator.geolocation) {
        browserSupportFlag = true;
        // use the geo log and depending and if the user allows the service
        // to work and it returns properly or they choose not to or it fails
        // for whatever reason call one function or the other to set pass or
        // fail.
        navigator.geolocation.getCurrentPosition(
            function(position) {
                initialLoc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                map.setCenter(initialLoc);
            },
            function() {
                noGeoHandler();
            });
    } else {
        // if geo log W3C stylee doesn't work then we're not bothering with
        // other styles for the moment. GL W3C has enough coverage.
        noGeoHandler();

    }

    // now we set up event handlers to deal with the changes
    google.maps.event.addListener(map, 'bounds_changed',
      function() {
        if (EventID) {
          clearTimeout(EventID);
          //console.log("cleared");
        }
        EventID = setTimeout(boundaryChange, 1000);
      }
    );

}

function loadGMapScript() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
    document.body.appendChild(script);
}

<|endoftext|>


<commit_before><commit_msg>test: add test for stylesheet<commit_after><|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var request = require('request')
var mongoose = require('mongoose')
var User = require('../lib/models/user')
var Repo = require('../lib/models/repo')
var Doclet = require('../lib/models/doclet')

mongoose.connect('mongodb://192.168.99.100/app', function () {
  User.remove({})
  Repo.remove({})
  Doclet.remove({})
})

var replayGitHubEvent = function (eventDir, done) {
  var payload = fs.readFileSync(path.join(__dirname, '../test/fixtures/events', eventDir, 'payload.json'))
  var headers = require(path.join(__dirname, '../test/fixtures/events', eventDir, 'headers.js'))
  request({
    url: 'http://192.168.99.100:3420/github/callback',
    method: headers.method,
    body: payload,
    headers: headers
  }, function () {})
}

var x = ['acme-push', 'acme-tag']

x.forEach(function (event) {
  replayGitHubEvent(event)
})
<commit_msg>fix paths for fixtures<commit_after>var fs = require('fs')
var path = require('path')
var request = require('request')
var mongoose = require('mongoose')
var User = require('../lib/models/user')
var Repo = require('../lib/models/repo')
var Doclet = require('../lib/models/doclet')

mongoose.connect('mongodb://192.168.99.100/app', function () {
  User.remove({})
  Repo.remove({})
  Doclet.remove({})
})

var replayGitHubEvent = function (eventDir, done) {
  var payload = fs.readFileSync(path.join(__dirname, '../fixtures/events', eventDir, 'payload.json'))
  var headers = require(path.join(__dirname, '../fixtures/events', eventDir, 'headers.js'))
  request({
    url: 'http://192.168.99.100:3420/github/callback',
    method: headers.method,
    body: payload,
    headers: headers
  }, function () {})
}

var x = ['acme-push', 'acme-tag']

x.forEach(function (event) {
  replayGitHubEvent(event)
})
<|endoftext|>


<commit_before>/* jshint -W117, -W030 */
describe('PeopleController', function() {
  var controller;
  var people = mockData.getMockPeople();

  beforeEach(function() {
    bard.appModule('app.people');
    bard.inject(this, '$controller','$q', '$rootScope','$state');

    var ds = {
      getPeople: function() {
        return $q.when(people);
      }
    };

    controller = $controller('PeopleController',{
      dataservice: ds
    });

  });

  it('should exist',function() {
    expect(controller).to.exist;
  });

  it('should have empty people array before activation',function() {
    expect(controller.people).to.exist;
  });

  describe('after activation', function() {
    beforeEach(function() {
      $rootScope.$apply();
    });

    it('selecting a person triggers a state change',function() {
      controller.goToPerson({id: 3});
      expect($state.current.name).to.equal('person');
    });

    it('should have people',function() {
      expect(controller.people).to.have.length.above(0);
    });

    it('should have mock people',function() {
      expect(controller.people).to.have.length(people.length);
    });

  });

});
<commit_msg>Only inject state in test that needs it.<commit_after>/* jshint -W117, -W030 */
describe('PeopleController', function() {
  var controller;
  var people = mockData.getMockPeople();

  beforeEach(function() {
    bard.appModule('app.people');
    bard.inject('$controller','$q', '$rootScope');

    var ds = {
      getPeople: function() {
        return $q.when(people);
      }
    };

    controller = $controller('PeopleController',{
      dataservice: ds
    });

  });

  it('should exist',function() {
    expect(controller).to.exist;
  });

  it('should have empty people array before activation',function() {
    expect(controller.people).to.exist;
  });

  describe('after activation', function() {
    beforeEach(function() {
      bard.inject('$state');
      $rootScope.$apply();
    });

    it('selecting a person triggers a state change',function() {
      controller.goToPerson({id: 3});
      expect($state.current.name).to.equal('person');
    });

    it('should have people',function() {
      expect(controller.people).to.have.length.above(0);
    });

    it('should have mock people',function() {
      expect(controller.people).to.have.length(people.length);
    });

  });

});
<|endoftext|>


<commit_before>angular.module('futurism')
    .factory('autoLogin', function($location, $rootScope, authService, session) {
        'use strict';

        var self = this;
        var removeListener;

        self.activate = function() {
            if(!removeListener) {
                removeListener = $rootScope.$on('event:auth-loginRequired', loginRequiredHandler);
            }
        };

        self.deactivate = function() {
            if(removeListener) {
                removeListener();
                removeListener = null;
            }
        };

        var loginRequiredHandler = function() {
            session.renew(function(error) {
                if(error) {
                    return $location.path('/error');
                }
                return authService.loginConfirmed(null);
            });
        };

        return self;
    });<commit_msg>fix session continueation on refresh<commit_after>angular.module('futurism')
    .factory('autoLogin', function($location, $rootScope, authService, session) {
        'use strict';

        var loginRequiredHandler = function() {
            session.renew(function(error) {
                if(error) {
                    return $location.path('/error');
                }
                return authService.loginConfirmed(null);
            });
        };

        var self = this;
        var removeListener;

        self.activate = function() {
            if(!removeListener) {
                removeListener = $rootScope.$on('event:auth-loginRequired', loginRequiredHandler);
            }
        };

        self.deactivate = function() {
            if(removeListener) {
                removeListener();
                removeListener = null;
            }
        };

        return self;
    });<|endoftext|>


<commit_before>import assert from 'assert';
import makeDebug from 'debug';
import { Service, helpers, createService } from 'mostly-feathers-mongoose';
import fp from 'mostly-func';
import path from 'path';
import { plural } from 'pluralize';

import defaultHooks from './document-hooks';
import { subDocumentEvents } from './document-events';
import { getParentAces } from '../../helpers';
import DocumentModel from '../../models/document-model';

const debug = makeDebug('playing:content-services:documents');

const defaultOptions = {
  name: 'documents'
};

class DocumentService extends Service {
  constructor(options) {
    options = Object.assign({}, defaultOptions, options);
    super(options);
  }

  setup(app) {
    super.setup(app);
    this.options.entities = app.get('entities');
    this.hooks(defaultHooks(this.options));
    subDocumentEvents(this.app, this.options);
  }

  find(params) {
    const type = fp.dotPath('query.type', params);
    if (fp.is(String, type) && type !== 'document') {
      return this.app.service(plural(type)).find(params);
    } else {
      return super.find(params).then(result => {
        return helpers.discriminatedFind(this.app, 'document', result, params, this.options);
      });
    }
  }

  get(id, params) {
    const type = fp.dotPath('query.type', params);
    if (fp.is(String, type) && type !== 'document') {
      return this.app.service(plural(type)).get(params);
    } else {
      return super.get(id, params).then(doc => {
        return helpers.discriminatedGet(this.app, 'document', doc, params);
      });
    }
  }

  create(data, params) {
    if (data.type && data.type !== 'document') {
      return this.app.service(plural(data.type)).create(data, params);
    } else {
      return super.create(data, params);
    }
  }

  update(id, data, params) {
    if (data.type && data.type !== 'document') {
      return this.app.service(plural(data.type)).update(id, data, params);
    } else {
      return super.update(id, data, params);
    }
  }

  patch(id, data, params) {
    if (data.type && data.type !== 'document') {
      return this.app.service(plural(data.type)).patch(id, data, params);
    } else {
      return super.patch(id, data, params);
    }
  }

  remove(id, params) {
    const type = fp.dotPath('query.type', params);
    if (fp.is(String, type) && type !== 'document') {
      return this.app.service(plural(type)).remove(id, params);
    } else {
      const more = params && fp.dotPath('query.more', params);
      if (more) {
        const moreIds = [id].concat(more.split(','));
        delete params.query.more;
        return Promise.all(moreIds.map(id => super.remove(id, params)));
      } else {
        return super.remove(id, params);
      }
    }
  }

  _tag(id, data, params, doc) {
    assert(data.tags, 'data.tags not provided.');

    const svcTags = this.app.service('tags');

    let tags = fp.union(doc.tags || [], data.tags);
    return Promise.all([
      super.patch(doc.id, { tags }, params),
      data.tags.map((tag) => svcTags.action('upsert').create({
        id: tag.toLowerCase(),
        label: tag
      }))
    ]).then(([docs, tags]) => docs);
  }

  _untag(id, data, params, doc) {
    assert(data.tags, 'data.tags not provided.');

    let tags = fp.without(data.tags, doc.tags || []);
    return super.patch(doc.id, { tags }, params);
  }

  _copyDocument(id, data, params, target) {
    assert(data.documents, 'data.documents not provided.');
    assert(data.target, 'data.target not provided.');
    debug('copyDocument target', target.id, data.documents);

    const copyDoc = (id) => {
      return this.get(id).then((doc) => {
        let service = plural(doc.type || 'document');
        let clone = fp.omit(['id', 'metadata', 'parent', 'path', 'ancestors', 'createdAt', 'updatedAt', 'destroyedAt'], doc);
        clone.parent = target.id;
        return this.app.service(service).create(clone);
      });
    };

    return Promise.all(data.documents.map(copyDoc));
  }

  _moveDocument(id, data, params, target) {
    assert(data.documents, 'data.documents not provided.');
    assert(data.target, 'data.target not provided.');
    debug('moveDocument target', target.id, data.documents);

    const moveDoc = (id) => {
      return this.get(id).then((doc) => {
        let service = plural(doc.type || 'document');
        let data = {
          parent: target.id,
          path: path.resolve(target.path, path.basename(doc.path)),
          type: doc.type
        };
        return this.app.service(service).patch(doc.id, data);
      });
    };

    return Promise.all(data.documents.map(moveDoc));
  }

  _lockDocument(id, data, params, doc) {
    return super.patch(doc.id, {
      locker: data.creator,
      lockedAt: new Date()
    });
  }

  _unlockDocument(id, data, params, doc) {
    return super.patch(doc.id, {
      locker: null,
      lockedAt: null
    });
  }

  _addPermission(id, data, params, doc) {
    assert(doc, 'target document is not exists.');
    assert(data.action, 'data.action is not provided.');
    assert(data.user, 'data.user is not provided.');

    const svcPermissions = this.app.service('user-permissions');
    return svcPermissions.create({
      actions: [data.action],
      subject: `${doc.type}:${doc.id}`,
      user: data.user,
      role: data.role,
      creator: params.user.id,
      begin: data.begin,
      end: data.end
    });
  }

  _replacePermission(id, data, params, doc) {
    return this.addPermission(id, data, params, doc);
  }

  _removePermission(id, data, params, doc) {
    assert(doc, 'target document is not exists.');
    assert(data.action, 'data.action is not provided');
    assert(data.user, 'data.user is not provided');

    const svcPermissions = this.app.service('user-permissions');
    return svcPermissions.remove(null, {
      query: {
        actions: [data.action],
        subject: `${doc.type}:${doc.id}`,
        user: data.user,
        role: data.role
      },
      $multi: true
    });
  }

  _blockPermissionInheritance(id, data, params, doc) {
    assert(doc, 'target document is not exists.');

    // copy inherited permissions
    const svcPermissions = this.app.service('user-permissions');
    return getParentAces(this.app, [doc], '*').then(inheritedAces => {
      if (inheritedAces && inheritedAces[doc.id]) {
        return Promise.all(fp.map(ace => {
          ace.subject = `${doc.type}:${doc.id}`;
          ace.creator = params.user.id;
          return svcPermissions.create(ace);
        }, inheritedAces[doc.id]));
      }
    }).then(results => {
      return super.patch(id, { inherited: false }, params);
    });
  }

  _unblockPermissionInheritance(id, data, params, doc) {
    assert(doc, 'target document is not exists.');
    return super.patch(id, { inherited: true }, params);
  }
}

export default function init(app, options) {
  options = Object.assign({ ModelName: 'document' }, options);
  return createService(app, DocumentService, DocumentModel, options);
}

init.Service = DocumentService;
<commit_msg>unblock inherited permission will remove copied permissions<commit_after>import assert from 'assert';
import makeDebug from 'debug';
import { Service, helpers, createService } from 'mostly-feathers-mongoose';
import fp from 'mostly-func';
import path from 'path';
import { plural } from 'pluralize';

import defaultHooks from './document-hooks';
import { subDocumentEvents } from './document-events';
import { getParentAces } from '../../helpers';
import DocumentModel from '../../models/document-model';

const debug = makeDebug('playing:content-services:documents');

const defaultOptions = {
  name: 'documents'
};

class DocumentService extends Service {
  constructor(options) {
    options = Object.assign({}, defaultOptions, options);
    super(options);
  }

  setup(app) {
    super.setup(app);
    this.options.entities = app.get('entities');
    this.hooks(defaultHooks(this.options));
    subDocumentEvents(this.app, this.options);
  }

  find(params) {
    const type = fp.dotPath('query.type', params);
    if (fp.is(String, type) && type !== 'document') {
      return this.app.service(plural(type)).find(params);
    } else {
      return super.find(params).then(result => {
        return helpers.discriminatedFind(this.app, 'document', result, params, this.options);
      });
    }
  }

  get(id, params) {
    const type = fp.dotPath('query.type', params);
    if (fp.is(String, type) && type !== 'document') {
      return this.app.service(plural(type)).get(params);
    } else {
      return super.get(id, params).then(doc => {
        return helpers.discriminatedGet(this.app, 'document', doc, params);
      });
    }
  }

  create(data, params) {
    if (data.type && data.type !== 'document') {
      return this.app.service(plural(data.type)).create(data, params);
    } else {
      return super.create(data, params);
    }
  }

  update(id, data, params) {
    if (data.type && data.type !== 'document') {
      return this.app.service(plural(data.type)).update(id, data, params);
    } else {
      return super.update(id, data, params);
    }
  }

  patch(id, data, params) {
    if (data.type && data.type !== 'document') {
      return this.app.service(plural(data.type)).patch(id, data, params);
    } else {
      return super.patch(id, data, params);
    }
  }

  remove(id, params) {
    const type = fp.dotPath('query.type', params);
    if (fp.is(String, type) && type !== 'document') {
      return this.app.service(plural(type)).remove(id, params);
    } else {
      const more = params && fp.dotPath('query.more', params);
      if (more) {
        const moreIds = [id].concat(more.split(','));
        delete params.query.more;
        return Promise.all(moreIds.map(id => super.remove(id, params)));
      } else {
        return super.remove(id, params);
      }
    }
  }

  _tag(id, data, params, doc) {
    assert(data.tags, 'data.tags not provided.');

    const svcTags = this.app.service('tags');

    let tags = fp.union(doc.tags || [], data.tags);
    return Promise.all([
      super.patch(doc.id, { tags }, params),
      data.tags.map((tag) => svcTags.action('upsert').create({
        id: tag.toLowerCase(),
        label: tag
      }))
    ]).then(([docs, tags]) => docs);
  }

  _untag(id, data, params, doc) {
    assert(data.tags, 'data.tags not provided.');

    let tags = fp.without(data.tags, doc.tags || []);
    return super.patch(doc.id, { tags }, params);
  }

  _copyDocument(id, data, params, target) {
    assert(data.documents, 'data.documents not provided.');
    assert(data.target, 'data.target not provided.');
    debug('copyDocument target', target.id, data.documents);

    const copyDoc = (id) => {
      return this.get(id).then((doc) => {
        let service = plural(doc.type || 'document');
        let clone = fp.omit(['id', 'metadata', 'parent', 'path', 'ancestors', 'createdAt', 'updatedAt', 'destroyedAt'], doc);
        clone.parent = target.id;
        return this.app.service(service).create(clone);
      });
    };

    return Promise.all(data.documents.map(copyDoc));
  }

  _moveDocument(id, data, params, target) {
    assert(data.documents, 'data.documents not provided.');
    assert(data.target, 'data.target not provided.');
    debug('moveDocument target', target.id, data.documents);

    const moveDoc = (id) => {
      return this.get(id).then((doc) => {
        let service = plural(doc.type || 'document');
        let data = {
          parent: target.id,
          path: path.resolve(target.path, path.basename(doc.path)),
          type: doc.type
        };
        return this.app.service(service).patch(doc.id, data);
      });
    };

    return Promise.all(data.documents.map(moveDoc));
  }

  _lockDocument(id, data, params, doc) {
    return super.patch(doc.id, {
      locker: data.creator,
      lockedAt: new Date()
    });
  }

  _unlockDocument(id, data, params, doc) {
    return super.patch(doc.id, {
      locker: null,
      lockedAt: null
    });
  }

  _addPermission(id, data, params, doc) {
    assert(doc, 'target document is not exists.');
    assert(data.action, 'data.action is not provided.');
    assert(data.user, 'data.user is not provided.');

    const svcPermissions = this.app.service('user-permissions');
    return svcPermissions.create({
      actions: [data.action],
      subject: `${doc.type}:${doc.id}`,
      user: data.user,
      role: data.role,
      creator: params.user.id,
      begin: data.begin,
      end: data.end
    });
  }

  _replacePermission(id, data, params, doc) {
    return this.addPermission(id, data, params, doc);
  }

  _removePermission(id, data, params, doc) {
    assert(doc, 'target document is not exists.');
    assert(data.action, 'data.action is not provided');
    assert(data.user, 'data.user is not provided');

    const svcPermissions = this.app.service('user-permissions');
    return svcPermissions.remove(null, {
      query: {
        actions: [data.action],
        subject: `${doc.type}:${doc.id}`,
        user: data.user,
        role: data.role
      },
      $multi: true
    });
  }

  _blockPermissionInheritance(id, data, params, doc) {
    assert(doc, 'target document is not exists.');

    // copy inherited permissions
    const svcPermissions = this.app.service('user-permissions');
    return getParentAces(this.app, [doc], '*').then(inheritedAces => {
      if (inheritedAces && inheritedAces[doc.id]) {
        return Promise.all(fp.map(ace => {
          ace.subject = `${doc.type}:${doc.id}`;
          ace.creator = params.user.id;
          return svcPermissions.create(ace);
        }, inheritedAces[doc.id]));
      }
    }).then(results => {
      return super.patch(id, { inherited: false }, params);
    });
  }

  _unblockPermissionInheritance(id, data, params, doc) {
    assert(doc, 'target document is not exists.');

    // remove copied permissions
    const svcPermissions = this.app.service('user-permissions');
    return getParentAces(this.app, [doc], '*').then(inheritedAces => {
      if (inheritedAces && inheritedAces[doc.id]) {
        return Promise.all(fp.map(ace => {
          return svcPermissions.remove(null, {
            query: {
              actions: ace.actions,
              subject: `${doc.type}:${doc.id}`,
              user: ace.user,
              role: ace.role,
              creator: params.user.id
            },
            $multi: true
          });
        }, inheritedAces[doc.id]));
      }
    }).then(results => {
      return super.patch(id, { inherited: true }, params);
    });
  }
}

export default function init(app, options) {
  options = Object.assign({ ModelName: 'document' }, options);
  return createService(app, DocumentService, DocumentModel, options);
}

init.Service = DocumentService;
<|endoftext|>


<commit_before>angular.module('rapid-build').run(['$rootScope', '$location', 'typeService', ($rootScope, $location, typeService) => {
	const doc             = window.document;
	const SEPARATOR       = '·';
	const DOC_TITLE       = `${doc.title} ${SEPARATOR}`;
	const SEPARATOR_INDEX = DOC_TITLE.indexOf(SEPARATOR) + 2;
	const COMMON_TITLE    = DOC_TITLE.slice(0, SEPARATOR_INDEX);
	const FORMAT_MAP = {
		nodashes(v) { return v.replace(/-/g, ' ') },
		lowercase: 'toLowerCase',
		titlecase: 'toTitleCase',
		uppercase: 'toUpperCase'
	}

	var setTitle = title => { // :void
		doc.title = `${COMMON_TITLE} ${title}`;
	};

	var getTitle = (title, opts={}) => { // :string
		switch(typeService.get(opts.format)) {
			case 'boolean': title = title; break;
			case 'string': title = getFormattedTitle(title, opts.format); break;
			case 'array':
				for (let format of opts.format)
					title = getFormattedTitle(title, format);
				break;
			default:
				for (let format of ['nodashes', 'titlecase'])
					title = getFormattedTitle(title, format);
		}
		return title;
	};

	var getFormattedTitle = (title, format) => { // :string
		if (!typeService.is.string(format)) return title;
		format = format.toLowerCase();
		for (let [key, formatter] of Object.entries(FORMAT_MAP)) {
			if (key !== format) continue;
			title = typeService.is.function(formatter) ? formatter(title) : title[formatter]();
		}
		return title;
	};

	$rootScope.$on('$routeChangeSuccess', (e, current, previous) => { // :void
		if (!current.$$route) return;
		if (current.redirectTo) return;
		var path = $location.path();

		// route is homepage
		if (path === '/') return setTitle('Showcase');

		// route.title :string
		var title     = current.$$route.title, // :string | {}
			titleOpts = typeService.is.object(title) ? title : void 0;
		if (typeService.is.string(title)) return setTitle(title);

		// route.title :{} | undefined
		var lastChar = path[path.length - 1];
		if (lastChar === '/') path = path.slice(0, -1);
		var index = path.lastIndexOf('/') + 1, // last url slash index
			title = path.slice(index);         // last url segment

		title = getTitle(title, titleOpts);
		setTitle(title);
	});
}]);<commit_msg>docs(homepage title): change from Showcase to Web Components<commit_after>angular.module('rapid-build').run(['$rootScope', '$location', 'typeService', ($rootScope, $location, typeService) => {
	const doc             = window.document;
	const SEPARATOR       = '·';
	const DOC_TITLE       = `${doc.title} ${SEPARATOR}`;
	const SEPARATOR_INDEX = DOC_TITLE.indexOf(SEPARATOR) + 2;
	const COMMON_TITLE    = DOC_TITLE.slice(0, SEPARATOR_INDEX);
	const FORMAT_MAP = {
		nodashes(v) { return v.replace(/-/g, ' ') },
		lowercase: 'toLowerCase',
		titlecase: 'toTitleCase',
		uppercase: 'toUpperCase'
	}

	var setTitle = title => { // :void
		doc.title = `${COMMON_TITLE} ${title}`;
	};

	var getTitle = (title, opts={}) => { // :string
		switch(typeService.get(opts.format)) {
			case 'boolean': title = title; break;
			case 'string': title = getFormattedTitle(title, opts.format); break;
			case 'array':
				for (let format of opts.format)
					title = getFormattedTitle(title, format);
				break;
			default:
				for (let format of ['nodashes', 'titlecase'])
					title = getFormattedTitle(title, format);
		}
		return title;
	};

	var getFormattedTitle = (title, format) => { // :string
		if (!typeService.is.string(format)) return title;
		format = format.toLowerCase();
		for (let [key, formatter] of Object.entries(FORMAT_MAP)) {
			if (key !== format) continue;
			title = typeService.is.function(formatter) ? formatter(title) : title[formatter]();
		}
		return title;
	};

	$rootScope.$on('$routeChangeSuccess', (e, current, previous) => { // :void
		if (!current.$$route) return;
		if (current.redirectTo) return;
		var path = $location.path();

		// route is homepage
		if (path === '/') return setTitle('Web Components');

		// route.title :string
		var title     = current.$$route.title, // :string | {}
			titleOpts = typeService.is.object(title) ? title : void 0;
		if (typeService.is.string(title)) return setTitle(title);

		// route.title :{} | undefined
		var lastChar = path[path.length - 1];
		if (lastChar === '/') path = path.slice(0, -1);
		var index = path.lastIndexOf('/') + 1, // last url slash index
			title = path.slice(index);         // last url segment

		title = getTitle(title, titleOpts);
		setTitle(title);
	});
}]);<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'com.chrome.origintrials.model',
  name: 'Experiment',
  ids: [ 'name' ],
  properties: [
    {
      class: 'String',
      name: 'name'
    },
    {
      class: 'EMail',
      name: 'owner'
    },
    {
      class: 'DateTime',
      name: 'startTime'
    }
  ]
});

foam.RELATIONSHIP({
  name: 'experiment',
  cardinality: '*:1',
  sourceModel: 'com.chrome.origintrials.model.Application',
  targetModel: 'com.chrome.origintrials.model.Experiment',
  oneWay: true
});
<commit_msg>EF: Remove startTime from Experiment temporarily<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'com.chrome.origintrials.model',
  name: 'Experiment',
  ids: [ 'name' ],
  properties: [
    {
      class: 'String',
      name: 'name'
    },
    {
      class: 'EMail',
      name: 'owner'
    }
  ]
});

foam.RELATIONSHIP({
  name: 'experiment',
  cardinality: '*:1',
  sourceModel: 'com.chrome.origintrials.model.Application',
  targetModel: 'com.chrome.origintrials.model.Experiment',
  oneWay: true
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name        toutiao-redirect
// @description auto redirect to product url in toutiao.io
// @include     http://toutiao.io/posts/
// @downloadURL https://raw.githubusercontent.com/goorockey/greasemonkey-scripts/master/toutiao-redirect.user.js
// @updateURL   https://raw.githubusercontent.com/goorockey/greasemonkey-scripts/master/toutiao-redirect.user.js
// @version     1.0
// author       kelvingu616@gmail.com
// github       github.com/goorockey
// ==/UserScript==

var url = document.querySelectorAll('.title a')[0];
if (url && url.href) {
  window.location.replace(url.href);
}
<commit_msg>update metadata of toutiao-redirect.user.js<commit_after>// ==UserScript==
// @name        toutiao-redirect
// @description auto redirect to product url in toutiao.io
// @include     http://toutiao.io/posts/*
// @downloadURL https://raw.githubusercontent.com/goorockey/greasemonkey-scripts/master/toutiao-redirect.user.js
// @updateURL   https://raw.githubusercontent.com/goorockey/greasemonkey-scripts/master/toutiao-redirect.user.js
// @version     1.0
// author       kelvingu616@gmail.com
// github       github.com/goorockey
// ==/UserScript==

var url = document.querySelectorAll('.title a')[0];
if (url && url.href) {
  window.location.replace(url.href);
}
<|endoftext|>