<commit_before>import _ from 'lodash';
// global moment

export default function(_data, _trades) {

  const trades = _trades.map(t => {
    return {
      price: t.price,
      date: new Date(t.date),
      action: t.action
    }
  });

  const data = _data.map(c => {
    return {
      price: c.close,
      date: new Date(c.start)
    }
  });

  var dates = data.map(c => +c.date);
  var prices = data.map(c => +c.price)

  var svg = d3.select("#chart");

  svg.attr("width", window.innerWidth - 20);

  var margin = {top: 20, right: 20, bottom: 110, left: 40};
  var margin2 = {top: 430, right: 20, bottom: 30, left: 40};
  var width = +svg.attr("width") - margin.left - margin.right;
  var height = +svg.attr("height") - margin.top - margin.bottom;
  var height2 = +svg.attr("height") - margin2.top - margin2.bottom;

  var x = d3.scaleTime().range([0, width]),
      x2 = d3.scaleTime().range([0, width]),
      y = d3.scaleLinear().range([height, 0]),
      y2 = d3.scaleLinear().range([height2, 0]);

  var xAxis = d3.axisBottom(x),
      xAxis2 = d3.axisBottom(x2),
      yAxis = d3.axisLeft(y);

  var brush = d3.brushX()
      .extent([[0, 0], [width, height2]])
      .on("brush end", brushed);

  var zoom = d3.zoom()
      .scaleExtent([1, 100])
      .translateExtent([[0, 0], [width, height]])
      .extent([[0, 0], [width, height]])
      .on("zoom", zoomed);

  var line = d3.line()
      .x(function(d) { return x(d.date); })
      .y(function(d) { return y(d.price); });

  var line2 = d3.line()
      .x(function(d) { return x2(d.date); })
      .y(function(d) { return y2(d.price); });

  svg.append("defs").append("clipPath")
      .attr("id", "clip")
    .append("rect")
      .attr("width", width)
      .attr("height", height);

  var focus = svg.append("g")
      .attr("class", "focus")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var context = svg.append("g")
      .attr("class", "context")
      .attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");

  x.domain(d3.extent(data, function(d) { return d.date; }));
  y.domain([
    d3.min(prices) * 0.99,
    d3.max(prices) * 1.01
  ]);
  x2.domain(x.domain());
  y2.domain(y.domain());

  focus.append("path")
      .datum(data)
      .attr("class", "line price")
      .attr("d", line);

  focus.append("g")
      .attr("class", "axis axis--x")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  focus.append("g")
      .attr("class", "axis axis--y")
      .call(yAxis);

  context.append("path")
      .datum(data)
      .attr("class", "line")
      .attr("d", line2);

  context.append("g")
      .attr("class", "axis axis--x")
      .attr("transform", "translate(0," + height2 + ")")
      .call(xAxis2);

  var circles = svg
    .append('g')
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
      .selectAll("circle")
      .data(trades)
      .enter().append("circle")
        .attr('class', function(d) { return d.action })
        .attr("cx", function(d) { return x(d.date); })
        .attr("cy", function(d) { return y(d.price); })
        .attr('r', 5);

  context.append("g")
      .attr("class", "brush")
      .call(brush)
      .call(brush.move, x.range());

  svg.append("rect")
      .attr("class", "zoom")
      .attr("width", width)
      .attr("height", height)
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
      .call(zoom);

  function brushed() {
    if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
    var s = d3.event.selection || x2.range();
    x.domain(s.map(x2.invert, x2));

    scaleY(x.domain());

    svg.select(".axis--y")
      .call(yAxis);

    circles
      .attr("cx", function(d) { return x(d.date); })
      .attr("cy", function(d) { return y(d.price); })

    focus.select(".line").attr("d", line);
    focus.select(".axis--x").call(xAxis);
    svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
        .scale(width / (s[1] - s[0]))
        .translate(-s[0], 0));
  }

  function scaleY(domain) {
    let [min, max] = domain;

    let minIndex = _.sortedIndex(dates, min);
    let maxIndex = _.sortedIndex(dates, max);

    let set = prices.slice(minIndex, maxIndex);
    y.domain([
      d3.min(set) * 0.9995,
      d3.max(set) * 1.0005
    ]);
  }

  function zoomed() {
    if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return; // ignore zoom-by-brush
    var t = d3.event.transform;

    scaleY(t.rescaleX(x2).domain());

    svg.select(".axis--y")
      .call(yAxis);

    x.domain(t.rescaleX(x2).domain());
    focus.select(".line").attr("d", line);

    circles
      .attr("cx", function(d) { return x(d.date); })
      .attr("cy", function(d) { return y(d.price); })

    focus.select(".axis--x").call(xAxis);
    context.select(".brush").call(brush.move, x.range().map(t.invertX, t));
  }
}<commit_msg>show trades on brush graph<commit_after>import _ from 'lodash';
// global moment

export default function(_data, _trades) {

  const trades = _trades.map(t => {
    return {
      price: t.price,
      date: new Date(t.date),
      action: t.action
    }
  });

  const data = _data.map(c => {
    return {
      price: c.close,
      date: new Date(c.start)
    }
  });

  var dates = data.map(c => +c.date);
  var prices = data.map(c => +c.price)

  var svg = d3.select("#chart");

  svg.attr("width", window.innerWidth - 20);

  var margin = {top: 20, right: 20, bottom: 110, left: 40};
  var margin2 = {top: 430, right: 20, bottom: 30, left: 40};
  var width = +svg.attr("width") - margin.left - margin.right;
  var height = +svg.attr("height") - margin.top - margin.bottom;
  var height2 = +svg.attr("height") - margin2.top - margin2.bottom;

  var x = d3.scaleTime().range([0, width]),
      x2 = d3.scaleTime().range([0, width]),
      y = d3.scaleLinear().range([height, 0]),
      y2 = d3.scaleLinear().range([height2, 0]);

  var xAxis = d3.axisBottom(x),
      xAxis2 = d3.axisBottom(x2),
      yAxis = d3.axisLeft(y);

  var brush = d3.brushX()
      .extent([[0, 0], [width, height2]])
      .on("brush end", brushed);

  var zoom = d3.zoom()
      .scaleExtent([1, 100])
      .translateExtent([[0, 0], [width, height]])
      .extent([[0, 0], [width, height]])
      .on("zoom", zoomed);

  var line = d3.line()
      .x(function(d) { return x(d.date); })
      .y(function(d) { return y(d.price); });

  var line2 = d3.line()
      .x(function(d) { return x2(d.date); })
      .y(function(d) { return y2(d.price); });

  svg.append("defs").append("clipPath")
      .attr("id", "clip")
    .append("rect")
      .attr("width", width)
      .attr("height", height);

  var focus = svg.append("g")
      .attr("class", "focus")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var context = svg.append("g")
      .attr("class", "context")
      .attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");

  x.domain(d3.extent(data, function(d) { return d.date; }));
  y.domain([
    d3.min(prices) * 0.99,
    d3.max(prices) * 1.01
  ]);
  x2.domain(x.domain());
  y2.domain(y.domain());

  focus.append("path")
      .datum(data)
      .attr("class", "line price")
      .attr("d", line);

  focus.append("g")
      .attr("class", "axis axis--x")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  focus.append("g")
      .attr("class", "axis axis--y")
      .call(yAxis);

  context.append("path")
      .datum(data)
      .attr("class", "line")
      .attr("d", line2);

  context.append("g")
      .attr("class", "axis axis--x")
      .attr("transform", "translate(0," + height2 + ")")
      .call(xAxis2);

  var circles = svg
    .append('g')
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
      .selectAll("circle")
      .data(trades)
      .enter().append("circle")
        .attr('class', function(d) { return d.action })
        .attr("cx", function(d) { return x(d.date); })
        .attr("cy", function(d) { return y(d.price); })
        .attr('r', 5);

  var brushCircles = context
    .append('g')
    // .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
      .selectAll("circle")
      .data(trades)
      .enter().append("circle")
        .attr('class', function(d) { return d.action })
        .attr("cx", function(d) { return x2(d.date); })
        .attr("cy", function(d) { return y2(d.price); })
        .attr('r', 3);

  context.append("g")
      .attr("class", "brush")
      .call(brush)
      .call(brush.move, x.range());

  svg.append("rect")
      .attr("class", "zoom")
      .attr("width", width)
      .attr("height", height)
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
      .call(zoom);

  function brushed() {
    if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
    var s = d3.event.selection || x2.range();
    x.domain(s.map(x2.invert, x2));

    scaleY(x.domain());

    svg.select(".axis--y")
      .call(yAxis);

    circles
      .attr("cx", function(d) { return x(d.date); })
      .attr("cy", function(d) { return y(d.price); })

    focus.select(".line").attr("d", line);
    focus.select(".axis--x").call(xAxis);
    svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
        .scale(width / (s[1] - s[0]))
        .translate(-s[0], 0));
  }

  function scaleY(domain) {
    let [min, max] = domain;

    let minIndex = _.sortedIndex(dates, min);
    let maxIndex = _.sortedIndex(dates, max);

    let set = prices.slice(minIndex, maxIndex);
    y.domain([
      d3.min(set) * 0.9995,
      d3.max(set) * 1.0005
    ]);
  }

  function zoomed() {
    if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return; // ignore zoom-by-brush
    var t = d3.event.transform;

    scaleY(t.rescaleX(x2).domain());

    svg.select(".axis--y")
      .call(yAxis);

    x.domain(t.rescaleX(x2).domain());
    focus.select(".line").attr("d", line);

    circles
      .attr("cx", function(d) { return x(d.date); })
      .attr("cy", function(d) { return y(d.price); })

    focus.select(".axis--x").call(xAxis);
    context.select(".brush").call(brush.move, x.range().map(t.invertX, t));
  }
}<|endoftext|>


<commit_before>define(["dojo/_base/declare", "dojo/Deferred", "dojo/when", "dojo/store/util/QueryResults", "dojo/store/util/SimpleQueryEngine"],
	function(declare, Deferred, when, QueryResults, SimpleQueryEngine){

	return declare(null, {
		// summary:
		//		This is a dojo/store wrapper for Cordova Contacts API.

		// displayName: Boolean
		//		Whether the store must force the presence of displayName property when null. Default is false.
		displayName: false,

		// contactsFields: String[]
		//		Defines array of contact fields that are returned when doing a query
		contactFields: ["id", "displayName", "name", "phoneNumbers", "emails", "addresses", "organizations"],

		// queryEngine: Function
		//		Defines the query engine to use for querying the data store
		queryEngine: SimpleQueryEngine,

		constructor: function(options){
			// summary:
			//		Creates a contacts object store.
			declare.safeMixin(this, options);
		},

		get: function(id){
			//	summary:
			//		Retrieves an object by its identity.
			//	id: String
			//		The identity to use to lookup the object
			//	returns: Object
			//		The object in the store that matches the given id.
			var deferred = new Deferred();
			this._find(id,
				function(contacts){
					// search is by keyword on all fields, so we need to double check
					// we did not get false positive results
					var i;
					for(i = 0; i < contacts.length; i++){
						// Cordova advertise String ids but at least sometimes we get Number...
						if(contacts[i].id == id){
							deferred.resolve(contacts[i]);
							return;
						}
					}
					deferred.resolve(null);
				},
				deferred, { multiple: false });
			return deferred.promise;
		},

		getIdentity: function(object){
			//	summary:
			//		Returns an object's identity
			//	object: Object
			//		The object to get the identity from
			//	returns: String
			return object.id;
		},

		query: function(query, options){
			var findDeferred = new Deferred(), deferred = new Deferred();
			var self = this;
			// get a minimal cordova API query from a the dojo/store type of query
			var cordovaQuery = "", key;
			for(key in query){
				if(!(query[key] instanceof RegExp)){
					cordovaQuery = query[key];
					break;
				}
			}
			this._find(cordovaQuery,
				function(contacts){
					findDeferred.resolve(contacts);
				},
				findDeferred, options);
			when(findDeferred, function(contacts){
				if(self.displayName){
					var contact, i;
					for(i = 0; i < contacts.length; i++){
						contact = contacts[i];
						if(!contact.displayName && contact.name.formatted){
							contact.displayName = contact.name.formatted;
						}
					}
				}
				deferred.resolve(self.queryEngine(query, options)(contacts));
			}, function(error){
				deferred.reject(error);
			});
			return QueryResults(deferred.promise);
		},

		// All the code below depends on Cordova Contacts API

		_find: function(query, success, deferred, options){
			var opts = new ContactFindOptions();
			var fields = (options && options.contactFields) || this.contactFields;
			opts.filter = query;
			opts.multiple = (options && options.hasOwnProperty("multiple")) ? options.multiple : true;
			navigator.contacts.find(fields, success, function(error){deferred.reject(error);}, opts);
		},

		put: function(object, directives){
			var deferred = new Deferred(), self = this;
			if(directives && directives.hasOwnProperty("id")){
				object.id = directives.id;
			}
			if(directives && directives.overwrite === false){
				when(this.get(object.id), function(contact){
					if(contact !== null){
						deferred.reject(new Error("object already exists"));
					}else{
						self._put(object, deferred);
					}
				});
			}else{
				this._put(object, deferred);
			}
			return deferred.promise;
		},

		_put: function(object, deferred){
			var contact = typeof object.save === "function" ? object : navigator.contacts.create(object);
			contact.save(function(contact){deferred.resolve(contact);}, function(error){deferred.reject(error);});
		},

		add: function(object, directives){
			(directives = directives || {}).overwrite = false;
			return this.put(object, directives);
		},

		remove: function(id){
			var deferred = new Deferred();
			var object = this.get(id);
			when(object, function(object){
				object.remove(function(contact){deferred.resolve(contact);}, function(error){deferred.reject(error);});
			});
			return deferred.promise;
		}
	});
});
<commit_msg>support displayName in add/put<commit_after>define(["dojo/_base/declare", "dojo/Deferred", "dojo/when", "dojo/store/util/QueryResults", "dojo/store/util/SimpleQueryEngine"],
	function(declare, Deferred, when, QueryResults, SimpleQueryEngine){

	return declare(null, {
		// summary:
		//		This is a dojo/store wrapper for Cordova Contacts API.

		// displayName: Boolean
		//		Whether the store must force the presence of displayName property when null. Default is false.
		displayName: false,

		// contactsFields: String[]
		//		Defines array of contact fields that are returned when doing a query
		contactFields: ["id", "displayName", "name", "phoneNumbers", "emails", "addresses", "organizations"],

		// queryEngine: Function
		//		Defines the query engine to use for querying the data store
		queryEngine: SimpleQueryEngine,

		constructor: function(options){
			// summary:
			//		Creates a contacts object store.
			declare.safeMixin(this, options);
		},

		get: function(id){
			//	summary:
			//		Retrieves an object by its identity.
			//	id: String
			//		The identity to use to lookup the object
			//	returns: Object
			//		The object in the store that matches the given id.
			var deferred = new Deferred();
			this._find(id,
				function(contacts){
					// search is by keyword on all fields, so we need to double check
					// we did not get false positive results
					var i;
					for(i = 0; i < contacts.length; i++){
						// Cordova advertise String ids but at least sometimes we get Number...
						if(contacts[i].id == id){
							deferred.resolve(contacts[i]);
							return;
						}
					}
					deferred.resolve(null);
				},
				deferred, { multiple: false });
			return deferred.promise;
		},

		getIdentity: function(object){
			//	summary:
			//		Returns an object's identity
			//	object: Object
			//		The object to get the identity from
			//	returns: String
			return object.id;
		},

		query: function(query, options){
			var findDeferred = new Deferred(), deferred = new Deferred();
			var self = this;
			// get a minimal cordova API query from a the dojo/store type of query
			var cordovaQuery = "", key;
			for(key in query){
				if(!(query[key] instanceof RegExp)){
					cordovaQuery = query[key];
					break;
				}
			}
			this._find(cordovaQuery,
				function(contacts){
					findDeferred.resolve(contacts);
				},
				findDeferred, options);
			when(findDeferred, function(contacts){
				if(self.displayName){
					var contact, i;
					for(i = 0; i < contacts.length; i++){
						contact = contacts[i];
						if(!contact.displayName && contact.name.formatted){
							contact.displayName = contact.name.formatted;
						}
					}
				}
				deferred.resolve(self.queryEngine(query, options)(contacts));
			}, function(error){
				deferred.reject(error);
			});
			return QueryResults(deferred.promise);
		},

		// All the code below depends on Cordova Contacts API

		_find: function(query, success, deferred, options){
			var opts = new ContactFindOptions();
			var fields = (options && options.contactFields) || this.contactFields;
			opts.filter = query;
			opts.multiple = (options && options.hasOwnProperty("multiple")) ? options.multiple : true;
			navigator.contacts.find(fields, success, function(error){deferred.reject(error);}, opts);
		},

		put: function(object, directives){
			var deferred = new Deferred(), self = this;
			if(directives && directives.hasOwnProperty("id")){
				object.id = directives.id;
			}
			if(directives && directives.overwrite === false){
				when(this.get(object.id), function(contact){
					if(contact !== null){
						deferred.reject(new Error("object already exists"));
					}else{
						self._put(object, deferred);
					}
				});
			}else{
				this._put(object, deferred);
			}
			return deferred.promise;
		},

		_put: function(object, deferred){
			var contact = typeof object.save === "function" ? object : navigator.contacts.create(object);
			var self = this;
			contact.save(function(contact){
				if(self.displayName && !contact.displayName && contact.name.formatted){
					contact.displayName = contact.name.formatted;
				}
				deferred.resolve(contact);
			}, function(error){deferred.reject(error);});
		},

		add: function(object, directives){
			(directives = directives || {}).overwrite = false;
			return this.put(object, directives);
		},

		remove: function(id){
			var deferred = new Deferred();
			var object = this.get(id);
			when(object, function(object){
				object.remove(function(contact){deferred.resolve(contact);}, function(error){deferred.reject(error);});
			});
			return deferred.promise;
		}
	});
});
<|endoftext|>


<commit_before>var disassemblerOptions = systemOptions.register(new OptionSet("Disassembler Options"));

var filter = disassemblerOptions.register(new Option("f", "filter", "string", "SpciMsm", "[S]ource, constant[p]ool, [c]lasses, [i]nstances, [M]etadata, [s]cripts, [m]ethods, multi[N]ames"));

function traceArray(writer, name, array, abc) {
  if (array.length === 0) {
    return;
  }
  writer.enter(name + " {");
  array.forEach(function (a, idx) {
    a.trace(writer, abc);
  });
  writer.leave("}");
}

AbcFile.prototype.trace = function trace(writer) {
  if (filter.value.indexOf("p") >= 0) {
    this.constantPool.trace(writer);
  }
  if (filter.value.indexOf("N") >= 0) {
    this.constantPool.traceMultinamesOnly(writer);
  }
  if (filter.value.indexOf("c") >= 0) {
    traceArray(writer, "classes", this.classes);
  }
  if (filter.value.indexOf("i") >= 0) {
    traceArray(writer, "instances", this.instances);
  }
  if (filter.value.indexOf("M") >= 0) {
    traceArray(writer, "metadata", this.metadata);
  }
  if (filter.value.indexOf("s") >= 0) {
    traceArray(writer, "scripts", this.scripts);
  }
  if (filter.value.indexOf("m") >= 0) {
    traceArray(writer, "methods", this.methods, this);
  }
  if (filter.value.indexOf("S") >= 0) {
    traceSource(writer, this);
  }
};

ConstantPool.prototype.trace = function (writer) {
  writer.enter("constantPool {");
  for (var key in this) {
    /* Special-case namespaces to print out full names. */
    if (key === "namespaces") {
      writer.enter("namespaces {");
      this.namespaces.forEach(function (ns, i) {
        writer.writeLn(("" + i).padRight(' ', 3) +
                 (ns ? ns.toString() : "*"));
      });
      writer.leave("}");
    } else if (this[key] instanceof Array) {
      writer.enter(key + " " + this[key].length + " {");
      writer.writeArray(this[key]);
      writer.leave("}");
    }
  }
  writer.leave("}");
};

ConstantPool.prototype.traceMultinamesOnly = function (writer) {
  writer.writeArray(this.multinames, null, true);
};

ClassInfo.prototype.trace = function (writer) {
  writer.enter("class " + this + " {");
  traceArray(writer, "traits", this.traits);
  writer.leave("}");
};

MetaDataInfo.prototype.trace = function (writer) {
  writer.enter(this + " {");
  this.items.forEach(function (item) {
    writer.writeLn((item.key ? item.key + ": " : "") + "\"" + item.value + "\"");
  });
  writer.leave("}");
};

InstanceInfo.prototype.trace = function (writer) {
  writer.enter("instance " + this + " {");
  traceArray(writer, "traits", this.traits);
  writer.leave("}");
};

ScriptInfo.prototype.trace = function (writer) {
  writer.enter("script " + this + " {");
  traceArray(writer, "traits", this.traits);
  writer.leave("}");
};

Trait.prototype.trace = function (writer) {
  if (this.metadata) {
    for (var key in this.metadata) {
      if (this.metadata.hasOwnProperty(key)) {
        this.metadata[key].trace(writer);
      }
    }
  }
  writer.writeLn(this);
};

function traceAbc(writer, abc) {
  abc.trace(writer);
}

function traceOperand(operand, abc, code) {
  var value = 0;
  switch(operand.size) {
    case "s08": value = code.readS8(); break;
    case "u08": value = code.readU8(); break;
    case "s16": value = code.readS16(); break;
    case "s24": value = code.readS24(); break;
    case "u30": value = code.readU30(); break;
    case "u32": value = code.readU32(); break;
    default: assert (false); break;
  }
  var description = "";
  switch(operand.type) {
    case "": break;
    case "I": description = abc.constantPool.ints[value]; break;
    case "U": description = abc.constantPool.uints[value]; break;
    case "D": description = abc.constantPool.doubles[value]; break;
    case "S": description = abc.constantPool.strings[value]; break;
    case "N": description = abc.constantPool.namespaces[value]; break;
    case "CI": description = abc.classes[value]; break;
    case "M":
      return abc.constantPool.multinames[value];
    default: description = "?"; break;
  }
  return operand.name + ":" + value + (description === "" ? "" : " (" + description + ")");
}

function traceOperands(opcode, abc, code, rewind) {
  rewind = rewind || false;
  var old = code.position;
  var str = "";
  if (opcode.operands === null) {
    str = "null";
  } else {
    opcode.operands.forEach(function (op, i) {
      str += traceOperand(op, abc, code);
      if (i < opcode.operands.length - 1) {
        str += ", ";
      }
    });
  }
  if (rewind) {
    code.seek(old);
  }
  return str;
}

MethodInfo.prototype.trace = function trace(writer, abc) {
  writer.enter("method" + (this.name ? " " + this.name : "") + " {");
  writer.writeLn("flags: " + getFlags(this.flags, "NEED_ARGUMENTS|NEED_ACTIVATION|NEED_REST|HAS_OPTIONAL||NATIVE|SET_DXN|HAS_PARAM_NAMES".split("|")));

  if (!this.code) {
    writer.leave("}");
    return;
  }

  var code = new AbcStream(this.code);

  traceArray(writer, "traits", this.traits);

  writer.enter("code {");
  while (code.remaining() > 0) {
    var bc = code.readU8();
    var opcode = opcodeTable[bc];
    var str, defaultOffset, offset, count;
    str = ("" + code.position).padRight(' ', 6);
    switch (bc) {
      case OP_lookupswitch:
        str += opcode.name + ": defaultOffset: " + code.readS24();
        var caseCount = code.readU30();
        str += ", caseCount: " + caseCount;
        for (var i = 0; i < caseCount + 1; i++) {
          str += " offset: " + code.readS24();
        }
        writer.writeLn(str);
        break;
      default:
        if (opcode) {
          str += opcode.name.padRight(' ', 20);
          if (!opcode.operands) {
            assert(false, "Opcode: " + opcode.name + " has undefined operands.");
          } else {
            if (opcode.operands.length > 0) {
              str += traceOperands(opcode, abc, code);
            }
            writer.writeLn(str);
          }
        } else {
          assert(false, "Opcode: " + bc + " is not implemented.");
        }
        break;
    }
  }
  writer.leave("}");
  writer.leave("}");
}

var SourceTracer = (function () {
  function literal(value) {
    if (value === undefined) {
      return "undefined";
    } else if (value === null) {
      return "null";
    } else if (typeof (value) === "string") {
      return "\"" + value + "\"";
    } else {
      return String(value);
    }
  }

  function getSignature(mi, excludeTypesAndDefaultValues) {
    return mi.parameters.map(function (x) {
      var str = x.name;
      if (!excludeTypesAndDefaultValues) {
        if (x.type) {
          str += ":" + x.type.getName();
        }
        if (x.value !== undefined) {
          str += "=" + literal(x.value);
        }
      }
      return str;
    }).join(", ");
  }

  function SourceTracer(writer) {
    this.writer = writer;
  }

  SourceTracer.prototype = {
    traceTraits: function traceTraits(traits, isStatic, inInterfaceNamespace) {
      const writer = this.writer;
      const tracer = this;

      traits.forEach(function (trait) {
        var str;
        var accessModifier = trait.name.getAccessModifier();
        var namespaceName = trait.name.namespaces[0].originalURI;
        if (namespaceName) {
          if (namespaceName === "http://adobe.com/AS3/2006/builtin") {
            namespaceName = "AS3";
          }
          if (accessModifier === "public") {
            str = inInterfaceNamespace === namespaceName ? "" : namespaceName;
          } else {
            str = accessModifier;
          }
        } else {
          str = accessModifier;
        }
        if (isStatic) {
          str += " static";
        }
        if (trait.isSlot() || trait.isConst()) {
          tracer.traceMetadata(trait.metadata);
          if (trait.isConst()) {
            str += " const";
          } else {
            str += " var";
          }
          str += " " + trait.name.getName();
          if (trait.typeName) {
            str += ":" + trait.typeName.getName();
          }
          if (trait.value) {
            str += " = " + literal(trait.value);
          }
          writer.writeLn(str + ";");
        } else if (trait.isMethod() || trait.isGetter() || trait.isSetter()) {
          tracer.traceMetadata(trait.metadata);
          var mi = trait.methodInfo;
          if (trait.attributes & ATTR_Override) {
            str += " override";
          }
          if (mi.isNative()) {
            str += " native";
          }
          str += " function";
          str += trait.isGetter() ? " get" : (trait.isSetter() ? " set" : "");
          str += " " + trait.name.getName();
          str += "(" + getSignature(mi) + ")";
          str += mi.returnType ? ":" + mi.returnType.getName() : "";
          if (mi.isNative()) {
            writer.writeLn(str + ";");
          } else {
            if (inInterfaceNamespace) {
              writer.writeLn(str + ";");
            } else {
              writer.writeLn(str + " { notImplemented(\"" + trait.name.getName() + "\"); }");
            }
          }
        } else if (trait.isClass()) {
          var className = trait.classInfo.instanceInfo.name;
          writer.enter("package " + className.namespaces[0].originalURI + " {\n");
          tracer.traceMetadata(trait.metadata);
          tracer.traceClass(trait.classInfo);
          writer.leave("\n}");
          tracer.traceClassStub(trait);
        } else {
          notImplemented();
        }
      });
    },

    traceClassStub: function traceClassStub(trait) {
      const writer = this.writer;

      var ci = trait.classInfo;
      var ii = ci.instanceInfo;
      var name = ii.name.getName();
      var native = trait.metadata ? trait.metadata.native : null;
      if (!native) {
        return false;
      }

      writer.writeLn("Cut and paste the following into `native.js' and edit accordingly");
      writer.writeLn("8< --------------------------------------------------------------");
      writer.enter("natives." + native.cls + " = function " + native.cls + "(runtime, scope, instance, baseClass) {");
      writer.writeLn("var c = new Class(\"" + name + "\", instance, Class.passthroughCallable(instance));");
      writer.writeLn("c.extend(baseClass);\n");

      function traceTraits(traits, isStatic) {
        var nativeMethodTraits = [];

        traits.traits.forEach(function (trait, i) {
          if (trait.isMethod() || trait.isGetter() || trait.isSetter()) {
            if (trait.methodInfo.isNative()) {
              nativeMethodTraits.push(trait);
            }
          }
        });

        nativeMethodTraits.forEach(function (trait, i) {
          var mi = trait.methodInfo;
          var traitName = trait.name.getName();
          writer.writeLn("// " + traitName + " :: " +
                         (mi.parameters.length ? getSignature(mi) : "void") + " -> " +
                         (mi.returnType ? mi.returnType.getName() : "any"));
          var prop;
          if (trait.isGetter()) {
            prop = "\"get " + traitName + "\"";
          } else if (trait.isSetter()) {
            prop = "\"set " + traitName + "\"";
          } else {
            prop = traitName;
          }

          writer.enter(prop + ": function " + traitName + "(" + getSignature(mi, true) + ") {");
          writer.writeLn("  notImplemented(\"" + name + "." + traitName + "\");");
          writer.leave("}" + (i === nativeMethodTraits.length - 1 ? "" : ",\n"));
        });
      }

      writer.enter("c.nativeStatics = {");
      traceTraits(ci.traits, true);
      writer.leave("};\n");
      writer.enter("c.nativeMethods = {");
      traceTraits(ii.traits);
      writer.leave("};\n");

      writer.writeLn("return c;");
      writer.leave("};");
      writer.writeLn("-------------------------------------------------------------- >8");

      return true;
    },

    traceClass: function traceClass(ci) {
      const writer = this.writer;

      var ii = ci.instanceInfo;
      var name = ii.name;
      var str = name.getAccessModifier();
      if (ii.isFinal()) {
        str += " final";
      }
      if (!ii.isSealed()) {
        str += " dynamic";
      }
      str += ii.isInterface() ? " interface " : " class ";
      str += name.getName();
      if (ii.superName && ii.superName.getName() !== "Object") {
        str += " extends " + ii.superName.getName();
      }
      if (ii.interfaces.length) {
        str += " implements " + ii.interfaces.map(function (x) {
          return x.getName();
        }).join(", ");
      }
      writer.enter(str + " {");
      if (!ii.isInterface()) {
        writer.writeLn("public function " + name.getName() + "(" + getSignature(ii.init) + ") {}");
      }
      var interfaceNamespace;
      if (ii.isInterface()) {
        interfaceNamespace = name.namespaces[0].originalURI + ":" + name.name;
      }
      this.traceTraits(ci.traits, true, interfaceNamespace);
      this.traceTraits(ii.traits, false, interfaceNamespace);
      writer.leave("}");
    },

    traceMetadata: function traceMetadata(metadata) {
      const writer = this.writer;

      for (var key in metadata) {
        if (metadata.hasOwnProperty(key)) {
          if (key.indexOf("__") === 0) {
            continue;
          }
          writer.writeLn("[" + key + "(" + metadata[key].items.map(function (m) {
            var str = m.key ? m.key + "=" : "";
            return str + "\"" + m.value + "\"";
          }).join(", ") + ")]");
        }
      }
    }
  };

  return SourceTracer;
})();

function traceSource(writer, abc) {
  var tracer = new SourceTracer(writer);
  abc.scripts.forEach(function (script) {
    tracer.traceTraits(script.traits);
  });
}
<commit_msg>Fix disassembler bug.<commit_after>var disassemblerOptions = systemOptions.register(new OptionSet("Disassembler Options"));

var filter = disassemblerOptions.register(new Option("f", "filter", "string", "SpciMsm", "[S]ource, constant[p]ool, [c]lasses, [i]nstances, [M]etadata, [s]cripts, [m]ethods, multi[N]ames"));

function traceArray(writer, name, array, abc) {
  if (array.length === 0) {
    return;
  }
  writer.enter(name + " {");
  array.forEach(function (a, idx) {
    a.trace(writer, abc);
  });
  writer.leave("}");
}

AbcFile.prototype.trace = function trace(writer) {
  if (filter.value.indexOf("p") >= 0) {
    this.constantPool.trace(writer);
  }
  if (filter.value.indexOf("N") >= 0) {
    this.constantPool.traceMultinamesOnly(writer);
  }
  if (filter.value.indexOf("c") >= 0) {
    traceArray(writer, "classes", this.classes);
  }
  if (filter.value.indexOf("i") >= 0) {
    traceArray(writer, "instances", this.instances);
  }
  if (filter.value.indexOf("M") >= 0) {
    traceArray(writer, "metadata", this.metadata);
  }
  if (filter.value.indexOf("s") >= 0) {
    traceArray(writer, "scripts", this.scripts);
  }
  if (filter.value.indexOf("m") >= 0) {
    traceArray(writer, "methods", this.methods, this);
  }
  if (filter.value.indexOf("S") >= 0) {
    traceSource(writer, this);
  }
};

ConstantPool.prototype.trace = function (writer) {
  writer.enter("constantPool {");
  for (var key in this) {
    /* Special-case namespaces to print out full names. */
    if (key === "namespaces") {
      writer.enter("namespaces {");
      this.namespaces.forEach(function (ns, i) {
        writer.writeLn(("" + i).padRight(' ', 3) +
                 (ns ? ns.toString() : "*"));
      });
      writer.leave("}");
    } else if (this[key] instanceof Array) {
      writer.enter(key + " " + this[key].length + " {");
      writer.writeArray(this[key]);
      writer.leave("}");
    }
  }
  writer.leave("}");
};

ConstantPool.prototype.traceMultinamesOnly = function (writer) {
  writer.writeArray(this.multinames, null, true);
};

ClassInfo.prototype.trace = function (writer) {
  writer.enter("class " + this + " {");
  traceArray(writer, "traits", this.traits);
  writer.leave("}");
};

MetaDataInfo.prototype.trace = function (writer) {
  writer.enter(this + " {");
  this.items.forEach(function (item) {
    writer.writeLn((item.key ? item.key + ": " : "") + "\"" + item.value + "\"");
  });
  writer.leave("}");
};

InstanceInfo.prototype.trace = function (writer) {
  writer.enter("instance " + this + " {");
  traceArray(writer, "traits", this.traits);
  writer.leave("}");
};

ScriptInfo.prototype.trace = function (writer) {
  writer.enter("script " + this + " {");
  traceArray(writer, "traits", this.traits);
  writer.leave("}");
};

Trait.prototype.trace = function (writer) {
  if (this.metadata) {
    for (var key in this.metadata) {
      if (this.metadata.hasOwnProperty(key)) {
        this.metadata[key].trace(writer);
      }
    }
  }
  writer.writeLn(this);
};

function traceAbc(writer, abc) {
  abc.trace(writer);
}

function traceOperand(operand, abc, code) {
  var value = 0;
  switch(operand.size) {
    case "s08": value = code.readS8(); break;
    case "u08": value = code.readU8(); break;
    case "s16": value = code.readS16(); break;
    case "s24": value = code.readS24(); break;
    case "u30": value = code.readU30(); break;
    case "u32": value = code.readU32(); break;
    default: assert (false); break;
  }
  var description = "";
  switch(operand.type) {
    case "": break;
    case "I": description = abc.constantPool.ints[value]; break;
    case "U": description = abc.constantPool.uints[value]; break;
    case "D": description = abc.constantPool.doubles[value]; break;
    case "S": description = abc.constantPool.strings[value]; break;
    case "N": description = abc.constantPool.namespaces[value]; break;
    case "CI": description = abc.classes[value]; break;
    case "M":
      return abc.constantPool.multinames[value];
    default: description = "?"; break;
  }
  return operand.name + ":" + value + (description === "" ? "" : " (" + description + ")");
}

function traceOperands(opcode, abc, code, rewind) {
  rewind = rewind || false;
  var old = code.position;
  var str = "";
  if (opcode.operands === null) {
    str = "null";
  } else {
    opcode.operands.forEach(function (op, i) {
      str += traceOperand(op, abc, code);
      if (i < opcode.operands.length - 1) {
        str += ", ";
      }
    });
  }
  if (rewind) {
    code.seek(old);
  }
  return str;
}

MethodInfo.prototype.trace = function trace(writer, abc) {
  writer.enter("method" + (this.name ? " " + this.name : "") + " {");
  writer.writeLn("flags: " + getFlags(this.flags, "NEED_ARGUMENTS|NEED_ACTIVATION|NEED_REST|HAS_OPTIONAL||NATIVE|SET_DXN|HAS_PARAM_NAMES".split("|")));

  if (!this.code) {
    writer.leave("}");
    return;
  }

  var code = new AbcStream(this.code);

  traceArray(writer, "traits", this.traits);

  writer.enter("code {");
  while (code.remaining() > 0) {
    var bc = code.readU8();
    var opcode = opcodeTable[bc];
    var str, defaultOffset, offset, count;
    str = ("" + code.position).padRight(' ', 6);
    switch (bc) {
      case OP_lookupswitch:
        str += opcode.name + ": defaultOffset: " + code.readS24();
        var caseCount = code.readU30();
        str += ", caseCount: " + caseCount;
        for (var i = 0; i < caseCount + 1; i++) {
          str += " offset: " + code.readS24();
        }
        writer.writeLn(str);
        break;
      default:
        if (opcode) {
          str += opcode.name.padRight(' ', 20);
          if (!opcode.operands) {
            assert(false, "Opcode: " + opcode.name + " has undefined operands.");
          } else {
            if (opcode.operands.length > 0) {
              str += traceOperands(opcode, abc, code);
            }
            writer.writeLn(str);
          }
        } else {
          assert(false, "Opcode: " + bc + " is not implemented.");
        }
        break;
    }
  }
  writer.leave("}");
  writer.leave("}");
}

var SourceTracer = (function () {
  function literal(value) {
    if (value === undefined) {
      return "undefined";
    } else if (value === null) {
      return "null";
    } else if (typeof (value) === "string") {
      return "\"" + value + "\"";
    } else {
      return String(value);
    }
  }

  function getSignature(mi, excludeTypesAndDefaultValues) {
    return mi.parameters.map(function (x) {
      var str = x.name;
      if (!excludeTypesAndDefaultValues) {
        if (x.type) {
          str += ":" + x.type.getName();
        }
        if (x.value !== undefined) {
          str += "=" + literal(x.value);
        }
      }
      return str;
    }).join(", ");
  }

  function SourceTracer(writer) {
    this.writer = writer;
  }

  SourceTracer.prototype = {
    traceTraits: function traceTraits(traits, isStatic, inInterfaceNamespace) {
      const writer = this.writer;
      const tracer = this;

      traits.forEach(function (trait) {
        var str;
        var accessModifier = trait.name.getAccessModifier();
        var namespaceName = trait.name.namespaces[0].originalURI;
        if (namespaceName) {
          if (namespaceName === "http://adobe.com/AS3/2006/builtin") {
            namespaceName = "AS3";
          }
          if (accessModifier === "public") {
            str = inInterfaceNamespace === namespaceName ? "" : namespaceName;
          } else {
            str = accessModifier;
          }
        } else {
          str = accessModifier;
        }
        if (isStatic) {
          str += " static";
        }
        if (trait.isSlot() || trait.isConst()) {
          tracer.traceMetadata(trait.metadata);
          if (trait.isConst()) {
            str += " const";
          } else {
            str += " var";
          }
          str += " " + trait.name.getName();
          if (trait.typeName) {
            str += ":" + trait.typeName.getName();
          }
          if (trait.value) {
            str += " = " + literal(trait.value);
          }
          writer.writeLn(str + ";");
        } else if (trait.isMethod() || trait.isGetter() || trait.isSetter()) {
          tracer.traceMetadata(trait.metadata);
          var mi = trait.methodInfo;
          if (trait.attributes & ATTR_Override) {
            str += " override";
          }
          if (mi.isNative()) {
            str += " native";
          }
          str += " function";
          str += trait.isGetter() ? " get" : (trait.isSetter() ? " set" : "");
          str += " " + trait.name.getName();
          str += "(" + getSignature(mi) + ")";
          str += mi.returnType ? ":" + mi.returnType.getName() : "";
          if (mi.isNative()) {
            writer.writeLn(str + ";");
          } else {
            if (inInterfaceNamespace) {
              writer.writeLn(str + ";");
            } else {
              writer.writeLn(str + " { notImplemented(\"" + trait.name.getName() + "\"); }");
            }
          }
        } else if (trait.isClass()) {
          var className = trait.classInfo.instanceInfo.name;
          writer.enter("package " + className.namespaces[0].originalURI + " {\n");
          tracer.traceMetadata(trait.metadata);
          tracer.traceClass(trait.classInfo);
          writer.leave("\n}");
          tracer.traceClassStub(trait);
        } else {
          notImplemented();
        }
      });
    },

    traceClassStub: function traceClassStub(trait) {
      const writer = this.writer;

      var ci = trait.classInfo;
      var ii = ci.instanceInfo;
      var name = ii.name.getName();
      var native = trait.metadata ? trait.metadata.native : null;
      if (!native) {
        return false;
      }

      writer.writeLn("Cut and paste the following into `native.js' and edit accordingly");
      writer.writeLn("8< --------------------------------------------------------------");
      writer.enter("natives." + native.cls + " = function " + native.cls + "(runtime, scope, instance, baseClass) {");
      writer.writeLn("var c = new Class(\"" + name + "\", instance, Class.passthroughCallable(instance));");
      writer.writeLn("c.extend(baseClass);\n");

      function traceTraits(traits, isStatic) {
        var nativeMethodTraits = [];

        traits.forEach(function (trait, i) {
          if (trait.isMethod() || trait.isGetter() || trait.isSetter()) {
            if (trait.methodInfo.isNative()) {
              nativeMethodTraits.push(trait);
            }
          }
        });

        nativeMethodTraits.forEach(function (trait, i) {
          var mi = trait.methodInfo;
          var traitName = trait.name.getName();
          writer.writeLn("// " + traitName + " :: " +
                         (mi.parameters.length ? getSignature(mi) : "void") + " -> " +
                         (mi.returnType ? mi.returnType.getName() : "any"));
          var prop;
          if (trait.isGetter()) {
            prop = "\"get " + traitName + "\"";
          } else if (trait.isSetter()) {
            prop = "\"set " + traitName + "\"";
          } else {
            prop = traitName;
          }

          writer.enter(prop + ": function " + traitName + "(" + getSignature(mi, true) + ") {");
          writer.writeLn("  notImplemented(\"" + name + "." + traitName + "\");");
          writer.leave("}" + (i === nativeMethodTraits.length - 1 ? "" : ",\n"));
        });
      }

      writer.enter("c.nativeStatics = {");
      traceTraits(ci.traits, true);
      writer.leave("};\n");
      writer.enter("c.nativeMethods = {");
      traceTraits(ii.traits);
      writer.leave("};\n");

      writer.writeLn("return c;");
      writer.leave("};");
      writer.writeLn("-------------------------------------------------------------- >8");

      return true;
    },

    traceClass: function traceClass(ci) {
      const writer = this.writer;

      var ii = ci.instanceInfo;
      var name = ii.name;
      var str = name.getAccessModifier();
      if (ii.isFinal()) {
        str += " final";
      }
      if (!ii.isSealed()) {
        str += " dynamic";
      }
      str += ii.isInterface() ? " interface " : " class ";
      str += name.getName();
      if (ii.superName && ii.superName.getName() !== "Object") {
        str += " extends " + ii.superName.getName();
      }
      if (ii.interfaces.length) {
        str += " implements " + ii.interfaces.map(function (x) {
          return x.getName();
        }).join(", ");
      }
      writer.enter(str + " {");
      if (!ii.isInterface()) {
        writer.writeLn("public function " + name.getName() + "(" + getSignature(ii.init) + ") {}");
      }
      var interfaceNamespace;
      if (ii.isInterface()) {
        interfaceNamespace = name.namespaces[0].originalURI + ":" + name.name;
      }
      this.traceTraits(ci.traits, true, interfaceNamespace);
      this.traceTraits(ii.traits, false, interfaceNamespace);
      writer.leave("}");
    },

    traceMetadata: function traceMetadata(metadata) {
      const writer = this.writer;

      for (var key in metadata) {
        if (metadata.hasOwnProperty(key)) {
          if (key.indexOf("__") === 0) {
            continue;
          }
          writer.writeLn("[" + key + "(" + metadata[key].items.map(function (m) {
            var str = m.key ? m.key + "=" : "";
            return str + "\"" + m.value + "\"";
          }).join(", ") + ")]");
        }
      }
    }
  };

  return SourceTracer;
})();

function traceSource(writer, abc) {
  var tracer = new SourceTracer(writer);
  abc.scripts.forEach(function (script) {
    tracer.traceTraits(script.traits);
  });
}
<|endoftext|>


<commit_before>$(document).ready(function() {
    $(".search-box").on("input", function(){
        var val = $(this).val().toLowerCase();

        var notags = [];
        var nomatches = val.match(/notag:\w+/g);
        if (nomatches) {
            $.each(nomatches, function(k, v) {
                notags.push(v.substring(6).toLowerCase());
            });
        }
        val = $.trim(val.replace(/\s*notag:\w+/g, ""));

        var tags = [];

        var show_online = false;
        var show_offline = false;

        var matches = val.match(/tag:\w+/g);
        if (matches) {
            $.each(matches, function(k, v) {
                var tag = v.substring(4).toLowerCase();
                if (tag == "online") {
                    show_online = true;
                }
                else if (tag == "offline") {
                    show_offline = true;
                }
                else {
                    tags.push(tag);
                }
            });
        }
        val = $.trim(val.replace(/\s*tag:\w+/g, ""));
        var search_objects = $(this).data("search");
        var search_fields = $(this).data("fields").split(",");
        $(search_objects).each(function(k, v) {
            var t = $(this);
            var fields = $.map(search_fields, function(val, i) {
                return t.find(val).text().toLowerCase();
            });
            var show = true;
            var site_tags = null;
            if (tags.length || notags.length) {
                site_tags = [];
                $(this).find(".tag").each(function(k, v) {
                    site_tags.push($(this).text().replace(/\W/g, "").toLowerCase());
                });
            }
            if (tags.length) {
                show = false;
                $.each(tags, function(k, v) {
                    $.each(site_tags, function(k2, v2) {
                        if (v2.indexOf(v) != -1) {
                            show = true;
                            return false;
                        }
                    });
                });
            }
            if (notags.length) {
                $.each(notags, function(k, v) {
                    $.each(site_tags, function(k2, v2) {
                        if (v2.indexOf(v) != -1) {
                            show = false;
                            return false;
                        }
                    });
                });
            }
            var matches = false;
            $.each(fields, function(k, v) {
                if (v.includes(val)) {
                    matches = true;
                    return false;
                }
            });
            if (show_offline) {
                if (!$(this).find(".fa.pull-left span").hasClass("red")) {
                    show = false;
                }
            }
            if (show_online) {
                if (!$(this).find(".fa.pull-left span").hasClass("green")) {
                    show = false;
                }
            }
            if (show && matches) {
                $(this).show();
            }
            else {
                $(this).hide();
            }
        });
        var sites_shown = $(search_objects + ":visible").length;
        var sites_total = $(search_objects).length;
        if (sites_shown < sites_total) {
            $("#filtered").html("(" + sites_shown + " shown out of " + sites_total + ")");
        }
        else {
            $("#filtered").html("");
        }
    });
});
<commit_msg>search by site type<commit_after>$(document).ready(function() {
    $(".search-box").on("input", function(){
        var val = $(this).val().toLowerCase();

        var notags = [];
        var nomatches = val.match(/notag:\w+/g);
        if (nomatches) {
            $.each(nomatches, function(k, v) {
                notags.push(v.substring(6).toLowerCase());
            });
        }
        val = $.trim(val.replace(/\s*notag:\w+/g, ""));

        var tags = [];

        var show_online = false;
        var show_offline = false;

        var matches = val.match(/tag:\w+/g);
        if (matches) {
            $.each(matches, function(k, v) {
                var tag = v.substring(4).toLowerCase();
                if (tag == "online") {
                    show_online = true;
                }
                else if (tag == "offline") {
                    show_offline = true;
                }
                else {
                    tags.push(tag);
                }
            });
        }
        val = $.trim(val.replace(/\s*tag:\w+/g, ""));

        matches = val.match(/type:\w+/g);
        var types = [];
        if (matches) {
            $.each(matches, function(k, v) {
                types.push(v.substring(5).toLowerCase());
            });
        }
        val = $.trim(val.replace(/\s*type:\w+/g, ""));

        var search_objects = $(this).data("search");
        var search_fields = $(this).data("fields").split(",");
        $(search_objects).each(function(k, v) {
            var t = $(this);
            var fields = $.map(search_fields, function(val, i) {
                return t.find(val).text().toLowerCase();
            });
            var show = true;
            var site_tags = null;
            if (tags.length || notags.length) {
                site_tags = [];
                $(this).find(".tag").each(function(k, v) {
                    site_tags.push($(this).text().replace(/\W/g, "").toLowerCase());
                });
            }
            if (tags.length) {
                show = false;
                $.each(tags, function(k, v) {
                    $.each(site_tags, function(k2, v2) {
                        if (v2.indexOf(v) != -1) {
                            show = true;
                            return false;
                        }
                    });
                });
            }
            if (notags.length) {
                $.each(notags, function(k, v) {
                    $.each(site_tags, function(k2, v2) {
                        if (v2.indexOf(v) != -1) {
                            show = false;
                            return false;
                        }
                    });
                });
            }
            var matches = false;
            $.each(fields, function(k, v) {
                if (v.includes(val)) {
                    matches = true;
                    return false;
                }
            });
            if (show_offline) {
                if (!$(this).find(".fa.pull-left span").hasClass("red")) {
                    show = false;
                }
            }
            if (show_online) {
                if (!$(this).find(".fa.pull-left span").hasClass("green")) {
                    show = false;
                }
            }
            if (types) {
                var cmpObj = $(this).find(".fa.pull-left");
                var cmp = "other";
                if (cmpObj.hasClass("fa-user")) {
                    cmp = "user";
                }
                else if (cmpObj.hasClass("fa-snowflake")) {
                    cmp = "legacy";
                }
                else if (cmpObj.hasClass("fa-globe")) {
                    cmp = "activity";
                }
                if (types.indexOf(cmp) == -1) {
                    show = false;
                }
            }
            if (show && matches) {
                $(this).show();
            }
            else {
                $(this).hide();
            }
        });
        var sites_shown = $(search_objects + ":visible").length;
        var sites_total = $(search_objects).length;
        if (sites_shown < sites_total) {
            $("#filtered").html("(" + sites_shown + " shown out of " + sites_total + ")");
        }
        else {
            $("#filtered").html("");
        }
    });
});
<|endoftext|>


<commit_before>'use strict';

app.directive('volumeEditAccessForm', [
  '$q', 'constantService', 'messageService', 'displayService',
  function ($q, constants, messages, display) {
    var link = function ($scope) {
      var volume = $scope.volume;
      var form = $scope.volumeEditAccessForm;

      form.preset = volume.accessPreset;
      form.data = _.values(volume.access);

      var presetForm = $scope.accessPresetForm;
      var subforms = [];

      $scope.permissionName = function (p) {
        return constants.permission[p];
      };

      function savePreset() {
        if (form.preset == null)
          return;
        form.$setSubmitted();
        $q.all(constants.accessPreset[form.preset].map(function (a, pi) {
          volume.accessSave(constants.accessPreset.parties[pi], {
            individual: a,
            children: a,
          });
        })).then(function () {
          messages.add({
            body: constants.message('access.preset.save.success'),
            type: 'green',
            owner: form
          });
          form.$setPristine();
        }, function (res) {
          form.$setUnsubmitted();
          messages.addError({
            body: constants.message('access.preset.save.error'),
            report: res,
            owner: form
          });
        });
      }

      form.saveAll = function () {
        messages.clear(form);
        subforms.forEach(function (subform) {
          if (subform.$dirty)
            subform.save(false);
        });
        if (presetForm.$dirty)
          savePreset();
      };

      $scope.$on('accessGrantForm-init', function (event, grantForm) {
        subforms.push(grantForm);

        grantForm.removeSuccessFn = function (access) {
          form.data.remove(access);
          subforms.remove(grantForm);
        };
      });

      $scope.selectFn = function (found) {
        form.data.push({
          new: true,
          party: found,
        });
        display.scrollTo('fieldset .access-grant:last');
      };

      form.preSelect = function (p) {
        if (form.data.some(function (a) { return a.party.id === p.id; }))
          display.scrollTo("#access-"+p.id);
        else
          $scope.selectFn(p);
      };

      $scope.$emit('volumeEditAccessForm-init', form);
    };

    return {
      restrict: 'E',
      templateUrl: 'volume/editAccess.html',
      link: link
    };
  }
]);
<commit_msg>Don't error on re-added access party, and add to bottom<commit_after>'use strict';

app.directive('volumeEditAccessForm', [
  '$q', 'constantService', 'messageService', 'displayService',
  function ($q, constants, messages, display) {
    var link = function ($scope) {
      var volume = $scope.volume;
      var form = $scope.volumeEditAccessForm;

      form.preset = volume.accessPreset;
      form.data = _.values(volume.access);

      var presetForm = $scope.accessPresetForm;
      var subforms = [];

      $scope.permissionName = function (p) {
        return constants.permission[p];
      };

      function savePreset() {
        if (form.preset == null)
          return;
        form.$setSubmitted();
        $q.all(constants.accessPreset[form.preset].map(function (a, pi) {
          volume.accessSave(constants.accessPreset.parties[pi], {
            individual: a,
            children: a,
          });
        })).then(function () {
          messages.add({
            body: constants.message('access.preset.save.success'),
            type: 'green',
            owner: form
          });
          form.$setPristine();
        }, function (res) {
          form.$setUnsubmitted();
          messages.addError({
            body: constants.message('access.preset.save.error'),
            report: res,
            owner: form
          });
        });
      }

      form.saveAll = function () {
        messages.clear(form);
        subforms.forEach(function (subform) {
          if (subform.$dirty)
            subform.save(false);
        });
        if (presetForm.$dirty)
          savePreset();
      };

      $scope.$on('accessGrantForm-init', function (event, grantForm) {
        subforms.push(grantForm);

        grantForm.removeSuccessFn = function (access) {
          form.data.remove(access);
          subforms.remove(grantForm);
        };
      });

      $scope.selectFn = function (p) {
        if (form.data.some(function (a) { return a.party.id === p.id; })) {
          display.scrollTo("#access-"+p.id);
        } else {
          form.data.push({
            new: true,
            party: p,
            individual: 0
          });
          display.scrollTo('fieldset .access-grant:last');
        }
      };

      form.preSelect = $scope.selectFn;

      $scope.$emit('volumeEditAccessForm-init', form);
    };

    return {
      restrict: 'E',
      templateUrl: 'volume/editAccess.html',
      link: link
    };
  }
]);
<|endoftext|>


<commit_before>'use strict';

var Assert = require('assert');
var Fs = require('fs');
var JsYaml = require('../../lib/js-yaml');
var Common = require('../../lib/js-yaml/common');
var Nodes = require('../../lib/js-yaml/nodes');
var Helper = require('../helper');

module.exports = {
  "Test implicit resolver": Helper.functional({
    dirname: __dirname + '/data',
    files: ['.data', '.detect'],
    test: function (dataFilename, detectFilename) {
      var correctTag, node;

      node = JsYaml.compose(Fs.readFileSync(dataFilename, 'utf8'));
      correctTag = Fs.readFileSync(detectFilename, 'utf8')
        .replace(/^[ \s]+|[ \s]+$/g, '');

      Assert.equal(Common.isInstanceOf(node, Nodes.SequenceNode), true);

      Common.each(node.value, function (scalar) {
        Assert.equal(Common.isInstanceOf(scalar, Nodes.ScalarNode), true);
        Assert.equal(scalar.tag, correctTag);
      });
    }
  })
};

////////////////////////////////////////////////////////////////////////////////
// vim:ts=2:sw=2
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Port 'functional/resolver' tests to new API.<commit_after>'use strict';

var assert = require('chai').assert;
var functional = require('../helpers/functional');
var jsyaml = require('../../lib/js-yaml');
var $$ = require('../../lib/js-yaml/common');
var _nodes  = require('../../lib/js-yaml/nodes');

functional.generateTests({
  description: "Test implicit resolver.",
  files: ['.data', '.detect'],
  handler: function (dataFile, detectFile) {
    var node, correctTag;

    node = jsyaml.compose(dataFile.data);
    correctTag = detectFile.data.replace(/^[ \s]+|[ \s]+$/g, '');

    assert.isTrue($$.isInstanceOf(node, _nodes.SequenceNode));

    $$.each(node.value, function (scalar) {
      assert.isTrue($$.isInstanceOf(scalar, _nodes.ScalarNode));
      assert.equal(scalar.tag, correctTag);
    });
  }
});
<|endoftext|>


<commit_before>$(document).ready(function() {
    $(".search-box").on("input", function(){
        var val = $(this).val().toLowerCase();

        var notags = [];
        var nomatches = val.match(/notag:\w+/g);
        if (nomatches) {
            $.each(nomatches, function(k, v) {
                notags.push(v.substring(6).toLowerCase());
            });
        }
        val = $.trim(val.replace(/\s*notag:\w+/g, ""));

        var tags = [];

        var show_online = false;
        var show_offline = false;

        var matches = val.match(/tag:\w+/g);
        if (matches) {
            $.each(matches, function(k, v) {
                var tag = v.substring(4).toLowerCase();
                if (tag == "online") {
                    show_online = true;
                }
                else if (tag == "offline") {
                    show_offline = true;
                }
                else {
                    tags.push(tag);
                }
            });
        }
        val = $.trim(val.replace(/\s*tag:\w+/g, ""));

        matches = val.match(/type:\w+/g);
        var types = [];
        if (matches) {
            $.each(matches, function(k, v) {
                types.push(v.substring(5).toLowerCase());
            });
        }
        val = $.trim(val.replace(/\s*type:\w+/g, ""));

        var search_objects = $(this).data("search");
        var search_fields = $(this).data("fields").split(",");
        $(search_objects).each(function(k, v) {
            var t = $(this);
            var fields = $.map(search_fields, function(val, i) {
                return t.find(val).text().toLowerCase();
            });
            var show = true;
            var site_tags = null;
            if (tags.length || notags.length) {
                site_tags = [];
                $(this).find(".tag").each(function(k, v) {
                    site_tags.push($(this).text().replace(/\W/g, "").toLowerCase());
                });
            }
            if (tags.length) {
                show = false;
                $.each(tags, function(k, v) {
                    $.each(site_tags, function(k2, v2) {
                        if (v2.indexOf(v) != -1) {
                            show = true;
                            return false;
                        }
                    });
                });
            }
            if (notags.length) {
                $.each(notags, function(k, v) {
                    $.each(site_tags, function(k2, v2) {
                        if (v2.indexOf(v) != -1) {
                            show = false;
                            return false;
                        }
                    });
                });
            }
            var matches = false;
            $.each(fields, function(k, v) {
                if (v.includes(val)) {
                    matches = true;
                    return false;
                }
            });
            if (show_offline) {
                if (!$(this).find(".fa.pull-left span").hasClass("red")) {
                    show = false;
                }
            }
            if (show_online) {
                if (!$(this).find(".fa.pull-left span").hasClass("green")) {
                    show = false;
                }
            }
            if (types) {
                var cmpObj = $(this).find(".fa.pull-left");
                var cmp = "other";
                if (cmpObj.hasClass("fa-user")) {
                    cmp = "user";
                }
                else if (cmpObj.hasClass("fa-snowflake")) {
                    cmp = "legacy";
                }
                else if (cmpObj.hasClass("fa-globe")) {
                    cmp = "activity";
                }
                if (types.indexOf(cmp) == -1) {
                    show = false;
                }
            }
            if (show && matches) {
                $(this).show();
            }
            else {
                $(this).hide();
            }
        });
        var sites_shown = $(search_objects + ":visible").length;
        var sites_total = $(search_objects).length;
        if (sites_shown < sites_total) {
            $("#filtered").html("(" + sites_shown + " shown out of " + sites_total + ")");
        }
        else {
            $("#filtered").html("");
        }
    });
});
<commit_msg>fix search<commit_after>$(document).ready(function() {
    $(".search-box").on("input", function(){
        var val = $(this).val().toLowerCase();

        var notags = [];
        var nomatches = val.match(/notag:\w+/g);
        if (nomatches) {
            $.each(nomatches, function(k, v) {
                notags.push(v.substring(6).toLowerCase());
            });
        }
        val = $.trim(val.replace(/\s*notag:\w+/g, ""));

        var tags = [];

        var show_online = false;
        var show_offline = false;

        var matches = val.match(/tag:\w+/g);
        if (matches) {
            $.each(matches, function(k, v) {
                var tag = v.substring(4).toLowerCase();
                if (tag == "online") {
                    show_online = true;
                }
                else if (tag == "offline") {
                    show_offline = true;
                }
                else {
                    tags.push(tag);
                }
            });
        }
        val = $.trim(val.replace(/\s*tag:\w+/g, ""));

        matches = val.match(/type:\w+/g);
        var types = [];
        if (matches) {
            $.each(matches, function(k, v) {
                types.push(v.substring(5).toLowerCase());
            });
        }
        val = $.trim(val.replace(/\s*type:\w+/g, ""));

        var search_objects = $(this).data("search");
        var search_fields = $(this).data("fields").split(",");
        $(search_objects).each(function(k, v) {
            var t = $(this);
            var fields = $.map(search_fields, function(val, i) {
                return t.find(val).text().toLowerCase();
            });
            var show = true;
            var site_tags = null;
            if (tags.length || notags.length) {
                site_tags = [];
                $(this).find(".tag").each(function(k, v) {
                    site_tags.push($(this).text().replace(/\W/g, "").toLowerCase());
                });
            }
            if (tags.length) {
                show = false;
                $.each(tags, function(k, v) {
                    $.each(site_tags, function(k2, v2) {
                        if (v2.indexOf(v) != -1) {
                            show = true;
                            return false;
                        }
                    });
                });
            }
            if (notags.length) {
                $.each(notags, function(k, v) {
                    $.each(site_tags, function(k2, v2) {
                        if (v2.indexOf(v) != -1) {
                            show = false;
                            return false;
                        }
                    });
                });
            }
            var matches = false;
            $.each(fields, function(k, v) {
                if (v.includes(val)) {
                    matches = true;
                    return false;
                }
            });
            if (show_offline) {
                if (!$(this).find(".fa.pull-left span").hasClass("red")) {
                    show = false;
                }
            }
            if (show_online) {
                if (!$(this).find(".fa.pull-left span").hasClass("green")) {
                    show = false;
                }
            }
            if (types.length) {
                var cmpObj = $(this).find(".fa.pull-left");
                var cmp = "other";
                if (cmpObj.hasClass("fa-user")) {
                    cmp = "user";
                }
                else if (cmpObj.hasClass("fa-snowflake-o")) {
                    cmp = "legacy";
                }
                else if (cmpObj.hasClass("fa-globe")) {
                    cmp = "activity";
                }
                if (types.indexOf(cmp) == -1) {
                    show = false;
                }
            }
            if (show && matches) {
                $(this).show();
            }
            else {
                $(this).hide();
            }
        });
        var sites_shown = $(search_objects + ":visible").length;
        var sites_total = $(search_objects).length;
        if (sites_shown < sites_total) {
            $("#filtered").html("(" + sites_shown + " shown out of " + sites_total + ")");
        }
        else {
            $("#filtered").html("");
        }
    });
});
<|endoftext|>


<commit_before>var rights = JSON.parse("{" +
	"\"net-atos-entng-actualites-controllers-ActualitesController|comment\": \"net-atos-entng-actualites-controllers-CommentController|comment\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|deleteComment\": \"net-atos-entng-actualites-controllers-CommentController|deleteComment\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|listThreadInfos\": \"net-atos-entng-actualites-controllers-InfoController|listInfosByThreadId\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|getThread\": \"net-atos-entng-actualites-controllers-ThreadController|getThread\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|updatePending\": \"net-atos-entng-actualites-controllers-InfoController|updatePending\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|unpublish\": \"net-atos-entng-actualites-controllers-InfoController|unpublish\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|publish\": \"net-atos-entng-actualites-controllers-InfoController|publish\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|updateDraft\": \"net-atos-entng-actualites-controllers-InfoController|updateDraft\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|submit\": \"net-atos-entng-actualites-controllers-InfoController|submit\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|trash\": \"net-atos-entng-actualites-controllers-InfoController|trash\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|getInfo\": \"net-atos-entng-actualites-controllers-InfoController|getInfo\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|createDraft\": \"net-atos-entng-actualites-controllers-InfoController|createDraft\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|restore\": \"net-atos-entng-actualites-controllers-InfoController|restore\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|unsubmit\": \"net-atos-entng-actualites-controllers-InfoController|unsubmit\"" +
"}");

var info_old_rights = ["net-atos-entng-actualites-controllers-ActualitesController|comment",
                   "net-atos-entng-actualites-controllers-ActualitesController|deleteComment",
                   "net-atos-entng-actualites-controllers-ActualitesController|getInfo"];
var info_new_rights = ["net-atos-entng-actualites-controllers-CommentController|comment",
                       "net-atos-entng-actualites-controllers-CommentControllerr|deleteComment",
                       "net-atos-entng-actualites-controllers-InfoController|getInfo"];
var info_old_rights = ["net-atos-entng-actualites-controllers-ActualitesController|comment",
                       "net-atos-entng-actualites-controllers-ActualitesController|deleteComment",
                       "net-atos-entng-actualites-controllers-ActualitesController|getInfo"];
var contrib_rights = ["net-atos-entng-actualites-controllers-InfoController|listInfosByThreadId",
                      "net-atos-entng-actualites-controllers-ThreadController|getThread",
                      "net-atos-entng-actualites-controllers-InfoController|createPending",
                      "net-atos-entng-actualites-controllers-InfoController|shareInfo",
                      "net-atos-entng-actualites-controllers-InfoController|shareInfoRemove",
                      "net-atos-entng-actualites-controllers-InfoController|shareInfoSubmit" ];
var publish_rights = ["net-atos-entng-actualites-controllers-InfoController|createPublished",
					 "net-atos-entng-actualites-controllers-InfoController|updatePublished"];

print("BEGIN;");
db.actualites.threads.find().forEach(function(thread){
	if(thread.title !== undefined && thread.owner.userId !== undefined){
		// Insert user if not exist
		var user_query = "SELECT actualites.insert_user('" +
			thread.owner.userId + "', '" + thread.owner.displayName.replace(/'/g, "''") + "');";
		print(user_query);
		// thread entry
		var thread_query = "INSERT INTO actualites.thread (owner, created, modified, title";
		var thread_values = " VALUES ('"
			+ thread.owner.userId + "', '"
			+ thread.created.toISOString() + "', '"
			+ thread.modified.toISOString() + "', '"
			+ thread.title.replace(/'/g, "''") + "'";
		if(thread.icon !== undefined){
			thread_query += ", icon";
			thread_values += ", '" + thread.icon + "'";
		}
		thread_query += ", mode)";
		thread_values += (thread.mode !== undefined) ? ", " + thread.mode + ");" : ", 0);";
		thread_query = thread_query + thread_values;
		print(thread_query);
		if(thread.shared !== undefined){
			// thread_share entry
			var thread_share_query = "INSERT INTO actualites.thread_shares VALUES ";
			thread.shared.forEach(function(share){
				var keys = Object.keys(share);
				var memeberId = (share.userId !== undefined) ? share.userId : share.groupId;
				for(var i=1; i<keys.length; i++){
					if(share[keys[i]] === true && info_old_rights.indexOf(keys[i]) === -1){
						// getThread & listInfosByThreadId rights will be added with the contrib rights
						if(keys[i] !== "net-atos-entng-actualites-controllers-ActualitesController|getThread" &&
								keys[i] !== "net-atos-entng-actualites-controllers-ActualitesController|listThreadInfos"){
							thread_share_query += "('" + memeberId + "', currval('actualites.thread_id_seq'), '" + rights[keys[i]] + "'), ";
						}
						// add new publish rights
						if(keys[i] === "net-atos-entng-actualites-controllers-ActualitesController|publish"){
							publish_rights.forEach(function(right){
								thread_share_query += "('" + memeberId + "', currval('actualites.thread_id_seq'), '" + right + "'), ";
							});
						}
						// add new contrib rights
						if(keys[i] === "net-atos-entng-actualites-controllers-ActualitesController|createDraft"){
							contrib_rights.forEach(function(right){
								thread_share_query += "('" + memeberId + "', currval('actualites.thread_id_seq'), '" + right + "'), ";
							});
						}
					}
				}
				// Insert user / group if not exist
				if(share.userId !== undefined){
					var user_query = "SELECT actualites.insert_user('" +
						share.userId + "', '');";
					print(user_query);
				} else {
					var group_query = "SELECT actualites.insert_group('" +
						share.groupId + "', '');";
					print(group_query);
				}
			});
			print(thread_share_query.replace(/, $/, ";"));
		}
		if(thread.infos !== undefined){
			thread.infos.forEach(function(info){
				if(info.title !== undefined && info.status !== undefined && info.owner.userId !== undefined){
					// Insert user if not exist
					var user_query = "SELECT actualites.insert_user('" +
						thread.owner.userId + "', '" + thread.owner.displayName.replace(/'/g, "''") + "');";
					print(user_query);
					var info_query = "INSERT INTO actualites.info (owner, created, modified, title";
					var info_values = " VALUES ('"
						+ info.owner.userId
						+ "', '" + info.created.toISOString()
						+ "', '" + info.modified.toISOString()
						+ "', '" + info.title.replace(/'/g, "''");
					if(info.content !== undefined){
						info_query += ", content";
						info_values += "', '" + info.content.replace(/'/g, "''");
					}
					info_query += ", status";
					info_values += "', " + info.status;
					if(info.publicationDate !== null){
						info_query += ", publication_date";
						info_values += ", '" + info.publicationDate.toISOString() + "'";
					}
					if(info.expirationDate !== null){
						info_query += ", expiration_date";
						info_values += ", '" + info.expirationDate.toISOString() + "'";
					}
					info_query += ", is_headline, thread_id)";
					info_values += (info.isHeadline !== undefined) ? ", " + info.isHeadline : ", false";
					info_values += ", currval('actualites.thread_id_seq'));";
					info_query = info_query + info_values;
					print(info_query);
					if(thread.shared !== undefined){
						// info_share entry
						var info_share_query = "INSERT INTO actualites.info_shares VALUES ";
						thread.shared.forEach(function(share){
							var keys = Object.keys(share);
							var memeberId = (share.userId !== undefined) ? share.userId : share.groupId;
							var can_read = false;
							for(var i=1; !can_read && i<keys.length; i++){
								// can read info ?
								if(share[keys[i]] === true && info_old_rights.indexOf(keys[i]) !== -1){
									can_read = true;
									info_new_rights.forEach(function(right){
										info_share_query += "('" + memeberId + "', currval('actualites.info_id_seq'), '" + right + "'), ";
									});
								}
							}
							// Insert user / group if not exist
							if(share.userId !== undefined){
								var user_query = "SELECT actualites.insert_user('" +
									share.userId + "', '');";
								print(user_query);
							} else {
								var group_query = "SELECT actualites.insert_group('" +
									share.groupId + "', '');";
								print(group_query);
							}
						});
						print(info_share_query.replace(/, $/, ";"));
					}
					if(info.comments !== undefined){
						info.comments.forEach(function(comment){
							if(comment.comment !== undefined && comment.author !== undefined){
								var comment_query = "INSERT INTO actualites.comment (owner, created, modified, comment, info_id) VALUES ('"
									+ comment.author.replace(/'/g, "''") + "', '"
									+ comment.posted.toISOString() + "', '"
									+ comment.posted.toISOString() + "', '"
									+ comment.comment.replace(/'/g, "''") + "', "
									+ "currval('actualites.info_id_seq'));";
							}
							print(comment_query);
						});
					}
				}
			});
		}
	}
});
print("COMMIT;");<commit_msg>#2895 corrections<commit_after>var rights = JSON.parse("{" +
	"\"net-atos-entng-actualites-controllers-ActualitesController|comment\": \"net-atos-entng-actualites-controllers-CommentController|comment\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|deleteComment\": \"net-atos-entng-actualites-controllers-CommentController|deleteComment\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|listThreadInfos\": \"net-atos-entng-actualites-controllers-InfoController|listInfosByThreadId\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|getThread\": \"net-atos-entng-actualites-controllers-ThreadController|getThread\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|updatePending\": \"net-atos-entng-actualites-controllers-InfoController|updatePending\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|unpublish\": \"net-atos-entng-actualites-controllers-InfoController|unpublish\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|publish\": \"net-atos-entng-actualites-controllers-InfoController|publish\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|updateDraft\": \"net-atos-entng-actualites-controllers-InfoController|updateDraft\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|submit\": \"net-atos-entng-actualites-controllers-InfoController|submit\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|trash\": \"net-atos-entng-actualites-controllers-InfoController|trash\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|getInfo\": \"net-atos-entng-actualites-controllers-InfoController|getInfo\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|createDraft\": \"net-atos-entng-actualites-controllers-InfoController|createDraft\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|restore\": \"net-atos-entng-actualites-controllers-InfoController|restore\", " +
	"\"net-atos-entng-actualites-controllers-ActualitesController|unsubmit\": \"net-atos-entng-actualites-controllers-InfoController|unsubmit\"" +
"}");

var info_old_rights = ["net-atos-entng-actualites-controllers-ActualitesController|comment",
                   "net-atos-entng-actualites-controllers-ActualitesController|deleteComment",
                   "net-atos-entng-actualites-controllers-ActualitesController|getInfo"];
var info_new_rights = ["net-atos-entng-actualites-controllers-CommentController|comment",
                       "net-atos-entng-actualites-controllers-CommentControllerr|deleteComment",
                       "net-atos-entng-actualites-controllers-InfoController|getInfo"];
var info_old_rights = ["net-atos-entng-actualites-controllers-ActualitesController|comment",
                       "net-atos-entng-actualites-controllers-ActualitesController|deleteComment",
                       "net-atos-entng-actualites-controllers-ActualitesController|getInfo"];
var contrib_rights = ["net-atos-entng-actualites-controllers-InfoController|listInfosByThreadId",
                      "net-atos-entng-actualites-controllers-ThreadController|getThread",
                      "net-atos-entng-actualites-controllers-InfoController|createPending",
                      "net-atos-entng-actualites-controllers-InfoController|shareInfo",
                      "net-atos-entng-actualites-controllers-InfoController|shareInfoRemove",
                      "net-atos-entng-actualites-controllers-InfoController|shareInfoSubmit" ];
var publish_rights = ["net-atos-entng-actualites-controllers-InfoController|createPublished",
					 "net-atos-entng-actualites-controllers-InfoController|updatePublished"];

print("BEGIN;");
db.actualites.threads.find().forEach(function(thread){
	if(thread.title && thread.owner.userId){
		// Insert user if not exist
		var user_query = "SELECT actualites.insert_user('" +
			thread.owner.userId + "', '" + thread.owner.displayName.replace(/'/g, "''") + "');";
		print(user_query);
		// thread entry
		var thread_query = "INSERT INTO actualites.thread (owner, created, modified, title";
		var thread_values = " VALUES ('"
			+ thread.owner.userId + "', '"
			+ thread.created.toISOString() + "', '"
			+ thread.modified.toISOString() + "', '"
			+ thread.title.replace(/'/g, "''") + "'";
		if(thread.icon){
			thread_query += ", icon";
			thread_values += ", '" + thread.icon + "'";
		}
		thread_query += ", mode)";
		thread_values += (thread.mode !== undefined) ? ", " + thread.mode + ");" : ", 0);";
		thread_query = thread_query + thread_values;
		print(thread_query);
		if(thread.shared && thread.shared.length > 0){
			// thread_share entry
			var thread_share_query = "INSERT INTO actualites.thread_shares VALUES ";
			thread.shared.forEach(function(share){
				var keys = Object.keys(share);
				var memeberId = (share.userId) ? share.userId : share.groupId;
				for(var i=1; i<keys.length; i++){
					if(share[keys[i]] === true && info_old_rights.indexOf(keys[i]) === -1){
						// getThread & listInfosByThreadId rights will be added with the contrib rights
						if(keys[i] !== "net-atos-entng-actualites-controllers-ActualitesController|getThread" &&
								keys[i] !== "net-atos-entng-actualites-controllers-ActualitesController|listThreadInfos"){
							thread_share_query += "('" + memeberId + "', currval('actualites.thread_id_seq'), '" + rights[keys[i]] + "'), ";
						}
						// add new publish rights
						if(keys[i] === "net-atos-entng-actualites-controllers-ActualitesController|publish"){
							publish_rights.forEach(function(right){
								thread_share_query += "('" + memeberId + "', currval('actualites.thread_id_seq'), '" + right + "'), ";
							});
						}
						// add new contrib rights
						if(keys[i] === "net-atos-entng-actualites-controllers-ActualitesController|createDraft"){
							contrib_rights.forEach(function(right){
								thread_share_query += "('" + memeberId + "', currval('actualites.thread_id_seq'), '" + right + "'), ";
							});
						}
					}
				}
				// Insert user / group if not exist
				if(share.userId){
					var user_query = "SELECT actualites.insert_user('" +
						share.userId + "', '');";
					print(user_query);
				} else {
					var group_query = "SELECT actualites.insert_group('" +
						share.groupId + "', '');";
					print(group_query);
				}
			});
			print(thread_share_query.replace(/, $/, ";"));
		}
		if(thread.infos){
			thread.infos.forEach(function(info){
				if(info.title && info.status !== undefined && info.owner.userId){
					// Insert user if not exist
					var user_query = "SELECT actualites.insert_user('" +
						thread.owner.userId + "', '" + thread.owner.displayName.replace(/'/g, "''") + "');";
					print(user_query);
					var info_query = "INSERT INTO actualites.info (owner, created, modified, title";
					var info_values = " VALUES ('"
						+ info.owner.userId
						+ "', '" + info.created.toISOString()
						+ "', '" + info.modified.toISOString()
						+ "', '" + info.title.replace(/'/g, "''");
					if(info.content){
						info_query += ", content";
						info_values += "', '" + info.content.replace(/'/g, "''");
					}
					info_query += ", status";
					info_values += "', " + info.status;
					if(info.publicationDate){
						info_query += ", publication_date";
						info_values += ", '" + info.publicationDate.toISOString() + "'";
					}
					if(info.expirationDate){
						info_query += ", expiration_date";
						info_values += ", '" + info.expirationDate.toISOString() + "'";
					}
					info_query += ", is_headline, thread_id)";
					info_values += (info.isHeadline !== undefined) ? ", " + info.isHeadline : ", false";
					info_values += ", currval('actualites.thread_id_seq'));";
					info_query = info_query + info_values;
					print(info_query);
					if(thread.shared && thread.shared.length > 0){
						// info_share entry
						var info_share_query = "INSERT INTO actualites.info_shares VALUES ";
						thread.shared.forEach(function(share){
							var keys = Object.keys(share);
							var memeberId = (share.userId) ? share.userId : share.groupId;
							var can_read = false;
							for(var i=1; !can_read && i<keys.length; i++){
								// can read info ?
								if(share[keys[i]] === true && info_old_rights.indexOf(keys[i]) !== -1){
									can_read = true;
									info_new_rights.forEach(function(right){
										info_share_query += "('" + memeberId + "', currval('actualites.info_id_seq'), '" + right + "'), ";
									});
								}
							}
							// Insert user / group if not exist
							if(share.userId){
								var user_query = "SELECT actualites.insert_user('" +
									share.userId + "', '');";
								print(user_query);
							} else {
								var group_query = "SELECT actualites.insert_group('" +
									share.groupId + "', '');";
								print(group_query);
							}
						});
						print(info_share_query.replace(/, $/, ";"));
					}
					if(info.comments){
						info.comments.forEach(function(comment){
							if(comment.comment && comment.author){
								var comment_query = "INSERT INTO actualites.comment (owner, created, modified, comment, info_id) VALUES ('"
									+ comment.author.replace(/'/g, "''") + "', '"
									+ comment.posted.toISOString() + "', '"
									+ comment.posted.toISOString() + "', '"
									+ comment.comment.replace(/'/g, "''") + "', "
									+ "currval('actualites.info_id_seq'));";
							}
							print(comment_query);
						});
					}
				}
			});
		}
	}
});
print("COMMIT;");<|endoftext|>


<commit_before>.state('<%-s.friendly%>', {
 url: '<%-stateName%>',
 templateUrl: 'partial/<%=controller%>.html',
 controller: '<%=controller%>Ctrl'
})
<% Object.keys(s.elements).forEach(function(actionableName){
var a = s.elements[actionableName]; %>
.state('<%-s.friendly%>.<%=actionableName%>', {
  url: '/<%=actionableName%><%-a.subPath%>',
  templateUrl: 'partial/<%=controller%>.<%=actionableName%>.html',
  controller:function($scope, $stateParams,RestService, SocketService,$translate) {
    var stateName = '<%=actionableName%>';
    var id = $scope.params.id= $stateParams.id;
    if(id){
      RestService['FINDBYID']('<%- s.url %>', null,id,function(err,data){
        $scope.data[stateName]=data;
        console.log("Loaded %s",$stateParams.id,$scope.data[stateName]);
      });
    }
    <%
      var actions= a.components.actions;
      Object.keys(actions).forEach(function(act){
        var action = actions[act];
      %>
      // This method is called when using a REST API

      <% if(act.match(/find/i)){ %>
        $scope.currentPage=1;

        $scope.gridOptions = {
            data: 'table.results',
//            enableCellSelection: true,
//            enableRowSelection: false,
//            enableCellEditOnFocus: true,
            columnDefs: [
                         <%
                         console.log(a.components);
                         var elems =a.components.elements;
                         Object.keys(elems).forEach(function(elem){
                           var element=elems[elem];
                         %>
                         {field: '<%-elem%>', headerCellTemplate:"{{'<%-element.ui.title%>'|translate}}"},
                        <%});%>
                        ]
        }

        $scope.on<%= act %> = function(notUsed,page) {
          page = page || 1;
          var data = $scope.data['<%= act %>'];
          RestService['<%= act %>']('<%- s.url%>', data,page,function(err,data){
            console.log("loading page:", JSON.stringify(data,null,2))
            $scope.table=data;
          });
        }
        //$scope.$watch( 'currentPage', $scope.on<%= act %> );
      <% } else {%>
        $scope.on<%= act %> = function() {
          var data = $scope.data['<%= act %>'];
          RestService['<%= act %>']('<%- s.url%>', data,id,function(err,data){
            $scope.data['<%= act %>']=data;
          });
        }
      <% }%>
    <%});%>

  }
})
<% }); %>
<commit_msg>ng-grid<commit_after>.state('<%-s.friendly%>', {
 url: '<%-stateName%>',
 templateUrl: 'partial/<%=controller%>.html',
 controller: '<%=controller%>Ctrl'
})
<% Object.keys(s.elements).forEach(function(actionableName){
var a = s.elements[actionableName]; %>
.state('<%-s.friendly%>.<%=actionableName%>', {
  url: '/<%=actionableName%><%-a.subPath%>',
  templateUrl: 'partial/<%=controller%>.<%=actionableName%>.html',
  controller:function($scope, $stateParams,RestService, SocketService,$translate) {
    var stateName = '<%=actionableName%>';
    var id = $scope.params.id= $stateParams.id;
    if(id){
      RestService['FINDBYID']('<%- s.url %>', null,id,function(err,data){
        $scope.data[stateName]=data;
        console.log("Loaded %s",$stateParams.id,$scope.data[stateName]);
      });
    }
    <%
      var actions= a.components.actions;
      Object.keys(actions).forEach(function(act){
        var action = actions[act];
      %>
      // This method is called when using a REST API

      <% if(act.match(/find/i)){ %>
        $scope.currentPage=1;

        $scope.gridOptions = {
            data: 'table.results',
            enablePinning: true,
            enableColumnResize: true,
            columnDefs: [
                         <%
                         var elems =a.components.elements;
                         Object.keys(elems).forEach(function(elem, index, test){
                           var width = 'auto';
                           if(index == test.length-1){
                             width = '*';
                           }
                           var element=elems[elem];
                         %>
                         {
                           field: '<%-elem%>',
                           width: '<%-width%>',
                           minWidth: 150,
                           resizable: true,
                           headerCellTemplate:"
{{'<%-element.ui.title%>'|translate}}
" +
                              "

" +
                              "

" +
                           	  "

" +
                           		"

"
                         },
                        <%});%>
                        ]
        }

        $scope.on<%= act %> = function(notUsed,page) {
          page = page || 1;
          var data = $scope.data['<%= act %>'];
          RestService['<%= act %>']('<%- s.url%>', data,page,function(err,data){
            console.log("loading page:", JSON.stringify(data,null,2))
            $scope.table=data;
          });
        }
        //$scope.$watch( 'currentPage', $scope.on<%= act %> );
      <% } else {%>
        $scope.on<%= act %> = function() {
          var data = $scope.data['<%= act %>'];
          RestService['<%= act %>']('<%- s.url%>', data,id,function(err,data){
            $scope.data['<%= act %>']=data;
          });
        }
      <% }%>
    <%});%>

  }
})
<% }); %>
<|endoftext|>


<commit_before>function initialize() {
  var options = {
    'document' : 'urn:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6bm1fYnVja2V0L01HTV9EU1RfUGFuZWxMLkNBVFBhcnQ=',
    'env':'AutodeskProduction',
    'getAccessToken': getToken,
    'refreshToken': getToken,
  };
  var viewerElement = document.getElementById('viewer');
  var viewer = new Autodesk.Viewing.Viewer3D(viewerElement, {});
  Autodesk.Viewing.Initializer(options,function() {
    viewer.initialize();
    loadDocument(viewer, options.document);
  });
}

function getToken() {
  /*
  $.get("http://" + window.location.host + ':5000/api/token', function (accessToken){
    options.accessToken (responseText);
  });
  return accessToken;
  */
  return "AaBUsx35j2MY6rtAmyiXlvX84nqp";
}

function loadDocument(viewer, documentId) {
  // Find the first 3d geometry and load that.
  Autodesk.Viewing.Document.load(documentId, function(doc) {// onLoadCallback
  var geometryItems = [];
  geometryItems = Autodesk.Viewing.Document.getSubItemsWithProperties(doc.getRootItem(), {
      type : "geometry",
      role : "3d"
  }, true);
  if (geometryItems.length > 0) {
      viewer.load(doc.getViewablePath(geometryItems[0]));
  }
}, function(errorMsg) {// onErrorCallback
  alert("Load Error: " + errorMsg);
  });
}<commit_msg>Tokens<commit_after>function initialize() {
  var options = {
    "document" : "urn:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6bm1fYnVja2V0L01HTV9EU1RfUGFuZWxMLkNBVFBhcnQ=",
    "env" : "AutodeskProduction",
    "getAccessToken" : getToken,
    "refreshToken" : getToken
  };
  var viewerElement = document.getElementById('viewer');
  var viewer = new Autodesk.Viewing.Viewer3D(viewerElement, {});
  Autodesk.Viewing.Initializer(options,function() {
    viewer.initialize();
    loadDocument(viewer, options.document);
  });
}

function getToken() {
  /*
  $.get("http://" + window.location.host + ':5000/api/token', function (accessToken){
    options.accessToken (responseText);
  });
  return accessToken;
  */
  return "duxEqWiLPFnJLdUbL0RbACWxY0NU";
}

function loadDocument(viewer, documentId) {
  // Find the first 3d geometry and load that.
  Autodesk.Viewing.Document.load(documentId, function(doc) {// onLoadCallback
  var geometryItems = [];
  geometryItems = Autodesk.Viewing.Document.getSubItemsWithProperties(doc.getRootItem(), {
      "type" : "geometry",
      "role" : "3d"
  }, true);
  if (geometryItems.length > 0) {
      viewer.load(doc.getViewablePath(geometryItems[0]));
  }
}, function(errorMsg) {// onErrorCallback
  alert("Load Error: " + errorMsg);
  });
}<|endoftext|>