<commit_before>'use strict';

const { ObjCAvailable } = require('../darwin');
const java = require('../java');
const search = require('../search');
const utils = require('../utils');

function listClassesLoadedJson (args) {
  if (java.JavaAvailable) {
    return java.listClasses(args);
  }
  if (ObjCAvailable) {
    return JSON.stringify(ObjC.enumerateLoadedClassesSync());
  }
}

function listClassesLoaders (args) {
  if (!java.JavaAvailable) {
    return 'Error: icL is only available on Android targets.';
  }
  let res = '';
  javaPerform(function () {
    function s2o (s) {
      let indent = 0;
      let res = '';
      for (const ch of s.toString()) {
        switch (ch) {
          case '[':
            indent++;
            res += '[\n' + Array(indent + 1).join(' ');
            break;
          case ']':
            indent--;
            res += ']\n' + Array(indent + 1).join(' ');
            break;
          case ',':
            res += ',\n' + Array(indent + 1).join(' ');
            break;
          default:
            res += ch;
            break;
        }
      }
      return res;
    }
    const c = Java.enumerateClassLoadersSync();
    for (const cl in c) {
      const cs = s2o(c[cl].toString());
      res += cs;
    }
  });
  return res;
}

function listClassesLoaded (args) {
  if (java.JavaAvailable) {
    return listClasses(args);
  }
  if (ObjCAvailable) {
    const results = ObjC.enumerateLoadedClassesSync();
    const loadedClasses = [];
    for (const module of Object.keys(results)) {
      loadedClasses.push(...results[module]);
    }
    return loadedClasses.join('\n');
  }
  return [];
}

// only for java
function listAllClassesNatives (args) {
  return listClassesNatives(['.']);
}

function listClassesNatives (args) {
  const natives = [];
  const vkn = args[0] || 'com';
  javaPerform(function () {
    const klasses = listClassesJson([]);
    for (let kn of klasses) {
      kn = kn.toString();
      // if (kn.indexOf('android') !== -1) { continue; }
      if (kn.indexOf(vkn) === -1) {
        continue;
      }
      try {
        const handle = java.javaUse(kn);
        const klass = handle.class;
        const klassNatives = klass.getMethods().map(_ => _.toString()).filter(_ => _.indexOf('static native') !== -1);
        if (klassNatives.length > 0) {
          const kns = klassNatives.map((n) => {
            const p = n.indexOf('(');
            let sn = '';
            if (p !== -1) {
              const s = n.substring(0, p);
              const w = s.split(' ');
              sn = w[w.length - 1];
              return sn;
            }
            return n; // { name: sn, fullname: n };
          });
          console.error(kns.join('\n'));
          for (const tkn of kns) {
            if (natives.indexOf(tkn) === -1) {
              natives.push(tkn);
            }
          }
        }
      } catch (ignoreError) {
      }
    }
  });
  return natives;
}

function listClassesAllMethods (args) {
  return listClassesJson(args, 'all').join('\n');
}

function listClassSuperMethods (args) {
  return listClassesJson(args, 'super').join('\n');
}

function listClassVariables (args) {
  return listClassesJson(args, 'ivars').join('\n');
}

function listClassesHooks (args, mode) {
  let out = '';
  if (args.length === 0) {
    return 'Usage: :ich [kw]';
  }
  const moduleNames = {};
  const result = listClassesJson([]);
  if (ObjCAvailable) {
    const klasses = ObjC.classes;
    for (const k of result) {
      moduleNames[k] = ObjC.classes[k].$moduleName;
    }
  }
  for (const k of result) {
    const modName = moduleNames[k];
    if (k.indexOf(args[0]) !== -1 || (modName && modName.indexOf(args[0]) !== -1)) {
      const ins = search.searchInstancesJson([k]);
      const inss = ins.map((x) => { return x.address; }).join(' ');
      const a = 'OOO';
      const klass = ObjC.classes[k];
      if (klass) {
        for (const m of klass.$ownMethods) {
          // TODO: use instance.argumentTypes to generate the 'OOO'
          out += ':dtf objc:' + k + '.' + m + ' ' + a + '\n';
        }
      }
    }
  }
  return out;
}

function listClassesWhere (args, mode) {
  let out = '';
  if (args.length === 0) {
    const moduleNames = {};
    const result = listClassesJson([]);
    if (ObjCAvailable) {
      const klasses = ObjC.classes;
      for (const k of result) {
        moduleNames[k] = klasses[k].$moduleName;
      }
    }
    for (const klass of result) {
      const modName = moduleNames[klass];
      out += [modName, klass].join(' ') + '\n';
    }
    return out;
  } else {
    const moduleNames = {};
    const result = listClassesJson([]);
    if (ObjCAvailable) {
      const klasses = ObjC.classes;
      for (const k of result) {
        moduleNames[k] = ObjC.classes[k].$moduleName;
      }
    }
    for (const k of result) {
      const modName = moduleNames[k];
      if (modName && modName.indexOf(args[0]) !== -1) {
        const ins = search.searchInstancesJson([k]);
        const inss = ins.map((x) => { return x.address; }).join(' ');
        out += k + ' # ' + inss + '\n';
        if (mode === 'ivars') {
          for (const a of ins) {
            out += 'instance ' + utils.padPointer(a.address) + '\n';
            const i = new ObjC.Object(ptr(a.address));
            out += (JSON.stringify(i.$ivars)) + '\n';
          }
        }
      }
    }
    return out;
  }
}

function listClasses (args) {
  const result = listClassesJson(args);
  if (result instanceof Array) {
    return result.join('\n');
  }
  return Object.keys(result)
    .map(methodName => {
      const address = result[methodName];
      return [utils.padPointer(address), methodName].join(' ');
    })
    .join('\n');
}

function listClassesR2 (args) {
  const className = args[0];
  if (args.length === 0 || args[0].indexOf('*') !== -1) {
    let methods = '';
    if (ObjCAvailable) {
      for (const cn of Object.keys(ObjC.classes)) {
        if (_classGlob(cn, args[0])) {
          methods += listClassesR2([cn]);
        }
      }
    }
    return methods;
  }
  const result = listClassesJson(args);
  return Object.keys(result)
    .map(methodName => {
      const address = result[methodName];
      return ['f', flagName(methodName), '=', utils.padPointer(address)].join(' ');
    })
    .join('\n') + '\n';

  function flagName (m) {
    return 'sym.objc.' +
      (className + '.' + m)
        .replace(':', '')
        .replace(' ', '')
        .replace('-', '')
        .replace('+', '');
  }
}

function listClassMethods (args) {
  return listClassesJson(args, 'methods').join('\n');
}

function listClassMethodsJson (args) {
  return listClassesJson(args, 'methods');
}

function listClassesJson (args, mode) {
  if (java.JavaAvailable) {
    return java.listJavaClassesJson(args, mode === 'methods');
  }
  if (!ObjCAvailable) {
    return [];
  }
  if (args.length === 0) {
    return Object.keys(ObjC.classes);
  }
  const klassName = args[0];
  const klass = ObjC.classes[klassName];
  if (klass === undefined) {
    throw new Error('Class ' + klassName + ' not found');
  }
  let out = '';
  if (mode === 'ivars') {
    const ins = search.searchInstancesJson([klassName]);
    out += klassName + ': ';
    for (const i of ins) {
      out += 'instance ' + utils.padPointer(ptr(i.address)) + ': ';
      const ii = new ObjC.Object(ptr(i.address));
      out += JSON.stringify(ii.$ivars, null, '  ');
    }
    return [out];
  }
  const methods =
(mode === 'methods')
  ? klass.$ownMethods
  : (mode === 'super')
      ? klass.$super.$ownMethods
      : (mode === 'all')
          ? klass.$methods
          : klass.$ownMethods;
  const getImpl = ObjC.api.method_getImplementation;
  try {
    return methods
      .reduce((result, methodName) => {
        try {
          result[methodName] = getImpl(klass[methodName].handle);
        } catch (_) {
          console.error('warning: unsupported method \'' + methodName + '\' in ' + klassName);
        }
        return result;
      }, {});
  } catch (e) {
    return methods;
  }
}

function listProtocols (args) {
  return listProtocolsJson(args)
    .join('\n');
}

function listProtocolsJson (args) {
  if (!ObjCAvailable) {
    return [];
  }
  if (args.length === 0) {
    return Object.keys(ObjC.protocols);
  } else {
    const protocol = ObjC.protocols[args[0]];
    if (protocol === undefined) {
      throw new Error('Protocol not found');
    }
    return Object.keys(protocol.methods);
  }
}

function _classGlob (k, v) {
  if (!k || !v) {
    return true;
  }
  return k.indexOf(v.replace(/\*/g, '')) !== -1;
}

module.exports = {
  listClassesLoadedJson,
  listClassesLoaders,
  listClassesLoaded,
  listAllClassesNatives,
  listClassesNatives,
  listClassesAllMethods,
  listClassSuperMethods,
  listClassVariables,
  listClassesHooks,
  listClassesWhere,
  listClasses,
  listClassesR2,
  listClassMethods,
  listClassMethodsJson,
  listClassesJson,
  listProtocols,
  listProtocolsJson
};
<commit_msg>Improve error messages in `:ic*`<commit_after>'use strict';

const { ObjCAvailable } = require('../darwin');
const java = require('../java');
const search = require('../search');
const utils = require('../utils');

function listClassesLoadedJson (args) {
  if (java.JavaAvailable) {
    return java.listClasses(args);
  }
  if (ObjCAvailable) {
    return JSON.stringify(ObjC.enumerateLoadedClassesSync());
  }
}

function listClassesLoaders (args) {
  if (!java.JavaAvailable) {
    return 'Error: icL is only available on Android targets.';
  }
  let res = '';
  javaPerform(function () {
    function s2o (s) {
      let indent = 0;
      let res = '';
      for (const ch of s.toString()) {
        switch (ch) {
          case '[':
            indent++;
            res += '[\n' + Array(indent + 1).join(' ');
            break;
          case ']':
            indent--;
            res += ']\n' + Array(indent + 1).join(' ');
            break;
          case ',':
            res += ',\n' + Array(indent + 1).join(' ');
            break;
          default:
            res += ch;
            break;
        }
      }
      return res;
    }
    const c = Java.enumerateClassLoadersSync();
    for (const cl in c) {
      const cs = s2o(c[cl].toString());
      res += cs;
    }
  });
  return res;
}

function listClassesLoaded (args) {
  if (java.JavaAvailable) {
    return listClasses(args);
  }
  if (ObjCAvailable) {
    const results = ObjC.enumerateLoadedClassesSync();
    const loadedClasses = [];
    for (const module of Object.keys(results)) {
      loadedClasses.push(...results[module]);
    }
    return loadedClasses.join('\n');
  }
  return [];
}

// only for java
function listAllClassesNatives (args) {
  return listClassesNatives(['.']);
}

function listClassesNatives (args) {
  const natives = [];
  const vkn = args[0] || 'com';
  javaPerform(function () {
    const klasses = listClassesJson([]);
    for (let kn of klasses) {
      kn = kn.toString();
      // if (kn.indexOf('android') !== -1) { continue; }
      if (kn.indexOf(vkn) === -1) {
        continue;
      }
      try {
        const handle = java.javaUse(kn);
        const klass = handle.class;
        const klassNatives = klass.getMethods().map(_ => _.toString()).filter(_ => _.indexOf('static native') !== -1);
        if (klassNatives.length > 0) {
          const kns = klassNatives.map((n) => {
            const p = n.indexOf('(');
            let sn = '';
            if (p !== -1) {
              const s = n.substring(0, p);
              const w = s.split(' ');
              sn = w[w.length - 1];
              return sn;
            }
            return n; // { name: sn, fullname: n };
          });
          console.error(kns.join('\n'));
          for (const tkn of kns) {
            if (natives.indexOf(tkn) === -1) {
              natives.push(tkn);
            }
          }
        }
      } catch (ignoreError) {
      }
    }
  });
  return natives;
}

function listClassesAllMethods (args) {
  return listClassesJson(args, 'all').join('\n');
}

function listClassSuperMethods (args) {
  return listClassesJson(args, 'super').join('\n');
}

function listClassVariables (args) {
  return listClassesJson(args, 'ivars').join('\n');
}

function listClassesHooks (args, mode) {
  let out = '';
  if (args.length === 0) {
    return 'Usage: :ich [kw]';
  }
  const moduleNames = {};
  const result = listClassesJson([]);
  if (ObjCAvailable) {
    const klasses = ObjC.classes;
    for (const k of result) {
      moduleNames[k] = ObjC.classes[k].$moduleName;
    }
  }
  for (const k of result) {
    const modName = moduleNames[k];
    if (k.indexOf(args[0]) !== -1 || (modName && modName.indexOf(args[0]) !== -1)) {
      const ins = search.searchInstancesJson([k]);
      const inss = ins.map((x) => { return x.address; }).join(' ');
      const a = 'OOO';
      const klass = ObjC.classes[k];
      if (klass) {
        for (const m of klass.$ownMethods) {
          // TODO: use instance.argumentTypes to generate the 'OOO'
          out += ':dtf objc:' + k + '.' + m + ' ' + a + '\n';
        }
      }
    }
  }
  return out;
}

function listClassesWhere (args, mode) {
  let out = '';
  if (args.length === 0) {
    const moduleNames = {};
    const result = listClassesJson([]);
    if (ObjCAvailable) {
      const klasses = ObjC.classes;
      for (const k of result) {
        moduleNames[k] = klasses[k].$moduleName;
      }
    }
    for (const klass of result) {
      const modName = moduleNames[klass];
      out += [modName, klass].join(' ') + '\n';
    }
    return out;
  } else {
    const moduleNames = {};
    const result = listClassesJson([]);
    if (ObjCAvailable) {
      const klasses = ObjC.classes;
      for (const k of result) {
        moduleNames[k] = ObjC.classes[k].$moduleName;
      }
    }
    for (const k of result) {
      const modName = moduleNames[k];
      if (modName && modName.indexOf(args[0]) !== -1) {
        const ins = search.searchInstancesJson([k]);
        const inss = ins.map((x) => { return x.address; }).join(' ');
        out += k + ' # ' + inss + '\n';
        if (mode === 'ivars') {
          for (const a of ins) {
            out += 'instance ' + utils.padPointer(a.address) + '\n';
            const i = new ObjC.Object(ptr(a.address));
            out += (JSON.stringify(i.$ivars)) + '\n';
          }
        }
      }
    }
    return out;
  }
}

function listClasses (args) {
  const result = listClassesJson(args);
  if (result instanceof Array) {
    return result.join('\n');
  }
  return Object.keys(result)
    .map(methodName => {
      const address = result[methodName];
      return [utils.padPointer(address), methodName].join(' ');
    })
    .join('\n');
}

function listClassesR2 (args) {
  const className = args[0];
  if (args.length === 0 || args[0].indexOf('*') !== -1) {
    let methods = '';
    if (ObjCAvailable) {
      for (const cn of Object.keys(ObjC.classes)) {
        if (_classGlob(cn, args[0])) {
          methods += listClassesR2([cn]);
        }
      }
    }
    return methods;
  }
  const result = listClassesJson(args);
  return Object.keys(result)
    .map(methodName => {
      const address = result[methodName];
      return ['f', flagName(methodName), '=', utils.padPointer(address)].join(' ');
    })
    .join('\n') + '\n';

  function flagName (m) {
    return 'sym.objc.' +
      (className + '.' + m)
        .replace(':', '')
        .replace(' ', '')
        .replace('-', '')
        .replace('+', '');
  }
}

function listClassMethods (args) {
  return listClassesJson(args, 'methods').join('\n');
}

function listClassMethodsJson (args) {
  return listClassesJson(args, 'methods');
}

function listClassesJson (args, mode) {
  if (java.JavaAvailable) {
    return java.listJavaClassesJson(args, mode === 'methods');
  }
  if (!ObjCAvailable) {
    return [];
  }
  if (args.length === 0) {
    return Object.keys(ObjC.classes);
  }
  const klassName = args[0];
  const klass = ObjC.classes[klassName];
  if (klass === undefined) {
    throw new Error('Class ' + klassName + ' not found');
  }
  let out = '';
  if (mode === 'ivars') {
    const ins = search.searchInstancesJson([klassName]);
    out += klassName + ': ';
    for (const i of ins) {
      out += 'instance ' + utils.padPointer(ptr(i.address)) + ': ';
      const ii = new ObjC.Object(ptr(i.address));
      out += JSON.stringify(ii.$ivars, null, '  ');
    }
    return [out];
  }
  const methods =
(mode === 'methods')
  ? klass.$ownMethods
  : (mode === 'super')
      ? klass.$super.$ownMethods
      : (mode === 'all')
          ? klass.$methods
          : klass.$ownMethods;
  const getImpl = ObjC.api.method_getImplementation;
  try {
    return methods
      .reduce((result, methodName) => {
        try {
          result[methodName] = getImpl(klass[methodName].handle);
        } catch (e) {
          console.error(e, ' in \'' + methodName + '\' of ' + klassName);
        }
        return result;
      }, {});
  } catch (e) {
    return methods;
  }
}

function listProtocols (args) {
  return listProtocolsJson(args)
    .join('\n');
}

function listProtocolsJson (args) {
  if (!ObjCAvailable) {
    return [];
  }
  if (args.length === 0) {
    return Object.keys(ObjC.protocols);
  } else {
    const protocol = ObjC.protocols[args[0]];
    if (protocol === undefined) {
      throw new Error('Protocol not found');
    }
    return Object.keys(protocol.methods);
  }
}

function _classGlob (k, v) {
  if (!k || !v) {
    return true;
  }
  return k.indexOf(v.replace(/\*/g, '')) !== -1;
}

module.exports = {
  listClassesLoadedJson,
  listClassesLoaders,
  listClassesLoaded,
  listAllClassesNatives,
  listClassesNatives,
  listClassesAllMethods,
  listClassSuperMethods,
  listClassVariables,
  listClassesHooks,
  listClassesWhere,
  listClasses,
  listClassesR2,
  listClassMethods,
  listClassMethodsJson,
  listClassesJson,
  listProtocols,
  listProtocolsJson
};
<|endoftext|>


<commit_before>System.import("index.coffee!")
<commit_msg>Delete bootstrap.js<commit_after><|endoftext|>


<commit_before>var Rank = React.createClass({
	render: function() {
		return (

				{this.props.rank}

		)
	}
});

var ArticleLink = React.createClass({
	render: function() {
		return (
			{this.props.title}
		)
	}
});

var OrginalLink = React.createClass({
	render: function() {
		return (

		)
	}
});

var DomainLink = React.createClass({
	render: function() {
		return (

				({this.props.domain})

		)
	}
});

var EntryTitle = React.createClass({
	render: function() {
		return (

				<ArticleLink aid={this.props.aid} title={this.props.title} />
				<OrginalLink url={this.props.url} />
				<DomainLink domain={this.props.domain} />

		)
	}
});

var SpiderName = React.createClass({
	render: function() {
		return (

				[{this.props.spname}]

		)
	}
});

var ArticleTag = React.createClass({
	render: function() {
		return (

				{this.props.tag}

	  )
	}
});

var EntryTags = React.createClass({
	render: function() {
	  var tags = this.props.tags;
		return (

				{tags.map(function(tag) {
					return <ArticleTag tag={tag} />;
				})}

		)
	}
});

var Entry = React.createClass({
	render: function() {
		var index = this.props.index;
		var entry = this.props.entry;
		return (

				<Rank rank={index} />
				<EntryTitle aid={entry[0]} title={entry[1]} url={entry[7]} domain={entry[6]} />

		)
	}
});

var Entries = React.createClass({
	render: function() {
		var entries = this.props.entries;
		return (

				{entries.map(function(entry, index) {
					return <Entry index={index} entry={entry} />
				})}

		)
	}
});

var Category = React.createClass({
	onClick: function(category) {
		this.props.onCategoryClick(category);
	},

	render: function() {
		return (

				{this.props.category}

		)
	}
});

var CategoryDiv = React.createClass({
	render: function() {
		var categories = this.props.categories;
		var onCategoryClick = this.props.onCategoryClick;
		return (

					{categories.map(function(category) {
						return <Category category={category} onCategoryClick={onCategoryClick} />;
					})}

		)
	}
});

var ContentDiv = React.createClass({
	loadFromServer: function() {
		console.log("loadFromServer");
		$.getJSON("/api/day", {day: "2016-06-24"}).done(function(data) {
			var categories = [];
			var entries = data["entries"];
			$.each(entries, function(key, val) {
				categories.push(key);
			});
			this.setState({category: categories[0], data: entries});
		}.bind(this));
	},

	getInitialState: function() {
		return {category: "init", data: {init: []}};
	},

	componentDidMount: function() {
		this.loadFromServer();
	},

	onCategoryClick: function(category) {
		console.log(category);
		this.setState({category: category});
	},

	render: function() {
		var categories = [];
		$.each(this.state.data, function(key, val) {
			categories.push(key);
		});

		var entries = this.state.data[this.state.category];

		return (

				<CategoryDiv categories={categories} onCategoryClick={this.onCategoryClick} />

				<Entries entries={entries} />

		)
	}
});

ReactDOM.render(
  <ContentDiv />,
  document.getElementById('content')
);
<commit_msg>react<commit_after>var Rank = React.createClass({
	render: function() {
		return (

				{this.props.rank}

		)
	}
});

var ArticleLink = React.createClass({
	render: function() {
		return (
			{this.props.title}
		)
	}
});

var OrginalLink = React.createClass({
	render: function() {
		return (

		)
	}
});

var DomainLink = React.createClass({
	render: function() {
		return (

				({this.props.domain})

		)
	}
});

var EntryTitle = React.createClass({
	render: function() {
		return (

				<ArticleLink aid={this.props.aid} title={this.props.title} />
				<OrginalLink url={this.props.url} />
				<DomainLink domain={this.props.domain} />

		)
	}
});

var SpiderTag = React.createClass({
	render: function() {
		var spid = this.props.spider.spid;
		var spname = this.props.spider.spname;
		return (

				[{spname}]

		)
	}
});

var ArticleTag = React.createClass({
	render: function() {
		return (

				{this.props.tag}

	  )
	}
});

var EntryTags = React.createClass({
	render: function() {
		return (

				<SpiderTag spider={this.props.spider} />

		)
	}
});

var Entry = React.createClass({
	render: function() {
		var index = this.props.index;
		var entry = this.props.entry;
		var spider = {spid: entry[5], spname: entry[3]};
		console.log(entry);
		return (

				<Rank rank={index} />
				<EntryTitle aid={entry[0]} title={entry[1]} url={entry[7]} domain={entry[6]} />
				<EntryTags spider={spider} />

		)
	}
});

var Entries = React.createClass({
	render: function() {
		var entries = this.props.entries;
		return (

				{entries.map(function(entry, index) {
					return <Entry index={index} entry={entry} />
				})}

		)
	}
});

var Category = React.createClass({
	onClick: function(category) {
		this.props.onCategoryClick(category);
	},

	render: function() {
		return (

				{this.props.category}

		)
	}
});

var CategoryDiv = React.createClass({
	render: function() {
		var categories = this.props.categories;
		var onCategoryClick = this.props.onCategoryClick;
		return (

					{categories.map(function(category) {
						return <Category category={category} onCategoryClick={onCategoryClick} />;
					})}

		)
	}
});

var ContentDiv = React.createClass({
	loadFromServer: function() {
		console.log("loadFromServer");
		$.getJSON("/api/day", {day: "2016-06-24"}).done(function(data) {
			var categories = [];
			var entries = data["entries"];
			$.each(entries, function(key, val) {
				categories.push(key);
			});
			this.setState({category: categories[0], data: entries});
		}.bind(this));
	},

	getInitialState: function() {
		return {category: "init", data: {init: []}};
	},

	componentDidMount: function() {
		this.loadFromServer();
	},

	onCategoryClick: function(category) {
		console.log(category);
		this.setState({category: category});
	},

	render: function() {
		var categories = [];
		$.each(this.state.data, function(key, val) {
			categories.push(key);
		});

		var entries = this.state.data[this.state.category];

		return (

				<CategoryDiv categories={categories} onCategoryClick={this.onCategoryClick} />

				<Entries entries={entries} />

		)
	}
});

ReactDOM.render(
  <ContentDiv />,
  document.getElementById('content')
);
<|endoftext|>


<commit_before> define(['app','underscore','linqjs', 'ngMaterial','ngAria','angular-animate',
   '/app/views/search/measure-matrix-countries-directive.html.js',
   '/app/js/common.js',
   '/app/views/search-new/search-results/result-grouped-national-record.js',
   '/app/services/search-service.js', '/app/services/app-config-service.js'
 ], function(app, _, linqjs) {

    app.directive('countryProfile', function() {
        return {
            restrict: 'EAC',
            templateUrl: '/app/views/countries/country-profile-directive.html',
            replace: true,
            scope: {
                api : '=?',
                code : '='
            },
            controller: ["$scope", "$http", "$routeParams", "linqjs", "$filter", "realm",
                "commonjs", "$q", '$element', '$timeout','commonjs','IStorage','$rootScope',
                'schemaTypes','breadcrumbs','smoothScroll','$location', 'searchService', 'appConfigService',
                function($scope, $http, $routeParams, linqjs, $filter, realm, commonjs, $q,
                            $element, $timeout, countriescommonjs, IStorage,$rootScope,
                            schemaTypes, breadcrumbs,smoothScroll,$location, searchService, appConfigService) {

                $scope.api = {
                    loadCountryDetails : $scope.loadCountryDetails
                }
                $scope.$watch('code', function(newVal){
                    if(newVal){
                        $scope.loadCountryDetails(newVal);
                    }
                })
                //**********************************************************
                function resetList(){
                        $scope.showCPC = false;
                        $scope.showIRCC = false;
                        $scope.showMSR = false;
                        $scope.showNFP = false;
                        $scope.showNDB = false;
                        $scope.showCNA = false;
                        $scope.showCP = false;
                        $scope.showCPCRecv = false;
                        $scope.showNR = false;

                        $scope.sortMeasure="[jurisdiction_sort, type_sort, status_sort, createdDate_dt, title_t]";
                        $scope.reverseMeasure=false;
                        $scope.sortPermit='title_t';
                        $scope.reversePermit=false;
                        $scope.sortCPC='title_t';
                        $scope.reverseCPC=false;
                        $scope.sortCPCReceived='title_t'
                        $scope.reverseCPCReceived=false;
                        $scope.filterSchema=null;
                }

                    resetList();

                    //facet counts
                    $scope.cpcReceivedCount = 0;
                    $scope.nfpCount= 0;
                    $scope.nationalMeasure= 0;
                    $scope.Permit= 0;
                    $scope.absCheckpoint= 0;
                    $scope.absCheckpointCommunique = 0;
                    $scope.database= 0;
                    $scope.showMatrix = false;
                    $scope.absNationalReport = 0;

                    if ($location.absUrl().toLowerCase().indexOf("://absch.cbddev.xyz") > 0 || $location.absUrl().toLowerCase().indexOf("localhost:2010") > 0 ||
                        $location.absUrl().toLowerCase().indexOf("://training-absch.cbd.int") > 0) {
                        $scope.showMatrix = true;
                    }

                    //**********************************************************
                    $scope.loadCountryDetails = function(countryCode) {

                    $scope.code = countryCode || $routeParams.code;

                    $scope.documentCount = 0;
                    $scope.currentPage = 0;
                    $scope.searchText = '';
                    $scope.autocompleteData = [];
                    $scope.absch_nfp = null;

                    if ($scope.code) {

                    $q.when(commonjs.getCountry($scope.code.toUpperCase()))
                    .then(function(country) {
                        $scope.country = country;
                    });

                    //*******************************************************
                        // var queryCPCRevURL = '/api/v2013/index/select?fl=id,identifier_s,title_t,keywords_CEN_ss'+
                        //                 'checkpoint_CEN_ss,createdDate_dt,geneticRessourceUsers_s,government_s,permit_ss,' +
                        //                 '&q=(realm_ss:' + realm.value.toLowerCase() + ' OR realm_ss:absch) AND schema_s:absCheckpointCommunique AND (originCountries_ss:'+
                        //                 $scope.code.toLowerCase() + ' OR permitSourceCountry_ss:' + $scope.code.toLowerCase() + ')' +
                        //                 '&rows=100&sort=createdDate_dt+desc,+title_t+asc&start=0&wt=json';

                    var searchQuery = {
                        fields  : 'id, rec_date:updatedDate_dt, identifier_s, uniqueIdentifier_s, url_ss, government_s, schema_s, government_EN_t, schemaSort_i, sort1_i, sort2_i, sort3_i, sort4_i, _revision_i,rec_countryName:government_EN_t, rec_title:title_EN_t, rec_summary:description_t,rec_type:type_EN_t, rec_meta1:meta1_EN_txt, rec_meta2:meta2_EN_txt, rec_meta3:meta3_EN_txt,rec_meta4:meta4_EN_txt,rec_meta5:meta5_EN_txt, entryIntoForce_dt,adoption_dt,retired_dt',
                        query   : 'schema_s:(' + appConfigService.nationalSchemas.join(' ') +') AND (government_s:' + $scope.code.toLowerCase() + ' OR (originCountries_ss:' +
                                   $scope.code.toLowerCase() + ' OR permitSourceCountry_ss:' + $scope.code.toLowerCase() + '))',
                        rowsPerPage    : 500
                    };
                    //
                    // var queryCPCRecv = $http.get(queryCPCRevURL, {cache: true})

                    $q.all([searchService.list(searchQuery)])//,queryCPCRecv
                        .then(function(results) {

                        $scope.absch_nfp = results[0].data.response.docs;
                        // $scope.cpcReceived = results[1].data.response.docs;
                        var measureMatrixDocuments = [];

                        $scope.absch_nfp.forEach(function(document){
                            document.identifier = document.identifier_s;

                            if(document.ownerGovernment_s)
                                document.ownerGovernment = {identifier:document.ownerGovernment_s};

                            if(document.schema_s == "focalPoint" ){
                                if(document.description_t)
                                    document.description_t = document.description_t.replace(/\n/g, '
');
                                document.documentId = commonjs.hexToInteger(document.identifier_s);
                            }
                            else if(document.schema_s == "authority" || document.schema_s == "database" ||
                                document.schema_s == "absCheckpoint"){
                                    document.description_t = '';
                                    $q.when(IStorage.documents.get(document.identifier_s,{info:""}))
                                    .then(function(data) {
                                        var doc = data.data.body;
                                        var details = '';
                                        if(doc.address)
                                            details += $filter("lstring")(doc.address) + '
';
                                        if(doc.city)
                                            details += $filter("lstring")(doc.city)  + '
';
                                        if(doc.postalCode)
                                            details += $filter("lstring")(doc.postalCode)  + '
';
                                        if(document.government_CEN_s)
                                            details += $filter("lstring")(JSON.parse(document.government_CEN_s));

                                        document.description_t = details;
                                        document.telephones = doc.phones;
                                        document.emails = doc.emails;
                                        document.doc = data.data;
                                    });
                            }
                            else if(document.schema_s=="absCheckpointCommunique"){

                                if(document.geneticRessourceUsers_s){
                                    document.geneticRessourceUsers = $scope.parseJSON(document.geneticRessourceUsers_s);
                                }
                            }
                            //create seprate collection for measure matrix
                            if(document.schema_s=='measure'){

                                //  if(document.type_EN_t =="Strategy / Action Plan")
                                //     document.type_sort = 1;
                                //  if(document.type_EN_t =="Policy Document")
                                //     document.type_sort = 2;
                                //  if(document.type_EN_t =="Law")
                                //     document.type_sort = 3;
                                //  if(document.type_EN_t =="Regulatory or Administrative Measures")
                                //     document.type_sort = 4;
                                //  if(document.type_EN_t =="Guidelines")
                                //     document.type_sort = 5;
                                //  if(document.type_EN_t =="Explanatory Information")
                                //     document.type_sort = 6;
                                //  if(document.type_EN_t =="Other")
                                //     document.type_sort = 7;

                                //  if(document.status_EN_t =="Legally binding ")
                                //     document.status_sort = 1;
                                //  if(document.status_EN_t =="Not legally binding")
                                //     document.status_sort = 2;
                                //  if(document.status_EN_t =="Draft")
                                //     document.status_sort = 3;
                                //  if(document.status_EN_t =="Retired")
                                //     document.status_sort = 4;

                                //  if(document.jurisdiction_EN_t =="Regional / Multilateral")
                                //     document.jurisdiction_sort = 1;
                                //  if(document.jurisdiction_EN_t =="National / Federal")
                                //     document.jurisdiction_sort = 2;
                                //  if(document.jurisdiction_EN_t =="Sub-national")
                                //     document.jurisdiction_sort = 3;
                                //  if(document.jurisdiction_EN_t =="Community")
                                //     document.jurisdiction_sort = 4;
                                //  if(document.jurisdiction_EN_t =="Other")
                                //     document.jurisdiction_sort = 5;

                                if(!document.retired_dt || moment() <= moment(document.retired_dt)){
                                    document.measureMatrix = true;
                                }
                                // else{
                                //     //retired measures
                                //     document.jurisdiction_sort = 9;
                                // }
                                measureMatrixDocuments.push(document);

                            }

                        });
                        $scope.measureMatrixDocuments = measureMatrixDocuments;
                        $scope.measureMatrixDocuments.selectAll = true;
                        // $scope.cpcReceived.forEach(function(document){
                        //     if(document.geneticRessourceUsers_s){
                        //         document.geneticRessourceUsers = $scope.parseJSON(document.geneticRessourceUsers_s);
                        //     }
                        //     $scope.cpcReceivedCount++;
                        // });
                        $scope.getFacets($scope.absch_nfp);
                        $('[data-toggle="tooltip"]').tooltip()

                        if($routeParams.countryCode && $routeParams.documentType){
                            if($routeParams.documentType.toLowerCase()=='measure-matrix'){
                                $scope.showMSR = true;
                            }else{
                                $scope['show' + $routeParams.documentType.toUpperCase()] = true;
                            }
                        }
                    });
                    }
                }

                //**********************************************************
                $scope.$watch('absch_nfp', function(value) {
                    if (!value) return;
                    $scope.getFacets(value);
                });

                //**********************************************************
                $scope.getFacets = function(data) {

                    var linqObj = linqjs.from(data);
                    $scope.nationalAuthority = linqObj.count(function(schema) {

                    return schema.schema_s.toLowerCase() == 'authority';
                    });
                    //console.log(response.data.response.docs);
                    $scope.nfpCount = linqObj.count(function(schema) {
                    // console.log(schema.schema_EN_t.toLowerCase() + ' ' + 'national focal point'.toLowerCase());
                    return schema.schema_s.toLowerCase() == 'focalpoint'.toLowerCase();
                    });

                    $scope.nationalMeasure = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'measure';
                    });

                    $scope.Permit = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'abspermit';
                    });

                    $scope.absCheckpoint = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'abscheckpoint';
                    });

                    $scope.absCheckpointCommunique = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'abscheckpointcommunique';
                    });

                    $scope.database = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'database';
                    });
                    $scope.resource = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'resource';
                    });

                    $scope.absNationalReport = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'absnationalreport';
                    });
                }

                $scope.showlist = false;

                //**********************************************************
                $scope.countriescommonjs = countriescommonjs;
                $scope.$on('loadCountryProfile', function(evt, evtData){
                    $scope.loadCountryDetails(evtData.data.countryCode);
                })

                $scope.isContactInformation = function(entity){

                    return entity && (entity.schema_s == "focalPoint" ||
                                entity.schema_s == "authority" || entity.schema_s == "database" ||
                                entity.schema_s == "absCheckpoint")
                }

                $scope.isMeasure = function(entity){

                    return entity && entity.schema_s == "measure";
                }
                $scope.isCheckpointCommunique = function(entity){

                    return entity && entity.schema_s == "absCheckpointCommunique";
                }

                $scope.isPermit = function(entity){

                    return entity && entity.schema_s == "absPermit";
                }

                $scope.isCheckpointCommuniqueReceived = function(entity){
                    return entity && entity.schema_s == "absCheckpointCommunique"
                    && (entity.originCountries_ss==$scope.code  || entity.permitSourceCountry_ss==$scope.code);
                }

                $scope.isCheckpoint = function(entity){

                    return entity && entity.schema_s == "absCheckpoint";
                }
                $scope.isFocalpoint = function(entity){

                    return entity && entity.schema_s == "focalPoint";
                }
                $scope.isDatabase = function(entity){

                    return entity && entity.schema_s == "database";
                }
                $scope.isCNA = function(entity){

                    return entity && entity.schema_s == "authority";
                }

                $scope.isNationalReport = function(entity){

                    return entity && entity.schema_s == "absNationalReport";
                }

                $scope.showDetails = function(document){
                    //$scope.currentDocument = documentId;
                    if(!document.data){
                            var doc = IStorage.documents.get(document.identifier_s);
                            var docInfo = IStorage.documents.get(document.identifier_s,{ info: true});
                            $q.all([doc,docInfo])
                            .then(function(result){
                                document.data = result[0].data;
                                document.data.info = result[1].data;
                            });
                        }
                };

                //**********************************************************
                $scope.getTitle = function(schema,type, schemaFull){
                    if(schema == 'focalPoint'){

                            if(_.contains(type,'NP-FP') || _.contains(type,'ABS-FP'))
                                return 'ABS National Focal Point';
                            // else if(_.contains(type,'ABS-IC'))
                            //     return 'ABS ICNP Focal Point';
                            else if(_.contains(type,'CBD-FP1') ||  _.contains(type,'CBD-FP2'))
                                return 'CBD Primart Focal Point';
                            else
                                return 'National Focal Point';
                    }
                    else
                        return schemaFull;

                }

                //**********************************************************
                $scope.parseJSON = function(value){
                    if(value)
                        return JSON.parse(value);
                }

                $scope.isForMeasureMatrix = function(measure){
                    return measure.measureMatrix;
                }

                $scope.selectAllForMatrix = function(){
                    _.map($scope.measureMatrixDocuments,function(item){
                        item.measureMatrix = !$scope.measureMatrixDocuments.selectAll;
                    })
                }
            }]

        };
    });
});
<commit_msg>remove unused code<commit_after> define(['app','underscore','linqjs', 'ngMaterial','ngAria','angular-animate',
   '/app/views/search/measure-matrix-countries-directive.html.js',
   '/app/js/common.js',
   '/app/views/search-new/search-results/result-grouped-national-record.js',
   '/app/services/search-service.js', '/app/services/app-config-service.js'
 ], function(app, _, linqjs) {

    app.directive('countryProfile', function() {
        return {
            restrict: 'EAC',
            templateUrl: '/app/views/countries/country-profile-directive.html',
            replace: true,
            scope: {
                api : '=?',
                code : '='
            },
            controller: ["$scope", "$http", "$routeParams", "linqjs", "$filter", "realm",
                "commonjs", "$q", '$element', '$timeout','commonjs','IStorage','$rootScope',
                'schemaTypes','breadcrumbs','smoothScroll','$location', 'searchService', 'appConfigService',
                function($scope, $http, $routeParams, linqjs, $filter, realm, commonjs, $q,
                            $element, $timeout, countriescommonjs, IStorage,$rootScope,
                            schemaTypes, breadcrumbs,smoothScroll,$location, searchService, appConfigService) {

                $scope.api = {
                    loadCountryDetails : $scope.loadCountryDetails
                }
                $scope.$watch('code', function(newVal){
                    if(newVal){
                        $scope.loadCountryDetails(newVal);
                    }
                })
                //**********************************************************
                function resetList(){
                        $scope.showCPC = false;
                        $scope.showIRCC = false;
                        $scope.showMSR = false;
                        $scope.showNFP = false;
                        $scope.showNDB = false;
                        $scope.showCNA = false;
                        $scope.showCP = false;
                        $scope.showCPCRecv = false;
                        $scope.showNR = false;

                        $scope.sortMeasure="[jurisdiction_sort, type_sort, status_sort, createdDate_dt, title_t]";
                        $scope.reverseMeasure=false;
                        $scope.sortPermit='title_t';
                        $scope.reversePermit=false;
                        $scope.sortCPC='title_t';
                        $scope.reverseCPC=false;
                        $scope.sortCPCReceived='title_t'
                        $scope.reverseCPCReceived=false;
                        $scope.filterSchema=null;
                }

                    resetList();

                    //facet counts
                    $scope.cpcReceivedCount = 0;
                    $scope.nfpCount= 0;
                    $scope.nationalMeasure= 0;
                    $scope.Permit= 0;
                    $scope.absCheckpoint= 0;
                    $scope.absCheckpointCommunique = 0;
                    $scope.database= 0;
                    $scope.showMatrix = false;
                    $scope.absNationalReport = 0;

                    if ($location.absUrl().toLowerCase().indexOf("://absch.cbddev.xyz") > 0 || $location.absUrl().toLowerCase().indexOf("localhost:2010") > 0 ||
                        $location.absUrl().toLowerCase().indexOf("://training-absch.cbd.int") > 0) {
                        $scope.showMatrix = true;
                    }

                    //**********************************************************
                    $scope.loadCountryDetails = function(countryCode) {

                    $scope.code = countryCode || $routeParams.code;

                    $scope.documentCount = 0;
                    $scope.currentPage = 0;
                    $scope.searchText = '';
                    $scope.autocompleteData = [];
                    $scope.absch_nfp = null;

                    if ($scope.code) {

                    $q.when(commonjs.getCountry($scope.code.toUpperCase()))
                    .then(function(country) {
                        $scope.country = country;
                    });

                    //*******************************************************
                        // var queryCPCRevURL = '/api/v2013/index/select?fl=id,identifier_s,title_t,keywords_CEN_ss'+
                        //                 'checkpoint_CEN_ss,createdDate_dt,geneticRessourceUsers_s,government_s,permit_ss,' +
                        //                 '&q=(realm_ss:' + realm.value.toLowerCase() + ' OR realm_ss:absch) AND schema_s:absCheckpointCommunique AND (originCountries_ss:'+
                        //                 $scope.code.toLowerCase() + ' OR permitSourceCountry_ss:' + $scope.code.toLowerCase() + ')' +
                        //                 '&rows=100&sort=createdDate_dt+desc,+title_t+asc&start=0&wt=json';

                    var searchQuery = {
                        fields  : 'id, rec_date:updatedDate_dt, identifier_s, uniqueIdentifier_s, url_ss, government_s, schema_s, government_EN_t, schemaSort_i, sort1_i, sort2_i, sort3_i, sort4_i, _revision_i,rec_countryName:government_EN_t, rec_title:title_EN_t, rec_summary:description_t,rec_type:type_EN_t, rec_meta1:meta1_EN_txt, rec_meta2:meta2_EN_txt, rec_meta3:meta3_EN_txt,rec_meta4:meta4_EN_txt,rec_meta5:meta5_EN_txt, entryIntoForce_dt,adoption_dt,retired_dt',
                        query   : 'schema_s:(' + appConfigService.nationalSchemas.join(' ') +') AND (government_s:' + $scope.code.toLowerCase() + ' OR (originCountries_ss:' +
                                   $scope.code.toLowerCase() + ' OR permitSourceCountry_ss:' + $scope.code.toLowerCase() + '))',
                        rowsPerPage    : 500
                    };
                    //
                    // var queryCPCRecv = $http.get(queryCPCRevURL, {cache: true})

                    $q.all([searchService.list(searchQuery)])//,queryCPCRecv
                        .then(function(results) {

                        $scope.absch_nfp = results[0].data.response.docs;
                        // $scope.cpcReceived = results[1].data.response.docs;
                        var measureMatrixDocuments = [];

                        $scope.absch_nfp.forEach(function(document){
                            document.identifier = document.identifier_s;

                            if(document.ownerGovernment_s)
                                document.ownerGovernment = {identifier:document.ownerGovernment_s};

                            if(document.schema_s == "focalPoint" ){
                                if(document.description_t)
                                    document.description_t = document.description_t.replace(/\n/g, '
');
                                document.documentId = commonjs.hexToInteger(document.identifier_s);
                            }
                            else if(document.schema_s == "authority" || document.schema_s == "database" ||
                                document.schema_s == "absCheckpoint"){
                                    document.description_t = '';
                                    $q.when(IStorage.documents.get(document.identifier_s,{info:""}))
                                    .then(function(data) {
                                        var doc = data.data.body;
                                        var details = '';
                                        if(doc.address)
                                            details += $filter("lstring")(doc.address) + '
';
                                        if(doc.city)
                                            details += $filter("lstring")(doc.city)  + '
';
                                        if(doc.postalCode)
                                            details += $filter("lstring")(doc.postalCode)  + '
';
                                        if(document.government_CEN_s)
                                            details += $filter("lstring")(JSON.parse(document.government_CEN_s));

                                        document.description_t = details;
                                        document.telephones = doc.phones;
                                        document.emails = doc.emails;
                                        document.doc = data.data;
                                    });
                            }
                            else if(document.schema_s=="absCheckpointCommunique"){

                                if(document.geneticRessourceUsers_s){
                                    document.geneticRessourceUsers = $scope.parseJSON(document.geneticRessourceUsers_s);
                                }
                            }
                            //create seprate collection for measure matrix
                            if(document.schema_s=='measure'){

                                if(!document.retired_dt || moment() <= moment(document.retired_dt)){
                                    document.measureMatrix = true;
                                }
                                else
                                    document.measureMatrix = false;

                                measureMatrixDocuments.push(document);

                            }

                        });
                        $scope.measureMatrixDocuments = measureMatrixDocuments;
                        $scope.measureMatrixDocuments.selectAll = true;
                        // $scope.cpcReceived.forEach(function(document){
                        //     if(document.geneticRessourceUsers_s){
                        //         document.geneticRessourceUsers = $scope.parseJSON(document.geneticRessourceUsers_s);
                        //     }
                        //     $scope.cpcReceivedCount++;
                        // });
                        $scope.getFacets($scope.absch_nfp);
                        $('[data-toggle="tooltip"]').tooltip()

                        if($routeParams.countryCode && $routeParams.documentType){
                            if($routeParams.documentType.toLowerCase()=='measure-matrix'){
                                $scope.showMSR = true;
                            }else{
                                $scope['show' + $routeParams.documentType.toUpperCase()] = true;
                            }
                        }
                    });
                    }
                }

                //**********************************************************
                $scope.$watch('absch_nfp', function(value) {
                    if (!value) return;
                    $scope.getFacets(value);
                });

                //**********************************************************
                $scope.getFacets = function(data) {

                    var linqObj = linqjs.from(data);
                    $scope.nationalAuthority = linqObj.count(function(schema) {

                    return schema.schema_s.toLowerCase() == 'authority';
                    });
                    //console.log(response.data.response.docs);
                    $scope.nfpCount = linqObj.count(function(schema) {
                    // console.log(schema.schema_EN_t.toLowerCase() + ' ' + 'national focal point'.toLowerCase());
                    return schema.schema_s.toLowerCase() == 'focalpoint'.toLowerCase();
                    });

                    $scope.nationalMeasure = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'measure';
                    });

                    $scope.Permit = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'abspermit';
                    });

                    $scope.absCheckpoint = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'abscheckpoint';
                    });

                    $scope.absCheckpointCommunique = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'abscheckpointcommunique';
                    });

                    $scope.database = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'database';
                    });
                    $scope.resource = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'resource';
                    });

                    $scope.absNationalReport = linqObj.count(function(schema) {
                    return schema.schema_s.toLowerCase() == 'absnationalreport';
                    });
                }

                $scope.showlist = false;

                //**********************************************************
                $scope.countriescommonjs = countriescommonjs;
                $scope.$on('loadCountryProfile', function(evt, evtData){
                    $scope.loadCountryDetails(evtData.data.countryCode);
                })

                $scope.isContactInformation = function(entity){

                    return entity && (entity.schema_s == "focalPoint" ||
                                entity.schema_s == "authority" || entity.schema_s == "database" ||
                                entity.schema_s == "absCheckpoint")
                }

                $scope.isMeasure = function(entity){

                    return entity && entity.schema_s == "measure";
                }
                $scope.isCheckpointCommunique = function(entity){

                    return entity && entity.schema_s == "absCheckpointCommunique";
                }

                $scope.isPermit = function(entity){

                    return entity && entity.schema_s == "absPermit";
                }

                $scope.isCheckpointCommuniqueReceived = function(entity){
                    return entity && entity.schema_s == "absCheckpointCommunique"
                    && (entity.originCountries_ss==$scope.code  || entity.permitSourceCountry_ss==$scope.code);
                }

                $scope.isCheckpoint = function(entity){

                    return entity && entity.schema_s == "absCheckpoint";
                }
                $scope.isFocalpoint = function(entity){

                    return entity && entity.schema_s == "focalPoint";
                }
                $scope.isDatabase = function(entity){

                    return entity && entity.schema_s == "database";
                }
                $scope.isCNA = function(entity){

                    return entity && entity.schema_s == "authority";
                }

                $scope.isNationalReport = function(entity){

                    return entity && entity.schema_s == "absNationalReport";
                }

                $scope.showDetails = function(document){
                    //$scope.currentDocument = documentId;
                    if(!document.data){
                            var doc = IStorage.documents.get(document.identifier_s);
                            var docInfo = IStorage.documents.get(document.identifier_s,{ info: true});
                            $q.all([doc,docInfo])
                            .then(function(result){
                                document.data = result[0].data;
                                document.data.info = result[1].data;
                            });
                        }
                };

                //**********************************************************
                $scope.getTitle = function(schema,type, schemaFull){
                    if(schema == 'focalPoint'){

                            if(_.contains(type,'NP-FP') || _.contains(type,'ABS-FP'))
                                return 'ABS National Focal Point';
                            // else if(_.contains(type,'ABS-IC'))
                            //     return 'ABS ICNP Focal Point';
                            else if(_.contains(type,'CBD-FP1') ||  _.contains(type,'CBD-FP2'))
                                return 'CBD Primart Focal Point';
                            else
                                return 'National Focal Point';
                    }
                    else
                        return schemaFull;

                }

                //**********************************************************
                $scope.parseJSON = function(value){
                    if(value)
                        return JSON.parse(value);
                }

                $scope.isForMeasureMatrix = function(measure){
                    return measure.measureMatrix;
                }

                // $scope.selectAllForMatrix = function(){
                //     _.map($scope.measureMatrixDocuments,function(item){
                //         item.measureMatrix = !$scope.measureMatrixDocuments.selectAll;
                //     })
                // }
            }]

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


<commit_before>'use strict'; // indicate that code is executed in strict mode

var classBrowser = angular.module('classBrowserApp', ['ngAnimate', 'ngRoute', 'utilities'])

	.config(function($routeProvider) {
		$routeProvider
			.when('/', {templateUrl: 'views/start.html'})
			.when('/browse', { templateUrl: 'views/browseData.html' })
			.when('/datatypes', { templateUrl: 'views/datatypes.html' })
			.when('/about', { templateUrl: 'views/about.html' })
			.when('/view', { templateUrl: 'views/view.html' })
			.otherwise({redirectTo: '/'});
	})

	.factory('Arguments', function($http, $route, jsonData, util){
		var args = {};
		const statusStartValues = {
			entityType: "classes",
			from: 0,
			to:jsonData.TABLE_SIZE,
			classesFilter: {
				label: "",
				instances: [0, 4000000],
				subclasses: [0, 200000]
			},
			propertiesFilter: {
				label: "",
				statements: [0, 20000000],
				qualifiers: [0, 100000],
				references: [0, 100000],
				datatypes: {id: 1, name: "Any property type"}

			}
		};
		var status = util.cloneObject(statusStartValues);
		return {
			refreshArgs: function(){
				args = {
					from: ($route.current.params.from) ? parseInt(($route.current.params.from)) : status.from,
					to: ($route.current.params.to) ? parseInt(($route.current.params.to)) : status.to,
					type: ($route.current.params.type) ? ($route.current.params.type) : status.entityType
				}
				status.from = args.from;
				status.to = args.to;
				status.entityType = args.type;
			},
			getArgs: function(){
				return args;
			},
			getStatus: function(){
				return status;
			},
			getStatusStartValues:function(){
				return util.cloneObject(statusStartValues);
			}
		}
	})

	.factory('Properties', function($http, $route){
		var promise;
		var properties;

		var getData = function(id, key, defaultValue) {
			try {
				var result = properties[id][key];
				if (typeof result !== 'undefined' && result !== null) {
					return result;
				}
			} catch(e){
				return defaultValue;
			}
		}

		var getLabel = function(id) { return getData(id, 'l', null); }
		var getLabelOrId = function(id) { return getData(id, 'l', 'P' + id); }
		var getUrl = function(id) { return "#/view?id=P" + id; }

		var formatRelatedProperties = function(relatedProperties, threshold){
			var ret = [];
			try {
				var relPropsList = [];
				for (var relProp in relatedProperties) relPropsList.push([relProp, relatedProperties[relProp]]);

				relPropsList.sort(function(a, b) {
					var a = a[1];
					var b = b[1];
					return a < b ? 1 : (a > b ? -1 : 0);
				});

				for (var i = 0; i < relPropsList.length; i++) {
					if (relPropsList[i][1] < threshold) break;
					var propId = relPropsList[i][0];
					var resultObj = {label : getLabelOrId(propId) , link: getUrl(propId)};
					ret.push(resultObj);
				}
			} catch (e){}

			return ret;
		}

		var getQualifiers = function(id){ return getData(id, 'qs', {}); }

		var getFormattedQualifiers = function(id) {
			var ret = [];
			angular.forEach(getQualifiers(id), function(usageCount, qualifierId) {
				ret.push({label : getLabelOrId(qualifierId) , url: getUrl(qualifierId), count: usageCount});
			});
			ret.sort(function(a, b) {
					var a = a.count;
					var b = b.count;
					return a < b ? 1 : (a > b ? -1 : 0);
			});
			return ret;
		}

		var getStatementCount = function(id){ return getData(id, 's', 0); }

		if (!promise) {
			promise = $http.get("data/properties.json").then(function(response){
				properties = response.data;
				return {
					propertiesHeader: [["Label (ID)", "col-xs-5"], ["Datatype", "col-xs-1"], ["Uses in statements", "col-xs-2"], ["Uses in qualifiers", "col-xs-2"], ["Uses in references", "col-xs-2"]],
					getProperties: function(){ return properties; },
					hasEntity: function(id){ return (id in properties); },
					getLabel: getLabel,
					getLabelOrId: getLabelOrId,
					getItemCount: function(id){ return getData(id, 'i', 0); },
					getDatatype: function(id){ return getData(id, 'd', null); },
					getStatementCount: getStatementCount,
					getQualifierCount: function(id){ return getData(id, 'q', 0); },
					getReferenceCount: function(id){ return getData(id, 'e', 0); },
					getRelatedProperties: function(id){ return getData(id, 'r', {}); },
					getQualifiers: getQualifiers,
					getFormattedQualifiers: getFormattedQualifiers,
					getMainUsageCount: getStatementCount,
					getUrl: getUrl,
					getUrlPattern: function(id){ return getData(id, 'u', null); },
					getClasses: function(id){ return getData(id, 'pc', []); },
					formatRelatedProperties: formatRelatedProperties,
				}
			});
		}
		return promise;
	})

	.factory('Classes', function($http, $route) {
		var promise;
		var classes;

		var getData = function(id, key, defaultValue) {
			try {
				var result = classes[id][key];
				if (typeof result !== 'undefined' && result !== null) {
					return result;
				}
			} catch(e){
				// fall through
			}
			return defaultValue;
		};

		var getLabel = function(id){ return getData(id, 'l', null); };
		var getUrl = function(id) { return "#/view?id=Q" + id; };
		var getAllInstanceCount = function(id){ return getData(id, 'ai', 0); };

		var getNonemptySubclasses = function(id) {
			var ret = [];
			var subClasses = getData(id,'sb', []);
			for ( var i in subClasses ) {
				var label = getLabel(subClasses[i]);
				if ( label === null ) label = "Q" + subClasses[i];
				ret.push( {label: label, url: getUrl(subClasses[i]), icount: getAllInstanceCount(subClasses[i])} );
			}
			ret.sort(function(a, b) {
				return a.icount < b.icount ? 1 : (a.icount > b.icount ? -1 : 0);
			});
			return ret;
		};

		if (!promise){
			promise = $http.get("data/classes.json").then(function(response){
				classes = response.data;
				return {
					classesHeader: [["Label (ID)", "col-xs-10"], ["Instances", "col-xs-1"], ["Subclasses", "col-xs-1"]],
					getClasses: function(){ return classes; },
					hasEntity: function(id){ return (id in classes); },
					getLabel: getLabel,
					getLabelOrId: function(id){ return getData(id, 'l', 'Q' + id); },
					getDirectInstanceCount: function(id){ return getData(id, 'i', 0); },
					getDirectSubclassCount: function(id){ return getData(id, 's', 0); },
					getAllInstanceCount: getAllInstanceCount,
					getAllSubclassCount: function(id){ return getData(id, 'as', 0); },
					getRelatedProperties: function(id){ return getData(id, 'r', {}); },
					getSuperClasses: function(id){ return getData(id, 'sc', []); },
					getMainUsageCount: getAllInstanceCount,
					getUrl: getUrl,
					getNonemptySubclasses: getNonemptySubclasses
				}
			});
		}
		return promise;
	})

	.factory('statistics', function($http, $route) {
		var promise;
		var statistics;

		if (!promise){
			promise = $http.get("data/statistics.json").then(function(response){
				statistics = response.data;
				return {
					getDumpDateStamp: function(){ return statistics['dumpDate']; },
					getDumpDateString: function(){
						var dateStamp = statistics['dumpDate'];
						return dateStamp.substring(0,4) + '-' + dateStamp.substring(4,6) + '-' + dateStamp.substring(6,8);
					}
				}
			});
		}
		return promise;
	})

	.filter('to_trusted', ['$sce', function($sce){
		return function(text) {
			return $sce.trustAsHtml(text);
		};
	}])

	.directive('ngSlider', function(){
	    var SCALE_FACTOR = 1.005;
	    var scale = function(val){
	      if (val > 0) {
	      	return Math.ceil(Math.log(val) / Math.log(SCALE_FACTOR));
	      }
	      else {
	        return 0;
	      }
	    }

	    var antiScale = function(val){
	      if (val > 0) {
	       	if ((Math.pow(SCALE_FACTOR, val) > 1) && (Math.pow(SCALE_FACTOR, val) < 1.5)){
	       		return 1;
	       	}
	        return Math.ceil(Math.pow(SCALE_FACTOR, val));
	      }else{
	        return 0;
	      }
	    }
	    function link(scope, element, attrs){
	      scope.$watchGroup(['startval', 'endval'], function(){
	        element.slider({
	          range: true,
	          min: scale(parseInt(scope.begin)),
	          max: scale(parseInt(scope.end)),
	          values: [ scale(scope.startval), scale(scope.endval) ],
	          slide: function( event, ui ) {
	            scope.$parent.slider[parseInt(scope.index)].startVal = antiScale(ui.values[0]);
	            scope.$parent.slider[parseInt(scope.index)].endVal = Math.min(antiScale(ui.values[1]), scope.end);
	            scope.$parent.updateStatus();
	            scope.$apply();
	          }
	        });
	      });
	    }

	    return {
	      scope:{
	        begin: '=begin',
	        end: '=end',
	        index: '=index', // TODO and startVal and endVal
	        startval: '=startval',
	        endval: '=endval'
	      },
	      link: link
	    };
	})

	.controller('TypeSelectorController', function($scope, Arguments){
		Arguments.refreshArgs();
		var args = Arguments.getArgs();
		switch (args.type) {
			case "classes":
				$scope.firstActive = "active";
				$scope.secondActive = "";
				break;
			case "properties":
				$scope.firstActive = "";
				$scope.secondActive = "active";
				break;
			default:
				console.log("type: " + args.type + " is unknown");
				$scope.firstActive = "active";
				$scope.secondActive = "";
		}
	});
<commit_msg>change const to var for compatibility<commit_after>'use strict'; // indicate that code is executed in strict mode

var classBrowser = angular.module('classBrowserApp', ['ngAnimate', 'ngRoute', 'utilities'])

	.config(function($routeProvider) {
		$routeProvider
			.when('/', {templateUrl: 'views/start.html'})
			.when('/browse', { templateUrl: 'views/browseData.html' })
			.when('/datatypes', { templateUrl: 'views/datatypes.html' })
			.when('/about', { templateUrl: 'views/about.html' })
			.when('/view', { templateUrl: 'views/view.html' })
			.otherwise({redirectTo: '/'});
	})

	.factory('Arguments', function($http, $route, jsonData, util){
		var args = {};
		var statusStartValues = {
			entityType: "classes",
			from: 0,
			to:jsonData.TABLE_SIZE,
			classesFilter: {
				label: "",
				instances: [0, 4000000],
				subclasses: [0, 200000]
			},
			propertiesFilter: {
				label: "",
				statements: [0, 20000000],
				qualifiers: [0, 100000],
				references: [0, 100000],
				datatypes: {id: 1, name: "Any property type"}

			}
		};
		var status = util.cloneObject(statusStartValues);
		return {
			refreshArgs: function(){
				args = {
					from: ($route.current.params.from) ? parseInt(($route.current.params.from)) : status.from,
					to: ($route.current.params.to) ? parseInt(($route.current.params.to)) : status.to,
					type: ($route.current.params.type) ? ($route.current.params.type) : status.entityType
				}
				status.from = args.from;
				status.to = args.to;
				status.entityType = args.type;
			},
			getArgs: function(){
				return args;
			},
			getStatus: function(){
				return status;
			},
			getStatusStartValues:function(){
				return util.cloneObject(statusStartValues);
			}
		}
	})

	.factory('Properties', function($http, $route){
		var promise;
		var properties;

		var getData = function(id, key, defaultValue) {
			try {
				var result = properties[id][key];
				if (typeof result !== 'undefined' && result !== null) {
					return result;
				}
			} catch(e){
				return defaultValue;
			}
		}

		var getLabel = function(id) { return getData(id, 'l', null); }
		var getLabelOrId = function(id) { return getData(id, 'l', 'P' + id); }
		var getUrl = function(id) { return "#/view?id=P" + id; }

		var formatRelatedProperties = function(relatedProperties, threshold){
			var ret = [];
			try {
				var relPropsList = [];
				for (var relProp in relatedProperties) relPropsList.push([relProp, relatedProperties[relProp]]);

				relPropsList.sort(function(a, b) {
					var a = a[1];
					var b = b[1];
					return a < b ? 1 : (a > b ? -1 : 0);
				});

				for (var i = 0; i < relPropsList.length; i++) {
					if (relPropsList[i][1] < threshold) break;
					var propId = relPropsList[i][0];
					var resultObj = {label : getLabelOrId(propId) , link: getUrl(propId)};
					ret.push(resultObj);
				}
			} catch (e){}

			return ret;
		}

		var getQualifiers = function(id){ return getData(id, 'qs', {}); }

		var getFormattedQualifiers = function(id) {
			var ret = [];
			angular.forEach(getQualifiers(id), function(usageCount, qualifierId) {
				ret.push({label : getLabelOrId(qualifierId) , url: getUrl(qualifierId), count: usageCount});
			});
			ret.sort(function(a, b) {
					var a = a.count;
					var b = b.count;
					return a < b ? 1 : (a > b ? -1 : 0);
			});
			return ret;
		}

		var getStatementCount = function(id){ return getData(id, 's', 0); }

		if (!promise) {
			promise = $http.get("data/properties.json").then(function(response){
				properties = response.data;
				return {
					propertiesHeader: [["Label (ID)", "col-xs-5"], ["Datatype", "col-xs-1"], ["Uses in statements", "col-xs-2"], ["Uses in qualifiers", "col-xs-2"], ["Uses in references", "col-xs-2"]],
					getProperties: function(){ return properties; },
					hasEntity: function(id){ return (id in properties); },
					getLabel: getLabel,
					getLabelOrId: getLabelOrId,
					getItemCount: function(id){ return getData(id, 'i', 0); },
					getDatatype: function(id){ return getData(id, 'd', null); },
					getStatementCount: getStatementCount,
					getQualifierCount: function(id){ return getData(id, 'q', 0); },
					getReferenceCount: function(id){ return getData(id, 'e', 0); },
					getRelatedProperties: function(id){ return getData(id, 'r', {}); },
					getQualifiers: getQualifiers,
					getFormattedQualifiers: getFormattedQualifiers,
					getMainUsageCount: getStatementCount,
					getUrl: getUrl,
					getUrlPattern: function(id){ return getData(id, 'u', null); },
					getClasses: function(id){ return getData(id, 'pc', []); },
					formatRelatedProperties: formatRelatedProperties,
				}
			});
		}
		return promise;
	})

	.factory('Classes', function($http, $route) {
		var promise;
		var classes;

		var getData = function(id, key, defaultValue) {
			try {
				var result = classes[id][key];
				if (typeof result !== 'undefined' && result !== null) {
					return result;
				}
			} catch(e){
				// fall through
			}
			return defaultValue;
		};

		var getLabel = function(id){ return getData(id, 'l', null); };
		var getUrl = function(id) { return "#/view?id=Q" + id; };
		var getAllInstanceCount = function(id){ return getData(id, 'ai', 0); };

		var getNonemptySubclasses = function(id) {
			var ret = [];
			var subClasses = getData(id,'sb', []);
			for ( var i in subClasses ) {
				var label = getLabel(subClasses[i]);
				if ( label === null ) label = "Q" + subClasses[i];
				ret.push( {label: label, url: getUrl(subClasses[i]), icount: getAllInstanceCount(subClasses[i])} );
			}
			ret.sort(function(a, b) {
				return a.icount < b.icount ? 1 : (a.icount > b.icount ? -1 : 0);
			});
			return ret;
		};

		if (!promise){
			promise = $http.get("data/classes.json").then(function(response){
				classes = response.data;
				return {
					classesHeader: [["Label (ID)", "col-xs-10"], ["Instances", "col-xs-1"], ["Subclasses", "col-xs-1"]],
					getClasses: function(){ return classes; },
					hasEntity: function(id){ return (id in classes); },
					getLabel: getLabel,
					getLabelOrId: function(id){ return getData(id, 'l', 'Q' + id); },
					getDirectInstanceCount: function(id){ return getData(id, 'i', 0); },
					getDirectSubclassCount: function(id){ return getData(id, 's', 0); },
					getAllInstanceCount: getAllInstanceCount,
					getAllSubclassCount: function(id){ return getData(id, 'as', 0); },
					getRelatedProperties: function(id){ return getData(id, 'r', {}); },
					getSuperClasses: function(id){ return getData(id, 'sc', []); },
					getMainUsageCount: getAllInstanceCount,
					getUrl: getUrl,
					getNonemptySubclasses: getNonemptySubclasses
				}
			});
		}
		return promise;
	})

	.factory('statistics', function($http, $route) {
		var promise;
		var statistics;

		if (!promise){
			promise = $http.get("data/statistics.json").then(function(response){
				statistics = response.data;
				return {
					getDumpDateStamp: function(){ return statistics['dumpDate']; },
					getDumpDateString: function(){
						var dateStamp = statistics['dumpDate'];
						return dateStamp.substring(0,4) + '-' + dateStamp.substring(4,6) + '-' + dateStamp.substring(6,8);
					}
				}
			});
		}
		return promise;
	})

	.filter('to_trusted', ['$sce', function($sce){
		return function(text) {
			return $sce.trustAsHtml(text);
		};
	}])

	.directive('ngSlider', function(){
	    var SCALE_FACTOR = 1.005;
	    var scale = function(val){
	      if (val > 0) {
	      	return Math.ceil(Math.log(val) / Math.log(SCALE_FACTOR));
	      }
	      else {
	        return 0;
	      }
	    }

	    var antiScale = function(val){
	      if (val > 0) {
	       	if ((Math.pow(SCALE_FACTOR, val) > 1) && (Math.pow(SCALE_FACTOR, val) < 1.5)){
	       		return 1;
	       	}
	        return Math.ceil(Math.pow(SCALE_FACTOR, val));
	      }else{
	        return 0;
	      }
	    }
	    function link(scope, element, attrs){
	      scope.$watchGroup(['startval', 'endval'], function(){
	        element.slider({
	          range: true,
	          min: scale(parseInt(scope.begin)),
	          max: scale(parseInt(scope.end)),
	          values: [ scale(scope.startval), scale(scope.endval) ],
	          slide: function( event, ui ) {
	            scope.$parent.slider[parseInt(scope.index)].startVal = antiScale(ui.values[0]);
	            scope.$parent.slider[parseInt(scope.index)].endVal = Math.min(antiScale(ui.values[1]), scope.end);
	            scope.$parent.updateStatus();
	            scope.$apply();
	          }
	        });
	      });
	    }

	    return {
	      scope:{
	        begin: '=begin',
	        end: '=end',
	        index: '=index', // TODO and startVal and endVal
	        startval: '=startval',
	        endval: '=endval'
	      },
	      link: link
	    };
	})

	.controller('TypeSelectorController', function($scope, Arguments){
		Arguments.refreshArgs();
		var args = Arguments.getArgs();
		switch (args.type) {
			case "classes":
				$scope.firstActive = "active";
				$scope.secondActive = "";
				break;
			case "properties":
				$scope.firstActive = "";
				$scope.secondActive = "active";
				break;
			default:
				console.log("type: " + args.type + " is unknown");
				$scope.firstActive = "active";
				$scope.secondActive = "";
		}
	});
<|endoftext|>