<commit_before>var _ = require('underscore');

exports.plugin = function($N) {
    return {
        name: 'Schema.org',
        description: 'Useful schemas',
        options: {},
        version: '1.0',
        author: 'http://schema.org',
        start: function() {
            var propPrefix = 's_'; //for schema.org

            var schemaorg = require('./schema.org.json');
            var types = schemaorg.types;
            var properties = schemaorg.properties;

            function mapURI(u) {
                if (u === 'Person')
                    return 'Human';
                return u;
            }
            function mapTagName(u, n) {
                if (u === 'Person')
                    return 'Human';
                return n;
            }

            var excludeProperties = ['description', 'image', 'name', 'url', 'about', 'sameAs', 'additionalType', 'alternateName'];
            var excludeTypes = ['Class', 'Property'];
            var rootTypes = ['Action'];

            //http://schema.org/docs/full.html
            $N.addAll(_.map(properties, function(prop) {
                function propType(ranges) {
                    if (_.contains(ranges, 'URL')) {
                        return 'url';
                    }
                    else if (_.contains(ranges, 'Text')) {
                        return 'text';
                    }
                    else if (_.contains(ranges, 'Number')) {
                        return 'real';
                    }
                    else if (_.contains(ranges, 'Boolean')) {
                        return 'boolean';
                    }
                    else if (_.contains(ranges, 'Date')) {
                        return 'timerange';
                    }
                    else if (_.contains(ranges, 'DateTime')) {
                        return 'timepoint';
                    }
                    else if (_.contains(ranges, 'Time')) {
                        return 'timerange';
                    }
                    else if (_.contains(ranges, 'Float')) {
                        return 'real';
                    }
                    else if (_.contains(ranges, 'Integer')) {
                        return 'integer';
                    }
                    else {
                        return 'object'; //ranges;
                    }
                }

                var pt = propType(prop.ranges);
                var p = {
                    id: propPrefix + prop.id,
                    name: prop.label,
                    description: prop.comment,
                    extend: pt
                };
                if (p.description.length === 0)
                    delete p.description;
                if (pt === 'object') {
                    p.tag = _.map(prop.ranges, function(r) {
                        return mapURI(r);
                    });
                }

                return p;
            }));

            $N.addAll(_.map(types, function(type) {
                if (_.contains(excludeTypes, type.id))
                    return;
                var t = {
                    id: mapURI(type.id),
                    name: mapTagName(type.id, type.label),
                    description: type.comment,
                    value: _.map(_.difference(type.properties, excludeProperties), function(p) {
                        return propPrefix + p;
                    }),
                    extend: type.supertypes
                };
                if (t.description.length == 0)
                    delete t.description;
                if (t.id !== type.id)
                    t.sid = type.id; //the original schema.org URI

                if (_.contains(rootTypes, type.id)) {
                    t.extend = null;
                }
                return t;
            }));

        },
        stop: function() {
            //TODO remove any schema.org tags that may have been created
        }
    };
};

/*var schema, code;
 var types = {};

 function getSchemaRoots() {
 var roots = { };
 $.each(schema.types, function(k, v) {
 if (v.ancestors.length == 1) {
 if (v.ancestors[0] == 'Thing')
 roots[k] = v;
 }
 });
 return roots;
 }
 function getSchemaChildren(parent) {
 var roots = { };
 var count = 0;
 var maxItems = 500;
 $.each(schema.types, function(k, v) {
 for (var i = 0; i < v.ancestors.length; i++) {
 if (v.ancestors[i] == parent) {
 roots[k] = v;
 count++;
 }
 if (count > maxItems)
 return roots;
 }
 });
 return roots;
 }

 function loadTypeMenu(parent, children) {
 if (parent!=null)
 if (children.length == 0)
 if (schema.types[parent].properties.length < 1)
 return '';

 var s = '';
 $.each(children, function(k, v) {
 var sc = getSchemaChildren(k);
 var scLen = Object.keys(sc).length;
 //s+= '
' + k + ' ' + scLen + '
';

 var tt = '';
 if (scLen > 0) {
 tt = loadTypeMenu(k, sc);
 }
 s+= '
' + v.label + '' + tt + '
';
 });

 return '
' + s + '
';

 }

 function getProperties(type) {
 var t = schema.types[type];
 if (t!=undefined)
 return schema.types[type].properties;
 else
 return [];
 }

 function isCommonProperty(v) {
 return (v == 'url') || (v == 'description') || (v == 'name') || (v == 'image');
 }
 function isDataPropertyType(v) {
 return (v == 'Integer') || (v == 'URL') || (v=='Text') || (v=='Boolean') || (v=='Geo') || (v=='Float') || (v=='Date') || (v=='DataType') || (v=='Number') || (v=='Thing');
 }
 function isSupertype(parent, child) {
 if (isDataPropertyType(child)) {
 return false;
 }
 var parents = schema.types[child];
 if (parents==undefined)
 return false;

 parents = parents.supertypes;
 $.each(parents, function(t) {
 if (t == parent)
 return true;
 if (isSupertype(parent, t))
 return true;
 });
 return false;
 }

 function loadPropertiesMenu(type, history) {
 var MAXDEPTH = 3;

 if (history == undefined) history = [ type ];
 var level = history.length - 1;
 if (level >= MAXDEPTH) return '';

 var t = '';
 var props = getProperties(type);

 $.each(props, function(k, v) {
 if (isCommonProperty(v)) {
 //do not add
 }
 else if (schema.properties[v].comment.indexOf('legacy spelling')!=-1) {

 }
 else {
 var label = schema.properties[v].label;
 var range = schema.properties[v].ranges[0];

 if (isDataPropertyType(range))  {
 t += '
' + label + '
';
 }
 else if (level < MAXDEPTH-1) {
 if (!isSupertype(type, range)) {
 if (schema.types[range].properties.length > 0) {
 history.push(v);
 t += '
' + label + '' + loadPropertiesMenu(range, history) + "
";
 history.pop();
 }
 }
 }
 }
 });
 if (level == 0)
 t += '
Remove
';
 return '
 ' + t + '
';
 }

 function isDataType(t) {
 return (t == 'Text') || (t == 'Boolean') || (t == 'URL') || (t == 'Integer') || (t == 'Float') || (t == 'Number') || (t == 'Date') || (t=='Thing');
 }

 function loadSchema(path, whenSchemaLoaded) {
 $.getJSON(path, function(data) {
 schema = data;

 if (whenSchemaLoaded!=undefined)
 whenSchemaLoaded();
 });
 }
 */
<commit_msg>schema.org update<commit_after>var _ = require('underscore');

exports.plugin = function($N) {
    return {
        name: 'Schema.org',
        description: 'Useful schemas',
        options: {},
        version: '1.0',
        author: 'http://schema.org',
        start: function() {
            var propPrefix = 's_'; //for schema.org

            var schemaorg = require('./schema.org.json');
            var types = schemaorg.types;
            var properties = schemaorg.properties;

            function mapURI(u) {
                if (u === 'Person')
                    return 'Human';
                return u;
            }
            function mapTagName(u, n) {
                if (u === 'Person')
                    return 'Human';
                return n;
            }
            function mapPropertyName(u, n) {
                if (u === 's_email')
                    return 'email';
                return n;
            }

            var excludeProperties = ['description', 'image', 'name', 'url', 'about', 'sameAs', 'additionalType', 'alternateName'];
            var excludeTypes = ['Class', 'Property'];
            var rootTypes = ['Action'];

            //http://schema.org/docs/full.html
            $N.addAll(_.map(properties, function(prop) {
                function propType(ranges) {
                    if (_.contains(ranges, 'URL')) {
                        return 'url';
                    }
                    else if (_.contains(ranges, 'Text')) {
                        return 'text';
                    }
                    else if (_.contains(ranges, 'Number')) {
                        return 'real';
                    }
                    else if (_.contains(ranges, 'Boolean')) {
                        return 'boolean';
                    }
                    else if (_.contains(ranges, 'Date')) {
                        return 'timerange';
                    }
                    else if (_.contains(ranges, 'DateTime')) {
                        return 'timepoint';
                    }
                    else if (_.contains(ranges, 'Time')) {
                        return 'timerange';
                    }
                    else if (_.contains(ranges, 'Float')) {
                        return 'real';
                    }
                    else if (_.contains(ranges, 'Integer')) {
                        return 'integer';
                    }
                    else {
                        return 'object'; //ranges;
                    }
                }

                var pt = propType(prop.ranges);
                var p = {
                    id: mapPropertyName(propPrefix + prop.id),
                    name: prop.label,
                    description: prop.comment,
                    extend: pt
                };
                if (p.description.length === 0)
                    delete p.description;
                if (pt === 'object') {
                    p.tag = _.map(prop.ranges, function(r) {
                        return mapURI(r);
                    });
                }

                return p;
            }));

            $N.addAll(_.map(types, function(type) {
                if (_.contains(excludeTypes, type.id))
                    return;
                var t = {
                    id: mapURI(type.id),
                    name: mapTagName(type.id, type.label),
                    description: type.comment,
                    value: _.map(_.difference(type.properties, excludeProperties), function(p) {
                        return propPrefix + p;
                    }),
                    extend: type.supertypes
                };
                if (t.description.length == 0)
                    delete t.description;
                if (t.id !== type.id)
                    t.sid = type.id; //the original schema.org URI

                if (_.contains(rootTypes, type.id)) {
                    t.extend = null;
                }
                return t;
            }));

        },
        stop: function() {
            //TODO remove any schema.org tags that may have been created
        }
    };
};

/*var schema, code;
 var types = {};

 function getSchemaRoots() {
 var roots = { };
 $.each(schema.types, function(k, v) {
 if (v.ancestors.length == 1) {
 if (v.ancestors[0] == 'Thing')
 roots[k] = v;
 }
 });
 return roots;
 }
 function getSchemaChildren(parent) {
 var roots = { };
 var count = 0;
 var maxItems = 500;
 $.each(schema.types, function(k, v) {
 for (var i = 0; i < v.ancestors.length; i++) {
 if (v.ancestors[i] == parent) {
 roots[k] = v;
 count++;
 }
 if (count > maxItems)
 return roots;
 }
 });
 return roots;
 }

 function loadTypeMenu(parent, children) {
 if (parent!=null)
 if (children.length == 0)
 if (schema.types[parent].properties.length < 1)
 return '';

 var s = '';
 $.each(children, function(k, v) {
 var sc = getSchemaChildren(k);
 var scLen = Object.keys(sc).length;
 //s+= '
' + k + ' ' + scLen + '
';

 var tt = '';
 if (scLen > 0) {
 tt = loadTypeMenu(k, sc);
 }
 s+= '
' + v.label + '' + tt + '
';
 });

 return '
' + s + '
';

 }

 function getProperties(type) {
 var t = schema.types[type];
 if (t!=undefined)
 return schema.types[type].properties;
 else
 return [];
 }

 function isCommonProperty(v) {
 return (v == 'url') || (v == 'description') || (v == 'name') || (v == 'image');
 }
 function isDataPropertyType(v) {
 return (v == 'Integer') || (v == 'URL') || (v=='Text') || (v=='Boolean') || (v=='Geo') || (v=='Float') || (v=='Date') || (v=='DataType') || (v=='Number') || (v=='Thing');
 }
 function isSupertype(parent, child) {
 if (isDataPropertyType(child)) {
 return false;
 }
 var parents = schema.types[child];
 if (parents==undefined)
 return false;

 parents = parents.supertypes;
 $.each(parents, function(t) {
 if (t == parent)
 return true;
 if (isSupertype(parent, t))
 return true;
 });
 return false;
 }

 function loadPropertiesMenu(type, history) {
 var MAXDEPTH = 3;

 if (history == undefined) history = [ type ];
 var level = history.length - 1;
 if (level >= MAXDEPTH) return '';

 var t = '';
 var props = getProperties(type);

 $.each(props, function(k, v) {
 if (isCommonProperty(v)) {
 //do not add
 }
 else if (schema.properties[v].comment.indexOf('legacy spelling')!=-1) {

 }
 else {
 var label = schema.properties[v].label;
 var range = schema.properties[v].ranges[0];

 if (isDataPropertyType(range))  {
 t += '
' + label + '
';
 }
 else if (level < MAXDEPTH-1) {
 if (!isSupertype(type, range)) {
 if (schema.types[range].properties.length > 0) {
 history.push(v);
 t += '
' + label + '' + loadPropertiesMenu(range, history) + "
";
 history.pop();
 }
 }
 }
 }
 });
 if (level == 0)
 t += '
Remove
';
 return '
 ' + t + '
';
 }

 function isDataType(t) {
 return (t == 'Text') || (t == 'Boolean') || (t == 'URL') || (t == 'Integer') || (t == 'Float') || (t == 'Number') || (t == 'Date') || (t=='Thing');
 }

 function loadSchema(path, whenSchemaLoaded) {
 $.getJSON(path, function(data) {
 schema = data;

 if (whenSchemaLoaded!=undefined)
 whenSchemaLoaded();
 });
 }
 */
<|endoftext|>


<commit_before><commit_msg>Update shop.js<commit_after><|endoftext|>


<commit_before>'use strict';

angular.module('metadatamanagementApp').service('VariableBuilderService',
  function(VariableResource, CleanJSObjectService) {
    var buildVariable = function(variableFromExcel, variableFromJson,
      dataAcquisitionProjectId) {
      if (!variableFromExcel || !variableFromJson ||
        !dataAcquisitionProjectId) {
        return null;
      }

      var variableObj = {
        id: variableFromExcel.id,
        dataType: variableFromJson.dataType,
        scaleLevel: variableFromJson.scaleLevel,
        name: variableFromJson.name,
        label: variableFromJson.label,
        questionId: variableFromExcel.questionId,
        annotations: {
          en: variableFromExcel['annotations.en'],
          de: variableFromExcel['annotations.de']
        },
        accessWays: CleanJSObjectService.
        removeWhiteSpace(variableFromExcel.accessWays),
        relatedQuestionStrings: {
          en: variableFromExcel['relatedQuestionStrings.en'],
          de: variableFromExcel['relatedQuestionStrings.de']
        },
        filterDetails: {
          expression: variableFromExcel['filterDetails.expression'],
          description: {
            en: variableFromExcel['filterDetails.description.de'],
            de: variableFromExcel['filterDetails.description.en']
          },
          expressionLanguage: variableFromExcel[
            'filterDetails.expressionLanguage'
          ]
        },
        sameVariablesInPanel: variableFromJson.sameVariablesInPanel,
        relatedVariables: variableFromJson.relatedVariables,
        surveyIds: variableFromJson.surveyIds,
        dataSetIds: variableFromJson.dataSetIds,
        dataAcquisitionProjectId: dataAcquisitionProjectId,
        generationDetails: {
          rule: variableFromExcel['generationDetails.rule'],
          ruleExpressionLanguage: variableFromExcel[
            'generationDetails.ruleExpressionLanguage'],
          description: {
            en: variableFromExcel['generationDetails.description.en'],
            de: variableFromExcel['generationDetails.description.de']
          }
        },
        distribution: variableFromJson.distribution,
      };
      console.log(variableObj);
      return new VariableResource(CleanJSObjectService.removeEmptyJsonObjects(
        variableObj));
    };
    return {
      buildVariable: buildVariable
    };
  });
<commit_msg>#803 removed console log output<commit_after>'use strict';

angular.module('metadatamanagementApp').service('VariableBuilderService',
  function(VariableResource, CleanJSObjectService) {
    var buildVariable = function(variableFromExcel, variableFromJson,
      dataAcquisitionProjectId) {
      if (!variableFromExcel || !variableFromJson ||
        !dataAcquisitionProjectId) {
        return null;
      }

      var variableObj = {
        id: variableFromExcel.id,
        dataType: variableFromJson.dataType,
        scaleLevel: variableFromJson.scaleLevel,
        name: variableFromJson.name,
        label: variableFromJson.label,
        questionId: variableFromExcel.questionId,
        annotations: {
          en: variableFromExcel['annotations.en'],
          de: variableFromExcel['annotations.de']
        },
        accessWays: CleanJSObjectService.
        removeWhiteSpace(variableFromExcel.accessWays),
        relatedQuestionStrings: {
          en: variableFromExcel['relatedQuestionStrings.en'],
          de: variableFromExcel['relatedQuestionStrings.de']
        },
        filterDetails: {
          expression: variableFromExcel['filterDetails.expression'],
          description: {
            en: variableFromExcel['filterDetails.description.de'],
            de: variableFromExcel['filterDetails.description.en']
          },
          expressionLanguage: variableFromExcel[
            'filterDetails.expressionLanguage'
          ]
        },
        sameVariablesInPanel: variableFromJson.sameVariablesInPanel,
        relatedVariables: variableFromJson.relatedVariables,
        surveyIds: variableFromJson.surveyIds,
        dataSetIds: variableFromJson.dataSetIds,
        dataAcquisitionProjectId: dataAcquisitionProjectId,
        generationDetails: {
          rule: variableFromExcel['generationDetails.rule'],
          ruleExpressionLanguage: variableFromExcel[
            'generationDetails.ruleExpressionLanguage'],
          description: {
            en: variableFromExcel['generationDetails.description.en'],
            de: variableFromExcel['generationDetails.description.de']
          }
        },
        distribution: variableFromJson.distribution,
      };
      return new VariableResource(CleanJSObjectService.removeEmptyJsonObjects(
        variableObj));
    };
    return {
      buildVariable: buildVariable
    };
  });
<|endoftext|>


<commit_before>var vids = document.querySelectorAll(".vid")

window.images = []

vids.forEach(function(vid) {

    var src = vid.attributes.src.value

    var image = document.createElement("img")
    var width = 300

    try {
        width = vid.attributes.width.value|0
    }
    catch(e) {

    }

    image.src = "https://img.youtube.com/vi/" + src + "/hqdefault.jpg"
    image.width = width
    image.height = width * 3/4///16

    images.push(image)
    vid.appendChild(image)
})

setTimeout(function() {
    var vids = document.querySelectorAll(".vid")

    vids.forEach(function(vid) {
        var src = vid.attributes.src.value

        vid.firstChild.onclick = function() {
            console.log(vid.firstChild)
            playVideo(src)
        }
    })

}, 500)

function playVideo(src) {
    // show overlay

    var overlay = document.getElementById("overlay")
    overlay.style.display = "block"

    overlay.innerHTML =  '

'

    var iframe = document.getElementById("iframe")
    // iframe.style.background = "https://img.youtube.com/vi/" + src + "/0.jpg"

    iframe.src ="https://www.youtube.com/embed/" + src + "?ecver=1&theme=dark&color=white&autoplay=1&autohide=1&cc_load_policy=1&modestbranding=1&showinfo=0&rel=0"

    var ratio = window.innerWidth < window.innerHeight ? 1 : 0.7

    var w = window.innerWidth * ratio
    var h = w * 315/560
    iframe.width = w
    iframe.height = h

    iframe.style.left = (window.innerWidth - w) /2
    iframe.style.top = (window.innerHeight - h) /2
    iframe.style.position = 'absolute'

    overlay.onclick = function() {
        overlay.innerHTML = ""
        overlay.style.display = "none"
    }

}

var html = "

"
html += ""

document.body.innerHTML += html<commit_msg>bigger when its mobile<commit_after>var vids = document.querySelectorAll(".vid")

window.images = []

vids.forEach(function(vid) {

    var src = vid.attributes.src.value

    var image = document.createElement("img")
    var width = 300

    try {
        width = vid.attributes.width.value|0
    }
    catch(e) {

    }

    image.src = "https://img.youtube.com/vi/" + src + "/hqdefault.jpg"
    image.width = width
    image.height = width * 3/4///16

    images.push(image)
    vid.appendChild(image)
})

setTimeout(function() {
    var vids = document.querySelectorAll(".vid")

    vids.forEach(function(vid) {
        var src = vid.attributes.src.value

        vid.firstChild.onclick = function() {
            console.log(vid.firstChild)
            playVideo(src)
        }
    })

}, 500)

function playVideo(src) {
    // show overlay

    var overlay = document.getElementById("overlay")
    overlay.style.display = "block"

    overlay.innerHTML =  '

'

    var iframe = document.getElementById("iframe")
    // iframe.style.background = "https://img.youtube.com/vi/" + src + "/0.jpg"

    iframe.src ="https://www.youtube.com/embed/" + src + "?ecver=1&theme=dark&color=white&autoplay=1&autohide=1&cc_load_policy=1&modestbranding=1&showinfo=0&rel=0"

    var ratio = window.innerWidth < window.innerHeight ? 1 : 0.7

    var w = window.innerWidth * ratio
    var h = w * 315/560
    iframe.width = w
    iframe.height = h

    iframe.style.left = (window.innerWidth - w) /2
    iframe.style.top = (window.innerHeight - h) /2
    iframe.style.position = 'absolute'
    document.body.style.overflow = 'hidden'

    overlay.onclick = function() {
        overlay.innerHTML = ""
        overlay.style.display = "none"
        document.body.style.overflow = 'default'
    }

}

var html = "

"
html += ""

document.body.innerHTML += html<|endoftext|>


<commit_before>/* global html_beautify */
/* Author: Daniel Katzberg */
'use strict';

angular.module('metadatamanagementApp')
  .controller('VariableDetailController', function($scope, entity,
    QuestionSearchService, VariableSearchService, Principal,
    SimpleMessageToastService, PageTitleService, LanguageService,
    CleanJSObjectService, $state, ToolbarHeaderService) {
    $scope.generationCodeToggleFlag = true;
    $scope.filterDetailsCodeToggleFlag = true;
    $scope.notAllRowsVisible = true;
    $scope.counts = {};
    $scope.validResponsesOrMissingsAvailable = false;
    entity.promise.then(function(result) {
      if (result.release || Principal.hasAuthority('ROLE_PUBLISHER')) {
        $scope.variable = result;
        if (!CleanJSObjectService.isNullOrEmpty($scope
          .variable.distribution.missings) || !CleanJSObjectService
          .isNullOrEmpty($scope.variable
            .distribution.validResponses)) {
          $scope.validResponsesOrMissingsAvailable = true;
        }
        var currenLanguage = LanguageService.getCurrentInstantly();
        var secondLanguage = currenLanguage === 'de' ? 'en' : 'de';
        PageTitleService.setPageTitle('variable-management.detail.title', {
          label: $scope.variable.label[currenLanguage] ? $scope.variable
          .label[currenLanguage] : $scope.variable.label[
            secondLanguage],
          variableId: $scope.variable.id
        });
        $scope.study = $scope.variable.study;
        $scope.dataSet = $scope.variable.dataSet;
        QuestionSearchService.countBy('variables.id', $scope.variable.id)
        .then(function(questionsCount) {
          $scope.counts.questionsCount = questionsCount.count;
          if (questionsCount.count === 1) {
            QuestionSearchService
            .findByVariableId($scope.variable.id, ['number', 'instrumentNumber',
            'questionText', 'id'])
            .then(function(question) {
              $scope.question = question.hits.hits[0]._source;
            });
          }
        });
        $scope.counts.surveysCount = $scope.variable.surveys.length;
        if ($scope.counts.surveysCount === 1) {
          $scope.survey = $scope.variable.surveys[0];
        }
        if ($scope.variable.panelIdentifier) {
          VariableSearchService
          .countBy('panelIdentifier', $scope.variable.panelIdentifier)
          .then(function(variablesInPanel) {
            $scope.counts.variablesInPanel = variablesInPanel.count;
          });
        } else {
          $scope.counts.variablesInPanel = 0;
        }
        $scope.counts.publicationsCount = $scope.variable
        .relatedPublications.length;
        if ($scope.counts.publicationsCount === 1) {
          $scope.relatedPublication = $scope.variable
          .relatedPublications[0];
        }
        ToolbarHeaderService.updateToolbarHeader({
          'stateName': $state.current.name,
          'name': $scope.variable.name,
          'dataSetId': $scope.variable.dataSetId,
          'dataSetNumber': $scope.variable.dataSetNumber,
          'studyId': $scope.variable.studyId,
          'projectId': $scope.variable.
          dataAcquisitionProjectId});
        if ($scope.variable.filterDetails) {
          html_beautify($scope.variable.filterDetails.expression); //jscs:ignore
        }
        if ($scope.variable.generationDetails) {
          html_beautify($scope.variable.generationDetails.rule); //jscs:ignore
        }
      } else {
        SimpleMessageToastService.openSimpleMessageToast(
          'variable-management.detail.not-released-toast', {id: result.id}
        );
      }
    });
    $scope.isRowHidden = function(index) {
      if (index <= 4 || index >= $scope
        .variable.distribution.validResponses.length - 5) {
        return false;
      } else {
        return $scope.notAllRowsVisible;
      }
    };
    $scope.toggleAllRowsVisible = function() {
      $scope.notAllRowsVisible = !$scope.notAllRowsVisible;
    };
    $scope.toggleGenerationCode = function() {
      $scope.generationCodeToggleFlag = !$scope.generationCodeToggleFlag;
    };
    $scope.toggleFilterDetailsCode = function() {
      $scope.filterDetailsCodeToggleFlag = !$scope.filterDetailsCodeToggleFlag;
    };
    $scope.openSuccessCopyToClipboardToast = function(message) {
      SimpleMessageToastService.openSimpleMessageToast(message, []);
    };

    /* Show headline for Central Tendency,
      if one element is filled with data. */
    $scope.checkCentralTendencyElements = function() {

      return $scope.variable.distribution != null &&
        $scope.variable.distribution.statistics != null &&
        ($scope.variable.distribution.statistics.meanValue != null ||
          $scope.variable.distribution.statistics.median != null ||
          $scope.variable.distribution.statistics.mode != null);
    };

    /* Show headline for Dispersion, if one element is filled with data. */
    $scope.checkDispersionElements = function() {
      return $scope.variable.distribution != null &&
        $scope.variable.distribution.statistics != null &&
        ($scope.variable.distribution.statistics.standardDeviation != null ||
          $scope.variable.distribution.statistics.meanDeviation != null ||
          $scope.variable.distribution.statistics.deviance != null);
    };

    /* Show headline for Distribution, if one element is filled with data. */
    $scope.checkDistributionElements = function() {
      return $scope.variable.distribution != null &&
        $scope.variable.distribution.statistics != null &&
        ($scope.variable.distribution.statistics.skewness != null ||
          $scope.variable.distribution.statistics.kurtosis != null);
    };

  });
<commit_msg>#667 enabled page title and toolbar header for unreleased objects<commit_after>/* global html_beautify */
/* Author: Daniel Katzberg */
'use strict';

angular.module('metadatamanagementApp')
  .controller('VariableDetailController', function($scope, entity,
    QuestionSearchService, VariableSearchService, Principal,
    SimpleMessageToastService, PageTitleService, LanguageService,
    CleanJSObjectService, $state, ToolbarHeaderService) {
    $scope.generationCodeToggleFlag = true;
    $scope.filterDetailsCodeToggleFlag = true;
    $scope.notAllRowsVisible = true;
    $scope.counts = {};
    $scope.validResponsesOrMissingsAvailable = false;
    entity.promise.then(function(result) {
      var currenLanguage = LanguageService.getCurrentInstantly();
      var secondLanguage = currenLanguage === 'de' ? 'en' : 'de';
      PageTitleService.setPageTitle('variable-management.detail.title', {
        label: result.label[currenLanguage] ? result.label[currenLanguage]
          : result.label[secondLanguage],
        variableId: result.id
      });
      ToolbarHeaderService.updateToolbarHeader({
        'stateName': $state.current.name,
        'name': result.name,
        'dataSetId': result.dataSetId,
        'dataSetNumber': result.dataSetNumber,
        'studyId': result.studyId,
        'projectId': result.dataAcquisitionProjectId});
      if (result.release || Principal.hasAuthority('ROLE_PUBLISHER')) {
        $scope.variable = result;
        if (!CleanJSObjectService.isNullOrEmpty($scope
          .variable.distribution.missings) || !CleanJSObjectService
          .isNullOrEmpty($scope.variable
            .distribution.validResponses)) {
          $scope.validResponsesOrMissingsAvailable = true;
        }
        $scope.study = $scope.variable.study;
        $scope.dataSet = $scope.variable.dataSet;
        QuestionSearchService.countBy('variables.id', $scope.variable.id)
        .then(function(questionsCount) {
          $scope.counts.questionsCount = questionsCount.count;
          if (questionsCount.count === 1) {
            QuestionSearchService
            .findByVariableId($scope.variable.id, ['number', 'instrumentNumber',
            'questionText', 'id'])
            .then(function(question) {
              $scope.question = question.hits.hits[0]._source;
            });
          }
        });
        $scope.counts.surveysCount = $scope.variable.surveys.length;
        if ($scope.counts.surveysCount === 1) {
          $scope.survey = $scope.variable.surveys[0];
        }
        if ($scope.variable.panelIdentifier) {
          VariableSearchService
          .countBy('panelIdentifier', $scope.variable.panelIdentifier)
          .then(function(variablesInPanel) {
            $scope.counts.variablesInPanel = variablesInPanel.count;
          });
        } else {
          $scope.counts.variablesInPanel = 0;
        }
        $scope.counts.publicationsCount = $scope.variable
        .relatedPublications.length;
        if ($scope.counts.publicationsCount === 1) {
          $scope.relatedPublication = $scope.variable
          .relatedPublications[0];
        }
        if ($scope.variable.filterDetails) {
          html_beautify($scope.variable.filterDetails.expression); //jscs:ignore
        }
        if ($scope.variable.generationDetails) {
          html_beautify($scope.variable.generationDetails.rule); //jscs:ignore
        }
      } else {
        SimpleMessageToastService.openSimpleMessageToast(
          'variable-management.detail.not-released-toast', {id: result.id}
        );
      }
    });
    $scope.isRowHidden = function(index) {
      if (index <= 4 || index >= $scope
        .variable.distribution.validResponses.length - 5) {
        return false;
      } else {
        return $scope.notAllRowsVisible;
      }
    };
    $scope.toggleAllRowsVisible = function() {
      $scope.notAllRowsVisible = !$scope.notAllRowsVisible;
    };
    $scope.toggleGenerationCode = function() {
      $scope.generationCodeToggleFlag = !$scope.generationCodeToggleFlag;
    };
    $scope.toggleFilterDetailsCode = function() {
      $scope.filterDetailsCodeToggleFlag = !$scope.filterDetailsCodeToggleFlag;
    };
    $scope.openSuccessCopyToClipboardToast = function(message) {
      SimpleMessageToastService.openSimpleMessageToast(message, []);
    };

    /* Show headline for Central Tendency,
      if one element is filled with data. */
    $scope.checkCentralTendencyElements = function() {

      return $scope.variable.distribution != null &&
        $scope.variable.distribution.statistics != null &&
        ($scope.variable.distribution.statistics.meanValue != null ||
          $scope.variable.distribution.statistics.median != null ||
          $scope.variable.distribution.statistics.mode != null);
    };

    /* Show headline for Dispersion, if one element is filled with data. */
    $scope.checkDispersionElements = function() {
      return $scope.variable.distribution != null &&
        $scope.variable.distribution.statistics != null &&
        ($scope.variable.distribution.statistics.standardDeviation != null ||
          $scope.variable.distribution.statistics.meanDeviation != null ||
          $scope.variable.distribution.statistics.deviance != null);
    };

    /* Show headline for Distribution, if one element is filled with data. */
    $scope.checkDistributionElements = function() {
      return $scope.variable.distribution != null &&
        $scope.variable.distribution.statistics != null &&
        ($scope.variable.distribution.statistics.skewness != null ||
          $scope.variable.distribution.statistics.kurtosis != null);
    };

  });
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: "foam.apploader",
  name: "NoClassLoaderContext",
  requires: [
  ],
  exports: [
    'classloader'
  ],
  properties: [
    {
      name: "classloader",
      factory: function() {
        return {
          load: function(id) {
            var cls = foam.lookup(id, true);
            return cls ? Promise.resolve(cls) : Promise.reject('No classloader enabled.');
          },
          addClassPath: function(){},
          maybeLoad: function() { return this.load().catch(function() { return null; }); },
          latch: function() {}
        };
      }
    }
  ]
});

foam.SCRIPT({
  package: 'foam.apploader',
  name: 'NoClassLoaderContextScript',
  requires: [
    'foam.apploader.NoClassLoaderContext',
  ],
  code: function() {
    var classLoaderContext = foam.apploader.NoClassLoaderContext.create(
        null, foam.__context__);
    foam.__context__ = classLoaderContext.__subContext__;
  }
});
<commit_msg>Formatting.<commit_after>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: "foam.apploader",
  name: "NoClassLoaderContext",

  exports: [
    'classloader'
  ],

  properties: [
    {
      name: "classloader",
      factory: function() {
        return {
          load: function(id) {
            var cls = foam.lookup(id, true);
            return cls ? Promise.resolve(cls) : Promise.reject('No classloader enabled.');
          },
          addClassPath: function(){},
          maybeLoad: function() { return this.load().catch(function() { return null; }); },
          latch: function() {}
        };
      }
    }
  ]
});

foam.SCRIPT({
  package: 'foam.apploader',
  name: 'NoClassLoaderContextScript',

  requires: [
    'foam.apploader.NoClassLoaderContext',
  ],

  code: function() {
    var classLoaderContext = foam.apploader.NoClassLoaderContext.create(
        null, foam.__context__);
    foam.__context__ = classLoaderContext.__subContext__;
  }
});
<|endoftext|>


<commit_before>var assert = require('assert'),
    should = require('should'),
    spawn = require('child_process').spawn,
    fs = require('fs'),
    path = require('path')

TESTING_DIR = '/tmp/dejaTest'

function testing_setup(testingDir, callback) {

  // if temp dir exists, delete contents
  path.exists(testingDir, function(exists) {

    // if the testing directory is already here, remove it
    if (exists) {
      var rm = spawn('rm', ['-r', '-f', testingDir])

      rm.on('exit', function(code) {

        makeTestDirectory(testingDir, callback)
      })
    }
    else {

      makeTestDirectory(testingDir, callback)
    }
  })
}

function makeTestDirectory(testingDir, callback) {

  // make testing directory
  fs.mkdirSync(testingDir, 0777)

  // if testing directory doesn't now exit, abort testing
  path.exists(testingDir, function(exists) {

    if (!exists) {
      console.log('Error: could not create testing directory.')
      error(1)
    }
    else {
      callback()
    }
  })
}

function testing_teardown(testingDir, callback) {

  path.exists(testingDir, function(exists) {

    // if the testing directory is already here, remove it
    if (exists) {
      var rm = spawn('rm', ['-r', '-f', testingDir])

      rm.on('exit', function(code) {
        if (callback) {
          callback()
        }
      })
    }
    else {
      if (callback) {
        callback()
      }
    }
  })
}

function spawnInTestHome(command, args, testingDir) {

  process.env.HOME = testingDir
  return spawn(command, args, {env: process.env})
}

function doClone(testingDir, repoBaseName, repoUrl, exists_callback) {

  var dejaArgs = ['clone', repoUrl]
  var deja = spawnInTestHome('deja', dejaArgs, testingDir)
  deja.on('exit', function(code) {
    path.exists(testingDir + '/.deja/' + repoBaseName + '/.git', exists_callback)
  })
}

function doMockClone(testingDir, repoBaseName, exists_callback) {

  var pathToDeja = testingDir + '/.deja'

  // make deja directory
  fs.mkdirSync(pathToDeja, 0777)

  path.exists(pathToDeja, function(exists) {
    exists.should.equal(true)

    var pathToMockRepo = pathToDeja + '/' + repoBaseName

    // make mock repo directory
    fs.mkdirSync(pathToMockRepo, 0777)

    path.exists(pathToMockRepo, function(exists) {
      exists.should.equal(true)

      var pathToMockGitDir = pathToMockRepo + '/.git'

      // stick fake .git dir in fake repo
      fs.mkdirSync(pathToMockGitDir, 0777)

      path.exists(pathToMockGitDir, function(exists) {
        exists.should.equal(true)

        var pathToFakeVimrc = pathToMockRepo + '/.vimrc'
        var touch = spawn('touch', [pathToFakeVimrc])

        touch.on('exit', function(code) {
          path.exists(pathToFakeVimrc, exists_callback)
        })
      })
    })
  })
}

function testCloneThenTeardown(testingDir, repoBaseName, repoUrl) {

  doClone(testingDir, repoBaseName, repoUrl, function(exists) {
    exists.should.equal(true)
    testing_teardown(testingDir)
  })
}

module.exports = {
  'test .deja dir creation': function() {
    var testingDir = TESTING_DIR + '_a'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        var deja = spawnInTestHome('deja', ['help'], testingDir)
        deja.on('exit', function(code) {
          code.should.equal(0)
          if (code == 0) {
            path.exists(testingDir + '/.deja', function(exists) {
              exists.should.equal(true)
              testing_teardown(testingDir)
            })
          }
        })
      })
    })
  },

  'test deja clone': function() {
    var testingDir = TESTING_DIR + '_b'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        testCloneThenTeardown(testingDir, 'dotfiles', 'git://github.com/mcantelon/dotfiles.git')
      })
    })
  },

  'test deja clone with shortform': function() {
    var testingDir = TESTING_DIR + '_c'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        testCloneThenTeardown(testingDir, 'dotfiles', 'mcantelon/dotfiles')
      })
    })
  },

  'test deja rm': function() {
    var testingDir = TESTING_DIR + '_d'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        doMockClone(testingDir, 'dotfiles', function(exists) {
          exists.should.equal(true)
          if (exists) {
            var deja = spawnInTestHome('deja', ['rm', 'dotfiles'], testingDir)
            deja.on('exit', function(code) {
              path.exists(testingDir + '/.deja/dotfiles', function(exists) {
                // the repo should have been deleted by "deja rm dotfiles"
                exists.should.equal(false)
                testing_teardown(testingDir)
              })
            })
          }
       })
     })
    })
  },

  'test deja ls': function() {
    var testingDir = TESTING_DIR + '_e'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        doMockClone(testingDir, 'dotfiles', function(exists) {
          exists.should.equal(true)
          if (exists) {
            var deja = spawnInTestHome('deja', ['ls'], testingDir)
            deja.stdout.on('data', function(data) {
              data.toString().should.equal("dotfiles\n")
             testing_teardown(testingDir)
            })
         }
       })
      })
    })
  },

  'test deja link': function() {
    var testingDir = TESTING_DIR + '_f'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        doMockClone(testingDir, 'dotfiles', function(exists) {
          exists.should.equal(true)
          if (exists) {
            var deja = spawnInTestHome('deja', ['link', 'dotfiles'], testingDir)
            deja.on('exit', function(code) {
              code.should.equal(0)
              fs.lstat(testingDir + '/.vimrc', function(err, stats) {
                stats.isSymbolicLink().should.equal(true)
                testing_teardown(testingDir)
              })
            })
          }
        })
      })
    })
  },

  'test deja unlink': function() {
    var testingDir = TESTING_DIR + '_g'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        doMockClone(testingDir, 'dotfiles', function(exists) {
          exists.should.equal(true)
          if (exists) {
            var deja = spawnInTestHome('deja', ['link', 'dotfiles'], testingDir)
            deja.on('exit', function(code) {
              code.should.equal(0)
              fs.lstat(testingDir + '/.vimrc', function(err, stats) {
                stats.isSymbolicLink().should.equal(true)

                var deja = spawnInTestHome('deja', ['unlink', 'dotfiles'], testingDir)
                deja.on('exit', function(code) {
                  code.should.equal(0)

                  fs.lstat(testingDir + '/.vimrc', function(err, stats) {
                    assert.isUndefined(stats)
                    testing_teardown(testingDir)
                  })
                })
              })
            })
          }
        })
      })
    })
  },

  'test deja duplicate repo name handling': function() {
    var repoUrl = 'mcantelon/dotfiles'
    var testingDir = TESTING_DIR + '_h'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        doClone(testingDir, 'dotfiles', repoUrl, function(exists) {
          exists.should.equal(true)
          if (exists) {
            var dejaArgs = ['clone', repoUrl]
            var deja = spawnInTestHome('deja', dejaArgs, testingDir)
            deja.on('exit', function(code) {
              // deja should have padding the repo name as it's a duplicate
              path.exists(testingDir + '/.deja/dotfiles_1/.git', function(exists) {
                exists.should.equal(true)
                testing_teardown(testingDir)
             })
            })
          }
        })
      })
    })
  }
}
<commit_msg>Commas first.<commit_after>var assert = require('assert')
  , should = require('should')
  , spawn = require('child_process').spawn
  , fs = require('fs')
  , path = require('path')

TESTING_DIR = '/tmp/dejaTest'

function testing_setup(testingDir, callback) {

  // if temp dir exists, delete contents
  path.exists(testingDir, function(exists) {

    // if the testing directory is already here, remove it
    if (exists) {
      var rm = spawn('rm', ['-r', '-f', testingDir])

      rm.on('exit', function(code) {

        makeTestDirectory(testingDir, callback)
      })
    }
    else {

      makeTestDirectory(testingDir, callback)
    }
  })
}

function makeTestDirectory(testingDir, callback) {

  // make testing directory
  fs.mkdirSync(testingDir, 0777)

  // if testing directory doesn't now exit, abort testing
  path.exists(testingDir, function(exists) {

    if (!exists) {
      console.log('Error: could not create testing directory.')
      error(1)
    }
    else {
      callback()
    }
  })
}

function testing_teardown(testingDir, callback) {

  path.exists(testingDir, function(exists) {

    // if the testing directory is already here, remove it
    if (exists) {
      var rm = spawn('rm', ['-r', '-f', testingDir])

      rm.on('exit', function(code) {
        if (callback) {
          callback()
        }
      })
    }
    else {
      if (callback) {
        callback()
      }
    }
  })
}

function spawnInTestHome(command, args, testingDir) {

  process.env.HOME = testingDir
  return spawn(command, args, {env: process.env})
}

function doClone(testingDir, repoBaseName, repoUrl, exists_callback) {

  var dejaArgs = ['clone', repoUrl]
  var deja = spawnInTestHome('deja', dejaArgs, testingDir)
  deja.on('exit', function(code) {
    path.exists(testingDir + '/.deja/' + repoBaseName + '/.git', exists_callback)
  })
}

function doMockClone(testingDir, repoBaseName, exists_callback) {

  var pathToDeja = testingDir + '/.deja'

  // make deja directory
  fs.mkdirSync(pathToDeja, 0777)

  path.exists(pathToDeja, function(exists) {
    exists.should.equal(true)

    var pathToMockRepo = pathToDeja + '/' + repoBaseName

    // make mock repo directory
    fs.mkdirSync(pathToMockRepo, 0777)

    path.exists(pathToMockRepo, function(exists) {
      exists.should.equal(true)

      var pathToMockGitDir = pathToMockRepo + '/.git'

      // stick fake .git dir in fake repo
      fs.mkdirSync(pathToMockGitDir, 0777)

      path.exists(pathToMockGitDir, function(exists) {
        exists.should.equal(true)

        var pathToFakeVimrc = pathToMockRepo + '/.vimrc'
        var touch = spawn('touch', [pathToFakeVimrc])

        touch.on('exit', function(code) {
          path.exists(pathToFakeVimrc, exists_callback)
        })
      })
    })
  })
}

function testCloneThenTeardown(testingDir, repoBaseName, repoUrl) {

  doClone(testingDir, repoBaseName, repoUrl, function(exists) {
    exists.should.equal(true)
    testing_teardown(testingDir)
  })
}

module.exports = {
  'test .deja dir creation': function() {
    var testingDir = TESTING_DIR + '_a'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        var deja = spawnInTestHome('deja', ['help'], testingDir)
        deja.on('exit', function(code) {
          code.should.equal(0)
          if (code == 0) {
            path.exists(testingDir + '/.deja', function(exists) {
              exists.should.equal(true)
              testing_teardown(testingDir)
            })
          }
        })
      })
    })
  },

  'test deja clone': function() {
    var testingDir = TESTING_DIR + '_b'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        testCloneThenTeardown(testingDir, 'dotfiles', 'git://github.com/mcantelon/dotfiles.git')
      })
    })
  },

  'test deja clone with shortform': function() {
    var testingDir = TESTING_DIR + '_c'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        testCloneThenTeardown(testingDir, 'dotfiles', 'mcantelon/dotfiles')
      })
    })
  },

  'test deja rm': function() {
    var testingDir = TESTING_DIR + '_d'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        doMockClone(testingDir, 'dotfiles', function(exists) {
          exists.should.equal(true)
          if (exists) {
            var deja = spawnInTestHome('deja', ['rm', 'dotfiles'], testingDir)
            deja.on('exit', function(code) {
              path.exists(testingDir + '/.deja/dotfiles', function(exists) {
                // the repo should have been deleted by "deja rm dotfiles"
                exists.should.equal(false)
                testing_teardown(testingDir)
              })
            })
          }
       })
     })
    })
  },

  'test deja ls': function() {
    var testingDir = TESTING_DIR + '_e'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        doMockClone(testingDir, 'dotfiles', function(exists) {
          exists.should.equal(true)
          if (exists) {
            var deja = spawnInTestHome('deja', ['ls'], testingDir)
            deja.stdout.on('data', function(data) {
              data.toString().should.equal("dotfiles\n")
             testing_teardown(testingDir)
            })
         }
       })
      })
    })
  },

  'test deja link': function() {
    var testingDir = TESTING_DIR + '_f'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        doMockClone(testingDir, 'dotfiles', function(exists) {
          exists.should.equal(true)
          if (exists) {
            var deja = spawnInTestHome('deja', ['link', 'dotfiles'], testingDir)
            deja.on('exit', function(code) {
              code.should.equal(0)
              fs.lstat(testingDir + '/.vimrc', function(err, stats) {
                stats.isSymbolicLink().should.equal(true)
                testing_teardown(testingDir)
              })
            })
          }
        })
      })
    })
  },

  'test deja unlink': function() {
    var testingDir = TESTING_DIR + '_g'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        doMockClone(testingDir, 'dotfiles', function(exists) {
          exists.should.equal(true)
          if (exists) {
            var deja = spawnInTestHome('deja', ['link', 'dotfiles'], testingDir)
            deja.on('exit', function(code) {
              code.should.equal(0)
              fs.lstat(testingDir + '/.vimrc', function(err, stats) {
                stats.isSymbolicLink().should.equal(true)

                var deja = spawnInTestHome('deja', ['unlink', 'dotfiles'], testingDir)
                deja.on('exit', function(code) {
                  code.should.equal(0)

                  fs.lstat(testingDir + '/.vimrc', function(err, stats) {
                    assert.isUndefined(stats)
                    testing_teardown(testingDir)
                  })
                })
              })
            })
          }
        })
      })
    })
  },

  'test deja duplicate repo name handling': function() {
    var repoUrl = 'mcantelon/dotfiles'
    var testingDir = TESTING_DIR + '_h'
    testing_teardown(testingDir, function() {
      testing_setup(testingDir, function() {
        doClone(testingDir, 'dotfiles', repoUrl, function(exists) {
          exists.should.equal(true)
          if (exists) {
            var dejaArgs = ['clone', repoUrl]
            var deja = spawnInTestHome('deja', dejaArgs, testingDir)
            deja.on('exit', function(code) {
              // deja should have padding the repo name as it's a duplicate
              path.exists(testingDir + '/.deja/dotfiles_1/.git', function(exists) {
                exists.should.equal(true)
                testing_teardown(testingDir)
             })
            })
          }
        })
      })
    })
  }
}
<|endoftext|>


<commit_before>/* global describe, it */
'use strict';

var assert = require('assert');
var csv = require('csv');
var exec = require('child_process').exec;
var path = require('path');

describe('directory search', function () {
  let cmd;
  beforeEach(function () {
    cmd = 'node ' + path.join(__dirname, '../bin/directory') + ' ';
  });

  it('--help should run without errors', function (done) {
    exec(cmd + '--help', function (error, stdout, stderr) {
      assert(!error);
      done();
    });
  });
  it('--version should run without errors', function (done) {
    exec(cmd + '--version', function (error, stdout, stderr) {
      assert(!error);
      done();
    });
  });
  it('should return error on missing command', function (done) {
    this.timeout(4000);

    exec(cmd, function (error, stdout, stderr) {
      assert(error);
      assert.equal(error.code, 1);
      done();
    });
  });

  it('should filter by name', function (done) {
    this.timeout(4000);

    let name = 'rhett';

    cmd += ` --json --name ${name}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      // number of results equals number of people
      // who have ${name} in their name
      assert.equal(
        data.length,
        data.filter(i => {
          return (new RegExp(name, 'i')).test(i.fname + ' ' + i.lname);
        }).length,
        `all people in results should have the ${name} in their full name`
      );

      done();
    });
  });
  it('should filter by department', function (done) {
    this.timeout(4000);

    let dept = 'education';

    cmd += ` --json --name john --department ${dept}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      // number of results equals number of people
      // who have ${dept} in their dept
      assert.equal(
        data.length,
        data
          .filter(i => i.department && (new RegExp(dept, 'i')).test(i.department))
          .length
        ,
        `all people in results should contain the provided dept`
      );

      done();
    });
  });
  it('should filter by UCINetID', function (done) {
    this.timeout(4000);

    let id = 'rhett';

    cmd += ` --json --ucinetid ${id}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'Only UCINetID ${id} should be returned');

      done();
    });
  });
  it('should allow UCINetID, or others, to allow wildcards', function (done) {
    this.timeout(4000);

    let id = 'rhett*';

    cmd += ` --json --ucinetid ${id}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      // number of results equals number of people
      // who have ${id} in their id
      assert.equal(
        data.length,
        data
          .filter(i => i.ucinetid && (new RegExp(id, 'i')).test(i.ucinetid))
          .length
        ,
        `all people in results should have UCINetID containing ${id}`
      );

      done();
    });
  });
  it('should filter by Title', function (done) {
    this.timeout(4000);

    let title = '*developer*';

    cmd += ` --json --name rhett --title ${title}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      // number of results equals number of people
      // who have ${title} in their title
      assert.equal(
        data.length,
        data
          .filter(i => i.title && (new RegExp(title.replace(/\*/g, ''), 'i')).test(i.title))
          .length
        ,
        `all people in results should have Title containing ${title}`
      );

      done();
    });
  });
  it('should filter by CampusID', function (done) {
    this.timeout(4000);

    let campusid = '1181700';

    cmd += ` --json --campusid ${campusid}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many results.');
      assert((new RegExp(`^0*${campusid}$`, 'i')).test(data[0].campusid), `campus id should be ${campusid} preceeded by 0-n "0" chars`);

      done();
    });
  });
  it('should filter by email', function (done) {
    this.timeout(4000);

    let email = 'rhett@uci.edu';

    cmd += ` --json --email ${email}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many results.');
      assert.equal(email, data[0].email, `Person should have email given ${email}`);

      done();
    });
  });
  it('should filter by email with alias name', function (done) {
    this.timeout(4000);

    let email = 'nayssan.safavian@uci.edu';

    cmd += ` --json --email ${email}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many/few results.');
      assert.equal(email, data[0].aliasEmail.toLowerCase(), `Person should have email given ${email}`);

      done();
    });
  });
  it('should filter by email delivery point', function (done) {
    this.timeout(4000);

    let point = 'gmail';

    cmd += ` --json --delivery-point ${point} --name rhett `;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(
        data.length,
        data
          .filter(i => i.deliveryPoint && /@gmailbox/i.test(i.deliveryPoint))
          .length
        ,
        `all people in results should point to gmail servers`
      );

      done();
    });
  });
  it('should throw error if email delivery point is not listed value (gmail|o365|es|hs|exchange|other)', function (done) {
    this.timeout(4000);

    let point = 'blah';

    cmd += ` --json --delivery-point ${point} --department education --employee`;
    exec(cmd, function (error, stdout, stderr) {
      assert(error);
      assert.equal(error.code, 1);

      done();
    });
  });
  it('should filter by phone number (4-digit)', function (done) {
    this.timeout(4000);

    let phone = '8564';

    cmd += ` --json --phone ${phone}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many results.');
      assert.equal('949824' + phone, data[0].phone.replace(/[^\d]/g, ''), `Person should have phone number 949824${phone}.`);

      done();
    });
  });
  it('should filter by phone number (5-digit)', function (done) {
    this.timeout(4000);

    let phone = '48564';

    cmd += ` --json --phone ${phone}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many results.');
      assert.equal('94982' + phone, data[0].phone.replace(/[^\d]/g, ''), `Person should have phone number 94982${phone}.`);

      done();
    });
  });
  it('should filter by phone number (10-digit)', function (done) {
    this.timeout(4000);

    let phone = '9498248564';

    cmd += ` --json --phone ${phone}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many results.');
      assert.equal(phone, data[0].phone.replace(/[^\d]/g, ''), `Person should have phone number 94982${phone}.`);

      done();
    });
  });
  it('should filter by phone number (11-digit)', function (done) {
    this.timeout(4000);

    let phone = '19498248564';

    cmd += ` --json --phone ${phone}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many results.');
      assert.equal(phone.slice(1), data[0].phone.replace(/[^\d]/g, ''), `Person should have phone number 94982${phone}.`);

      done();
    });
  });
  it('should filter by employee', function (done) {
    this.timeout(4000);

    cmd += ` --json --employee rhett`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(
        data.length,
        data
          .filter(i => i.employee)
          .length
        ,
        `all people in results should be employees`
      );

      done();
    });
  });

  it('should output in raw LDAP', function (done) {
    this.timeout(4000);

    let name = 'rhett';

    cmd += ` --raw --name ${name}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(
        data.length,
        data
          .filter(i => i.dn)
          .length
        ,
        `all results should have dn raw LDAP flag`
      );

      done();
    });
  });
  it('should output in json', function (done) {
    this.timeout(4000);

    let name = 'rhett';

    cmd += ` --json --name ${name}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert(data, 'Data should return as a json string with --json flag');
      assert(data.filter, 'Data should return as array');

      done();
    });
  });
  it('should output in json with pretty spacing', function (done) {
    this.timeout(4000);

    let name = 'rhett';

    cmd += ` --json-pretty --name ${name}`;
    exec(cmd, function (error, pretty, stderr) {
      assert(!error);

      exec(cmd.replace(/--json-pretty/, '--json'), function (error, mini, stderr) {
        assert(!error);

        assert.notEqual(pretty, mini, 'texts should not be the same. pretty should have additional tabs or spaces');

        let prettyData = JSON.parse(pretty);
        let miniData = JSON.parse(mini);

        assert(prettyData, 'pretty json string should compile to object');
        assert(miniData, 'mini json string should compile to object');
        assert.deepStrictEqual(prettyData, miniData, 'Data should return as array');

        done();
      });
    });
  });
  it('should output in csv', function (done) {
    this.timeout(4000);

    cmd += ` --csv --ucinetid rhett`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      csv.parse(stdout, function (err, lines) {
        assert(!err, 'output text should be parse-able csv');
        assert(lines.map, 'parsed csv data should be an array');
        assert.equal(1, lines.length, '--ucinetid should only have 1 result')

        done();
      });

    });
  });
  it('should output in csv with headers', function (done) {
    this.timeout(4000);

    cmd += ` --csv --csv-headers --ucinetid rhett`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      csv.parse(stdout, function (err, lines) {
        assert(!err, 'output text should be parse-able csv');
        assert(lines.map, 'parsed csv data should be an array');
        assert.equal(2, lines.length, '--ucinetid should only have 1 result plus 1 row headers')

        done();
      });

    });
  });

  it('should limit returned results', function (done) {
    this.timeout(6000);

    cmd += ` --json --limit 1 --phone 5118`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);
      assert.equal(1, data.length, 'should only have one entry');

      done();
    });
  });
  it('should skip returned results', function (done) {
    this.timeout(6000);

    cmd += ` --json --phone 5118 --limit 5`;
    exec(cmd, function (error, full, stderr) {
      assert(!error);

      let fullData = JSON.parse(full);

      cmd += ` --skip 1`;
      exec(cmd, function (error, part, stderr) {
        assert(!error);

        let partialData = JSON.parse(part);
        assert.deepStrictEqual(fullData[1], partialData[0], 'should only have one entry');

        done();
      });
    });
  });
});
<commit_msg>adding missing semi-colun<commit_after>/* global describe, it */
'use strict';

var assert = require('assert');
var csv = require('csv');
var exec = require('child_process').exec;
var path = require('path');

describe('directory search', function () {
  let cmd;
  beforeEach(function () {
    cmd = 'node ' + path.join(__dirname, '../bin/directory') + ' ';
  });

  it('--help should run without errors', function (done) {
    exec(cmd + '--help', function (error, stdout, stderr) {
      assert(!error);
      done();
    });
  });
  it('--version should run without errors', function (done) {
    exec(cmd + '--version', function (error, stdout, stderr) {
      assert(!error);
      done();
    });
  });
  it('should return error on missing command', function (done) {
    this.timeout(4000);

    exec(cmd, function (error, stdout, stderr) {
      assert(error);
      assert.equal(error.code, 1);
      done();
    });
  });

  it('should filter by name', function (done) {
    this.timeout(4000);

    let name = 'rhett';

    cmd += ` --json --name ${name}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      // number of results equals number of people
      // who have ${name} in their name
      assert.equal(
        data.length,
        data.filter(i => {
          return (new RegExp(name, 'i')).test(i.fname + ' ' + i.lname);
        }).length,
        `all people in results should have the ${name} in their full name`
      );

      done();
    });
  });
  it('should filter by department', function (done) {
    this.timeout(4000);

    let dept = 'education';

    cmd += ` --json --name john --department ${dept}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      // number of results equals number of people
      // who have ${dept} in their dept
      assert.equal(
        data.length,
        data
          .filter(i => i.department && (new RegExp(dept, 'i')).test(i.department))
          .length
        ,
        `all people in results should contain the provided dept`
      );

      done();
    });
  });
  it('should filter by UCINetID', function (done) {
    this.timeout(4000);

    let id = 'rhett';

    cmd += ` --json --ucinetid ${id}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'Only UCINetID ${id} should be returned');

      done();
    });
  });
  it('should allow UCINetID, or others, to allow wildcards', function (done) {
    this.timeout(4000);

    let id = 'rhett*';

    cmd += ` --json --ucinetid ${id}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      // number of results equals number of people
      // who have ${id} in their id
      assert.equal(
        data.length,
        data
          .filter(i => i.ucinetid && (new RegExp(id, 'i')).test(i.ucinetid))
          .length
        ,
        `all people in results should have UCINetID containing ${id}`
      );

      done();
    });
  });
  it('should filter by Title', function (done) {
    this.timeout(4000);

    let title = '*developer*';

    cmd += ` --json --name rhett --title ${title}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      // number of results equals number of people
      // who have ${title} in their title
      assert.equal(
        data.length,
        data
          .filter(i => i.title && (new RegExp(title.replace(/\*/g, ''), 'i')).test(i.title))
          .length
        ,
        `all people in results should have Title containing ${title}`
      );

      done();
    });
  });
  it('should filter by CampusID', function (done) {
    this.timeout(4000);

    let campusid = '1181700';

    cmd += ` --json --campusid ${campusid}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many results.');
      assert((new RegExp(`^0*${campusid}$`, 'i')).test(data[0].campusid), `campus id should be ${campusid} preceeded by 0-n "0" chars`);

      done();
    });
  });
  it('should filter by email', function (done) {
    this.timeout(4000);

    let email = 'rhett@uci.edu';

    cmd += ` --json --email ${email}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many results.');
      assert.equal(email, data[0].email, `Person should have email given ${email}`);

      done();
    });
  });
  it('should filter by email with alias name', function (done) {
    this.timeout(4000);

    let email = 'nayssan.safavian@uci.edu';

    cmd += ` --json --email ${email}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many/few results.');
      assert.equal(email, data[0].aliasEmail.toLowerCase(), `Person should have email given ${email}`);

      done();
    });
  });
  it('should filter by email delivery point', function (done) {
    this.timeout(4000);

    let point = 'gmail';

    cmd += ` --json --delivery-point ${point} --name rhett `;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(
        data.length,
        data
          .filter(i => i.deliveryPoint && /@gmailbox/i.test(i.deliveryPoint))
          .length
        ,
        `all people in results should point to gmail servers`
      );

      done();
    });
  });
  it('should throw error if email delivery point is not listed value (gmail|o365|es|hs|exchange|other)', function (done) {
    this.timeout(4000);

    let point = 'blah';

    cmd += ` --json --delivery-point ${point} --department education --employee`;
    exec(cmd, function (error, stdout, stderr) {
      assert(error);
      assert.equal(error.code, 1);

      done();
    });
  });
  it('should filter by phone number (4-digit)', function (done) {
    this.timeout(4000);

    let phone = '8564';

    cmd += ` --json --phone ${phone}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many results.');
      assert.equal('949824' + phone, data[0].phone.replace(/[^\d]/g, ''), `Person should have phone number 949824${phone}.`);

      done();
    });
  });
  it('should filter by phone number (5-digit)', function (done) {
    this.timeout(4000);

    let phone = '48564';

    cmd += ` --json --phone ${phone}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many results.');
      assert.equal('94982' + phone, data[0].phone.replace(/[^\d]/g, ''), `Person should have phone number 94982${phone}.`);

      done();
    });
  });
  it('should filter by phone number (10-digit)', function (done) {
    this.timeout(4000);

    let phone = '9498248564';

    cmd += ` --json --phone ${phone}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many results.');
      assert.equal(phone, data[0].phone.replace(/[^\d]/g, ''), `Person should have phone number 94982${phone}.`);

      done();
    });
  });
  it('should filter by phone number (11-digit)', function (done) {
    this.timeout(4000);

    let phone = '19498248564';

    cmd += ` --json --phone ${phone}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(1, data.length, 'found too many results.');
      assert.equal(phone.slice(1), data[0].phone.replace(/[^\d]/g, ''), `Person should have phone number 94982${phone}.`);

      done();
    });
  });
  it('should filter by employee', function (done) {
    this.timeout(4000);

    cmd += ` --json --employee rhett`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(
        data.length,
        data
          .filter(i => i.employee)
          .length
        ,
        `all people in results should be employees`
      );

      done();
    });
  });

  it('should output in raw LDAP', function (done) {
    this.timeout(4000);

    let name = 'rhett';

    cmd += ` --raw --name ${name}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert.equal(
        data.length,
        data
          .filter(i => i.dn)
          .length
        ,
        `all results should have dn raw LDAP flag`
      );

      done();
    });
  });
  it('should output in json', function (done) {
    this.timeout(4000);

    let name = 'rhett';

    cmd += ` --json --name ${name}`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);

      assert(data, 'Data should return as a json string with --json flag');
      assert(data.filter, 'Data should return as array');

      done();
    });
  });
  it('should output in json with pretty spacing', function (done) {
    this.timeout(4000);

    let name = 'rhett';

    cmd += ` --json-pretty --name ${name}`;
    exec(cmd, function (error, pretty, stderr) {
      assert(!error);

      exec(cmd.replace(/--json-pretty/, '--json'), function (error, mini, stderr) {
        assert(!error);

        assert.notEqual(pretty, mini, 'texts should not be the same. pretty should have additional tabs or spaces');

        let prettyData = JSON.parse(pretty);
        let miniData = JSON.parse(mini);

        assert(prettyData, 'pretty json string should compile to object');
        assert(miniData, 'mini json string should compile to object');
        assert.deepStrictEqual(prettyData, miniData, 'Data should return as array');

        done();
      });
    });
  });
  it('should output in csv', function (done) {
    this.timeout(4000);

    cmd += ` --csv --ucinetid rhett`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      csv.parse(stdout, function (err, lines) {
        assert(!err, 'output text should be parse-able csv');
        assert(lines.map, 'parsed csv data should be an array');
        assert.equal(1, lines.length, '--ucinetid should only have 1 result')

        done();
      });

    });
  });
  it('should output in csv with headers', function (done) {
    this.timeout(4000);

    cmd += ` --csv --csv-headers --ucinetid rhett`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      csv.parse(stdout, function (err, lines) {
        assert(!err, 'output text should be parse-able csv');
        assert(lines.map, 'parsed csv data should be an array');
        assert.equal(2, lines.length, '--ucinetid should only have 1 result plus 1 row headers');

        done();
      });

    });
  });

  it('should limit returned results', function (done) {
    this.timeout(6000);

    cmd += ` --json --limit 1 --phone 5118`;
    exec(cmd, function (error, stdout, stderr) {
      assert(!error);

      let data = JSON.parse(stdout);
      assert.equal(1, data.length, 'should only have one entry');

      done();
    });
  });
  it('should skip returned results', function (done) {
    this.timeout(6000);

    cmd += ` --json --phone 5118 --limit 5`;
    exec(cmd, function (error, full, stderr) {
      assert(!error);

      let fullData = JSON.parse(full);

      cmd += ` --skip 1`;
      exec(cmd, function (error, part, stderr) {
        assert(!error);

        let partialData = JSON.parse(part);
        assert.deepStrictEqual(fullData[1], partialData[0], 'should only have one entry');

        done();
      });
    });
  });
});
<|endoftext|>