<commit_before>/* eslint-disable */
window.CaseController = (() => {
  return {
    init: () => {
      var token = window.sessionStorage.getItem('userInfo-token');
      $.ajax({
        type: 'GET',
        url: 'http://localhost:3000/cases/3',
        headers: {
          'x-access-token': token,
        },
      }).done((data) => {
        $.getScript('js/caseFieldFunctionality.js', () => {
          caseUI.fields['drNum']['input'].val(data.drNumber);
          caseUI.fields['masterDrNum']['input'].val(data.masterDrNumber);
          caseUI.fields['division']['input'].val(data.division);
          caseUI.fields['bureau']['input'].val(data.bureau);
          caseUI.fields['notes']['input'].val(data.notes);
          moment.tz.add('America/Los_Angeles|PST PDT|80 70|0101|1Lzm0 1zb0 Op0');
          caseUI.fields['dateOccured']['input'].val(moment(data.dateOccured).tz('America/Los_Angeles').format('YYYY-MM-DD'));
          caseUI.fields['dateReported']['input'].val(moment(data.dateReported).tz('America/Los_Angeles').format('YYYY-MM-DD'));
          caseUI.fields['reportingDistrict']['input'].val(data.reportingDistrict);
          caseUI.fields['caseStatus']['input'].val(data.caseStatus);
          caseUI.fields['caseStatusDate']['input'].val(moment(data.caseStatusDate).tz('America/Los_Angeles').format('YYYY-MM-DD'));
          caseUI.fields['solvabilityFactor']['input'].val(data.solvabilityFactor);
          console.log(Object.values(data.weaponUsed));
          console.log(Object.values(data.motive));
          // var weapons = {
          //   handgun: caseUI.fields['weapon']['inputs']['weaponInput_handgun'],
          //   rifle: caseUI.fields['weapon']['inputs']['weaponInput_rifle'],
          //   blunt_force: caseUI.fields['weapon']['inputs']['weaponInput_bluntForce'],
          //   bodily_force: caseUI.fields['weapon']['inputs']['weaponInput_bodilyForce'],
          //   knife: caseUI.fields['weapon']['inputs']['weaponInput_knife'],
          //   unknown: caseUI.fields['weapon']['inputs']['weaponInput_unknown']
          // }
          //
          // var motive = {
          //   robbery: caseUI.fields['motive']['inputs']['motiveInput_robbery'],
          //   burglary: caseUI.fields['motive']['inputs']['motiveInput_burglary'],
          //   gang: caseUI.fields['motive']['inputs']['motiveInput_gang'],
          //   narcotics: caseUI.fields['motive']['inputs']['motiveInput_narcotics'],
          //   domestic_violence: caseUI.fields['motive']['inputs']['motiveInput_domesticViolence'],
          //   dispute: caseUI.fields['motive']['inputs']['motiveInput_dispute'],
          //   accidental: caseUI.fields['motive']['inputs']['motiveInput_accidental'],
          //   self_defense: caseUI.fields['motive']['inputs']['motiveInput_selfDefense'],
          //   unknown: caseUI.fields['motive']['inputs']['motiveInput_unknown']
          // }

          caseUI.fields['streetNumber']['input'].val(data.address.streetNumber);
          caseUI.fields['streetName']['input'].val(data.address.streetName);
          caseUI.fields['city']['input'].val(data.address.city);
          caseUI.fields['zipCode']['input'].val(data.address.zipCode);

          // if there is more than one victim
          caseUI.fields['victFirstName']['input'].val(data.victim.victName.first);
          caseUI.fields['victMiddleName']['input'].val(data.victim.victName.middle);
          caseUI.fields['victLastName']['input'].val(data.victim.victName.last);
          caseUI.fields['victSex']['input'].val(data.victim.victSex);
          caseUI.fields['victDesc']['input'].val(data.victim.victDesc);
          caseUI.fields['victAge']['input'].val(data.victim.victAge);
          caseUI.fields['victId']['input'].val(data.victim._id);

          // if there is more than one suspect
          caseUI.fields['suspFirstName']['input'].val(data.suspects[0].suspName.first);
          caseUI.fields['suspMiddleName']['input'].val(data.suspects[0].suspName.middle);
          caseUI.fields['suspLastName']['input'].val(data.suspects[0].suspName.last);
          caseUI.fields['suspSex']['input'].val(data.suspects[0].suspSex);
          caseUI.fields['suspSupervisedReleaseStatus']['input'].val(data.suspects[0].supervisedReleaseStatus);
          caseUI.fields['suspDesc']['input'].val(data.suspects[0].suspDesc);
          caseUI.fields['suspAge']['input'].val(data.suspects[0].suspAge);
          // not fully working
          caseUI.fields['juvenileTriedAsAdult']['input'].val(data.suspects[0].juvenileTriedAsAdult);
          caseUI.fields['suspId']['input'].val(data.suspects[0]._id);

          $('#drNumInput').prop('readonly', true);
          $('#masterDrNumInput').prop('readonly', true);
          $('#divisionInput').prop('disabled', true);
          $('#bureauInput').prop('disabled', true);
          $('#notesInput').prop('readonly', true);
          $('#dateOccuredInput').prop('readonly', true);
          $('#dateReportedInput').prop('readonly', true);
          $('#reportingDistrictInput').prop('disabled', true);
          $('#caseStatusInput').prop('disabled', true);
          $('#caseStatusDateInput').prop('readonly', true);
          $('#solvabilityFactorInput').prop('disabled', true);

          // weaponsList
          $('#weaponInput_handgun').prop('disabled', true);
          $('#weaponInput_rifle').prop('disabled', true);
          $('#weaponInput_bluntForce').prop('disabled', true);
          $('#weaponInput_bodilyForce').prop('disabled', true);
          $('#weaponInput_knife').prop('disabled', true);
          $('#weaponInput_unknown').prop('disabled', true);

          // motivesList
          $('#motiveInput_robbery').prop('disabled', true);
          $('#motiveInput_burglary').prop('disabled', true);
          $('#motiveInput_gang').prop('disabled', true);
          $('#motiveInput_narcotics').prop('disabled', true);
          $('#motiveInput_domesticViolence').prop('disabled', true);
          $('#motiveInput_dispute').prop('disabled', true);
          $('#motiveInput_accidental').prop('disabled', true);
          $('#motiveInput_selfDefense').prop('disabled', true);
          $('#motiveInput_unknown').prop('disabled', true);

          // address
          $('#streetNumberInput').prop('readonly', true);
          $('#streetNameInput').prop('readonly', true);
          $('#cityInput').prop('readonly', true);
          $('#zipCodeInput').prop('readonly', true);

          // victimInformation
          $('#victFirstNameInput').prop('readonly', true);
          $('#victMiddleNameInput').prop('readonly', true);
          $('#victLastNameInput').prop('readonly', true);
          $('#victSexInput').prop('disabled', true);
          $('#victDescInput').prop('readonly', true);
          $('#victAgeInput').prop('readonly', true);
          $('#victIdInput').prop('disabled', true);

          // suspectInformation
          $('#suspFirstNameInput').prop('readonly', true);
          $('#suspMiddleNameInput').prop('readonly', true);
          $('#suspLastNameInput').prop('readonly', true);
          $('#suspSexInput').prop('disabled', true);
          $('#suspSupervisedReleaseStatusInput').prop('disabled', true);
          $('#suspDescInput').prop('readonly', true);
          $('#suspAgeInput').prop('readonly', true);
          $('#juvenileTriedAsAdultInput').prop('disabled', true);
          $('#suspIdInput').prop('disabled', true);

          var save = document.getElementById('button-save-page');
          $(save).prop('disabled', true);

          var edit = document.getElementById('edit');
          edit.onclick = function() {
            $('#drNumInput').removeAttr('readonly');
            $('#masterDrNumInput').removeAttr('readonly');
            $('#divisionInput').removeAttr('disabled');
            $('#bureauInput').removeAttr('disabled');
            $('#notesInput').removeAttr('readonly');
            $('#dateOccuredInput').removeAttr('readonly');
            $('#dateReportedInput').removeAttr('readonly');
            $('#reportingDistrictInput').removeAttr('disabled');
            $('#caseStatusInput').removeAttr('disabled');
            $('#caseStatusDateInput').removeAttr('readonly');
            $('#solvabilityFactorInput').removeAttr('disabled');

            $('#weaponInput_handgun').removeAttr('disabled');
            $('#weaponInput_rifle').removeAttr('disabled');
            $('#weaponInput_bluntForce').removeAttr('disabled');
            $('#weaponInput_bodilyForce').removeAttr('disabled');
            $('#weaponInput_knife').removeAttr('disabled');
            $('#weaponInput_unknown').removeAttr('disabled');

            $('#motiveInput_robbery').removeAttr('disabled');
            $('#motiveInput_burglary').removeAttr('disabled');
            $('#motiveInput_gang').removeAttr('disabled');
            $('#motiveInput_narcotics').removeAttr('disabled');
            $('#motiveInput_domesticViolence').removeAttr('disabled');
            $('#motiveInput_dispute').removeAttr('disabled');
            $('#motiveInput_accidental').removeAttr('disabled');
            $('#motiveInput_selfDefense').removeAttr('disabled');
            $('#motiveInput_unknown').removeAttr('disabled');

            $('#streetNumberInput').removeAttr('readonly');
            $('#streetNameInput').removeAttr('readonly');
            $('#cityInput').removeAttr('readonly');
            $('#zipCodeInput').removeAttr('readonly');

            $('#victFirstNameInput').removeAttr('readonly');
            $('#victMiddleNameInput').removeAttr('readonly');
            $('#victLastNameInput').removeAttr('readonly');
            $('#victSexInput').removeAttr('disabled');
            $('#victDescInput').removeAttr('readonly');
            $('#victAgeInput').removeAttr('readonly');
            $('#victIdInput').removeAttr('disabled');

            $('#suspFirstNameInput').removeAttr('readonly');
            $('#suspMiddleNameInput').removeAttr('readonly');
            $('#suspLastNameInput').removeAttr('readonly');
            $('#suspSexInput').removeAttr('disabled');
            $('#suspSupervisedReleaseStatusInput').removeAttr('disabled');
            $('#suspDescInput').removeAttr('readonly');
            $('#suspAgeInput').removeAttr('readonly');
            $('#juvenileTriedAsAdultInput').removeAttr('disabled');
            $('#suspIdInput').removeAttr('disabled');

            $(save).removeAttr('disabled');
            // $(save).onclick(function() {
            //   $.post('http://localhost:3000/cases/3')
            // })
            // be able to edit items and save changes in the database
          }

          var deleteButton = document.getElementById('delete');
          deleteButton.onclick = function() {
            alert('Are you sure you want to delete this case?');
            // be able to delete a case from the database
            // redirect to the homepage
          }
        });
      })
    }

  };

})();
<commit_msg>trying to fill boxes and get delete button working<commit_after>/* eslint-disable */
window.CaseController = (() => {
  return {
    init: () => {
      var token = window.sessionStorage.getItem('userInfo-token');
      $.ajax({
        type: 'GET',
        url: 'http://localhost:3000/cases/3',
        headers: {
          'x-access-token': token,
        },
      }).done((data) => {
        $.getScript('js/caseFieldFunctionality.js', () => {
          caseUI.fields['drNum']['input'].val(data.drNumber);
          caseUI.fields['masterDrNum']['input'].val(data.masterDrNumber);
          caseUI.fields['division']['input'].val(data.division);
          caseUI.fields['bureau']['input'].val(data.bureau);
          caseUI.fields['notes']['input'].val(data.notes);
          moment.tz.add('America/Los_Angeles|PST PDT|80 70|0101|1Lzm0 1zb0 Op0');
          caseUI.fields['dateOccured']['input'].val(moment(data.dateOccured).tz('America/Los_Angeles').format('YYYY-MM-DD'));
          caseUI.fields['dateReported']['input'].val(moment(data.dateReported).tz('America/Los_Angeles').format('YYYY-MM-DD'));
          caseUI.fields['reportingDistrict']['input'].val(data.reportingDistrict);
          caseUI.fields['caseStatus']['input'].val(data.caseStatus);
          caseUI.fields['caseStatusDate']['input'].val(moment(data.caseStatusDate).tz('America/Los_Angeles').format('YYYY-MM-DD'));
          caseUI.fields['solvabilityFactor']['input'].val(data.solvabilityFactor);
          console.log(Object.values(data.weaponUsed));
          console.log(Object.values(data.motive));

          const caseInfo = JSON.parse(data)[0];
          const weaponArray = ['handgun', 'rifle', 'blunt force', 'bodily force', 'knife', 'unknown'];
          const motiveArray = ['robbery', 'burglary', 'gang', 'narcotics', 'domestic violence', 'dispute', 'accidental', 'selfDefense', 'unknown'];

          function indexOfData(index, dataInIndex) {
            return caseInfo[index].toLowerCase().indexOf(dataInIndex);
          }

          for (let i = 0; i < weaponArray.length; i += 1) {
            caseUI.fields['weapon']['inputs'][i].prop('checked', indexOfData('weaponUsed', weaponArray[i]) > -1);
          }

          for (let i = 0; i < motiveArray.length; i += 1) {
            caseUI.fields['motive']['inputs'][i].prop('checked', indexOfData('motive', motiveArray[i]) > -1);
          }
          // var weapons = {
          //   handgun: caseUI.fields['weapon']['inputs']['weaponInput_handgun'],
          //   rifle: caseUI.fields['weapon']['inputs']['weaponInput_rifle'],
          //   blunt_force: caseUI.fields['weapon']['inputs']['weaponInput_bluntForce'],
          //   bodily_force: caseUI.fields['weapon']['inputs']['weaponInput_bodilyForce'],
          //   knife: caseUI.fields['weapon']['inputs']['weaponInput_knife'],
          //   unknown: caseUI.fields['weapon']['inputs']['weaponInput_unknown']
          // }
          //
          // var motive = {
          //   robbery: caseUI.fields['motive']['inputs']['motiveInput_robbery'],
          //   burglary: caseUI.fields['motive']['inputs']['motiveInput_burglary'],
          //   gang: caseUI.fields['motive']['inputs']['motiveInput_gang'],
          //   narcotics: caseUI.fields['motive']['inputs']['motiveInput_narcotics'],
          //   domestic_violence: caseUI.fields['motive']['inputs']['motiveInput_domesticViolence'],
          //   dispute: caseUI.fields['motive']['inputs']['motiveInput_dispute'],
          //   accidental: caseUI.fields['motive']['inputs']['motiveInput_accidental'],
          //   self_defense: caseUI.fields['motive']['inputs']['motiveInput_selfDefense'],
          //   unknown: caseUI.fields['motive']['inputs']['motiveInput_unknown']
          // }

          caseUI.fields['streetNumber']['input'].val(data.address.streetNumber);
          caseUI.fields['streetName']['input'].val(data.address.streetName);
          caseUI.fields['city']['input'].val(data.address.city);
          caseUI.fields['zipCode']['input'].val(data.address.zipCode);

          // if there is more than one victim
          caseUI.fields['victFirstName']['input'].val(data.victim.victName.first);
          caseUI.fields['victMiddleName']['input'].val(data.victim.victName.middle);
          caseUI.fields['victLastName']['input'].val(data.victim.victName.last);
          caseUI.fields['victSex']['input'].val(data.victim.victSex);
          caseUI.fields['victDesc']['input'].val(data.victim.victDesc);
          caseUI.fields['victAge']['input'].val(data.victim.victAge);
          caseUI.fields['victId']['input'].val(data.victim._id);

          // if there is more than one suspect
          caseUI.fields['suspFirstName']['input'].val(data.suspects[0].suspName.first);
          caseUI.fields['suspMiddleName']['input'].val(data.suspects[0].suspName.middle);
          caseUI.fields['suspLastName']['input'].val(data.suspects[0].suspName.last);
          caseUI.fields['suspSex']['input'].val(data.suspects[0].suspSex);
          caseUI.fields['suspSupervisedReleaseStatus']['input'].val(data.suspects[0].supervisedReleaseStatus);
          caseUI.fields['suspDesc']['input'].val(data.suspects[0].suspDesc);
          caseUI.fields['suspAge']['input'].val(data.suspects[0].suspAge);
          // not fully working
          caseUI.fields['juvenileTriedAsAdult']['input'].val(data.suspects[0].juvenileTriedAsAdult);
          caseUI.fields['suspId']['input'].val(data.suspects[0]._id);

          $('#drNumInput').prop('readonly', true);
          $('#masterDrNumInput').prop('readonly', true);
          $('#divisionInput').prop('disabled', true);
          $('#bureauInput').prop('disabled', true);
          $('#notesInput').prop('readonly', true);
          $('#dateOccuredInput').prop('readonly', true);
          $('#dateReportedInput').prop('readonly', true);
          $('#reportingDistrictInput').prop('disabled', true);
          $('#caseStatusInput').prop('disabled', true);
          $('#caseStatusDateInput').prop('readonly', true);
          $('#solvabilityFactorInput').prop('disabled', true);

          // weaponsList
          $('#weaponInput_handgun').prop('disabled', true);
          $('#weaponInput_rifle').prop('disabled', true);
          $('#weaponInput_bluntForce').prop('disabled', true);
          $('#weaponInput_bodilyForce').prop('disabled', true);
          $('#weaponInput_knife').prop('disabled', true);
          $('#weaponInput_unknown').prop('disabled', true);

          // motivesList
          $('#motiveInput_robbery').prop('disabled', true);
          $('#motiveInput_burglary').prop('disabled', true);
          $('#motiveInput_gang').prop('disabled', true);
          $('#motiveInput_narcotics').prop('disabled', true);
          $('#motiveInput_domesticViolence').prop('disabled', true);
          $('#motiveInput_dispute').prop('disabled', true);
          $('#motiveInput_accidental').prop('disabled', true);
          $('#motiveInput_selfDefense').prop('disabled', true);
          $('#motiveInput_unknown').prop('disabled', true);

          // address
          $('#streetNumberInput').prop('readonly', true);
          $('#streetNameInput').prop('readonly', true);
          $('#cityInput').prop('readonly', true);
          $('#zipCodeInput').prop('readonly', true);

          // victimInformation
          $('#victFirstNameInput').prop('readonly', true);
          $('#victMiddleNameInput').prop('readonly', true);
          $('#victLastNameInput').prop('readonly', true);
          $('#victSexInput').prop('disabled', true);
          $('#victDescInput').prop('readonly', true);
          $('#victAgeInput').prop('readonly', true);
          $('#victIdInput').prop('disabled', true);

          // suspectInformation
          $('#suspFirstNameInput').prop('readonly', true);
          $('#suspMiddleNameInput').prop('readonly', true);
          $('#suspLastNameInput').prop('readonly', true);
          $('#suspSexInput').prop('disabled', true);
          $('#suspSupervisedReleaseStatusInput').prop('disabled', true);
          $('#suspDescInput').prop('readonly', true);
          $('#suspAgeInput').prop('readonly', true);
          $('#juvenileTriedAsAdultInput').prop('disabled', true);
          $('#suspIdInput').prop('disabled', true);

          var save = document.getElementById('button-save-page');
          $(save).prop('disabled', true);

          var edit = document.getElementById('edit');
          edit.onclick = function() {
            $('#drNumInput').removeAttr('readonly');
            $('#masterDrNumInput').removeAttr('readonly');
            $('#divisionInput').removeAttr('disabled');
            $('#bureauInput').removeAttr('disabled');
            $('#notesInput').removeAttr('readonly');
            $('#dateOccuredInput').removeAttr('readonly');
            $('#dateReportedInput').removeAttr('readonly');
            $('#reportingDistrictInput').removeAttr('disabled');
            $('#caseStatusInput').removeAttr('disabled');
            $('#caseStatusDateInput').removeAttr('readonly');
            $('#solvabilityFactorInput').removeAttr('disabled');

            $('#weaponInput_handgun').removeAttr('disabled');
            $('#weaponInput_rifle').removeAttr('disabled');
            $('#weaponInput_bluntForce').removeAttr('disabled');
            $('#weaponInput_bodilyForce').removeAttr('disabled');
            $('#weaponInput_knife').removeAttr('disabled');
            $('#weaponInput_unknown').removeAttr('disabled');

            $('#motiveInput_robbery').removeAttr('disabled');
            $('#motiveInput_burglary').removeAttr('disabled');
            $('#motiveInput_gang').removeAttr('disabled');
            $('#motiveInput_narcotics').removeAttr('disabled');
            $('#motiveInput_domesticViolence').removeAttr('disabled');
            $('#motiveInput_dispute').removeAttr('disabled');
            $('#motiveInput_accidental').removeAttr('disabled');
            $('#motiveInput_selfDefense').removeAttr('disabled');
            $('#motiveInput_unknown').removeAttr('disabled');

            $('#streetNumberInput').removeAttr('readonly');
            $('#streetNameInput').removeAttr('readonly');
            $('#cityInput').removeAttr('readonly');
            $('#zipCodeInput').removeAttr('readonly');

            $('#victFirstNameInput').removeAttr('readonly');
            $('#victMiddleNameInput').removeAttr('readonly');
            $('#victLastNameInput').removeAttr('readonly');
            $('#victSexInput').removeAttr('disabled');
            $('#victDescInput').removeAttr('readonly');
            $('#victAgeInput').removeAttr('readonly');
            $('#victIdInput').removeAttr('disabled');

            $('#suspFirstNameInput').removeAttr('readonly');
            $('#suspMiddleNameInput').removeAttr('readonly');
            $('#suspLastNameInput').removeAttr('readonly');
            $('#suspSexInput').removeAttr('disabled');
            $('#suspSupervisedReleaseStatusInput').removeAttr('disabled');
            $('#suspDescInput').removeAttr('readonly');
            $('#suspAgeInput').removeAttr('readonly');
            $('#juvenileTriedAsAdultInput').removeAttr('disabled');
            $('#suspIdInput').removeAttr('disabled');

            $(save).removeAttr('disabled');
            // $(save).onclick(function() {
            //   $.post('http://localhost:3000/cases/3')
            // })
            // be able to edit items and save changes in the database
          }

          var deleteButton = document.getElementById('delete');
          deleteButton.onclick = function() {
            alert('Are you sure you want to delete this case?');
            // be able to delete a case from the database
            // redirect to the homepage

            // getting a 400 Bad Request
            // $.ajax({
            //   url: 'http://localhost:3000/cases/3',
            //   type: 'DELETE',
            //   headers: {
            //     'x-access-token': token,
            //   },
            //   success: function(result) {
            //     window.location.replace("http://localhost:3000/home");
            //   }
            // });
          }
        });
      })
    }

  };

})();
<|endoftext|>


<commit_before>const path = require('path');
const json = require(path.resolve('./package.json'));
const os = require('os');
const exec = require('child_process').exec;

const spec = {
    'platform': {
        '1': 'win32',
        '2': 'darwin',
        '3': 'linux'
    },
    'arch': {
        '1': 'ia32',
        '2': 'x64',
        '3': 'armv7l',
        '4': 'arm64',
        '5': 'amd64'
    }
};

const linuxConfig = `{
    "dest": "linux_installer",
    "categories": [
        "Utility"
    ],
    "lintianOverrides": [
        "changelog-file-missing-in-native-package"
    ]
}`;

switch (process.env.NODE_OS) {
    case "mac":
        exec("mkdir mac_installer && electron-installer-dmg ./mac_packager/" + json.name + "-" + spec['platform']['2'] + "-" + spec['arch']['2'] + "/" + json.name + ".app " + json.name + " --out=mac_installer --overwrite && rm -rf mac_packager");
        break;
    case "linux":
        exec("electron-installer-debian --src ./linux_packager/" + json.name + "-" + spec['platform']['3'] + "-" + spec['arch']['2'] + "/ --arch " + spec['arch']['5'] + " --dest linux_installer --config " + linuxConfig);
        break;
    case "win":
        const electronInstaller = require('electron-winstaller');

        var settings = {
            appDirectory: path.join(path.join((path.join('./'), 'win_packager'), json.name + "-" + spec['platform']['1'] + "-" + spec['arch']['1'] + '/')),
            outputDirectory: path.join(path.join('./'), 'win_installer'),
            authors: '',
            exe: json.name + '.exe'
        };

        console.log('Creating windows installer');

        resultPromise = electronInstaller.createWindowsInstaller(settings);

        resultPromise.then(() => {
            exec("del /s /q win_packager && rmdir /s /q win_packager");
            console.log("The installers of your application were succesfully created !");
        }, (e) => {
            console.log('Error : ' + e.message);
        });
        break;
    default:
        throw new Error("NODE_OS undefined");
}<commit_msg>windows doesnt like '-' in app name<commit_after>const path = require('path');
const json = require(path.resolve('./package.json'));
const os = require('os');
const exec = require('child_process').exec;

const spec = {
    'platform': {
        '1': 'win32',
        '2': 'darwin',
        '3': 'linux'
    },
    'arch': {
        '1': 'ia32',
        '2': 'x64',
        '3': 'armv7l',
        '4': 'arm64',
        '5': 'amd64'
    }
};

const linuxConfig = `{
    "dest": "linux_installer",
    "categories": [
        "Utility"
    ],
    "lintianOverrides": [
        "changelog-file-missing-in-native-package"
    ]
}`;

switch (process.env.NODE_OS) {
    case "mac":
        exec("mkdir mac_installer && electron-installer-dmg ./mac_packager/" + json.name + "-" + spec['platform']['2'] + "-" + spec['arch']['2'] + "/" + json.name + ".app " + json.name + " --out=mac_installer --overwrite && rm -rf mac_packager");
        break;
    case "linux":
        exec("electron-installer-debian --src ./linux_packager/" + json.name + "-" + spec['platform']['3'] + "-" + spec['arch']['2'] + "/ --arch " + spec['arch']['5'] + " --dest linux_installer --config " + linuxConfig);
        break;
    case "win":
        const electronInstaller = require('electron-winstaller');

        var settings = {
            appDirectory: path.join(path.join((path.join('./'), 'win_packager'), json.name + "-" + spec['platform']['1'] + "-" + spec['arch']['1'] + '/')),
            outputDirectory: path.join(path.join('./'), 'win_installer'),
            authors: '',
            exe: json.name + '.exe',
            name: json.name.replace(/-/g, "_")
        };

        console.log('Creating windows installer');

        resultPromise = electronInstaller.createWindowsInstaller(settings);

        resultPromise.then(() => {
            exec("del /s /q win_packager && rmdir /s /q win_packager");
            console.log("The installers of your application were succesfully created !");
        }, (e) => {
            console.log('Error : ' + e.message);
        });
        break;
    default:
        throw new Error("NODE_OS undefined");
}<|endoftext|>


<commit_before>/* jslint asi: true */
/* globals _, print, JCU */

// Only show breadcrumbs if enabled and on pages that aren't the homepage
JCU.data.site_index_id = '%globals_site_index_id%'
JCU.data.site_breadcrumbs = '%globals_site_metadata_jcu.features.breadcrumbs%'
JCU.data.frontend_id = '%frontend_asset_assetid%'  // This should be corrected for index pages
JCU.data.frontend_breadcrumbs = '%frontend_asset_metadata_jcu.features.breadcrumbs%'

if (JCU.data.frontend_breadcrumbs === 'true' ||
    JCU.data.frontend_breadcrumbs === 'inherit' && JCU.data.site_breadcrumbs) {
  if (JCU.data.site_index_id !== JCU.data.frontend_id) {
    var lineage = JSON.parse("%frontend_asset_linking_lineage^json_encode%")
    if (lineage) {
      print(
        '
' +
          '')
      _.each(lineage, function(id) {
        if (id !== JCU.data.frontend_id) {
          print('%globals_asset_short_name:' + id + '%')
        } else {
          print('%globals_asset_short_name:' + id + '%')
        }
      })
      print(
          '' +
        '
')
    }
  }
}
<commit_msg>Revamp breadcrumb logic so it actually works<commit_after>/* jslint asi: true */
/* globals print, JCU */

// Relative path to current Site asset (eg empty if at index page)
JCU.data.url_site_path = '%frontend_asset_url_site_path%'
JCU.data.is_homepage = !JCU.data.url_site_path

JCU.data.frontend_id = '%frontend_asset_assetid%'
JCU.data.frontend_breadcrumbs = '%frontend_asset_metadata_jcu.features.breadcrumbs%'
JCU.data.homepage_breadcrumbs = '%globals_site_index_id^as_asset:asset_metadata_jcu.features.breadcrumbs%'
JCU.data.site_breadcrumbs = '%globals_site_metadata_jcu.features.breadcrumbs%'

function JCU_ssjs_debug() {
  JCU.debug = true
}

// Only show breadcrumbs if enabled
  // Special handling for Matrix's odd "frontend" asset keyword representing
  // the Site and not the homepage (index)
if (JCU.data.is_homepage) {
  if (JCU.data.homepage_breadcrumbs === 'true' || JCU.data.homepage_breadcrumbs === 'inherit' && JCU.data.site_breadcrumbs !== 'false' ) {
    JCU.data.breadcrumbs_enabled = true
    if (JCU.debug) {
      print('')
    }
  }
} else if (JCU.data.frontend_breadcrumbs === 'true' || JCU.data.frontend_breadcrumbs === 'inherit' && JCU.data.site_breadcrumbs !== 'false') {
    JCU.data.breadcrumbs_enabled = true
    if (JCU.debug) {
      print('')
    }
}

if (JCU.data.breadcrumbs_enabled) {
  var lineage = JSON.parse("%frontend_asset_linking_lineage^json_encode%")
  if (lineage) {
    print(
      '
' +
      '')
    lineage.forEach(function(id) {
      if (id !== JCU.data.frontend_id) {
        print('%globals_asset_short_name:' + id + '%')
      } else {
        print('%globals_asset_short_name:' + id + '%')
      }
    })
    print(
      '' +
      '
')
  }
}
<|endoftext|>


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

'use strict';

module.exports = {
  opts: {
    readme: './README.md',
    package: './package.json',
    template: './node_modules/jsdoc-fresh',
    recurse: true,
    verbose: true,
    destination: './docs/'
  },
  plugins: [
    'plugins/markdown',
    'jsdoc-region-tag'
  ],
  source: {
    excludePattern: '(^|\\/|\\\\)[._]',
    include: [
      'build/src'
    ],
    includePattern: '\\.js$'
  },
  templates: {
    copyright: 'Copyright 2019 Google, LLC.',
    includeDate: false,
    sourceFiles: false,
    systemName: '@google-cloud/redis',
    theme: 'lumen',
    default: {
      "outputSourceFiles": false
    }
  },
  markdown: {
    idInHeadings: true
  }
};
<commit_msg>chore: correct .jsdoc.js protos and double quotes (#282)<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

'use strict';

module.exports = {
  opts: {
    readme: './README.md',
    package: './package.json',
    template: './node_modules/jsdoc-fresh',
    recurse: true,
    verbose: true,
    destination: './docs/'
  },
  plugins: [
    'plugins/markdown',
    'jsdoc-region-tag'
  ],
  source: {
    excludePattern: '(^|\\/|\\\\)[._]',
    include: [
      'build/src',
      'protos'
    ],
    includePattern: '\\.js$'
  },
  templates: {
    copyright: 'Copyright 2019 Google, LLC.',
    includeDate: false,
    sourceFiles: false,
    systemName: '@google-cloud/redis',
    theme: 'lumen',
    default: {
      outputSourceFiles: false
    }
  },
  markdown: {
    idInHeadings: true
  }
};
<|endoftext|>


<commit_before>/* ==========================================================================
   exercism.io Theme custom application scripts
   ========================================================================== */

$(document).ready(function() {

  //Carousel
  $(".carousel").carousel();

  //Expand Code column
 /* $("#expand-code").on("click", function(){
    var $contentFirst = $("#content-first"),
		$sidebarSecond = $("#sidebar-second");
	if($contentFirst.hasClass("col-md-8")){
      $contentFirst.removeClass("col-md-8").addClass("col-md-12");
	  $sidebarSecond.removeClass("col-md-4").addClass("col-md-12");
	}else{
	  $contentFirst.removeClass("col-md-12").addClass("col-md-8");
	  $sidebarSecond.removeClass("col-md-12").addClass("col-md-4");
	}
  });*/

  /*****Add js for middle div expend ****/
   $("#expand-code").on("click", function(){
    var $contentFirst = $("#content-first"),
		$sidebarSecond = $("#sidebar-second");
	if($contentFirst.hasClass("col-md-8")){
      $contentFirst.removeClass("col-md-8").addClass("col-md-12");
	  $sidebarSecond.removeClass("col-md-4").addClass("col-md-12");
	}
	else if($contentFirst.hasClass("col-md-7"))
	{
		$contentFirst.removeClass("col-md-7").removeClass("code_midd").addClass("col-md-12");
	  $sidebarSecond.removeClass("col-md-5").removeClass("my_code_right").addClass("col-md-12");
	}
	else{
	  $contentFirst.removeClass("col-md-12").addClass("col-md-7").addClass("code_midd");
	  $sidebarSecond.removeClass("col-md-12").addClass("col-md-5").addClass("my_code_right");
	}
  });

  /*****End js for middle div expend ****/

  /* Navigation tree */
  $("label.tree-toggler").click(function () {
    $(this).parent().children("ul.tree").slideToggle(300);
	var $parent = $(this).parents(".list-menu");
	if($parent.hasClass("open")){
	  $parent.removeClass("open");
	}else{
	  $parent.addClass("open");
	}
  });

  /* Toggle Add Team Form */
  $(".toggle-add-team").on("click", function(){
    $(this).parents("li").find(".form-add-team").slideToggle(300);
  });

  /* Toggle Section Content */
  $(".section-toggle .toggle").on("click", function(){
    $(this).parents(".section-toggle").find(".toggle-content").slideToggle(300);
    var operator = $(this).text() == "-" ? "+" : "-";
    $(this).text(operator);
  });

  /* Toggle Account Settings box */
  $(".toggle-account-settings").click(function () {
	var $page = $("#account-settings");
	$page.animate({width: 'toggle'});
  });

  /************More Results*********/

   $("#more_res").click(function () {
		$( "#view_sol ul" ).append( '

anagram objective-c

JonanMoses (3) About 7 hours ago

3 Iterations

24 Nits

' );
  });

  /************ End More results ********/

  });

 $(".toggle-account-settings1").click(function () {
	var $page = $("#account-settings1");
	$page.animate({width: 'toggle'});
  });

$(document).ready(function(){
	 $("#add-nitpick").hide();
  $("#show1").click(function(){
    $("#add-nitpick").toggle();
  });
});

$(document).ready(function(){
  $("#xclosee").click(function(){
    $("#Re-Open").show();
	$("#xclosee").hide();
	return false;
  });
  $("#Re-Open").click(function(){
    $("#xclosee").show();
	 $("#Re-Open").hide();
	return false;
  });
});<commit_msg>Clean up v1.0 javascript<commit_after>$(document).ready(function() {

  $(".carousel").carousel();

  $("#expand-code").on("click", function(){
    var $contentFirst = $("#content-first"),
    $sidebarSecond = $("#sidebar-second");
    if($contentFirst.hasClass("col-md-8")){
      $contentFirst.removeClass("col-md-8").addClass("col-md-12");
      $sidebarSecond.removeClass("col-md-4").addClass("col-md-12");
    }
    else if($contentFirst.hasClass("col-md-7"))
    {
      $contentFirst.removeClass("col-md-7").removeClass("code_midd").addClass("col-md-12");
      $sidebarSecond.removeClass("col-md-5").removeClass("my_code_right").addClass("col-md-12");
    }
    else{
      $contentFirst.removeClass("col-md-12").addClass("col-md-7").addClass("code_midd");
      $sidebarSecond.removeClass("col-md-12").addClass("col-md-5").addClass("my_code_right");
    }
  });

  $("label.tree-toggler").click(function () {
    $(this).parent().children("ul.tree").slideToggle(300);
    var $parent = $(this).parents(".list-menu");
    if($parent.hasClass("open")){
      $parent.removeClass("open");
    }else{
      $parent.addClass("open");
    }
  });

  $(".toggle-add-team").on("click", function(){
    $(this).parents("li").find(".form-add-team").slideToggle(300);
  });

  $(".section-toggle .toggle").on("click", function(){
    $(this).parents(".section-toggle").find(".toggle-content").slideToggle(300);
    var operator = $(this).text() == "-" ? "+" : "-";
    $(this).text(operator);
  });
});
<|endoftext|>


<commit_before>var app = angular.module('App', [
  'templates', // Used by angular-rails-templates
  'ngRoute',
  'ngAnimate',
  'ng-rails-csrf',
  'flashular',

  // Services
  'AuthSvc',
  'RouteUtils',
  'Post',
  'User',
  'UsersCtrlInitSvc',

  // Controllers
  'AppCtrl',
  'HomeCtrl',
  'PostsCtrl',
  'UsersCtrl',

  // Directives
  'AuthenticationLinks',
  'FormErrors',
  'PleaseWait',
  'DataTable',
  'DateTimePicker',
  'Selectize',

  // Filters
  'StringFilters',

  // Modules
  'ResourceUtils',
  'QueryBuilder'
]);

app.config([
  'QBEditorProvider',
  function (QBEditorProvider) {
    QBEditorProvider.addEditorFactory({
      createEditorHtml: function (column, op) {
        if (column === 'date') {
          var editorHtml = '';
          var opArity = (op === 'range') ? 2 : 1;

          for (var i = 0; i < opArity; ++i) {
            editorHtml +=
              '<date-time-picker class="filter-value"'
                + ' ng-model="model.values[' + i + ']"'
                + ' options="{ format: \'LL\' }">' +
              '</date-time-picker>'
          }

          return editorHtml;
        }
      }
    });
  }]);
<commit_msg>fixed small bug in Angular admin/app.js<commit_after>var app = angular.module('App', [
  'templates', // Used by angular-rails-templates
  'ngRoute',
  'ngAnimate',
  'ng-rails-csrf',
  'flashular',

  // Services
  'AuthSvc',
  'RouteUtils',
  'Post',
  'User',
  'UsersCtrlInitSvc',

  // Controllers
  'AppCtrl',
  'HomeCtrl',
  'PostsCtrl',
  'UsersCtrl',

  // Directives
  'AuthenticationLinks',
  'FormErrors',
  'PleaseWait',
  'DataTable',
  'DateTimePicker',
  'Selectize',

  // Filters
  'StringFilters',

  // Modules
  'ResourceUtils',
  'QueryBuilder'
]);

app.config([
  'QBEditorProvider',
  function (QBEditorProvider) {
    QBEditorProvider.addEditorFactory({
      createEditorHtml: function (column, op) {
        if (column.type === 'date') {
          var editorHtml = '';
          var opArity = (op === 'range') ? 2 : 1;

          for (var i = 0; i < opArity; ++i) {
            editorHtml +=
              '<date-time-picker class="filter-value"'
                + ' ng-model="model.values[' + i + ']"'
                + ' options="{ format: \'LL\' }">' +
              '</date-time-picker>'
          }

          return editorHtml;
        }
      }
    });
  }]);
<|endoftext|>


<commit_before>var I18n = I18n || {};
I18n.translations = {"en":{"js":{"comment":{"flag_ask":"Flag this comment?","flag_process":"Flagging comment for deletion...","flag_notice":"Comment flagged for deletion","quote_error":"Error quoting comment","delete_ask":"Are you sure you want to delete this comment?","delete_error":"Error deleting comment: "},"denied":"Access Denied","dmail":{"fetch_prev_msg":"Fetching previous messages...","prev_msg_loaded":"Previous messages loaded"},"error":"Error: ","no_translation":"No translation: ","noone":"no one","vote":{"remove":"Remove vote","good":"Good","great":"Great","fav":"Favorite","saved":"Vote saved","voting":"Voting..."}}}};<commit_msg>Also forgot to export the translations file<commit_after>var I18n = I18n || {};
I18n.translations = {"en":{"js":{"comment":{"flag_ask":"Flag this comment?","flag_process":"Flagging comment for deletion...","flag_notice":"Comment flagged for deletion","quote_error":"Error quoting comment","delete_ask":"Are you sure you want to delete this comment?","delete_error":"Error deleting comment: "},"denied":"Access Denied","dmail":{"fetch_prev_msg":"Fetching previous messages...","prev_msg_loaded":"Previous messages loaded"},"error":"Error: ","forum":{"mark_as_read":"Marked all topics as read","quote_error":"Error quoting forum post"},"no_translation":"No translation: ","noone":"no one","said":"said:","vote":{"remove":"Remove vote","good":"Good","great":"Great","fav":"Favorite","saved":"Vote saved","voting":"Voting..."}}}};<|endoftext|>


<commit_before>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var OAE = require('oae-util/lib/oae');

var AuthenticationAPI = require('oae-authentication');

//////////////////////////////
// AUTHENTICATION PROVIDERS //
//////////////////////////////

require('./strategies/cas/rest');
require('./strategies/facebook/rest');
require('./strategies/google/rest');
require('./strategies/ldap/rest');
require('./strategies/local/rest');
require('./strategies/oauth/rest');
require('./strategies/shibboleth/rest');
require('./strategies/signed/rest');
require('./strategies/twitter/rest');

/*!
 * Logout from the global admin tenant
 */
OAE.globalAdminRouter.on('post', '/api/auth/logout', AuthenticationAPI.logout);

/*!
 * Logout from a tenant
 */
OAE.tenantRouter.on('post', '/api/auth/logout', AuthenticationAPI.logout);
<commit_msg>add REST documentation<commit_after>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var OAE = require('oae-util/lib/oae');

var AuthenticationAPI = require('oae-authentication');

//////////////////////////////
// AUTHENTICATION PROVIDERS //
//////////////////////////////

require('./strategies/cas/rest');
require('./strategies/facebook/rest');
require('./strategies/google/rest');
require('./strategies/ldap/rest');
require('./strategies/local/rest');
require('./strategies/oauth/rest');
require('./strategies/shibboleth/rest');
require('./strategies/signed/rest');
require('./strategies/twitter/rest');

/**
 * @REST postAuthLogout
 *
 * Log out of OAE
 *
 * @Server      admin,tenant
 * @Method      POST
 * @Path        /auth/logout
 */
OAE.globalAdminRouter.on('post', '/api/auth/logout', AuthenticationAPI.logout);
OAE.tenantRouter.on('post', '/api/auth/logout', AuthenticationAPI.logout);
<|endoftext|>


<commit_before>angular.module('app.services').factory('ActivityModel',
  function (JsModel, groups, $http, follows, iStorage, serverConfig) {
   return JsModel.extend({
      labels: {
        question: 'Question',
        petition: 'Petition',
        'leader-news': 'News',
        'leader-event': 'Event',
        'micro-petition': 'Petition',
        'payment-request': 'Payment',
        'crowdfunding-payment-request': 'Payment'
      },
      icons: {
        question: 'poll',
        petition: 'petition',
        'leader-news': 'discussion',
        'leader-event': 'event',
        'micro-petition': 'post',
        'payment-request': 'fundraiser',
        'crowdfunding-payment-request': 'fundraiser'
      },
      parsers: {
        expire_at: 'date',
        sent_at: 'date',
        owner: function (owner) {
          if (owner && owner.avatar_file_name) {
            owner.avatar_file_path = owner.avatar_file_name;
          }
          return owner;
        }
      },
      isOwn: function () {
        return this.get('owner').type === 'user' && this.get('owner').id === session.user_id;
      },
      isUnanswered: function () {
        return !this.get('answered') && !this.isExpired() && 'leader-news' !== this.get('entity').type;
      },
      isFollowing: function () {
        var owner = this.get('owner');
        return owner.type === 'user' && follows.some(function (following) {
          return following.get('user').id === owner.id && following.isApproved();
        });
      },

      dataType: function(){
        return this.get('entity').type
      },
      prepare: function () {
        if (this.get('entity').group_id) {
          var userGroup = groups.get(this.get('entity').group_id);
          this.set('owner_info_1', userGroup ? userGroup.official_title : null);
        }
      },
      setRead: function () {
        if (this.isUnread()) {
          var that = this
          var aID = this.get('id') // https://github.com/PowerlineApp/powerline-mobile/issues/84#issuecomment-230568369
          var payload = JSON.stringify({activities: [{id: aID, read: true}]})
          var headers = {headers: {'Content-Type': 'application/json'}}
          $http.patch(serverConfig.url + '/api/v2/activities', payload, headers).then(function(){
            that.set('read', true);
          })
        }
      },
      getResponsesToQuorum: function () {
        return this.get('quorum') ? Math.max(this.get('quorum') - this.get('responses_count'), 1) : 1;
      },
      getQuorumCompletedPercent: function () {
        return this.get('quorum') ?
          Math.min(this.get('responses_count') / this.get('quorum') * 100, 100) : 0;
      },
      getLabel: function () {
        return this.labels[this.get('entity').type];
      },
      getIcon: function () {
        return this.icons[this.get('entity').type];
      },

      isUserPetitionType: function(){
        var aType = this.get('entity').type
        return aType == 'micro-petition:long-petition'
      },
      isUserPostType: function(){
        var aType = this.get('entity').type
        return aType == 'micro-petition:quorum'
      },
      isUnread: function(){
        return(!this.get('read'))
      },
      isBoosted: function(){
        return(this.get('publish_status') == 1)
      },
      isExpired: function(){
        return this.get('expire_at') && Date.now() > this.get('expire_at').getTime()
      },
      isInPriorityZone: function() {
        if(this.isUserPetitionType()){
          return(this.isUnread())
        } else if(this.isUserPostType()){
          return(this.isBoosted() && !this.isExpired())
        } else
        	return(false)
      },
      getSortMultiplier: function () {
        if (this.isExpired()) {
          return 0;
        }

        if (this.isInPriorityZone()) {
          return 9;
        }

        return 1;
      },

      getPostID: function(){
        return this.attributes.id;
      },

      saveProfileSetting: function(){

       return $http({
          method: 'POST',
          url: serverConfig.url + '/api/profile/settings',
          data: null
        }).then(function(resp) {
          return resp.data;
        });
      },

      changeSubscribe: function(id){
        $http({
          method: 'POST',
          url: serverConfig.url + '/api/users/self/subscriptions',
          data: {"id": id}
        }).then(function(resp) {
          return resp.data;
        });
      },

      hasLinkPreviewMetadata: function(){
        return !!this.get('metadata');
      }
    });
  })
<commit_msg>#152: adopt new priority zone attribute<commit_after>angular.module('app.services').factory('ActivityModel',
  function (JsModel, groups, $http, follows, iStorage, serverConfig) {
   return JsModel.extend({
      labels: {
        question: 'Question',
        petition: 'Petition',
        'leader-news': 'News',
        'leader-event': 'Event',
        'micro-petition': 'Petition',
        'payment-request': 'Payment',
        'crowdfunding-payment-request': 'Payment'
      },
      icons: {
        question: 'poll',
        petition: 'petition',
        'leader-news': 'discussion',
        'leader-event': 'event',
        'micro-petition': 'post',
        'payment-request': 'fundraiser',
        'crowdfunding-payment-request': 'fundraiser'
      },
      parsers: {
        expire_at: 'date',
        sent_at: 'date',
        owner: function (owner) {
          if (owner && owner.avatar_file_name) {
            owner.avatar_file_path = owner.avatar_file_name;
          }
          return owner;
        }
      },
      isOwn: function () {
        return this.get('owner').type === 'user' && this.get('owner').id === session.user_id;
      },
      isUnanswered: function () {
        return !this.get('answered') && !this.isExpired() && 'leader-news' !== this.get('entity').type;
      },
      isFollowing: function () {
        var owner = this.get('owner');
        return owner.type === 'user' && follows.some(function (following) {
          return following.get('user').id === owner.id && following.isApproved();
        });
      },

      dataType: function(){
        return this.get('entity').type
      },
      prepare: function () {
        if (this.get('entity').group_id) {
          var userGroup = groups.get(this.get('entity').group_id);
          this.set('owner_info_1', userGroup ? userGroup.official_title : null);
        }
      },
      setRead: function () {
        if (this.isUnread()) {
          var that = this
          var aID = this.get('id') // https://github.com/PowerlineApp/powerline-mobile/issues/84#issuecomment-230568369
          var payload = JSON.stringify({activities: [{id: aID, read: true}]})
          var headers = {headers: {'Content-Type': 'application/json'}}
          $http.patch(serverConfig.url + '/api/v2/activities', payload, headers).then(function(){
            that.set('read', true);
          })
        }
      },
      getResponsesToQuorum: function () {
        return this.get('quorum') ? Math.max(this.get('quorum') - this.get('responses_count'), 1) : 1;
      },
      getQuorumCompletedPercent: function () {
        return this.get('quorum') ?
          Math.min(this.get('responses_count') / this.get('quorum') * 100, 100) : 0;
      },
      getLabel: function () {
        return this.labels[this.get('entity').type];
      },
      getIcon: function () {
        return this.icons[this.get('entity').type];
      },

      isUserPetitionType: function(){
        var aType = this.get('entity').type
        return aType == 'micro-petition:long-petition'
      },
      isUserPostType: function(){
        var aType = this.get('entity').type
        return aType == 'micro-petition:quorum'
      },
      isUnread: function(){
        return(!this.get('read'))
      },
      isBoosted: function(){
        return(this.get('publish_status') == 1)
      },
      isExpired: function(){
        return this.get('expire_at') && Date.now() > this.get('expire_at').getTime()
      },
      isInPriorityZone: function() {
        return (this.get('zone') == 'prioritized')
      },
      getSortMultiplier: function () {
        if (this.isExpired()) {
          return 0;
        }

        if (this.isInPriorityZone()) {
          return 9;
        }

        return 1;
      },

      getPostID: function(){
        return this.attributes.id;
      },

      saveProfileSetting: function(){

       return $http({
          method: 'POST',
          url: serverConfig.url + '/api/profile/settings',
          data: null
        }).then(function(resp) {
          return resp.data;
        });
      },

      changeSubscribe: function(id){
        $http({
          method: 'POST',
          url: serverConfig.url + '/api/users/self/subscriptions',
          data: {"id": id}
        }).then(function(resp) {
          return resp.data;
        });
      },

      hasLinkPreviewMetadata: function(){
        return !!this.get('metadata');
      }
    });
  })
<|endoftext|>


<commit_before>// View instantiates
// Stubs model
// Iterates over inputs
// Grabs values
// Generates widgets
// Binds change events from widgets to view
// View updates model on change
// Before view submits.
var Islay = {};

// Understands required
Islay.FormModel = Backbone.Model.extend({

});

Islay.Form = Backbone.View.extend({
  events: {submit: 'submit'},

  initialize: function() {
    _.bindAll(this, 'submit', 'tabClick');

    this.model = new Islay.FormModel();

    var inputs = this.$el.find('.field')
    this.widgets = _.reduce(inputs, this.initializeWidgets, {}, this);
    this.initiaizeTabs();
  },

  initiaizeTabs: function() {
    var tabs = this.$el.find('.tab');
    var list = $H('ul.tabset');
    _.each(tabs, function(t) {
      var tab = $(t);
      var node = $H('li', tab.find('legend').remove().text());
      if (!this.currentTab) {
        this.currentTab = node;
        node.addClass('selected');
      }
      list.append(node);
    }, this);

    list.click(this.tabClick);
    tabs.first().before(list);
  },

  tabClick: function(e) {
    var target = $(e.target);
    if (target.is('li')) {
      if (this.currentTab) {this.currentTab.removeClass('selected');}
      this.currentTab = target;
      this.currentTab.addClass('selected');
    }
  },

  initializeWidgets: function(obj, el) {
    var $el = $(el);
    var widget = null;

    var match = $el.attr('class').match(/^field ([\w\d\-_]+) .+$/);

    if (match) {
      switch(match[1]) {
        case 'select':
          widget = 'Select';
        break;
        case 'boolean':
          widget = 'Boolean';
        break;
        case 'radio_buttons':
          widget = 'Segmented';
        break;
        case 'check_boxes':
          widget = 'Checkboxes';
        break;
      }

      if (widget) {
        var instance = new Islay.Widgets[widget]({el: el});
        // obj[$input.attr('id')] = instance;
        instance.render();

        // TODO: Bind widgets to model
      }
    }

    return obj;
  },

  submit: function() {

  }
});

Islay.Widgets = Islay.Widgets || {};

Islay.Widgets.Base = Backbone.View.extend({
  events: {'click': '_click', keyup: 'keyup'},
  widgetClass: 'default',
  inputsSelector: ':input[type!=hidden]',
  removeSelector: ':input[class!=islay]',

  initialize: function() {
    this.fields = {};
    this.widget = $H('div.widget.' + this.widgetClass);
    this.inputs = this.$el.find(this.inputsSelector);
    this.$el.append(this.widget);
    this.initialValue = this.getInitialValue();
    this.initFields();
    this.$el.find(this.removeSelector).remove();
  },

  update: function(value, field) {
    if (field) {
      this.trigger('update', field, value);
      this.fields[field].val(value);
    }
    else {
      this.trigger('update', this.fieldName, value);
      this.fields[this.fieldName].val(value);
    }
  },

  addField: function(field, value) {
    var node = $H('input.islay', {type: 'hidden', value: value, name: field});
    this.fields[field] = node;
    this.$el.append(node);
    return node;
  },

  // Overridable
  initFields: function() {
    var field = this.$el.find(':input[type!=hidden]'),
        name = field.attr('name');

    this.addField(name, this.initialValue);
    this.fieldName = name;
  },

  // Overridable
  getInitialValue: function() {
    return this.inputs.val();
  },

  currentValue: function(field) {
    if (field) {
      return this.fields[field].val();
    }
    else {
      return this.fields[this.fieldName].val();
    }
  },

  render: function() {
    throw "Unimplemented";
  },

  click: function() {
    throw "Unimplemented";
  },

  keyup: function() {
    throw "Unimplemented";
  },

  eachLabelAndInput: function(fn) {
    _.each(this.inputs, function(input) {
      var i = $(input);
      fn(i, i.attr('name'), i.attr('value'), i.parent('label').text());
    }, this);
  },

  _click: function(e) {
    var target = $(e.target);
    this.click(e, target);
  }
});

/* -------------------------------------------------------------------------- */
/* SIMPLE SELECT
/* -------------------------------------------------------------------------- */
Islay.Widgets.Select = Islay.Widgets.Base.extend({
  widgetClass: 'select',
  removeSelector: 'select',

  open: function() {
    this.isOpen = true;
    this.widget.addClass('open');
    this.list.show();
  },

  close: function() {
    this.isOpen = false;
    this.widget.removeClass('open');
    this.list.hide();
  },

  click: function(e, target) {
    if (target.is('.frame, .button, .display, span')) {
      if (this.isOpen) {
        this.close();
      }
      else {
        this.open();
      }
    }
    else if (target.is('li')) {
      this.display.text(target.text());
      this.update(target.attr('data-value'));
      this.close();
    }
  },

  render: function() {
    this.display = $H('div.display');
    this.button = $H('div.button', $H('span', '>'));
    var frame = $H('div.frame', [this.display, this.button]);
    this.list = $H('ul.list');

    this.widget.append(frame, this.list);

    var currentValue = this.currentValue();
    _.each(this.inputs.find('option'), function(opt) {
      opt = $(opt);
      var value = opt.attr('value'),
          text  = opt.text();

      if (value == currentValue) {this.display.text(text);}
      if (value != '') {this.list.append($H('li', {'data-value': value}, text));}
    }, this);

    return this;
  }
});

/* -------------------------------------------------------------------------- */
/* BOOLEAN SWITCH
/* -------------------------------------------------------------------------- */
Islay.Widgets.Boolean = Islay.Widgets.Base.extend({
  widgetClass: 'boolean',

  click: function(e, target) {
    if (target.is('li, span')) {
      if (this.currentValue() == 1) {
        this.update(0);
        this.optionOn.removeClass('selected');
        this.optionOff.addClass('selected');
      }
      else {
        this.update(1);
        this.optionOff.removeClass('selected');
        this.optionOn.addClass('selected');
      }
    }
  },

  getInitialValue: function() {
    return this.$el.find(':input[type!=hidden]').is(':checked') ? 1 : 0;
  },

  render: function() {
    this.optionOff = $H('li.button.optionOff', $H('span', 'x'));
    this.optionOn = $H('li.button.optionOn', $H('span', 't'));
    var frame = $H('ul.frame', [this.optionOff, this.optionOn]);
    this.widget.append(frame);

    if (this.initialValue == 1) {
      this.optionOn.addClass('selected');
    }
    else {
      this.optionOff.addClass('selected');
    }

    return this;
  }
});

/* -------------------------------------------------------------------------- */
/* SEGMENTED CONTROL
/* -------------------------------------------------------------------------- */
Islay.Widgets.Segmented = Islay.Widgets.Base.extend({
  widgetClass: 'segmented',
  removeSelector: 'label.radio',

  click: function(e, target) {
    if (target.is('li')) {
      this.highlight(target);
    }
    else if (target.is('span')) {
      this.highlight(target.parent('li'));
    }
  },

  highlight: function(el) {
    this.update(el.attr('data-value'));
    if (this.currentNode) {this.currentNode.removeClass('selected');}
    this.currentNode = el;
    this.currentNode.addClass('selected');
  },

  render: function() {
    var frame = $H('ul.frame');
    var currentValue = this.inputs.filter(':checked').val();
    _.each(this.inputs, function(input) {
      var input = $(input),
          value = input.val();

      var node = $H('li.button', {'data-value': value}, $H('span', input.parent().text()));
      if (value == currentValue) {
        node.addClass('selected');
        this.currentNode = node;
      }
      frame.append(node);
    }, this);

    this.widget.append(frame);

    return this;
  }
});

/* -------------------------------------------------------------------------- */
/* CHECKBOXES
/* -------------------------------------------------------------------------- */
Islay.Widgets.Checkboxes = Islay.Widgets.Base.extend({
  widgetClass: 'checkboxes',
  removeSelector: 'label.checkbox',

  click: function(e, target) {
    if (target.is('li')) {
      this.highlight(target);
    }
    else if (target.is('span')) {
      this.highlight(target.parent('li'));
    }
  },

  initFields: function() {
    _.each(this.inputs, function(i) {
      var input = $(i);
      this.addField(input.attr('name'), input.val());
    }, this);
  },

  highlight: function(el) {
    if (el.hasClass('selected')) {
      this.update(0, el.attr('name'));
      el.removeClass('selected');
    }
    else {
      this.update(1, el.attr('name'));
      el.addClass('selected');
    }
  },

  render: function() {
    var frame = $H('ul.frame');

    this.eachLabelAndInput(function(input, name, value, text) {
      var node = $H('li.button', {'data-value': value, name: name}, $H('span', text));
      if (input.checked) {node.addClass('selected');}
      frame.append(node);
    });

    this.widget.append(frame);

    return this;
  }
});

/* -------------------------------------------------------------------------- */
/* MULTI-SELECT
/* -------------------------------------------------------------------------- */
Islay.Widgets.MultiSelect = Islay.Widgets.Base.extend({
  widgetClass: 'multi-select',

  click: function() {

  },

  render: function() {

    return this;
  }
});
<commit_msg>Support nested forms and add a working version of the tabs.<commit_after>// View instantiates
// Stubs model
// Iterates over inputs
// Grabs values
// Generates widgets
// Binds change events from widgets to view
// View updates model on change
// Before view submits.
var Islay = {};

// Understands required
Islay.FormModel = Backbone.Model.extend({

});

Islay.Form = Backbone.View.extend({
  events: {submit: 'submit'},

  initialize: function() {
    _.bindAll(this, 'submit', 'tabClick');

    this.model = new Islay.FormModel();

    if (this.$el.is('.sub-form')) {
      var inputs = this.$el.find('.field');
    }
    else {
      var inputs = this.$el.find('.field:not(.sub-form .field)');
      this.initializeTabs();
      var forms = this.$el.find('.sub-form');
      this.forms = _.map(forms, this.initializeForms, this);
    }

    this.widgets = _.reduce(inputs, this.initializeWidgets, {}, this);
  },

  initializeForms: function(el) {
    return new Islay.Form({el: el});
  },

  initializeTabs: function() {
    var tabs = this.$el.find('.tab');
    if (tabs.length > 0) {
      this.tabs = [];

      var list = $H('ul.tabset');
      _.each(tabs, function(t, i) {
        var tab = $(t);
        var node = $H('li', {'data-index': i}, tab.find('legend').remove().text());
        this.tabs.push(tab);
        if (!this.currentTab) {
          this.currentTab = node;
          node.addClass('selected');
        }
        else {
          tab.hide();
        }
        list.append(node);
      }, this);

      list.click(this.tabClick);
      tabs.first().before(list);
    }
  },

  tabClick: function(e) {
    var target = $(e.target);
    if (target.is('li')) {
      if (this.currentTab) {
        this.tabs[this.currentTab.attr('data-index')].hide();
        this.currentTab.removeClass('selected');
      }
      this.currentTab = target;
      this.currentTab.addClass('selected');
      this.tabs[this.currentTab.attr('data-index')].show();
    }
  },

  initializeWidgets: function(obj, el) {
    var $el = $(el);
    var widget = null;

    var match = $el.attr('class').match(/^field ([\w\d\-_]+) .+$/);

    if (match) {
      switch(match[1]) {
        case 'select':
          widget = 'Select';
        break;
        case 'boolean':
          widget = 'Boolean';
        break;
        case 'radio_buttons':
          widget = 'Segmented';
        break;
        case 'check_boxes':
          widget = 'Checkboxes';
        break;
      }

      if (widget) {
        var instance = new Islay.Widgets[widget]({el: el});
        // obj[$input.attr('id')] = instance;
        instance.render();

        // TODO: Bind widgets to model
      }
    }

    return obj;
  },

  submit: function() {

  }
});

Islay.Widgets = Islay.Widgets || {};

Islay.Widgets.Base = Backbone.View.extend({
  events: {'click': '_click', keyup: 'keyup'},
  widgetClass: 'default',
  inputsSelector: ':input[type!=hidden]',
  removeSelector: ':input[class!=islay]',

  initialize: function() {
    this.fields = {};
    this.widget = $H('div.widget.' + this.widgetClass);
    this.inputs = this.$el.find(this.inputsSelector);
    this.$el.append(this.widget);
    this.initialValue = this.getInitialValue();
    this.initFields();
    this.$el.find(this.removeSelector).remove();
  },

  update: function(value, field) {
    if (field) {
      this.trigger('update', field, value);
      this.fields[field].val(value);
    }
    else {
      this.trigger('update', this.fieldName, value);
      this.fields[this.fieldName].val(value);
    }
  },

  addField: function(field, value) {
    var node = $H('input.islay', {type: 'hidden', value: value, name: field});
    this.fields[field] = node;
    this.$el.append(node);
    return node;
  },

  // Overridable
  initFields: function() {
    var field = this.$el.find(':input[type!=hidden]'),
        name = field.attr('name');

    this.addField(name, this.initialValue);
    this.fieldName = name;
  },

  // Overridable
  getInitialValue: function() {
    return this.inputs.val();
  },

  currentValue: function(field) {
    if (field) {
      return this.fields[field].val();
    }
    else {
      return this.fields[this.fieldName].val();
    }
  },

  render: function() {
    throw "Unimplemented";
  },

  click: function() {
    throw "Unimplemented";
  },

  keyup: function() {
    throw "Unimplemented";
  },

  eachLabelAndInput: function(fn) {
    _.each(this.inputs, function(input) {
      var i = $(input);
      fn(i, i.attr('name'), i.attr('value'), i.parent('label').text());
    }, this);
  },

  _click: function(e) {
    var target = $(e.target);
    this.click(e, target);
  }
});

/* -------------------------------------------------------------------------- */
/* SIMPLE SELECT
/* -------------------------------------------------------------------------- */
Islay.Widgets.Select = Islay.Widgets.Base.extend({
  widgetClass: 'select',
  removeSelector: 'select',

  open: function() {
    this.isOpen = true;
    this.widget.addClass('open');
    this.list.show();
  },

  close: function() {
    this.isOpen = false;
    this.widget.removeClass('open');
    this.list.hide();
  },

  click: function(e, target) {
    if (target.is('.frame, .button, .display, span')) {
      if (this.isOpen) {
        this.close();
      }
      else {
        this.open();
      }
    }
    else if (target.is('li')) {
      this.display.text(target.text());
      this.update(target.attr('data-value'));
      this.close();
    }
  },

  render: function() {
    this.display = $H('div.display');
    this.button = $H('div.button', $H('span', '>'));
    var frame = $H('div.frame', [this.display, this.button]);
    this.list = $H('ul.list');

    this.widget.append(frame, this.list);

    var currentValue = this.currentValue();
    _.each(this.inputs.find('option'), function(opt) {
      opt = $(opt);
      var value = opt.attr('value'),
          text  = opt.text();

      if (value == currentValue) {this.display.text(text);}
      if (value != '') {this.list.append($H('li', {'data-value': value}, text));}
    }, this);

    return this;
  }
});

/* -------------------------------------------------------------------------- */
/* BOOLEAN SWITCH
/* -------------------------------------------------------------------------- */
Islay.Widgets.Boolean = Islay.Widgets.Base.extend({
  widgetClass: 'boolean',

  click: function(e, target) {
    if (target.is('li, span')) {
      if (this.currentValue() == 1) {
        this.update(0);
        this.optionOn.removeClass('selected');
        this.optionOff.addClass('selected');
      }
      else {
        this.update(1);
        this.optionOff.removeClass('selected');
        this.optionOn.addClass('selected');
      }
    }
  },

  getInitialValue: function() {
    return this.$el.find(':input[type!=hidden]').is(':checked') ? 1 : 0;
  },

  render: function() {
    this.optionOff = $H('li.button.optionOff', $H('span', 'x'));
    this.optionOn = $H('li.button.optionOn', $H('span', 't'));
    var frame = $H('ul.frame', [this.optionOff, this.optionOn]);
    this.widget.append(frame);

    if (this.initialValue == 1) {
      this.optionOn.addClass('selected');
    }
    else {
      this.optionOff.addClass('selected');
    }

    return this;
  }
});

/* -------------------------------------------------------------------------- */
/* SEGMENTED CONTROL
/* -------------------------------------------------------------------------- */
Islay.Widgets.Segmented = Islay.Widgets.Base.extend({
  widgetClass: 'segmented',
  removeSelector: 'label.radio',

  click: function(e, target) {
    if (target.is('li')) {
      this.highlight(target);
    }
    else if (target.is('span')) {
      this.highlight(target.parent('li'));
    }
  },

  highlight: function(el) {
    this.update(el.attr('data-value'));
    if (this.currentNode) {this.currentNode.removeClass('selected');}
    this.currentNode = el;
    this.currentNode.addClass('selected');
  },

  render: function() {
    var frame = $H('ul.frame');
    var currentValue = this.inputs.filter(':checked').val();
    _.each(this.inputs, function(input) {
      var input = $(input),
          value = input.val();

      var node = $H('li.button', {'data-value': value}, $H('span', input.parent().text()));
      if (value == currentValue) {
        node.addClass('selected');
        this.currentNode = node;
      }
      frame.append(node);
    }, this);

    this.widget.append(frame);

    return this;
  }
});

/* -------------------------------------------------------------------------- */
/* CHECKBOXES
/* -------------------------------------------------------------------------- */
Islay.Widgets.Checkboxes = Islay.Widgets.Base.extend({
  widgetClass: 'checkboxes',
  removeSelector: 'label.checkbox',

  click: function(e, target) {
    if (target.is('li')) {
      this.highlight(target);
    }
    else if (target.is('span')) {
      this.highlight(target.parent('li'));
    }
  },

  initFields: function() {
    _.each(this.inputs, function(i) {
      var input = $(i);
      this.addField(input.attr('name'), input.val());
    }, this);
  },

  highlight: function(el) {
    if (el.hasClass('selected')) {
      this.update(0, el.attr('name'));
      el.removeClass('selected');
    }
    else {
      this.update(1, el.attr('name'));
      el.addClass('selected');
    }
  },

  render: function() {
    var frame = $H('ul.frame');

    this.eachLabelAndInput(function(input, name, value, text) {
      var node = $H('li.button', {'data-value': value, name: name}, $H('span', text));
      if (input.checked) {node.addClass('selected');}
      frame.append(node);
    });

    this.widget.append(frame);

    return this;
  }
});

/* -------------------------------------------------------------------------- */
/* MULTI-SELECT
/* -------------------------------------------------------------------------- */
Islay.Widgets.MultiSelect = Islay.Widgets.Base.extend({
  widgetClass: 'multi-select',

  click: function() {

  },

  render: function() {

    return this;
  }
});
<|endoftext|>


<commit_before>"use strict";

var ResourceReferenceView = require('../resource_reference').View;

var InlineFormulaView = function(node, viewFactory) {
  ResourceReferenceView.call(this, node, viewFactory);
};

InlineFormulaView.Prototype = function() {

  this.render = function() {
    var formula = this.node.document.get(this.node.target);
    var formulaView = this.viewFactory.createView(formula);
    this.el.innerHTML = formulaView.render().el.innerHTML;
    return this;
  };

};
InlineFormulaView.Prototype.prototype = ResourceReferenceView.prototype;
InlineFormulaView.prototype = new InlineFormulaView.Prototype();

module.exports = InlineFormulaView;
<commit_msg>Fix regression (do not render inline-formulas as <a> tag)<commit_after>"use strict";

var ResourceReferenceView = require('../resource_reference').View;

var InlineFormulaView = function(node, viewFactory) {
  ResourceReferenceView.call(this, node, viewFactory);
};

InlineFormulaView.Prototype = function() {

  this.createElement = function() {
    var el = document.createElement('span');
    return el;
  };

  this.render = function() {
    var formula = this.node.document.get(this.node.target);
    var formulaView = this.viewFactory.createView(formula);
    this.el.innerHTML = formulaView.render().el.innerHTML;
    return this;
  };

};
InlineFormulaView.Prototype.prototype = ResourceReferenceView.prototype;
InlineFormulaView.prototype = new InlineFormulaView.Prototype();

module.exports = InlineFormulaView;
<|endoftext|>


<commit_before>angular.module('cesium.es.wot.services', ['ngResource', 'cesium.es.http.services'])

  .factory('esWot', function($q, esHttp, csCache) {
    'ngInject';

    var
      cachePrefix = 'esWot-',
      membershipsCache = csCache.get(cachePrefix + 'memberships-', csCache.constants.MEDIUM),
      raw = {
          user: {
            event: esHttp.post('/user/event/_search')
          }
        },

      loadMemberships = function(pubkey, options) {
        options = options || {};

        var result = (options.cache !== false) ? membershipsCache.get(pubkey) : null;
        if (result) return $q.when(result);

        // Get user events on membership state
        var request = {
          "size": 1000,
          "query": {
            "bool": {
              "filter": [
                {"term": {"recipient" : pubkey }},
                {"terms": {"code" : ["MEMBER_JOIN","MEMBER_ACTIVE","MEMBER_LEAVE","MEMBER_EXCLUDE","MEMBER_REVOKE"] }}
              ]
            }
          },
          "sort" : [
            { "time" : {"order" : "asc"}}
          ],
          _source: ["code", "time"]
        };

        return raw.user.event(request)

          .then(function(res) {
            if (!res.hits || !res.hits.total) return;

            // Compute member periods
            var lastJoinTime;
            var result = res.hits.hits.reduce(function(res, hit){
              var isMember = hit._source.code == 'MEMBER_JOIN' || hit._source.code == 'MEMBER_ACTIVE';
              // If join
              if (isMember && !lastJoinTime) {
                lastJoinTime = hit._source.time;
              }
              // If leave
              else if (!isMember && lastJoinTime) {
                // Add an entry
                res = res.concat({
                  joinTime: lastJoinTime,
                  leaveTime: hit._source.time
                });
                lastJoinTime = 0; // reset
              }
              return res;
            }, []);

            if (lastJoinTime) {
              // Add last entry if need
              result.push({
                joinTime: lastJoinTime,
                leaveTime: moment().utc().unix()
              });
            }

            // Put in the cache
            membershipsCache.put(pubkey, result);

            return result;
          });
      },

      cleanCache = function() {
        console.debug('[ES] [wot] Clean cache...');
        csCache.clear(cachePrefix);
      };

    // Listen if node changed
    esHttp.api.node.on.stop($rootScope, cleanCache, this);

    return {
      memberships: loadMemberships
    };
  });
<commit_msg>[fix] Fix JS Hint<commit_after>angular.module('cesium.es.wot.services', ['ngResource', 'cesium.es.http.services'])

  .factory('esWot', function($rootScope, $q, esHttp, csCache) {
    'ngInject';

    var
      cachePrefix = 'esWot-',
      membershipsCache = csCache.get(cachePrefix + 'memberships-', csCache.constants.MEDIUM),
      raw = {
          user: {
            event: esHttp.post('/user/event/_search')
          }
        },

      loadMemberships = function(pubkey, options) {
        options = options || {};

        var result = (options.cache !== false) ? membershipsCache.get(pubkey) : null;
        if (result) return $q.when(result);

        // Get user events on membership state
        var request = {
          "size": 1000,
          "query": {
            "bool": {
              "filter": [
                {"term": {"recipient" : pubkey }},
                {"terms": {"code" : ["MEMBER_JOIN","MEMBER_ACTIVE","MEMBER_LEAVE","MEMBER_EXCLUDE","MEMBER_REVOKE"] }}
              ]
            }
          },
          "sort" : [
            { "time" : {"order" : "asc"}}
          ],
          _source: ["code", "time"]
        };

        return raw.user.event(request)

          .then(function(res) {
            if (!res.hits || !res.hits.total) return;

            // Compute member periods
            var lastJoinTime;
            var result = res.hits.hits.reduce(function(res, hit){
              var isMember = hit._source.code == 'MEMBER_JOIN' || hit._source.code == 'MEMBER_ACTIVE';
              // If join
              if (isMember && !lastJoinTime) {
                lastJoinTime = hit._source.time;
              }
              // If leave
              else if (!isMember && lastJoinTime) {
                // Add an entry
                res = res.concat({
                  joinTime: lastJoinTime,
                  leaveTime: hit._source.time
                });
                lastJoinTime = 0; // reset
              }
              return res;
            }, []);

            if (lastJoinTime) {
              // Add last entry if need
              result.push({
                joinTime: lastJoinTime,
                leaveTime: moment().utc().unix()
              });
            }

            // Put in the cache
            membershipsCache.put(pubkey, result);

            return result;
          });
      },

      cleanCache = function() {
        console.debug('[ES] [wot] Clean cache...');
        csCache.clear(cachePrefix);
      };

    // Listen if node changed
    esHttp.api.node.on.stop($rootScope, cleanCache, this);

    return {
      memberships: loadMemberships
    };
  });
<|endoftext|>


<commit_before>/*
 * index.js: Top-level include for Winston
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 *
 */

var util = require('util'),
    crypto = require('crypto'),
    qs = require('querystring'),
    config = require('./../config');

//
// function setLevels (target, past, current)
//   Create functions on the target objects for each level
//   in current.levels. If past is defined, remove functions
//   for each of those levels.
//
var setLevels = exports.setLevels = function (target, past, current, isDefault) {
  if (past) {
    Object.keys(past).forEach(function (level) {
      delete target[level];
    });
  }

  target.levels = current || config.npm.levels;

  //
  //  Define prototype methods for each log level
  //  e.g. target.log('info', msg) <=> target.info(msg)
  //
  Object.keys(target.levels).forEach(function (level) {
    target[level] = function (msg) {
      var args = Array.prototype.slice.call(arguments),
          callback = typeof args[args.length - 1] === 'function' || args.length === 3 ? args.pop() : null,
          meta = args.length === 2 ? args.pop() : null;

      return target.log(level, msg, meta, callback);
    };
  });

  return target;
};

//
// function clone (obj)
//   Helper method for deep cloning pure JSON objects
//   i.e. JSON objects that are either literals or objects (no Arrays, etc)
//
var clone = exports.clone = function (obj) {
  var clone = {};
  for (var i in obj) {
    clone[i] = obj[i] instanceof Object ? exports.clone(obj[i]) : obj[i];
  }

  return clone;
};

var months = ['Jan', 'Feb', 'Mar', 'Apr',
              'May', 'Jun', 'Jul', 'Aug',
              'Sep', 'Oct', 'Nov', 'Dec'];

//
// Borrowed from node.js core because I wanted a universal lowercase header message
//
var pad = exports.pad = function (n) {
  return n < 10 ? '0' + n.toString(10) : n.toString(10);
}

//
// Borrowed from node.js core because I wanted a universal lowercase header message
//
var timestamp = exports.timestamp = function () {
  var d = new Date();
  var time = [pad(d.getHours()),
              pad(d.getMinutes()),
              pad(d.getSeconds())].join(':');
  return [d.getDate(), months[d.getMonth()], time].join(' ');
}

//
// function log (level, msg, meta)
//   Generic logging function for returning timestamped strings
//
var log = exports.log = function (level, msg, meta, options) {
  var output = options.timestamp ? timestamp() : '';
      targetLevel = options.colorize ? config.colorize(level) : level;

  output += ' - ' + targetLevel + ': ' + msg;

  if (meta && Object.keys(meta).length > 0) output += ' ' + qs.unescape(qs.stringify(meta, ','));

  return output;
}

//
// function hash (str)
//   Utility function for creating unique ids
//   e.g. Profiling incoming HTTP requests on the same tick
//
var hash = exports.hash = function (str) {
  return crypto.createHash('sha1').update(str).digest('hex');
};<commit_msg>[minor] Small formatting bug in non-timestamped logs<commit_after>/*
 * index.js: Top-level include for Winston
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 *
 */

var util = require('util'),
    crypto = require('crypto'),
    qs = require('querystring'),
    config = require('./../config');

//
// function setLevels (target, past, current)
//   Create functions on the target objects for each level
//   in current.levels. If past is defined, remove functions
//   for each of those levels.
//
var setLevels = exports.setLevels = function (target, past, current, isDefault) {
  if (past) {
    Object.keys(past).forEach(function (level) {
      delete target[level];
    });
  }

  target.levels = current || config.npm.levels;

  //
  //  Define prototype methods for each log level
  //  e.g. target.log('info', msg) <=> target.info(msg)
  //
  Object.keys(target.levels).forEach(function (level) {
    target[level] = function (msg) {
      var args = Array.prototype.slice.call(arguments),
          callback = typeof args[args.length - 1] === 'function' || args.length === 3 ? args.pop() : null,
          meta = args.length === 2 ? args.pop() : null;

      return target.log(level, msg, meta, callback);
    };
  });

  return target;
};

//
// function clone (obj)
//   Helper method for deep cloning pure JSON objects
//   i.e. JSON objects that are either literals or objects (no Arrays, etc)
//
var clone = exports.clone = function (obj) {
  var clone = {};
  for (var i in obj) {
    clone[i] = obj[i] instanceof Object ? exports.clone(obj[i]) : obj[i];
  }

  return clone;
};

var months = ['Jan', 'Feb', 'Mar', 'Apr',
              'May', 'Jun', 'Jul', 'Aug',
              'Sep', 'Oct', 'Nov', 'Dec'];

//
// Borrowed from node.js core because I wanted a universal lowercase header message
//
var pad = exports.pad = function (n) {
  return n < 10 ? '0' + n.toString(10) : n.toString(10);
}

//
// Borrowed from node.js core because I wanted a universal lowercase header message
//
var timestamp = exports.timestamp = function () {
  var d = new Date();
  var time = [pad(d.getHours()),
              pad(d.getMinutes()),
              pad(d.getSeconds())].join(':');
  return [d.getDate(), months[d.getMonth()], time].join(' ');
}

//
// function log (level, msg, meta)
//   Generic logging function for returning timestamped strings
//
var log = exports.log = function (level, msg, meta, options) {
  var output = options.timestamp ? timestamp() + ' - ' : '';
      targetLevel = options.colorize ? config.colorize(level) : level;

  output += targetLevel + ': ' + msg;

  if (meta && Object.keys(meta).length > 0) output += ' ' + qs.unescape(qs.stringify(meta, ','));

  return output;
}

//
// function hash (str)
//   Utility function for creating unique ids
//   e.g. Profiling incoming HTTP requests on the same tick
//
var hash = exports.hash = function (str) {
  return crypto.createHash('sha1').update(str).digest('hex');
};<|endoftext|>