<commit_before>
var api = require('../src/api.js');
var generator = require('../src/template-generator.js');
var translator = require('../src/translator.js');
var Z3 = require('../src/z3.js');
var async = require('async');
var templateUtil = require('../src/template-util.js');
var expr_str = require('../src/expr_str');

module.exports = Solver;

function Solver(task) {
    this.task = task;
    this.constraints = [];
    this.pendingConstraints = [];
    this.templateStatus = 'mismatch';
    this.template;

    this.z3;
    this.z3program;
    this.z3sat = true;

    this.programHoles;
    this.program;

}

Solver.prototype.addConstraint = function (constraints) {
    this.constraints.push(constraints);
    this.pendingConstraints.push(constraints);
}

Solver.prototype.evaluate = function (inputs, callback) {
    api.evaluate(this.task.id, '', inputs, function(response) {
        var i;
        console.log('EVAL: ' + response.status + ', Outpus: ' + response.outputs);

        pendingConstraints = [];
        for (i = 0; i < response.outputs.length; i += 1) {
            this.addConstraint([inputs[i], response.outputs[i]]);
        }
        this.z3program += translator.translate_constraint16(this.constraints);
        this.z3program += translator.check_sat();
        callback(null);
    }.bind(this));
}

Solver.prototype.guess = function (callback) {

    if (!this.z3sat) {
        callback(null);
        return;
    }

    api.guess(this.task.id, expr_str(this.program), function(response) {
        console.log(response.status);

        this.templateStatus = response.status;

        if (response.status === 'mismatch') {
            // add response.values to pending constraints
            this.pendingConstraints = [];
            this.addConstraint([response.values[0], response.values[1]]);
            this.z3program += translator.translate_constraint16([[response.values[0], response.values[1]]]);
            this.z3program += translator.check_sat();
        }
        callback(null);
    }.bind(this));
}

Solver.prototype.callZ3 = function(callback) {
    console.log(this.z3program);
    this.z3.write(this.z3program, function (response) {
        console.log(response);
        if(response.indexOf('sat') == 0) {
            this.z3.write('(get-model)', function (response) {
                console.log(response);
                this.programHoles = templateUtil.extractVariables(response);
                console.log(this.programHoles);

                this.program = templateUtil.toProgram(this.template, this.programHoles, this.task.operators)
                console.log(expr_str(this.program));
                this.z3program = '';
                callback(null);
            }.bind(this));
        }
        else {
            console.log(response);

            this.nextTemplate(true);

            if (this.template)
                this.callZ3(callback);
            else
                callback(null);
        }
    }.bind(this));

}

Solver.prototype.nextTemplate = function(check_sat) {
    this.template = generator.next_program(this.task.size, this.template, this.task.operators);
    if (!this.template) {
        this.z3sat = true;
        this.z3program = '';
        return;
    }

    console.log(expr_str(this.template));

    this.z3program = '(reset)\n';
    this.z3program += translator.translate_template(this.template, this.task.operators);
    this.z3program += translator.translate_constraint16(this.constraints);
    if (check_sat)
        this.z3program += translator.check_sat();
}

Solver.prototype.solveGuessLoop = function(cb1) {
    var that = this;

    async.whilst(
        function() {
            var ret = (that.templateStatus === 'mismatch') && that.z3sat;
//            console.log('Loop tested ' + ret + that.templateStatus);
            return ret;
        },

        function(cb2) {
            console.log('About to call series');
            async.series([
                function(cb3) {
                    console.log('About to call Z3');
                    that.callZ3(cb3);
                },

                function(cb3) { that.guess(cb3); },

                function(cb3) { cb3(null); cb2(null); }
            ]);
        },

        function(err) {
            console.log('Loop ended');
            cb1(null);
        }
    );

}

Solver.prototype.start = function() {

    var that = this;

    this.z3 = new Z3();

    this.nextTemplate();

    async.series([
        function(callback) {
            that.evaluate(['0xFE5645A7867867B3', '0x45FE35AB35041CD2'], callback);
        },

        that.solveGuessLoop.bind(that)
    ]);

}

Solver.prototype.stop = function() {
    //this.z3.kill();
}<commit_msg>Solver::start() takes task and a callback and kills z3 automatically<commit_after>
var api = require('../src/api.js');
var generator = require('../src/template-generator.js');
var translator = require('../src/translator.js');
var Z3 = require('../src/z3.js');
var async = require('async');
var templateUtil = require('../src/template-util.js');
var expr_str = require('../src/expr_str');

module.exports = Solver;

function Solver(task) {
    this.task = task;
    this.constraints = [];
    this.pendingConstraints = [];
    this.templateStatus = 'mismatch';
    this.template;

    this.z3;
    this.z3program;
    this.z3sat = true;

    this.programHoles;
    this.program;
}

Solver.prototype.addConstraint = function (constraints) {
    this.constraints.push(constraints);
    this.pendingConstraints.push(constraints);
}

Solver.prototype.evaluate = function (inputs, callback) {
    api.evaluate(this.task.id, '', inputs, function(response) {
        var i;
        console.log('EVAL: ' + response.status + ', Outpus: ' + response.outputs);

        pendingConstraints = [];
        for (i = 0; i < response.outputs.length; i += 1) {
            this.addConstraint([inputs[i], response.outputs[i]]);
        }
        this.z3program += translator.translate_constraint16(this.constraints);
        this.z3program += translator.check_sat();
        callback(null);
    }.bind(this));
}

Solver.prototype.guess = function (callback) {

    if (!this.z3sat) {
        callback(null);
        return;
    }

    api.guess(this.task.id, expr_str(this.program), function(response) {
        console.log(response.status);

        this.templateStatus = response.status;

        if (response.status === 'mismatch') {
            // add response.values to pending constraints
            this.pendingConstraints = [];
            this.addConstraint([response.values[0], response.values[1]]);
            this.z3program += translator.translate_constraint16([[response.values[0], response.values[1]]]);
            this.z3program += translator.check_sat();
        }
        callback(null);
    }.bind(this));
}

Solver.prototype.callZ3 = function(callback) {
    console.log(this.z3program);
    this.z3.write(this.z3program, function (response) {
        console.log(response);
        if(response.indexOf('sat') == 0) {
            this.z3.write('(get-model)', function (response) {
                console.log(response);
                this.programHoles = templateUtil.extractVariables(response);
                console.log(this.programHoles);

                this.program = templateUtil.toProgram(this.template, this.programHoles, this.task.operators)
                console.log(expr_str(this.program));
                this.z3program = '';
                callback(null);
            }.bind(this));
        }
        else {
            console.log(response);

            this.nextTemplate(true);

            if (this.template)
                this.callZ3(callback);
            else
                callback(null);
        }
    }.bind(this));

}

Solver.prototype.nextTemplate = function(check_sat) {
    this.template = generator.next_program(this.task.size, this.template, this.task.operators);
    if (!this.template) {
        this.z3sat = true;
        this.z3program = '';
        return;
    }

    console.log(expr_str(this.template));

    this.z3program = '(reset)\n';
    this.z3program += translator.translate_template(this.template, this.task.operators);
    this.z3program += translator.translate_constraint16(this.constraints);
    if (check_sat)
        this.z3program += translator.check_sat();
}

Solver.prototype.solveGuessLoop = function(cb1) {
    var that = this;

    async.whilst(
        function() {
            var ret = (that.templateStatus === 'mismatch') && that.z3sat;
//            console.log('Loop tested ' + ret + that.templateStatus);
            return ret;
        },

        function(cb2) {
            console.log('About to call series');
            async.series([
                function(cb3) {
                    console.log('About to call Z3');
                    that.callZ3(cb3);
                },

                function(cb3) { that.guess(cb3); },

                function(cb3) { cb3(null); cb2(null); }
            ]);
        },

        function(err) {
            console.log('Loop ended');
            cb1(null);
        }
    );

}

Solver.prototype.start = function(task, callback) {

    if (arguments.length === 0) {
        callback = function () {};
    } else if (arguments.length === 1) {
        if (task instanceof Function) {
            callback = task;
            task = null;
        }
    }

    if (task) this.task = task;

    var that = this;

    this.z3 = new Z3();

    this.nextTemplate();

    async.series([
        function(callback) {
            that.evaluate(['0xFE5645A7867867B3', '0x45FE35AB35041CD2'], callback);
        },

        that.solveGuessLoop.bind(that)
    ], function () {
        that.stop();
        callback(that);
    });

}

Solver.prototype.stop = function() {
    this.z3.kill();
}
<|endoftext|>


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

var __ = require('underscore');
var util = require('util');
var utils = require('../../../util/utils');
var resourceUtils = require('../resource/resourceUtils');
var tagUtils = require('../tag/tagUtils');
var $ = utils.getLocaleString;

function Publicip(cli, networkResourceProviderClient) {
  this.cli = cli;
  this.networkResourceProviderClient = networkResourceProviderClient;
}

__.extend(Publicip.prototype, {
  create: function (resourceGroupName, name, params, _) {
    var publicipProfile = this._parseAndValidatePublicIP(name, params);
    var publicip = this.get(resourceGroupName, name, _);
    if (publicip) {
      throw new Error(util.format($('A public ip address with name "%s" already exists in the resource group "%s"'), name, resourceGroupName));
    }

    var progress = this.cli.interaction.progress(util.format($('Creating public ip address "%s"'), name));
    try {
      this.networkResourceProviderClient.publicIpAddresses.createOrUpdate(resourceGroupName, name, publicipProfile, _);
    } finally {
      progress.end();
    }
    this.show(resourceGroupName, name, params, _);
  },

  set: function (resourceGroupName, name, params, _) {
    var self = this;
    var publicipProfile = this._parseAndValidatePublicIP(name, params);
    var publicip = this.get(resourceGroupName, name, _);
    if (!publicip) {
      throw new Error(util.format($('A public ip address with name "%s" not found in the resource group "%s"'), name, resourceGroupName));
    }

    if (params.idletimeout) publicip.publicIpAddress.idleTimeoutInMinutes = publicipProfile.idleTimeoutInMinutes;
    if (params.allocationMethod) publicip.publicIpAddress.publicIpAllocationMethod = publicipProfile.publicIpAllocationMethod;

    var optionalDomainLabel = utils.getOptionalArg(params.domainNameLabel);
    if (optionalDomainLabel.hasValue) {
      if (optionalDomainLabel.value !== null) {
        self._createDnsSettingsIfNotExist(publicip.publicIpAddress);
        publicip.publicIpAddress.dnsSettings.domainNameLabel = publicipProfile.dnsSettings.domainNameLabel;
      } else {
        delete publicip.publicIpAddress.dnsSettings;
      }
    }

    var optionalReverseFqdn = utils.getOptionalArg(params.reverseFqdn);
    if (optionalReverseFqdn.hasValue) {
      if (optionalReverseFqdn.value !== null) {
        self._createDnsSettingsIfNotExist(publicip.publicIpAddress);
        publicip.publicIpAddress.dnsSettings.reverseFqdn = publicipProfile.dnsSettings.reverseFqdn;
      } else {
        delete publicip.publicIpAddress.dnsSettings.reverseFqdn;
      }
    }

    if (params.tags) {
      tagUtils.appendTags(publicip.publicIpAddress, publicipProfile.tags);
    }

    if (params.tags === false) {
      publicip.publicIpAddress.tags = {};
    }

    this.update(resourceGroupName, name, publicip.publicIpAddress, _);
    this.show(resourceGroupName, name, params, _);
  },

  show: function (resourceGroupName, name, params, _) {
    var publicIP = this.get(resourceGroupName, name, _);
    var output = this.cli.output;
    var interaction = this.cli.interaction;

    if (publicIP) {
      var resourceInfo = resourceUtils.getResourceInformation(publicIP.publicIpAddress.id);
      interaction.formatOutput(publicIP.publicIpAddress, function (publicip) {
        output.nameValue($('Id'), publicip.id);
        output.nameValue($('Name'), publicip.name);
        output.nameValue($('Type'), resourceInfo.resourceType);
        output.nameValue($('Location'), publicip.location);
        output.nameValue($('Provisioning state'), publicip.provisioningState);
        output.nameValue($('Tags'), tagUtils.getTagsInfo(publicip.tags));
        output.nameValue($('Allocation method'), publicip.publicIpAllocationMethod);
        output.nameValue($('Idle timeout'), publicip.idleTimeoutInMinutes);
        output.nameValue($('IP Address'), publicip.ipAddress);
        if (publicip.dnsSettings) {
          var dnsSettings = publicip.dnsSettings;
          output.nameValue($('Domain name label'), dnsSettings.domainNameLabel);
          output.nameValue($('FQDN'), dnsSettings.fqdn);
          output.nameValue($('Reverse FQDN'), dnsSettings.reverseFqdn);
        }
      });
    } else {
      if (output.format().json) {
        output.json({});
      } else {
        output.warn(util.format($('A public ip address with name "%s" not found in the resource group "%s"'), name, resourceGroupName));
      }
    }
  },

  delete: function (resourceGroupName, name, params, _) {
    var publicIP = this.get(resourceGroupName, name, _);
    if (!publicIP) {
      throw new Error(util.format($('A public ip address with name "%s" not found in the resource group "%s"'), name, resourceGroupName));
    }

    if (!params.quiet && !this.cli.interaction.confirm(util.format($('Delete public ip address "%s"? [y/n] '), name), _)) {
      return;
    }

    var progress = this.cli.interaction.progress(util.format($('Deleting public ip address "%s"'), name));
    try {
      this.networkResourceProviderClient.publicIpAddresses.deleteMethod(resourceGroupName, name, _);
    } finally {
      progress.end();
    }
  },

  list: function (resourceGroupName, params, _) {
    var progress = this.cli.interaction.progress($('Getting the public ip addresses'));
    var publicIPs = null;
    try {
      publicIPs = this.networkResourceProviderClient.publicIpAddresses.list(resourceGroupName, _);
    } finally {
      progress.end();
    }

    var output = this.cli.output;
    this.cli.interaction.formatOutput(publicIPs.publicIpAddresses, function (outputData) {
      if (outputData.length === 0) {
        output.warn($('No public ip address found'));
      } else {
        output.table(outputData, function (row, item) {
          row.cell($('Name'), item.name);
          row.cell($('Location'), item.location);
          row.cell($('Allocation'), item.publicIpAllocationMethod);
          row.cell($('IP Address'), item.ipAddress || '');
          row.cell($('Idle timeout'), item.idleTimeoutInMinutes || '');
          var dnsName = '';
          if (item.dnsSettings) {
            dnsName = item.dnsSettings.fqdn;
          }
          row.cell($('DNS Name'), dnsName);
        });
      }
    });
  },

  get: function (resourceGroupName, name, _) {
    var progress = this.cli.interaction.progress(util.format($('Looking up the public ip "%s"'), name));
    try {
      var publicIP = this.networkResourceProviderClient.publicIpAddresses.get(resourceGroupName, name, _);
      return publicIP;
    } catch (e) {
      if (e.code === 'ResourceNotFound') {
        return null;
      }
      throw e;
    } finally {
      progress.end();
    }
  },

  update: function (resourceGroupName, name, publicIpProfile, _) {
    var progress = this.cli.interaction.progress(util.format($('Updating public ip address "%s"'), name));
    try {
      this.networkResourceProviderClient.publicIpAddresses.createOrUpdate(resourceGroupName, name, publicIpProfile, _);
    } catch (e) {
      throw e;
    } finally {
      progress.end();
    }
  },

  _parseAndValidatePublicIP: function (name, params) {
    var supportedAllocationTypes = ['Dynamic', 'Static'];
    var self = this;

    var publicipProfile = {
      name: name,
      publicIpAllocationMethod: supportedAllocationTypes[0]
    };

    if (params.idletimeout) {
      var timeoutAsInt = utils.parseInt(params.idletimeout);
      if (isNaN(timeoutAsInt) || timeoutAsInt === 0) {
        throw new Error($('idletimeout parameter must be an integer'));
      }
      publicipProfile.idleTimeoutInMinutes = timeoutAsInt;
    }

    if (params.allocationMethod) {
      if (utils.stringIsNullOrEmpty(params.allocationMethod)) {
        throw new Error($('allocation method parameter must not be null or empty string'));
      }
      publicipProfile.publicIpAllocationMethod = utils.verifyParamExistsInCollection(supportedAllocationTypes,
        params.allocationMethod, 'allocationMethod');
    }

    if (params.domainNameLabel) {
      self._createDnsSettingsIfNotExist(publicipProfile);
      publicipProfile.dnsSettings.domainNameLabel = params.domainNameLabel;
    }

    if (params.reverseFqdn) {
      self._createDnsSettingsIfNotExist(publicipProfile);
      publicipProfile.dnsSettings.reverseFqdn = params.reverseFqdn;
    }

    if (params.tags) {
      publicipProfile.tags = tagUtils.buildTagsParameter(null, params);
    }

    if (params.location) {
      publicipProfile.location = params.location;
    }

    return publicipProfile;
  },

  _createDnsSettingsIfNotExist: function (publicip) {
    if (!publicip.dnsSettings) publicip.dnsSettings = {};
  }
});

module.exports = Publicip;<commit_msg>ARM Public IP: using 'self' instead of 'this'<commit_after>/**
 * Copyright (c) Microsoft.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var __ = require('underscore');
var util = require('util');
var utils = require('../../../util/utils');
var resourceUtils = require('../resource/resourceUtils');
var tagUtils = require('../tag/tagUtils');
var $ = utils.getLocaleString;

function Publicip(cli, networkResourceProviderClient) {
  this.networkResourceProviderClient = networkResourceProviderClient;
  this.output = cli.output;
  this.interaction = cli.interaction;
}

__.extend(Publicip.prototype, {
  create: function (resourceGroupName, name, params, _) {
    var self = this;
    var publicipProfile = self._parsePublicIP(name, params);

    var publicip = self.get(resourceGroupName, name, _);
    if (publicip) {
      throw new Error(util.format($('A public ip address with name "%s" already exists in the resource group "%s"'), name, resourceGroupName));
    }

    var progress = self.interaction.progress(util.format($('Creating public ip address "%s"'), name));
    try {
      self.networkResourceProviderClient.publicIpAddresses.createOrUpdate(resourceGroupName, name, publicipProfile, _);
    } finally {
      progress.end();
    }
    self.show(resourceGroupName, name, params, _);
  },

  set: function (resourceGroupName, name, params, _) {
    var self = this;
    var publicipProfile = self._parsePublicIP(name, params);

    var publicip = self.get(resourceGroupName, name, _);
    if (!publicip) {
      throw new Error(util.format($('A public ip address with name "%s" not found in the resource group "%s"'), name, resourceGroupName));
    }

    if (params.idletimeout) publicip.publicIpAddress.idleTimeoutInMinutes = publicipProfile.idleTimeoutInMinutes;
    if (params.allocationMethod) publicip.publicIpAddress.publicIpAllocationMethod = publicipProfile.publicIpAllocationMethod;

    var optionalDomainLabel = utils.getOptionalArg(params.domainNameLabel);
    if (optionalDomainLabel.hasValue) {
      if (optionalDomainLabel.value !== null) {
        self._createDnsSettingsIfNotExist(publicip.publicIpAddress);
        publicip.publicIpAddress.dnsSettings.domainNameLabel = publicipProfile.dnsSettings.domainNameLabel;
      } else {
        delete publicip.publicIpAddress.dnsSettings;
      }
    }

    var optionalReverseFqdn = utils.getOptionalArg(params.reverseFqdn);
    if (optionalReverseFqdn.hasValue) {
      if (optionalReverseFqdn.value !== null) {
        self._createDnsSettingsIfNotExist(publicip.publicIpAddress);
        publicip.publicIpAddress.dnsSettings.reverseFqdn = publicipProfile.dnsSettings.reverseFqdn;
      } else {
        delete publicip.publicIpAddress.dnsSettings.reverseFqdn;
      }
    }

    if (params.tags) {
      tagUtils.appendTags(publicip.publicIpAddress, publicipProfile.tags);
    }

    if (params.tags === false) {
      publicip.publicIpAddress.tags = {};
    }

    self.update(resourceGroupName, name, publicip.publicIpAddress, _);
    self.show(resourceGroupName, name, params, _);
  },

  show: function (resourceGroupName, name, params, _) {
    var self = this;
    var publicIP = self.get(resourceGroupName, name, _);

    if (publicIP) {
      var resourceInfo = resourceUtils.getResourceInformation(publicIP.publicIpAddress.id);
      self.interaction.formatOutput(publicIP.publicIpAddress, function (publicip) {
        self.output.nameValue($('Id'), publicip.id);
        self.output.nameValue($('Name'), publicip.name);
        self.output.nameValue($('Type'), resourceInfo.resourceType);
        self.output.nameValue($('Location'), publicip.location);
        self.output.nameValue($('Provisioning state'), publicip.provisioningState);
        self.output.nameValue($('Tags'), tagUtils.getTagsInfo(publicip.tags));
        self.output.nameValue($('Allocation method'), publicip.publicIpAllocationMethod);
        self.output.nameValue($('Idle timeout'), publicip.idleTimeoutInMinutes);
        self.output.nameValue($('IP Address'), publicip.ipAddress);
        if (publicip.dnsSettings) {
          var dnsSettings = publicip.dnsSettings;
          self.output.nameValue($('Domain name label'), dnsSettings.domainNameLabel);
          self.output.nameValue($('FQDN'), dnsSettings.fqdn);
          self.output.nameValue($('Reverse FQDN'), dnsSettings.reverseFqdn);
        }
      });
    } else {
      if (self.output.format().json) {
        self.output.json({});
      } else {
        self.output.warn(util.format($('A public ip address with name "%s" not found in the resource group "%s"'), name, resourceGroupName));
      }
    }
  },

  delete: function (resourceGroupName, name, params, _) {
    var self = this;
    var publicIP = self.get(resourceGroupName, name, _);

    if (!publicIP) {
      throw new Error(util.format($('A public ip address with name "%s" not found in the resource group "%s"'), name, resourceGroupName));
    }

    if (!params.quiet && !self.interaction.confirm(util.format($('Delete public ip address "%s"? [y/n] '), name), _)) {
      return;
    }

    var progress = self.interaction.progress(util.format($('Deleting public ip address "%s"'), name));
    try {
      self.networkResourceProviderClient.publicIpAddresses.deleteMethod(resourceGroupName, name, _);
    } finally {
      progress.end();
    }
  },

  list: function (resourceGroupName, params, _) {
    var self = this;
    var progress = self.interaction.progress($('Getting the public ip addresses'));

    var publicIPs = null;
    try {
      publicIPs = self.networkResourceProviderClient.publicIpAddresses.list(resourceGroupName, _);
    } finally {
      progress.end();
    }

    self.interaction.formatOutput(publicIPs.publicIpAddresses, function (data) {
      if (data.length === 0) {
        self.output.warn($('No public ip address found'));
      } else {
        self.output.table(data, function (row, publicip) {
          row.cell($('Name'), publicip.name);
          row.cell($('Location'), publicip.location);
          row.cell($('Allocation'), publicip.publicIpAllocationMethod);
          row.cell($('IP Address'), publicip.ipAddress || '');
          row.cell($('Idle timeout'), publicip.idleTimeoutInMinutes || '');
          var dnsName = '';
          if (publicip.dnsSettings) {
            dnsName = publicip.dnsSettings.fqdn;
          }
          row.cell($('DNS Name'), dnsName);
        });
      }
    });
  },

  get: function (resourceGroupName, name, _) {
    var self = this;
    var progress = self.interaction.progress(util.format($('Looking up the public ip "%s"'), name));

    try {
      var publicIP = self.networkResourceProviderClient.publicIpAddresses.get(resourceGroupName, name, _);
      return publicIP;
    } catch (e) {
      if (e.code === 'ResourceNotFound') {
        return null;
      }
      throw e;
    } finally {
      progress.end();
    }
  },

  update: function (resourceGroupName, name, publicIpProfile, _) {
    var self = this;
    var progress = self.interaction.progress(util.format($('Updating public ip address "%s"'), name));

    try {
      self.networkResourceProviderClient.publicIpAddresses.createOrUpdate(resourceGroupName, name, publicIpProfile, _);
    } catch (e) {
      throw e;
    } finally {
      progress.end();
    }
  },

  _parsePublicIP: function (name, params) {
    var supportedAllocationTypes = ['Dynamic', 'Static'];
    var self = this;

    var publicipProfile = {
      name: name,
      publicIpAllocationMethod: supportedAllocationTypes[0]
    };

    if (params.idletimeout) {
      var timeoutAsInt = utils.parseInt(params.idletimeout);
      if (isNaN(timeoutAsInt) || timeoutAsInt === 0) {
        throw new Error($('idletimeout parameter must be an integer'));
      }
      publicipProfile.idleTimeoutInMinutes = timeoutAsInt;
    }

    if (params.allocationMethod) {
      if (utils.stringIsNullOrEmpty(params.allocationMethod)) {
        throw new Error($('allocation method parameter must not be null or empty string'));
      }
      publicipProfile.publicIpAllocationMethod = utils.verifyParamExistsInCollection(supportedAllocationTypes,
        params.allocationMethod, 'allocationMethod');
    }

    if (params.domainNameLabel) {
      self._createDnsSettingsIfNotExist(publicipProfile);
      publicipProfile.dnsSettings.domainNameLabel = params.domainNameLabel;
    }

    if (params.reverseFqdn) {
      self._createDnsSettingsIfNotExist(publicipProfile);
      publicipProfile.dnsSettings.reverseFqdn = params.reverseFqdn;
    }

    if (params.tags) {
      publicipProfile.tags = tagUtils.buildTagsParameter(null, params);
    }

    if (params.location) {
      publicipProfile.location = params.location;
    }

    return publicipProfile;
  },

  _createDnsSettingsIfNotExist: function (publicip) {
    if (!publicip.dnsSettings) publicip.dnsSettings = {};
  }
});

module.exports = Publicip;<|endoftext|>


<commit_before>(function () {
    'use strict';
    angular
        .module('app.form')
        .controller('busFormController', busFormController);

    function busFormController() {
        console.log('load busFormController');
        var vm = this;

        vm.form1 = true;
        vm.nohelp = false;

        vm.form = {
            premium: null,
            worker: null,
            admin: null,
            payroll: null
        };

        vm.next = function next() {
            console.log('next!');
            vm.form1 = false;
            vm.healthexpense = vm.form.premium +
                vm.form.worker * 0.59 +
                vm.form.admin;
            vm.healthexpense.toFixed(2);
            vm.ccexpense = vm.form.payroll*0.0333;
            vm.ccexpense.toFixed(2);
            vm.difference = vm.healthexpense - vm.ccexpense;
            vm.difference.toFixed(2);
        };

        vm.back = function back() {
            vm.form1 = true;
        };

        vm.clear = function clear() {
            vm.form = {
                premium: null,
                worker: null,
                admin: null,
                payroll: null
            };
        };
    }
})();<commit_msg>added hidden tooltips<commit_after>(function () {
    'use strict';
    angular
        .module('app.form')
        .controller('busFormController', busFormController);

    function busFormController() {
        console.log('load busFormController');
        var vm = this;

        vm.form1 = true;
        vm.nohelp = false;

        vm.form = {
            premium: null,
            worker: null,
            admin: null,
            payroll: null
        };

        vm.next = function next() {
            console.log('next!');
            vm.form1 = false;
            vm.healthexpense = vm.form.premium +
                vm.form.worker * 0.59 +
                vm.form.admin;
            vm.healthexpense.toFixed(2);
            vm.ccexpense = vm.form.payroll*0.067;
            vm.ccexpense.toFixed(2);
            vm.difference = vm.healthexpense - vm.ccexpense;
            vm.difference.toFixed(2);
        };

        vm.back = function back() {
            vm.form1 = true;
        };

        vm.clear = function clear() {
            vm.form = {
                premium: null,
                worker: null,
                admin: null,
                payroll: null
            };
        };
    }
})();<|endoftext|>


<commit_before>Tinytest.add(
  'Tracer - trace-method',
  function (test) {
    var ddpMessage = {
      id: 'the-id',
      msg: 'method',
      method: 'method-name'
    };
    var traceInfo = Apm.tracer.start({id: 'session-id', userId: 'uid'}, ddpMessage);
    Apm.tracer.event(traceInfo, 'start', {abc: 100});
    Apm.tracer.event(traceInfo, 'end', {abc: 200});
    removeDate(traceInfo);
    test.equal(traceInfo, {
      _id: 'session-id::the-id',
      id: 'the-id',
      session: 'session-id',
      userId: "uid",
      type: 'method',
      name: 'method-name',
      events: [
        ['start', 0, {abc: 100}],
        ['end', 0, {abc: 200}]
      ]
    });
  }
);

function removeDate (traceInfo) {
  traceInfo.events.forEach(function (event) {
    event[1] = 0;
  });
}
<commit_msg>Finish tracer tests<commit_after>Tinytest.add(
  'Tracer - Trace Method - method',
  function (test) {
    var ddpMessage = {
      id: 'the-id',
      msg: 'method',
      method: 'method-name'
    };
    var traceInfo = Apm.tracer.start({id: 'session-id', userId: 'uid'}, ddpMessage);
    Apm.tracer.event(traceInfo, 'start', {abc: 100});
    Apm.tracer.event(traceInfo, 'end', {abc: 200});
    removeDate(traceInfo);
    var expected = {
      _id: 'session-id::the-id',
      id: 'the-id',
      session: 'session-id',
      userId: "uid",
      type: 'method',
      name: 'method-name',
      events: [
        {type: 'start', data: {abc: 100}},
        {type: 'end', data: {abc: 200}}
      ]
    };
    test.equal(traceInfo, expected);
  }
);

Tinytest.add(
  'Tracer - Trace Method - complete after errored',
  function (test) {
    var ddpMessage = {
      id: 'the-id',
      msg: 'method',
      method: 'method-name'
    };
    var traceInfo = Apm.tracer.start({id: 'session-id', userId: 'uid'}, ddpMessage);
    Apm.tracer.event(traceInfo, 'start');
    Apm.tracer.event(traceInfo, 'error');
    Apm.tracer.event(traceInfo, 'complete');
    removeDate(traceInfo);
    var expected = {
      _id: 'session-id::the-id',
      id: 'the-id',
      session: 'session-id',
      userId: "uid",
      type: 'method',
      name: 'method-name',
      events: [
        {type: 'start'},
        {type: 'error'}
      ],
    };
    test.equal(traceInfo, expected);
  }
);

Tinytest.add(
  'Tracer - trace sub',
  function (test) {
    var ddpMessage = {
      id: 'the-id',
      msg: 'sub',
      name: 'sub-name'
    };
    var traceInfo = Apm.tracer.start({id: 'session-id'}, ddpMessage);
    Apm.tracer.event(traceInfo, 'start', {abc: 100});
    Apm.tracer.event(traceInfo, 'end', {abc: 200});
    removeDate(traceInfo);
    var expected = {
      _id: 'session-id::the-id',
      session: 'session-id',
      id: 'the-id',
      events: [
        {type: 'start', data: {abc: 100}},
        {type: 'end', data: {abc: 200}}
      ],
      type: 'sub',
      name: 'sub-name'
    };
    delete traceInfo.userId;
    test.equal(traceInfo, expected);
  }
);

Tinytest.add(
  'Tracer - trace other ddp',
  function (test) {
    var ddpMessage = {
      id: 'the-id',
      msg: 'unsub',
      name: 'sub-name'
    };
    var traceInfo = Apm.tracer.start({id: 'session-id'}, ddpMessage);
    test.equal(traceInfo, null);
  }
);

Tinytest.add(
  'Tracer - trace other events',
  function (test) {
    var ddpMessage = {
      id: 'the-id',
      msg: 'method',
      method: 'method-name'
    };
    var traceInfo = Apm.tracer.start({id: 'session-id'}, ddpMessage);
    Apm.tracer.event(traceInfo, 'start', {abc: 100});
    var eventId = Apm.tracer.event(traceInfo, 'db');
    Apm.tracer.eventEnd(traceInfo, eventId);
    Apm.tracer.event(traceInfo, 'end', {abc: 200});
    removeDate(traceInfo);
    var expected = {
      _id: 'session-id::the-id',
      id: 'the-id',
      session: 'session-id',
      type: 'method',
      name: 'method-name',
      events: [
        {type: 'start', data: {abc: 100}},
        {type: 'db'},
        {type: 'dbend'},
        {type: 'end', data: {abc: 200}}
      ],
      _lastEventId: null
    };
    delete traceInfo.userId;
    test.equal(traceInfo, expected);
  }
);

Tinytest.add(
  'Tracer - invalid eventId',
  function (test) {
    var ddpMessage = {
      id: 'the-id',
      msg: 'method',
      method: 'method-name'
    };
    var traceInfo = Apm.tracer.start({id: 'session-id'}, ddpMessage);
    Apm.tracer.event(traceInfo, 'start', {abc: 100});
    var eventId = Apm.tracer.event(traceInfo, 'db');
    Apm.tracer.event(traceInfo, 'db');
    Apm.tracer.eventEnd(traceInfo, 'invalid-eventId');
    Apm.tracer.event(traceInfo, 'end', {abc: 200});
    delete traceInfo._lastEventId;
    removeDate(traceInfo);
    var expected = {
      _id: 'session-id::the-id',
      id: 'the-id',
      session: 'session-id',
      type: 'method',
      name: 'method-name',
      events: [
        {type: 'start', data: {abc: 100}},
        {type: 'db'},
        {type: 'end', data: {abc: 200}}
      ]
    };
    delete traceInfo.userId;
    test.equal(traceInfo, expected);
  }
);

Tinytest.add(
  'Tracer - end last event',
  function (test) {
    var ddpMessage = {
      id: 'the-id',
      msg: 'method',
      method: 'method-name'
    };
    var traceInfo = Apm.tracer.start({id: 'session-id'}, ddpMessage);
    Apm.tracer.event(traceInfo, 'start', {abc: 100});
    var eventId = Apm.tracer.event(traceInfo, 'db');
    Apm.tracer.event(traceInfo, 'db');
    Apm.tracer.endLastEvent(traceInfo);
    Apm.tracer.event(traceInfo, 'end', {abc: 200});
    delete traceInfo._lastEventId;
    removeDate(traceInfo);
    var expected = {
      _id: 'session-id::the-id',
      id: 'the-id',
      session: 'session-id',
      type: 'method',
      name: 'method-name',
      events: [
        {type: 'start', data: {abc: 100}},
        {type: 'db'},
        {type: 'dbend'},
        {type: 'end', data: {abc: 200}}
      ]
    };
    delete traceInfo.userId;
    test.equal(traceInfo, expected);
  }
);

Tinytest.add(
  'Tracer - trace same event twice',
  function (test) {
    var ddpMessage = {
      id: 'the-id',
      msg: 'method',
      method: 'method-name'
    };
    var traceInfo = Apm.tracer.start({id: 'session-id'}, ddpMessage);
    Apm.tracer.event(traceInfo, 'start', {abc: 100});
    var eventId = Apm.tracer.event(traceInfo, 'db');
    Apm.tracer.event(traceInfo, 'db');
    Apm.tracer.eventEnd(traceInfo, eventId);
    Apm.tracer.event(traceInfo, 'end', {abc: 200});
    removeDate(traceInfo);
    var expected = {
      _id: 'session-id::the-id',
      id: 'the-id',
      session: 'session-id',
      type: 'method',
      name: 'method-name',
      events: [
        {type: 'start', data: {abc: 100}},
        {type: 'db'},
        {type: 'dbend'},
        {type: 'end', data: {abc: 200}}
      ],
      _lastEventId: null
    };
    delete traceInfo.userId;
    test.equal(traceInfo, expected);
  }
);

Tinytest.add(
  'Tracer - Build Trace - simple',
  function (test) {
    var now = Date.now();
    var traceInfo = {
      events: [
        {type: 'start', at: now},
        {type: 'wait', at: now},
        {type: 'waitend', at: now + 1000},
        {type: 'db', at: now + 2000},
        {type: 'dbend', at: now + 2500},
        {type: 'complete', at: now + 2500}
      ]
    };
    Apm.tracer.buildTrace(traceInfo);
    test.equal(traceInfo.metrics, {
      total: 2500,
      wait: 1000,
      db: 500,
      compute: 1000,
    });
    test.equal(traceInfo.errored, false);
  }
);

Tinytest.add(
  'Tracer - Build Trace - errored',
  function (test) {
    var now = Date.now();
    var traceInfo = {
      events: [
        {type: 'start', at: now},
        {type: 'wait', at: now},
        {type: 'waitend', at: now + 1000},
        {type: 'db', at: now + 2000},
        {type: 'dbend', at: now + 2500},
        {type: 'error', at: now + 2500}
      ]
    };
    Apm.tracer.buildTrace(traceInfo);
    test.equal(traceInfo.metrics, {
      total: 2500,
      wait: 1000,
      db: 500,
      compute: 1000,
    });
    test.equal(traceInfo.errored, true);
  }
);

Tinytest.add(
  'Tracer - Build Trace - no start',
  function (test) {
    var now = Date.now();
    var traceInfo = {
      events: [
        {type: 'wait', at: now},
        {type: 'waitend', at: now + 1000},
        {type: 'db', at: now + 2000},
        {type: 'dbend', at: now + 2500},
        {type: 'complete', at: now + 2500}
      ]
    };
    Apm.tracer.buildTrace(traceInfo);
    test.equal(traceInfo.metrics, undefined);
  }
);

Tinytest.add(
  'Tracer - Build Trace - no complete',
  function (test) {
    var now = Date.now();
    var traceInfo = {
      events: [
        {type: 'start', at: now},
        {type: 'wait', at: now},
        {type: 'waitend', at: now + 1000},
        {type: 'db', at: now + 2000},
        {type: 'dbend', at: now + 2500}
      ]
    };
    Apm.tracer.buildTrace(traceInfo);
    test.equal(traceInfo.metrics, undefined);
  }
);

Tinytest.add(
  'Tracer - Build Trace - event not ended',
  function (test) {
    var now = Date.now();
    var traceInfo = {
      events: [
        {type: 'start', at: now},
        {type: 'wait', at: now},
        {type: 'db', at: now + 2000},
        {type: 'dbend', at: now + 2500},
        {type: 'complete', at: now + 2500}
      ]
    };
    Apm.tracer.buildTrace(traceInfo);
    test.equal(traceInfo.metrics, undefined);
  }
);

function removeDate(traceInfo) {
  traceInfo.events.forEach(function(event) {
    delete event.at;
  });
}
<|endoftext|>


<commit_before>"use strict";
import {
  hasProperty
} from '../util/Utility';

const ActionStates = Object.freeze({
  DOWN: 'down',
  UP: 'up',
  PRESSED: 'pressed'
});

const Modifiers = Object.freeze({
  LSHIFT: 'l_shift',
  RSHIFT: 'r_shift',
  LALT: 'l_alt',
  RALT: 'r_alt',
  LCONTROL: 'l_ctrl',
  RCONTROL: 'r_ctrl',
  LMETA: 'l_meta',
  RMETA: 'r_meta'
});

const Input = {
  //Maintains a flag indicating which modifiers are pressed
  modifiers: {
    l_shift: false,
    r_shift: false,
    l_alt: false,
    r_alt: false,
    l_ctrl: false,
    r_ctrl: false,
    l_meta: false,
    r_meta: false
  },
  //Maintains a map of keys to action states
  keys: {}
};

function findModifierForEvent(event) {
  const key = event.key;
  const locationLeft = (event.location === KeyboardEvent.DOM_KEY_LOCATION_STANDARD || event.location === KeyboardEvent.DOM_KEY_LOCATION_LEFT);
  const locationRight = (event.location === KeyboardEvent.DOM_KEY_LOCATION_STANDARD || event.location === KeyboardEvent.DOM_KEY_LOCATION_RIGHT);

  switch (key) {

    case 'Shift':
      {
        return locationLeft ? Modifiers.LSHIFT : Modifiers.RSHIFT;
      }

    case 'Control':
      {
        return locationLeft ? Modifiers.LCONTROL : Modifiers.RCONTROL;
      }

    case 'Meta':
      {
        return locationLeft ? Modifiers.LMETA : Modifiers.RMETA;
      }

    case 'Alt':
      {
        return locationLeft ? Modifiers.LALT : Modifiers.RALT;
      }

    default:
      {
        return null;
      }
  }
}

function setup() {
  document.addEventListener('keydown', event => {
    //Update modifier state
    const modifier = findModifierForEvent(event);
    if (modifier !== null) {
      Input.modifiers[modifier] = true;
    }

    const key = event.key;
    if(hasProperty(Input.keys, key)) {
      Input.keys[key] = ActionStates.PRESSED;
    } else {
      Input.keys[key] = ActionStates.DOWN;
    }
  });
  document.addEventListener('keyup', event => {
    //Update modifier state
    const modifier = findModifierForEvent(event);
    if (modifier !== null) {
      Input.modifiers[modifier] = false;
    }
    const key = event.key;
    if(hasProperty(Input.keys, key)) {
      const actionState = Input.keys[key];
      if(actionState === ActionStates.DOWN || actionState === ActionStates.PRESSED) {
        Input.keys[key] = ActionStates.UP;
      }
    }
  });
}

setup();

const api = Object.freeze({
  modifier: function (code) {
    if (hasProperty(Input.modifiers, code)) {
      return Input.modifiers[code];
    }

    return false;
  },
  keyDown: function (key) {
    if(hasProperty(Input.keys, key)) {
      return Input.keys[key] === ActionStates.DOWN;
    }

    return false;
  },
  keyUp: function (key) {
    if(hasProperty(Input.keys, key)) {
      return Input.keys[key] === ActionStates.UP;
    }

    return false;
  },
  key: function (key) {
    if(hasProperty(Input.keys, key)) {
      return Input.keys[key] === ActionStates.DOWN || Input.keys[key] === ActionStates.PRESSED;
    }

    return false;
  },
  //For internal use only
  onFrameEnd: function() {
    let actionState;
    for(let key in Input.keys) {
      if(hasProperty(Input.keys, key)) {
        actionState = Input.keys[key];
        if(ActionStates.UP === actionState) {
          delete Input.keys[key];
        }
      }
    }
  }
});

export {
  ActionStates,
  Modifiers,
  api as Input
};
<commit_msg>Better conversion of input key state from down to pressed<commit_after>"use strict";
import {
  hasProperty
} from '../util/Utility';

const ActionStates = Object.freeze({
  DOWN: 'down',
  UP: 'up',
  PRESSED: 'pressed'
});

const Modifiers = Object.freeze({
  LSHIFT: 'l_shift',
  RSHIFT: 'r_shift',
  LALT: 'l_alt',
  RALT: 'r_alt',
  LCONTROL: 'l_ctrl',
  RCONTROL: 'r_ctrl',
  LMETA: 'l_meta',
  RMETA: 'r_meta'
});

const Input = {
  //Maintains a flag indicating which modifiers are pressed
  modifiers: {
    l_shift: false,
    r_shift: false,
    l_alt: false,
    r_alt: false,
    l_ctrl: false,
    r_ctrl: false,
    l_meta: false,
    r_meta: false
  },
  //Maintains a map of keys to action states
  keys: {}
};

function findModifierForEvent(event) {
  const key = event.key;
  const locationLeft = (event.location === KeyboardEvent.DOM_KEY_LOCATION_STANDARD || event.location === KeyboardEvent.DOM_KEY_LOCATION_LEFT);
  const locationRight = (event.location === KeyboardEvent.DOM_KEY_LOCATION_STANDARD || event.location === KeyboardEvent.DOM_KEY_LOCATION_RIGHT);

  switch (key) {

    case 'Shift':
      {
        return locationLeft ? Modifiers.LSHIFT : Modifiers.RSHIFT;
      }

    case 'Control':
      {
        return locationLeft ? Modifiers.LCONTROL : Modifiers.RCONTROL;
      }

    case 'Meta':
      {
        return locationLeft ? Modifiers.LMETA : Modifiers.RMETA;
      }

    case 'Alt':
      {
        return locationLeft ? Modifiers.LALT : Modifiers.RALT;
      }

    default:
      {
        return null;
      }
  }
}

function setup() {
  document.addEventListener('keydown', event => {
    //Update modifier state
    const modifier = findModifierForEvent(event);
    if (modifier !== null) {
      Input.modifiers[modifier] = true;
    }

    const key = event.key;
    if(!hasProperty(Input.keys, key)) {
      Input.keys[key] = ActionStates.DOWN;
    }
  });
  document.addEventListener('keyup', event => {
    //Update modifier state
    const modifier = findModifierForEvent(event);
    if (modifier !== null) {
      Input.modifiers[modifier] = false;
    }
    const key = event.key;
    if(hasProperty(Input.keys, key)) {
      const actionState = Input.keys[key];
      if(actionState === ActionStates.DOWN || actionState === ActionStates.PRESSED) {
        Input.keys[key] = ActionStates.UP;
      }
    }
  });
}

setup();

const api = Object.freeze({
  modifier: function (code) {
    if (hasProperty(Input.modifiers, code)) {
      return Input.modifiers[code];
    }

    return false;
  },
  keyDown: function (key) {
    if(hasProperty(Input.keys, key)) {
      return Input.keys[key] === ActionStates.DOWN;
    }

    return false;
  },
  keyUp: function (key) {
    if(hasProperty(Input.keys, key)) {
      return Input.keys[key] === ActionStates.UP;
    }

    return false;
  },
  key: function (key) {
    if(hasProperty(Input.keys, key)) {
      return Input.keys[key] === ActionStates.DOWN || Input.keys[key] === ActionStates.PRESSED;
    }

    return false;
  },
  //For internal use only
  onFrameEnd: function() {
    let actionState;
    for(let key in Input.keys) {
      if(hasProperty(Input.keys, key)) {
        actionState = Input.keys[key];
        if(ActionStates.UP === actionState) {
          delete Input.keys[key];
        } else if(ActionStates.DOWN === actionState) {
          Input.keys[key] = ActionStates.PRESSED;
        }
      }
    }
  }
});

export {
  ActionStates,
  Modifiers,
  api as Input
};
<|endoftext|>


<commit_before>var SqlParser = Editor.Parser = (function() {

  function wordRegexp(words) {
    return new RegExp("^(?:" + words.join("|") + ")$", "i");
  }

  var functions = wordRegexp([
    "abs", "acos", "adddate", "aes_encrypt", "aes_decrypt", "ascii",
    "asin", "atan", "atan2", "avg", "benchmark", "bin", "bit_and",
    "bit_count", "bit_length", "bit_or", "cast", "ceil", "ceiling",
    "char_length", "character_length", "checksum_agg", "coalesce", "concat", "concat_ws",
    "connection_id", "conv", "convert", "cos", "cot", "count", "curdate",
    "current_date", "current_time", "current_timestamp", "current_user",
    "curtime", "database", "dateadd", "datediff", "datename", "datepart",
    "day", "dayofmonth", "dayofweek", "dayofyear", "decode", "degrees", "dense_rank",
    "des_encrypt", "des_decrypt", "elt", "encode", "encrypt", "exp",
    "export_set", "extract", "field", "find_in_set", "floor", "format",
    "found_rows", "from_days", "from_unixtime", "get_lock", "getdate", "getutcdate", "greatest",
    "group_unique_users", "grouping", "hex", "ifnull", "inet_aton", "inet_ntoa", "instr",
    "interval", "is_free_lock", "isnull", "last_insert_id", "lcase", "least",
    "left", "length", "ln", "load_file", "locate", "log", "log2", "log10",
    "lower", "lpad", "ltrim", "make_set", "master_pos_wait", "max", "md5",
    "mid", "min", "mod", "month", "now", "ntile", "nullif", "oct", "octet_length",
    "ord", "password", "period_add", "period_diff", "pi", "position",
    "pow", "power", "quarter", "quote", "radians", "rand", "rank", "release_lock",
    "repeat", "reverse", "right", "round", "row_number", "rpad", "rtrim", "sec_to_time",
    "session_user", "sha", "sha1", "sign", "sin", "soundex", "space", "sqrt",
    "std", "stdev", "stdevp", "strcmp", "subdate", "substring", "substring_index",
    "sum", "sysdate", "system_user", "tan", "time_format", "time_to_sec",
    "to_days", "trim", "ucase", "unique_users", "unix_timestamp", "upper",
    "user", "var", "varp", "version", "week", "weekday", "year", "yearweek"
  ]);

  var keywords = wordRegexp([
    "alter", "grant", "revoke", "primary", "key", "table", "start", "top",
    "transaction", "select", "update", "insert", "delete", "create", "describe",
    "from", "into", "values", "where", "join", "inner", "left", "natural", "and",
    "or", "in", "not", "xor", "like", "using", "on", "order", "group", "by",
    "case", "when", "then", "else", "end", "with", "rollup", "cube", "over", "partition",
    "asc", "desc", "limit", "offset", "union", "all", "as", "distinct", "set",
    "commit", "rollback", "replace", "view", "database", "separator", "if",
    "exists", "null", "truncate", "status", "show", "lock", "unique", "having"
  ]);

  var types = wordRegexp([
    "bigint", "binary", "bit", "blob", "bool", "char", "character", "date",
    "datetime", "dec", "decimal", "double", "enum", "float", "float4", "float8",
    "int", "int1", "int2", "int3", "int4", "int8", "integer", "long", "longblob",
    "longtext", "mediumblob", "mediumint", "mediumtext", "middleint", "nchar",
    "numeric", "real", "set", "smallint", "text", "time", "timestamp", "tinyblob",
    "tinyint", "tinytext", "varbinary", "varchar", "string" // <- this is an SEDE hack
  ]);

  var operators = wordRegexp([
    ":=", "<", "<=", "==", "<>", ">", ">=", "like", "rlike", "in", "xor", "between"
  ]);

  var operatorChars = /[*+\-<>=&|:\/]/;

  var tokenizeSql = (function() {
    function normal(source, setState) {
      var ch = source.next();
      if (ch == "@" || ch == "$") {
        source.nextWhileMatches(/[\w\d]/);
        return "sql-var";
      }
      else if (ch == "["){
	    setState(inAlias(ch))
	  	return null;
      }
      else if (ch == "\"" || ch == "'" || ch == "`") {
        setState(inLiteral(ch));
        return null;
      }
      else if (ch == "," || ch == ";") {
        return "sql-separator"
      }
      else if (ch == '-') {
        if (source.peek() == "-") {
          while (!source.endOfLine()) source.next();
          return "sql-comment";
        }
        else if (/\d/.test(source.peek())) {
          source.nextWhileMatches(/\d/);
          if (source.peek() == '.') {
            source.next();
            source.nextWhileMatches(/\d/);
          }
          return "sql-number";
        }
        else
          return "sql-operator";
      }
      else if (operatorChars.test(ch)) {
        source.nextWhileMatches(operatorChars);
        return "sql-operator";
      }
      else if (/\d/.test(ch)) {
        source.nextWhileMatches(/\d/);
        if (source.peek() == '.') {
          source.next();
          source.nextWhileMatches(/\d/);
        }
        return "sql-number";
      }
      else if (/[()]/.test(ch)) {
        return "sql-punctuation";
      }
      else {
        source.nextWhileMatches(/[_\w\d]/);
        var word = source.get(), type;
        if (operators.test(word))
          type = "sql-operator";
        else if (keywords.test(word))
          type = "sql-keyword";
        else if (functions.test(word))
          type = "sql-function";
        else if (types.test(word))
          type = "sql-type";
        else
          type = "sql-word";
        return {style: type, content: word};
      }
    }

    function inAlias(quote) {
	  return function(source, setState) {
	    while (!source.endOfLine()) {
		  var ch = source.next();
		  if (ch == ']') {
		    setState(normal);
		    break;
		  }
	    }
	    return "sql-word";
	  }
    }

    function inLiteral(quote) {
      return function(source, setState) {
        var escaped = false;
        while (!source.endOfLine()) {
          var ch = source.next();
          if (ch == quote && !escaped) {
            setState(normal);
            break;
          }
          escaped = !escaped && ch == "\\";
        }
        return quote == "`" ? "sql-word" : "sql-literal";
      };
    }

    return function(source, startState) {
      return tokenizer(source, startState || normal);
    };
  })();

  function indentSql(context) {
    return function(nextChars) {
      var firstChar = nextChars && nextChars.charAt(0);
      var closing = context && firstChar == context.type;
      if (!context)
        return 0;
      else if (context.align)
        return context.col - (closing ? context.width : 0);
      else
        return context.indent + (closing ? 0 : indentUnit);
    }
  }

  function parseSql(source) {
    var tokens = tokenizeSql(source);
    var context = null, indent = 0, col = 0;
    function pushContext(type, width, align) {
      context = {prev: context, indent: indent, col: col, type: type, width: width, align: align};
    }
    function popContext() {
      context = context.prev;
    }

    var iter = {
      next: function() {
        var token = tokens.next();
        var type = token.style, content = token.content, width = token.value.length;

        if (content == "\n") {
          // token.indentation = indentSql(context);
          indent = col = 0;
          if (context && context.align == null) context.align = false;
        }
        else if (type == "whitespace" && col == 0) {
          indent = width;
        }
        else if (!context && type != "sql-comment") {
          pushContext(";", 0, false);
        }

        if (content != "\n") col += width;

        if (type == "sql-punctuation") {
          if (content == "(")
            pushContext(")", width);
          else if (content == ")")
            popContext();
        }
        else if (type == "sql-separator" && content == ";" && context && !context.prev) {
          popContext();
        }

        return token;
      },

      copy: function() {
        var _context = context, _indent = indent, _col = col, _tokenState = tokens.state;
        return function(source) {
          tokens = tokenizeSql(source, _tokenState);
          context = _context;
          indent = _indent;
          col = _col;
          return iter;
        };
      }
    };
    return iter;
  }

  // electric chars are just confusing
  return {make: parseSql, electricChars: ""};
})();
<commit_msg>Added more keyword highlighting<commit_after>var SqlParser = Editor.Parser = (function() {

  function wordRegexp(words) {
    return new RegExp("^(?:" + words.join("|") + ")$", "i");
  }

  var functions = wordRegexp([
    "abs", "acos", "adddate", "aes_encrypt", "aes_decrypt", "ascii",
    "asin", "atan", "atan2", "avg", "benchmark", "bin", "bit_and",
    "bit_count", "bit_length", "bit_or", "cast", "ceil", "ceiling",
    "char_length", "character_length", "checksum_agg", "coalesce", "concat", "concat_ws",
    "connection_id", "conv", "convert", "cos", "cot", "count", "curdate",
    "current_date", "current_time", "current_timestamp", "current_user",
    "curtime", "database", "dateadd", "datediff", "datename", "datepart",
    "day", "dayofmonth", "dayofweek", "dayofyear", "decode", "degrees", "dense_rank",
    "des_encrypt", "des_decrypt", "elt", "encode", "encrypt", "exp",
    "export_set", "extract", "field", "find_in_set", "floor", "format",
    "found_rows", "from_days", "from_unixtime", "get_lock", "getdate", "getutcdate", "greatest",
    "group_unique_users", "grouping", "hex", "ifnull", "inet_aton", "inet_ntoa", "instr",
    "interval", "is_free_lock", "isnull", "last_insert_id", "lcase", "least",
    "left", "length", "ln", "load_file", "locate", "log", "log2", "log10",
    "lower", "lpad", "ltrim", "make_set", "master_pos_wait", "max", "md5",
    "mid", "min", "mod", "month", "now", "ntile", "nullif", "oct", "octet_length",
    "ord", "password", "period_add", "period_diff", "pi", "position",
    "pow", "power", "quarter", "quote", "radians", "rand", "rank", "release_lock",
    "repeat", "reverse", "right", "round", "row_number", "rpad", "rtrim", "sec_to_time",
    "session_user", "sha", "sha1", "sign", "sin", "soundex", "space", "sqrt",
    "std", "stdev", "stdevp", "strcmp", "subdate", "substring", "substring_index",
    "sum", "sysdate", "system_user", "tan", "time_format", "time_to_sec",
    "to_days", "trim", "ucase", "unique_users", "unix_timestamp", "upper",
    "user", "var", "varp", "version", "week", "weekday", "year", "yearweek"
  ]);

  var keywords = wordRegexp([
    "alter", "grant", "revoke", "primary", "key", "clustered", "nonclustered", "table", "start", "top",
    "begin", "tran", "transaction", "select", "update", "insert", "delete", "merge", "create", "describe", "declare",
    "from", "into", "values", "where", "join", "inner", "left", "outer", "natural", "cross", "apply", "except", "and",
    "or", "in", "not", "xor", "like", "using", "on", "order", "group", "by",
    "case", "when", "then", "else", "end", "with", "rollup", "cube", "over", "partition",
    "asc", "desc", "limit", "offset", "union", "all", "as", "distinct", "set",
    "commit", "rollback", "replace", "view", "database", "separator", "if", "for", "while",
    "exists", "null", "truncate", "status", "show", "lock", "unique", "having"
  ]);

  var types = wordRegexp([
    "bigint", "binary", "bit", "blob", "bool", "char", "character", "date",
    "datetime", "dec", "decimal", "double", "enum", "float", "float4", "float8",
    "int", "int1", "int2", "int3", "int4", "int8", "integer", "long", "longblob",
    "longtext", "mediumblob", "mediumint", "mediumtext", "middleint", "nchar",
    "numeric", "real", "set", "smallint", "text", "time", "timestamp", "tinyblob",
    "tinyint", "tinytext", "varbinary", "varchar", "nvarchar", "xml", "string" // <- this is an SEDE hack
  ]);

  var operators = wordRegexp([
    ":=", "<", "<=", "==", "<>", ">", ">=", "like", "rlike", "in", "xor", "between"
  ]);

  var operatorChars = /[*+\-<>=&|:\/]/;

  var tokenizeSql = (function() {
    function normal(source, setState) {
      var ch = source.next();
      if (ch == "@" || ch == "$") {
        source.nextWhileMatches(/[\w\d]/);
        return "sql-var";
      }
      else if (ch == "["){
	    setState(inAlias(ch))
	  	return null;
      }
      else if (ch == "\"" || ch == "'" || ch == "`") {
        setState(inLiteral(ch));
        return null;
      }
      else if (ch == "," || ch == ";") {
        return "sql-separator"
      }
      else if (ch == '-') {
        if (source.peek() == "-") {
          while (!source.endOfLine()) source.next();
          return "sql-comment";
        }
        else if (/\d/.test(source.peek())) {
          source.nextWhileMatches(/\d/);
          if (source.peek() == '.') {
            source.next();
            source.nextWhileMatches(/\d/);
          }
          return "sql-number";
        }
        else
          return "sql-operator";
      }
      else if (operatorChars.test(ch)) {
        source.nextWhileMatches(operatorChars);
        return "sql-operator";
      }
      else if (/\d/.test(ch)) {
        source.nextWhileMatches(/\d/);
        if (source.peek() == '.') {
          source.next();
          source.nextWhileMatches(/\d/);
        }
        return "sql-number";
      }
      else if (/[()]/.test(ch)) {
        return "sql-punctuation";
      }
      else {
        source.nextWhileMatches(/[_\w\d]/);
        var word = source.get(), type;
        if (operators.test(word))
          type = "sql-operator";
        else if (keywords.test(word))
          type = "sql-keyword";
        else if (functions.test(word))
          type = "sql-function";
        else if (types.test(word))
          type = "sql-type";
        else
          type = "sql-word";
        return {style: type, content: word};
      }
    }

    function inAlias(quote) {
	  return function(source, setState) {
	    while (!source.endOfLine()) {
		  var ch = source.next();
		  if (ch == ']') {
		    setState(normal);
		    break;
		  }
	    }
	    return "sql-word";
	  }
    }

    function inLiteral(quote) {
      return function(source, setState) {
        var escaped = false;
        while (!source.endOfLine()) {
          var ch = source.next();
          if (ch == quote && !escaped) {
            setState(normal);
            break;
          }
          escaped = !escaped && ch == "\\";
        }
        return quote == "`" ? "sql-word" : "sql-literal";
      };
    }

    return function(source, startState) {
      return tokenizer(source, startState || normal);
    };
  })();

  function indentSql(context) {
    return function(nextChars) {
      var firstChar = nextChars && nextChars.charAt(0);
      var closing = context && firstChar == context.type;
      if (!context)
        return 0;
      else if (context.align)
        return context.col - (closing ? context.width : 0);
      else
        return context.indent + (closing ? 0 : indentUnit);
    }
  }

  function parseSql(source) {
    var tokens = tokenizeSql(source);
    var context = null, indent = 0, col = 0;
    function pushContext(type, width, align) {
      context = {prev: context, indent: indent, col: col, type: type, width: width, align: align};
    }
    function popContext() {
      context = context.prev;
    }

    var iter = {
      next: function() {
        var token = tokens.next();
        var type = token.style, content = token.content, width = token.value.length;

        if (content == "\n") {
          // token.indentation = indentSql(context);
          indent = col = 0;
          if (context && context.align == null) context.align = false;
        }
        else if (type == "whitespace" && col == 0) {
          indent = width;
        }
        else if (!context && type != "sql-comment") {
          pushContext(";", 0, false);
        }

        if (content != "\n") col += width;

        if (type == "sql-punctuation") {
          if (content == "(")
            pushContext(")", width);
          else if (content == ")")
            popContext();
        }
        else if (type == "sql-separator" && content == ";" && context && !context.prev) {
          popContext();
        }

        return token;
      },

      copy: function() {
        var _context = context, _indent = indent, _col = col, _tokenState = tokens.state;
        return function(source) {
          tokens = tokenizeSql(source, _tokenState);
          context = _context;
          indent = _indent;
          col = _col;
          return iter;
        };
      }
    };
    return iter;
  }

  // electric chars are just confusing
  return {make: parseSql, electricChars: ""};
})();
<|endoftext|>


<commit_before>import Ember from 'ember';
import ENV from 'weather-app/config/environment';

export default Ember.Controller.extend({

  locationCity: 'Red Hook',
  locationState: 'NY',

  currentDate: new Date(),

  currentWeather: {},
  currentTemperature: 0,
  currentTemperatureMin: 0,
  currentTemperatureMax: 0,

  weathers: [],
  totalDays: 4,

  actions: {
    //Gets called asap to set up the current location, time, and weather.
    setupMethod: function(){
      var me = this;

      //For updating the clock
      setInterval(function(){
        me.set('currentDate', new Date());
      }, 60000);

      navigator.geolocation.getCurrentPosition(function(res){

        //Get current weather
        //forecast doesn't always return today ¯\_(ツ)_/¯
        me.getCurrentWeather(
          res.coords.latitude,
          res.coords.longitude,
          function(success, weather){
            var currentWeather = me.get('currentWeather');
            weather.forecasts = currentWeather.forecasts;
            me.set('currentWeather', weather);
          }
        );

        //Get forecast weather
        me.getForecast(
          res.coords.latitude,
          res.coords.longitude,
          function(success, weather){
            var weathers = me.get('weathers');
            var totalDays = me.get('totalDays');

            var i = 0;
            var todaysDate = new Date();
            if(weather[0].date.getDate() === todaysDate.getDate()){
              var currentWeather = me.get('currentWeather');
              currentWeather.forecasts = weather[0].forecasts;
              me.set('currentWeather', currentWeather);
              i++;
            }
            for(i; i < weather.length; i++){
              if(i <= totalDays){
                weathers.pushObject(weather[i]);
              }
            }
          }
        );

        //Get current location
        me.getCurrentLocation(
          res.coords.latitude,
          res.coords.longitude,
          function(city, state){
            me.set('locationCity', city);
            me.set('locationState', state);
          }
        );

      });
    },

    /**
      *Show the breakdown for the current day
    **/
    showBreakdown: function(){
      var weatherObject = this.get('currentWeather');
      $('#weather-card-' + weatherObject.date.getDate() + '-modal').modal('show');
    }

  },

  /**
    *Get the current weather.
    *@param {float} latitude The latitude to look up.
    *@param {float} longitude The longitude to look up.
    *@param {function} callback Callback function, returns a weather object.
  **/
  getCurrentWeather: function(latitude, longitude, callback){
    var me = this;
    var weatherUrl = 'https://api.openweathermap.org/data/2.5/weather';
    weatherUrl += '?lat=' + latitude;
    weatherUrl += '&lon=' + longitude;
    weatherUrl += '&units=imperial';
    weatherUrl += '&appid=' + ENV.APP.openWeatherMapKey;

    $.ajax({
      url: weatherUrl,
      success: function(response){
        var weatherObj = me.parseWeather(response);
        if(callback){
          callback(true, weatherObj);
        }
      }
    });
  },

  /**
    *Get the forecast.
    *@param {float} latitude The latitude to look up.
    *@param {float} longitude The longitude to look up.
    *@param {function} callback Callback function, returns success and an array
    *                           of weather objects.
  **/
  getForecast: function(latitude, longitude, callback){
    var me = this;
    var weatherUrl = 'https://api.openweathermap.org/data/2.5/forecast';
    weatherUrl += '?lat=' + latitude;
    weatherUrl += '&lon=' + longitude;
    weatherUrl += '&units=imperial';
    weatherUrl += '&appid=' + ENV.APP.openWeatherMapKey;

    $.ajax({
      url: weatherUrl,
      success: function(response){
        var weatherObjects = {};
        //Create weather objects and group by day
        for(var i = 0; i < response.list.length; i++){
          var weather = response.list[i];

          //Create weather object to make things a bit easier
          var weatherObj = me.parseWeather(weather);

          //Group by the day and exclude
          if(!weatherObjects[weatherObj.date.getDate()]){
            weatherObjects[weatherObj.date.getDate()] = {forecasts: []};
          }

          //Push into the forecasts array
          var weatherObject = weatherObjects[weatherObj.date.getDate()];
          weatherObject.forecasts.push(weatherObj);
        }

        //Get averages
        for(var i in weatherObjects){
          var weatherObject = weatherObjects[i];

          var averageTemp    = 0;
          var averageTempMax = 0;
          var averageTempMin = 0;

          for(var j = 0; j < weatherObject.forecasts.length; j++){
            var forecast = weatherObject.forecasts[j];
            averageTemp    += forecast.temp;
            averageTempMax += forecast.tempMax;
            averageTempMin += forecast.tempMin;
          }
          averageTemp    = Math.round(averageTemp / j);
          averageTempMax = Math.round(averageTempMax / j);
          averageTempMin = Math.round(averageTempMin / j);

          weatherObject.averageTemp    = averageTemp;
          weatherObject.averageTempMax = averageTempMax;
          weatherObject.averageTempMin = averageTempMin;
          weatherObject.currentTemp    = Math.round(weatherObject.forecasts[0].temp);

          weatherObject.date = weatherObject.forecasts[0].date;
          weatherObject.weatherId = weatherObject.forecasts[0].weatherId;
        }

        var weatherArray = [];
        for(var i in weatherObjects){
          weatherArray.push(weatherObjects[i]);
        }
        if(callback){
          callback(true, weatherArray);
        }
      }
    });
  },

  /**
    *Gets the city and state of a lat lng.
    *@param {float} latitude Latitude to look up.
    *@param {float} longitude Longitude to look up.
    *@param {function} callback Callback function, returns city and state.
  **/
  getCurrentLocation: function(latitude, longitude, callback){
    var reverseGeolocationUrl = 'https://maps.googleapis.com/maps/api/geocode/json';
    reverseGeolocationUrl += '?latlng=' + latitude + ',' + longitude;
    reverseGeolocationUrl += '&key=' + ENV.APP.googleKey;

    $.ajax({
      url: reverseGeolocationUrl,
      success: function(response){
        var city = null;
        var state = null;

        for(var i = 0; i < response.results.length; i++){
          var result = response.results[i];
          for(var j = 0; j < result.address_components.length; j++){
            var addressComponent = result.address_components[j];
            if(!state || !city){
              for(var k = 0; k < addressComponent.types.length; k++){
                var addressType = addressComponent.types[k];
                if(!city){
                  if(addressType === 'locality'){
                    city = addressComponent.short_name;
                  }
                }
                if(!state){
                  if(addressType === 'administrative_area_level_1'){
                    state = addressComponent.short_name;
                  }
                }
              }
            }
          }
        }

        if(callback){
          callback(city, state);
        }
      }
    });
  },

  //Would probably be better to put this into a model or a serializer somewhere
  //so we can utilize actual data objects of the framework.
  /**
    *Parse a weather response from the weather api into something a bit nicer
    *for what we are using it for.
    *@param {object} weatherObject A weather object from an api call.
    *@return {object} A parsed weather object.
  **/
  parseWeather: function(weatherObject){

    var weatherDate = new Date();
    if(weatherObject.dt_txt){
      weatherDate = new Date(weatherObject.dt_txt);
    }
    var weather = {
      temp: Math.round(weatherObject.main.temp),
      tempMax: Math.round(weatherObject.main.temp_max),
      tempMin: Math.round(weatherObject.main.temp_min),
      cloudPercentage: weatherObject.clouds.all,
      date: weatherDate,
      humidity: weatherObject.main.humidity,
      rain: 0,
      weatherId: weatherObject.weather[0].id,
      wind: weatherObject.wind,
      windDirection: weatherObject.wind.deg
    };

    //Rain isn't always returned if it isn't going to rain
    if(weatherObject.rain){
      if(weatherObject.rain['3h']){
        weather.rain = weatherObject.rain['3h'];
      }
    }

    return weather;
  }
});
<commit_msg>apparently openweathermap doesn't have https<commit_after>import Ember from 'ember';
import ENV from 'weather-app/config/environment';

export default Ember.Controller.extend({

  locationCity: 'Red Hook',
  locationState: 'NY',

  currentDate: new Date(),

  currentWeather: {},
  currentTemperature: 0,
  currentTemperatureMin: 0,
  currentTemperatureMax: 0,

  weathers: [],
  totalDays: 4,

  actions: {
    //Gets called asap to set up the current location, time, and weather.
    setupMethod: function(){
      var me = this;

      //For updating the clock
      setInterval(function(){
        me.set('currentDate', new Date());
      }, 60000);

      navigator.geolocation.getCurrentPosition(function(res){

        //Get current weather
        //forecast doesn't always return today ¯\_(ツ)_/¯
        me.getCurrentWeather(
          res.coords.latitude,
          res.coords.longitude,
          function(success, weather){
            var currentWeather = me.get('currentWeather');
            weather.forecasts = currentWeather.forecasts;
            me.set('currentWeather', weather);
          }
        );

        //Get forecast weather
        me.getForecast(
          res.coords.latitude,
          res.coords.longitude,
          function(success, weather){
            var weathers = me.get('weathers');
            var totalDays = me.get('totalDays');

            var i = 0;
            var todaysDate = new Date();
            if(weather[0].date.getDate() === todaysDate.getDate()){
              var currentWeather = me.get('currentWeather');
              currentWeather.forecasts = weather[0].forecasts;
              me.set('currentWeather', currentWeather);
              i++;
            }
            for(i; i < weather.length; i++){
              if(i <= totalDays){
                weathers.pushObject(weather[i]);
              }
            }
          }
        );

        //Get current location
        me.getCurrentLocation(
          res.coords.latitude,
          res.coords.longitude,
          function(city, state){
            me.set('locationCity', city);
            me.set('locationState', state);
          }
        );

      });
    },

    /**
      *Show the breakdown for the current day
    **/
    showBreakdown: function(){
      var weatherObject = this.get('currentWeather');
      $('#weather-card-' + weatherObject.date.getDate() + '-modal').modal('show');
    }

  },

  /**
    *Get the current weather.
    *@param {float} latitude The latitude to look up.
    *@param {float} longitude The longitude to look up.
    *@param {function} callback Callback function, returns a weather object.
  **/
  getCurrentWeather: function(latitude, longitude, callback){
    var me = this;
    var weatherUrl = 'http://api.openweathermap.org/data/2.5/weather';
    weatherUrl += '?lat=' + latitude;
    weatherUrl += '&lon=' + longitude;
    weatherUrl += '&units=imperial';
    weatherUrl += '&appid=' + ENV.APP.openWeatherMapKey;

    $.ajax({
      url: weatherUrl,
      success: function(response){
        var weatherObj = me.parseWeather(response);
        if(callback){
          callback(true, weatherObj);
        }
      }
    });
  },

  /**
    *Get the forecast.
    *@param {float} latitude The latitude to look up.
    *@param {float} longitude The longitude to look up.
    *@param {function} callback Callback function, returns success and an array
    *                           of weather objects.
  **/
  getForecast: function(latitude, longitude, callback){
    var me = this;
    var weatherUrl = 'http://api.openweathermap.org/data/2.5/forecast';
    weatherUrl += '?lat=' + latitude;
    weatherUrl += '&lon=' + longitude;
    weatherUrl += '&units=imperial';
    weatherUrl += '&appid=' + ENV.APP.openWeatherMapKey;

    $.ajax({
      url: weatherUrl,
      success: function(response){
        var weatherObjects = {};
        //Create weather objects and group by day
        for(var i = 0; i < response.list.length; i++){
          var weather = response.list[i];

          //Create weather object to make things a bit easier
          var weatherObj = me.parseWeather(weather);

          //Group by the day and exclude
          if(!weatherObjects[weatherObj.date.getDate()]){
            weatherObjects[weatherObj.date.getDate()] = {forecasts: []};
          }

          //Push into the forecasts array
          var weatherObject = weatherObjects[weatherObj.date.getDate()];
          weatherObject.forecasts.push(weatherObj);
        }

        //Get averages
        for(var i in weatherObjects){
          var weatherObject = weatherObjects[i];

          var averageTemp    = 0;
          var averageTempMax = 0;
          var averageTempMin = 0;

          for(var j = 0; j < weatherObject.forecasts.length; j++){
            var forecast = weatherObject.forecasts[j];
            averageTemp    += forecast.temp;
            averageTempMax += forecast.tempMax;
            averageTempMin += forecast.tempMin;
          }
          averageTemp    = Math.round(averageTemp / j);
          averageTempMax = Math.round(averageTempMax / j);
          averageTempMin = Math.round(averageTempMin / j);

          weatherObject.averageTemp    = averageTemp;
          weatherObject.averageTempMax = averageTempMax;
          weatherObject.averageTempMin = averageTempMin;
          weatherObject.currentTemp    = Math.round(weatherObject.forecasts[0].temp);

          weatherObject.date = weatherObject.forecasts[0].date;
          weatherObject.weatherId = weatherObject.forecasts[0].weatherId;
        }

        var weatherArray = [];
        for(var i in weatherObjects){
          weatherArray.push(weatherObjects[i]);
        }
        if(callback){
          callback(true, weatherArray);
        }
      }
    });
  },

  /**
    *Gets the city and state of a lat lng.
    *@param {float} latitude Latitude to look up.
    *@param {float} longitude Longitude to look up.
    *@param {function} callback Callback function, returns city and state.
  **/
  getCurrentLocation: function(latitude, longitude, callback){
    var reverseGeolocationUrl = 'https://maps.googleapis.com/maps/api/geocode/json';
    reverseGeolocationUrl += '?latlng=' + latitude + ',' + longitude;
    reverseGeolocationUrl += '&key=' + ENV.APP.googleKey;

    $.ajax({
      url: reverseGeolocationUrl,
      success: function(response){
        var city = null;
        var state = null;

        for(var i = 0; i < response.results.length; i++){
          var result = response.results[i];
          for(var j = 0; j < result.address_components.length; j++){
            var addressComponent = result.address_components[j];
            if(!state || !city){
              for(var k = 0; k < addressComponent.types.length; k++){
                var addressType = addressComponent.types[k];
                if(!city){
                  if(addressType === 'locality'){
                    city = addressComponent.short_name;
                  }
                }
                if(!state){
                  if(addressType === 'administrative_area_level_1'){
                    state = addressComponent.short_name;
                  }
                }
              }
            }
          }
        }

        if(callback){
          callback(city, state);
        }
      }
    });
  },

  //Would probably be better to put this into a model or a serializer somewhere
  //so we can utilize actual data objects of the framework.
  /**
    *Parse a weather response from the weather api into something a bit nicer
    *for what we are using it for.
    *@param {object} weatherObject A weather object from an api call.
    *@return {object} A parsed weather object.
  **/
  parseWeather: function(weatherObject){

    var weatherDate = new Date();
    if(weatherObject.dt_txt){
      weatherDate = new Date(weatherObject.dt_txt);
    }
    var weather = {
      temp: Math.round(weatherObject.main.temp),
      tempMax: Math.round(weatherObject.main.temp_max),
      tempMin: Math.round(weatherObject.main.temp_min),
      cloudPercentage: weatherObject.clouds.all,
      date: weatherDate,
      humidity: weatherObject.main.humidity,
      rain: 0,
      weatherId: weatherObject.weather[0].id,
      wind: weatherObject.wind,
      windDirection: weatherObject.wind.deg
    };

    //Rain isn't always returned if it isn't going to rain
    if(weatherObject.rain){
      if(weatherObject.rain['3h']){
        weather.rain = weatherObject.rain['3h'];
      }
    }

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


<commit_before>import Ember from 'ember';

export default Ember.Service.extend({
  isCharging: null,
  level: null,
  chargingTime: null,
  dischargingTime: null,
  levelPercentage: Ember.computed('level', function() {
    return this.get('level') * 100;
  }),

  init() {
    this._super(...arguments);
    if (navigator && navigator.getBattery) {
      this.set('isSupported', true);
      navigator.getBattery().then((battery) => {
        this._battery = battery;
        this.set('isCharging', battery.charging);
        this.set('level', battery.level);
        this.set('chargingTime', battery.chargingTime);
        this.set('dischargingTime', battery.dischargingTime);
        this.addListeners();
      });
    } else {
      this.set('isSupported', false);
    }
  },

  addListeners() {
    this.onChargingChange = () => {
      this.set('isCharging', this._battery.charging);
    };

    this.onLevelChange = () => {
      this.set('level', this._battery.level);
    };

    this.onChargingTimeChange = () => {
      this.set('chargingTime', this._battery.chargingTime);
    };

    this.onDischargingTimeChange = () => {
      this.set('dischargingTime', this._battery.dischargingTime);
    };

    this._battery.addEventListener('chargingchange', this.onChargingChange);
    this._battery.addEventListener('levelchange', this.onLevelChange);
    this._battery.addEventListener('chargingtimechange', this.onChargingTimeChange);
    this._battery.addEventListener('dischargingtimechange', this.onDischargingTimeChange);
  },

  onDischargingTimeChange() {
     this.set('dischargingTime', this._battery.dischargingTime);
  },

  willDestroy() {
    this._super(...arguments);
    this.removeListeners();
  },

  removeListeners() {
    let battery = this.get('_battery');
    if (battery) {
      battery.removeEventListener('chargingchange', this.onChargingChange);
      battery.removeEventListener('levelchange', this.onLevelChange);
      battery.removeEventListener('chargingtimechange', this.onChargingTimeChange);
      battery.removeEventListener('dischargingtimechange', this.onDischargingTimeChange);
    }
  }
});
<commit_msg>remove leftover onDischargingTimeChange<commit_after>import Ember from 'ember';

export default Ember.Service.extend({
  isCharging: null,
  level: null,
  chargingTime: null,
  dischargingTime: null,
  levelPercentage: Ember.computed('level', function() {
    return this.get('level') * 100;
  }),

  init() {
    this._super(...arguments);
    if (navigator && navigator.getBattery) {
      this.set('isSupported', true);
      navigator.getBattery().then((battery) => {
        this._battery = battery;
        this.set('isCharging', battery.charging);
        this.set('level', battery.level);
        this.set('chargingTime', battery.chargingTime);
        this.set('dischargingTime', battery.dischargingTime);
        this.addListeners();
      });
    } else {
      this.set('isSupported', false);
    }
  },

  addListeners() {
    this.onChargingChange = () => {
      this.set('isCharging', this._battery.charging);
    };

    this.onLevelChange = () => {
      this.set('level', this._battery.level);
    };

    this.onChargingTimeChange = () => {
      this.set('chargingTime', this._battery.chargingTime);
    };

    this.onDischargingTimeChange = () => {
      this.set('dischargingTime', this._battery.dischargingTime);
    };

    this._battery.addEventListener('chargingchange', this.onChargingChange);
    this._battery.addEventListener('levelchange', this.onLevelChange);
    this._battery.addEventListener('chargingtimechange', this.onChargingTimeChange);
    this._battery.addEventListener('dischargingtimechange', this.onDischargingTimeChange);
  },

  willDestroy() {
    this._super(...arguments);
    this.removeListeners();
  },

  removeListeners() {
    let battery = this._battery;
    if (battery) {
      battery.removeEventListener('chargingchange', this.onChargingChange);
      battery.removeEventListener('levelchange', this.onLevelChange);
      battery.removeEventListener('chargingtimechange', this.onChargingTimeChange);
      battery.removeEventListener('dischargingtimechange', this.onDischargingTimeChange);
    }
  }
});
<|endoftext|>


<commit_before>(function($) {

  var filters;

  $.filters = filters = {
    append: function(field_label, field_name, field_type, field_value, field_operator, field_options, index) {
      var value_name = 'filters[' +  field_name + '][' + index + '][value]';
      var operator_name = 'filters[' +  field_name + '][' + index + '][operator]';
      switch(field_type) {
        case 'boolean':
          var control = '<select name="' + value_name + '">' +
            '<option value="_discard">...</option>' +
            '<option value="true"' + (field_value == "true" ? 'selected="selected"' : '') + '>True</option>' +
            '<option value="false"' + (field_value == "false" ? 'selected="selected"' : '') + '>False</option>' +
            '<option disabled="disabled">---------</option>' +
            '<option ' + (field_value == "_present" ? 'selected="selected"' : '') + ' value="_present">Is present</option>' +
            '<option ' + (field_value == "_blank"   ? 'selected="selected"' : '') + ' value="_blank"  >Is blank</option>' +
          '</select>';
          break;
        case 'date':
        case 'datetime':
        case 'timestamp':
          var control = '<select class="switch-additionnal-fieldsets" name="' + operator_name + '">' +
            '<option data-additional-fieldset="false" value="_discard">...</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "today"     ? 'selected="selected"' : '') + ' value="today">Today</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "yesterday" ? 'selected="selected"' : '') + ' value="yesterday">Yesterday</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "this_week" ? 'selected="selected"' : '') + ' value="this_week">This week</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "last_week" ? 'selected="selected"' : '') + ' value="last_week">Last week</option>' +
            '<option data-additional-fieldset="true" ' + (field_operator == "less_than" ? 'selected="selected"' : '') + ' value="less_than">Less than ... days ago</option>' +
            '<option data-additional-fieldset="true" ' + (field_operator == "more_than" ? 'selected="selected"' : '') + ' value="more_than">More than ... days ago</option>' +
            '<option disabled="disabled">---------</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "_present"  ? 'selected="selected"' : '') + ' value="_present">Is present</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "_blank"    ? 'selected="selected"' : '') + ' value="_blank" >Is blank</option>' +
          '</select>' +
          '<input class="additional-fieldset text_field" style="display:' + (field_operator == "less_than" || field_operator == "more_than" ? 'block' : 'none') + ';" type="text" name="' + value_name + '" value="' + field_value + '" /> ';
          break;
        case 'enum':
          field_options = $j('
').html(field_options).text(); // entities decode
          var control = '<select name="' + value_name + '">' +
            '<option value="_discard">...</option>' +
            field_options +
            '<option disabled="disabled">---------</option>' +
            '<option ' + (field_value == "_present" ? 'selected="selected"' : '') + ' value="_present">Is present</option>' +
            '<option ' + (field_value == "_blank"   ? 'selected="selected"' : '') + ' value="_blank"  >Is blank</option>' +
          '</select>';
          break;
        case 'string':
        case 'text':
        case 'belongs_to_association':
          var control = '<select class="switch-additionnal-fieldsets" value="' + field_operator + '" name="' + operator_name + '">' +
            '<option data-additional-fieldset="true"'  + (field_operator == "like"        ? 'selected="selected"' : '') + ' value="like">Contains</option>' +
            '<option data-additional-fieldset="true"'  + (field_operator == "is"          ? 'selected="selected"' : '') + ' value="is">Is exactly</option>' +
            '<option data-additional-fieldset="true"'  + (field_operator == "starts_with" ? 'selected="selected"' : '') + ' value="starts_with">Starts with</option>' +
            '<option data-additional-fieldset="true"'  + (field_operator == "ends_with"   ? 'selected="selected"' : '') + ' value="ends_with">Ends with</option>' +
            '<option disabled="disabled">---------</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "_present"    ? 'selected="selected"' : '') + ' value="_present">Is present</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "_blank"      ? 'selected="selected"' : '') + ' value="_blank">Is blank</option>' +
          '</select>' +
          '<input class="additional-fieldset text_field" style="display:' + (field_operator == "_blank" || field_operator == "_present" ? 'none' : 'block') + ';" type="text" name="' + value_name + '" value="' + field_value + '" /> ';
          break;
        default:
          var control = '<input type="text" name="' + value_name + '" value="' + field_value + '" class="text_field"/> ';
          break;
      }

      $('#filters_box').append(
        '
' +
          '

' +
          '' + field_label + '' +
          control +
        '
'
      );
    }
  }

$("#filter_select").live('change', function() {
    var option = $(this).find('option:selected')
    if ($(this).val() != '') {
      $(this).val(''); // reset select
      $.filters.append(
        option.data('field-label'),
        option.data('field-name'),
        option.data('field-type'),
        option.data('field-value'),
        option.data('field-operator'),
        option.data('field-options'),
        $.now()
      );
    }
  });

  $('#filters_box .delete').live('click', function() {
    $(this).parents('.filter').hide();
    $(this).append('<input type="hidden" name="' + $(this).data('disabler-name') + '" value="true" />')
  });

  $('#filters_box .switch-additionnal-fieldsets').live('change', function() {
    var selected_option = $(this).find('option:selected');

    if($(selected_option).data('additional-fieldset')) {
      $(this).siblings('.additional-fieldset').val('');
      $(this).siblings('.additional-fieldset').show();
    } else {
      $(this).siblings('.additional-fieldset').hide();
    }
  });
})( jQuery );
<commit_msg>Edited app/assets/javascripts/rails_admin/ra.filter-box.js via GitHub<commit_after>(function($) {

  var filters;

  $.filters = filters = {
    append: function(field_label, field_name, field_type, field_value, field_operator, field_options, index) {
      var value_name = 'filters[' +  field_name + '][' + index + '][value]';
      var operator_name = 'filters[' +  field_name + '][' + index + '][operator]';
      switch(field_type) {
        case 'boolean':
          var control = '<select name="' + value_name + '">' +
            '<option value="_discard">...</option>' +
            '<option value="true"' + (field_value == "true" ? 'selected="selected"' : '') + '>True</option>' +
            '<option value="false"' + (field_value == "false" ? 'selected="selected"' : '') + '>False</option>' +
            '<option disabled="disabled">---------</option>' +
            '<option ' + (field_value == "_present" ? 'selected="selected"' : '') + ' value="_present">Is present</option>' +
            '<option ' + (field_value == "_blank"   ? 'selected="selected"' : '') + ' value="_blank"  >Is blank</option>' +
          '</select>';
          break;
        case 'date':
        case 'datetime':
        case 'timestamp':
          var control = '<select class="switch-additionnal-fieldsets" name="' + operator_name + '">' +
            '<option data-additional-fieldset="false" value="_discard">...</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "today"     ? 'selected="selected"' : '') + ' value="today">Today</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "yesterday" ? 'selected="selected"' : '') + ' value="yesterday">Yesterday</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "this_week" ? 'selected="selected"' : '') + ' value="this_week">This week</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "last_week" ? 'selected="selected"' : '') + ' value="last_week">Last week</option>' +
            '<option data-additional-fieldset="true" ' + (field_operator == "less_than" ? 'selected="selected"' : '') + ' value="less_than">Less than ... days ago</option>' +
            '<option data-additional-fieldset="true" ' + (field_operator == "more_than" ? 'selected="selected"' : '') + ' value="more_than">More than ... days ago</option>' +
            '<option disabled="disabled">---------</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "_present"  ? 'selected="selected"' : '') + ' value="_present">Is present</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "_blank"    ? 'selected="selected"' : '') + ' value="_blank" >Is blank</option>' +
          '</select>' +
          '<input class="additional-fieldset text_field" style="display:' + (field_operator == "less_than" || field_operator == "more_than" ? 'block' : 'none') + ';" type="text" name="' + value_name + '" value="' + field_value + '" /> ';
          break;
        case 'enum':
          field_options = $j('
').html(field_options).text(); // entities decode
          var control = '<select name="' + value_name + '">' +
            '<option value="_discard">...</option>' +
            field_options +
            '<option disabled="disabled">---------</option>' +
            '<option ' + (field_value == "_present" ? 'selected="selected"' : '') + ' value="_present">Is present</option>' +
            '<option ' + (field_value == "_blank"   ? 'selected="selected"' : '') + ' value="_blank"  >Is blank</option>' +
          '</select>';
          break;
        case 'string':
        case 'text':
        case 'belongs_to_association':
          var control = '<select class="switch-additionnal-fieldsets" value="' + field_operator + '" name="' + operator_name + '">' +
            '<option data-additional-fieldset="true"'  + (field_operator == "like"        ? 'selected="selected"' : '') + ' value="like">Contains</option>' +
            '<option data-additional-fieldset="true"'  + (field_operator == "is"          ? 'selected="selected"' : '') + ' value="is">Is exactly</option>' +
            '<option data-additional-fieldset="true"'  + (field_operator == "starts_with" ? 'selected="selected"' : '') + ' value="starts_with">Starts with</option>' +
            '<option data-additional-fieldset="true"'  + (field_operator == "ends_with"   ? 'selected="selected"' : '') + ' value="ends_with">Ends with</option>' +
            '<option disabled="disabled">---------</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "_present"    ? 'selected="selected"' : '') + ' value="_present">Is present</option>' +
            '<option data-additional-fieldset="false"' + (field_operator == "_blank"      ? 'selected="selected"' : '') + ' value="_blank">Is blank</option>' +
          '</select>' +
          '<input class="additional-fieldset text_field" style="display:' + (field_operator == "_blank" || field_operator == "_present" ? 'none' : 'block') + ';" type="text" name="' + value_name + '" value="' + field_value + '" /> ';
          break;
        default:
          var control = '<input type="text" name="' + value_name + '" value="' + field_value + '" class="text_field"/> ';
          break;
      }

      $('#filters_box').append(
        '
' +
          '

' +
          '' + field_label + '' +
          control +
        '
'
      );
    }
  }

  $("#filter_select").live('change', function() {
    var option = $(this).find('option:selected')
    if ($(this).val() != '') {
      $(this).val(''); // reset select
      $.filters.append(
        option.data('field-label'),
        option.data('field-name'),
        option.data('field-type'),
        option.data('field-value'),
        option.data('field-operator'),
        option.data('field-options'),
        $.now()
      );
    }
  });

  $('#filters_box .delete').live('click', function() {
    $(this).parents('.filter').hide();
    $(this).append('<input type="hidden" name="' + $(this).data('disabler-name') + '" value="true" />')
  });

  $('#filters_box .switch-additionnal-fieldsets').live('change', function() {
    var selected_option = $(this).find('option:selected');

    if($(selected_option).data('additional-fieldset')) {
      $(this).siblings('.additional-fieldset').val('');
      $(this).siblings('.additional-fieldset').show();
    } else {
      $(this).siblings('.additional-fieldset').hide();
    }
  });
})( jQuery );
<|endoftext|>