<commit_before>module.exports = function(grunt) {
  'use strict';

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',

    clean: {
      examples: [
        '/examples/libglobal/dist/',
        '/examples/libglobal-hybrid/dist/',
        '/examples/multipage/www-built/',
        '/examples/multipage-shim/www-built/'
      ],
      tmp: ['tmp']
    },

    copy: {
      dist: {
        files: {
          'tmp/doNotKillAlmond/': 'test/fixtures/*.js'
        }
      }
    },

    // Configuration to be run (and then tested).
    requirejs: {
      compile: {
        options: {
          baseUrl: 'test/fixtures',
          name: 'project',
          out: 'tmp/requirejs.js'
        }
      },
      rmCombined: {
        options: {
          baseUrl: 'tmp/doNotKillAlmond',
          name: 'project',
          out: 'tmp/requirejs-killed.js',
          almond: true,
          removeCombined: true
        }
      },
      template: {
        options: {
          baseUrl: 'test/fixtures',
          name: 'project',
          out: 'tmp/requirejs-template.js'
        }
      },
      sourcemaps: {
        options: {
          baseUrl: 'test/fixtures',
          name: 'project',
          out: 'tmp/requirejs-sourcemaps.js',
          optimize: "uglify2",
          generateSourceMaps: true,
          preserveLicenseComments: false,
          useSourceUrl: true
        }
      }
    },

    nodeunit: {
      all: ['test/*_test.js']
    },

    qunit: {
      options: {
        timeout: 20000
      },
      all: [
        'examples/libglobal/tests/*.html',
        'examples/libglobal-hybrid/tests/*.html'
      ]
    },

    watch: {
      files: '<config:lint.files>',
      tasks: 'default'
    },

    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        node: true,
        es5: true,
        globals: {
          exports: true,
          require: true,
          module: true
        },
      },
      all: ['grunt.js', 'tasks/**/*.js', 'test/require_test.js', 'lib/**/*.js']
    }
  });

  // build all the projects from the ´examples´ folder
  // to run some tests against them
  grunt.registerTask('buildExampleProjects', function () {
    var done = this.async(),
        util = grunt.utils || grunt.util,
        preparation = [false, false, false, false],
        checkForPreparation = function () {
          if (util._.all(preparation, util._.identity)) {
            grunt.log.ok('all examples build');
            done();
          }
        };

    // build libglobal example
    util.spawn({
      cmd: 'grunt',
      args: ['build', '--force'],
      opts: {cwd: 'examples/libglobal'}
    }, function () {
      grunt.log.writeln('> "libglobal" example build');
      preparation[0] = true;
      checkForPreparation();
    });

    // build libglobal-hybrid example
    util.spawn({
      cmd: 'grunt',
      args: ['build', '--force'],
      opts: {cwd: 'examples/libglobal-hybrid'}
    }, function () {
      grunt.log.writeln('> "libglobal-hybrid" example build');
      preparation[3] = true;
      checkForPreparation();
    });

    // build multipage example
    util.spawn({
      cmd: 'grunt',
      args: ['build', '--force'],
      opts: {cwd: 'examples/multipage'}
    }, function () {
      grunt.log.writeln('> "multipage" example build');
      preparation[1] = true;
      checkForPreparation();
    });

    // build multipage-shim example
    util.spawn({
      cmd: 'grunt',
      args: ['build', '--force'],
      opts: {cwd: 'examples/multipage-shim'}
    }, function () {
      grunt.log.writeln('> "multipage-shim" example build');
      preparation[2] = true;
      checkForPreparation();
    });

  });

  // Load tasks.
  grunt.loadTasks('tasks');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-nodeunit');
  grunt.loadNpmTasks('grunt-contrib-qunit');

  // Setup the test environment task.
  grunt.registerTask('setUp', ['buildExampleProjects', 'copy', 'requirejs']);

  // Default task.
  grunt.registerTask('default', ['setUp', 'jshint', 'nodeunit', 'qunit', 'clean']);
};
<commit_msg>Changed qunit test order<commit_after>module.exports = function(grunt) {
  'use strict';

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',

    clean: {
      examples: [
        '/examples/libglobal/dist/',
        '/examples/libglobal-hybrid/dist/',
        '/examples/multipage/www-built/',
        '/examples/multipage-shim/www-built/'
      ],
      tmp: ['tmp']
    },

    copy: {
      dist: {
        files: {
          'tmp/doNotKillAlmond/': 'test/fixtures/*.js'
        }
      }
    },

    // Configuration to be run (and then tested).
    requirejs: {
      compile: {
        options: {
          baseUrl: 'test/fixtures',
          name: 'project',
          out: 'tmp/requirejs.js'
        }
      },
      rmCombined: {
        options: {
          baseUrl: 'tmp/doNotKillAlmond',
          name: 'project',
          out: 'tmp/requirejs-killed.js',
          almond: true,
          removeCombined: true
        }
      },
      template: {
        options: {
          baseUrl: 'test/fixtures',
          name: 'project',
          out: 'tmp/requirejs-template.js'
        }
      },
      sourcemaps: {
        options: {
          baseUrl: 'test/fixtures',
          name: 'project',
          out: 'tmp/requirejs-sourcemaps.js',
          optimize: "uglify2",
          generateSourceMaps: true,
          preserveLicenseComments: false,
          useSourceUrl: true
        }
      }
    },

    nodeunit: {
      all: ['test/*_test.js']
    },

    qunit: {
      options: {
        timeout: 20000
      },
      all: [
        'examples/libglobal/tests/*.html'
      ]
    },

    watch: {
      files: '<config:lint.files>',
      tasks: 'default'
    },

    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        node: true,
        es5: true,
        globals: {
          exports: true,
          require: true,
          module: true
        },
      },
      all: ['grunt.js', 'tasks/**/*.js', 'test/require_test.js', 'lib/**/*.js']
    }
  });

  // build all the projects from the ´examples´ folder
  // to run some tests against them
  grunt.registerTask('buildExampleProjects', function () {
    var done = this.async(),
        util = grunt.utils || grunt.util,
        preparation = [false, false, false, false],
        checkForPreparation = function () {
          if (util._.all(preparation, util._.identity)) {
            grunt.log.ok('all examples build');
            done();
          }
        };

    // build libglobal example
    util.spawn({
      cmd: 'grunt',
      args: ['build', '--force'],
      opts: {cwd: 'examples/libglobal'}
    }, function () {
      grunt.log.writeln('> "libglobal" example build');
      preparation[0] = true;
      checkForPreparation();
    });

    // build libglobal-hybrid example
    util.spawn({
      cmd: 'grunt',
      args: ['build', '--force'],
      opts: {cwd: 'examples/libglobal-hybrid'}
    }, function () {
      grunt.log.writeln('> "libglobal-hybrid" example build');
      preparation[3] = true;
      checkForPreparation();
    });

    // build multipage example
    util.spawn({
      cmd: 'grunt',
      args: ['build', '--force'],
      opts: {cwd: 'examples/multipage'}
    }, function () {
      grunt.log.writeln('> "multipage" example build');
      preparation[1] = true;
      checkForPreparation();
    });

    // build multipage-shim example
    util.spawn({
      cmd: 'grunt',
      args: ['build', '--force'],
      opts: {cwd: 'examples/multipage-shim'}
    }, function () {
      grunt.log.writeln('> "multipage-shim" example build');
      preparation[2] = true;
      checkForPreparation();
    });

  });

  // Load tasks.
  grunt.loadTasks('tasks');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-nodeunit');
  grunt.loadNpmTasks('grunt-contrib-qunit');

  // Setup the test environment task.
  grunt.registerTask('setUp', ['buildExampleProjects', 'copy', 'requirejs']);

  // Default task.
  grunt.registerTask('default', ['setUp', 'jshint', 'nodeunit', 'qunit', 'clean']);
};
<|endoftext|>


<commit_before>var mineflayer = require('../');
var vec3 = mineflayer.vec3;
var mc = require('minecraft-protocol');
var assert = require('assert');
var zlib = require('zlib');

describe("mineflayer", function() {
  var bot, server;
  beforeEach(function(done) {
    server = mc.createServer({ 'online-mode': false } );
    server.on('listening', function() {
      bot = mineflayer.createBot({
        username: "player",
      });
      done();
    });
  });
  afterEach(function(done) {
    bot.on('end', done);
    server.close();
  });
  it("chat", function(done) {
    bot.once('chat', function(username, message) {
      assert.strictEqual(username, "gary");
      assert.strictEqual(message, "hello");
      bot.chat("hi");
    });
    server.on('login', function(client) {
      var message = JSON.stringify({
        translate: 'chat.type.text',
        with: [{text: 'gary'
      },'hello']
      });
      client.write('chat', { message: message, position:0 });
      client.on('chat', function(packet) {
        assert.strictEqual(packet.message, "hi");
        done();
      });
    });
  });
  it("entity effects", function(done) {
    bot.once('entityEffect', function(entity, effect) {
      assert.strictEqual(entity.mobType, "creeper");
      assert.strictEqual(effect.id, 10);
      assert.strictEqual(effect.amplifier, 1);
      assert.strictEqual(effect.duration, 11);
      done();
    });
    server.on('login', function(client) {
      client.write('spawn_entity_living', {
        entityId: 8, // random
        type: 50, // creeper
        x: 10,
        y: 11,
        z: 12,
        yaw: 13,
        pitch: 14,
        headPitch: 14,
        velocityX: 16,
        velocityY: 17,
        velocityZ: 18,
        metadata: []
      });
      client.write('entity_effect', {
        entityId: 8,
        effectId: 10,
        amplifier: 1,
        duration: 11,
        hideParticles: false
      });
    });
  });
  it("blockAt", function(done) {
    var pos = vec3(1, 65, 1);
    var goldId = 41;
    bot.on('chunkColumnLoad', function(columnPoint) {
      assert.strictEqual(columnPoint.x, 0);
      assert.strictEqual(columnPoint.z, 0);
      assert.strictEqual(bot.blockAt(pos).type, goldId);
      done();
    });
    server.on('login', function(client) {
      var buffer = new Buffer((4096 + 2048 + 2048 + 2048) * 4 + 256);
      buffer.fill(0);
      buffer.writeUInt8(goldId, 8192 + 273);
      zlib.deflate(buffer, function(err, compressed) {
        assert.ifError(err);
        client.write('map_chunk', {
          x: 0,
          z: 0,
          groundUp: true,
          bitMap: parseInt('00111100', 2),
          chunkData: compressed,
        });
      });
    });
  });
  describe("physics", function() {
    var pos = vec3(1, 65, 1);
    var goldId = 41;
    it("gravity + land on solid block + jump", function(done) {
      var y = 80;
      var terminal = 10;
      var hitTerminal = false;
      bot.on('move', function() {
        assert.ok(bot.entity.position.y <= y);
        assert.ok(bot.entity.position.y >= pos.y);
        y = bot.entity.position.y;
        if (bot.entity.velocity.y > -terminal) hitTerminal = true;
        if (bot.entity.velocity.y === 0) {
          assert.ok(hitTerminal);
          assert.ok(bot.entity.onGround);
          assert.ok(bot.entity.position.y, pos.y);
          done();
        } else {
          assert.strictEqual(bot.entity.onGround, false);
        }
      });
      server.on('login', function(client) {
        var buffer = new Buffer((4096 + 2048 + 2048 + 2048) * 4 + 256);
        buffer.fill(0);
        buffer.writeUInt8(goldId, 8192 + 273);
        zlib.deflate(buffer, function(err, compressed) {
          assert.ifError(err);
          client.write('login', {
            entityId: 0,
            levelType: "fogetaboutit",
            gameMode: 0,
            dimension: 0,
            difficulty: 0,
            maxPlayers: 20,
            reducedDebugInfo:true
          });
          client.write('map_chunk', {
            x: 0,
            z: 0,
            groundUp: true,
            bitMap: parseInt('00111100', 2),
            chunkData: compressed
          });
          client.write('position', {
            x: 1.5,
            y: 80,
            z: 1.5,
            pitch: 0,
            yaw: 0,
            flags: 0
          });
        });
      });
    });
  });
  describe("entities", function() {
    it("sets players[player].entity to null upon despawn", function(done) {
      var serverClient = null;
      bot.once('entitySpawn', function(entity) {
        serverClient.write('entity_destroy', {
          entityIds: [8],
        });
      });
      bot.once("entityGone", function(entity) {
        assert.equal(bot.players[entity.username], null);
        done();
      });
      server.on('login', function(client) {
        serverClient = client;

        client.write('player_info',{ id: 56,
          state: 'play',
          action: 0,
          length: 1,
          data:
            [ { UUID: [1,2,3,4],
              name: 'bot5',
              propertiesLength: 0,
              properties: [],
              gamemode: 0,
              ping: 0,
              hasDisplayName: false } ] });

        client.write('named_entity_spawn', {
          entityId: 56,
          playerUUID: [1,2,3,4],
          x: 1,
          y: 2,
          z: 3,
          yaw: 0,
          pitch: 0,
          currentItem: -1,
          metadata: [],
        });
      });
    });
  });
});
<commit_msg>Remove zlib in test.js : compression is now done in node-minecraft-protocol (this doesn't fix these 2 tests)<commit_after>var mineflayer = require('../');
var vec3 = mineflayer.vec3;
var mc = require('minecraft-protocol');
var assert = require('assert');

describe("mineflayer", function() {
  var bot, server;
  beforeEach(function(done) {
    server = mc.createServer({ 'online-mode': false } );
    server.on('listening', function() {
      bot = mineflayer.createBot({
        username: "player",
      });
      done();
    });
  });
  afterEach(function(done) {
    bot.on('end', done);
    server.close();
  });
  it("chat", function(done) {
    bot.once('chat', function(username, message) {
      assert.strictEqual(username, "gary");
      assert.strictEqual(message, "hello");
      bot.chat("hi");
    });
    server.on('login', function(client) {
      var message = JSON.stringify({
        translate: 'chat.type.text',
        with: [{text: 'gary'
      },'hello']
      });
      client.write('chat', { message: message, position:0 });
      client.on('chat', function(packet) {
        assert.strictEqual(packet.message, "hi");
        done();
      });
    });
  });
  it("entity effects", function(done) {
    bot.once('entityEffect', function(entity, effect) {
      assert.strictEqual(entity.mobType, "creeper");
      assert.strictEqual(effect.id, 10);
      assert.strictEqual(effect.amplifier, 1);
      assert.strictEqual(effect.duration, 11);
      done();
    });
    server.on('login', function(client) {
      client.write('spawn_entity_living', {
        entityId: 8, // random
        type: 50, // creeper
        x: 10,
        y: 11,
        z: 12,
        yaw: 13,
        pitch: 14,
        headPitch: 14,
        velocityX: 16,
        velocityY: 17,
        velocityZ: 18,
        metadata: []
      });
      client.write('entity_effect', {
        entityId: 8,
        effectId: 10,
        amplifier: 1,
        duration: 11,
        hideParticles: false
      });
    });
  });
  it("blockAt", function(done) {
    var pos = vec3(1, 65, 1);
    var goldId = 41;
    bot.on('chunkColumnLoad', function(columnPoint) {
      assert.strictEqual(columnPoint.x, 0);
      assert.strictEqual(columnPoint.z, 0);
      assert.strictEqual(bot.blockAt(pos).type, goldId);
      done();
    });
    server.on('login', function(client) {
      var buffer = new Buffer((4096 + 2048 + 2048 + 2048) * 4 + 256);
      buffer.fill(0);
      buffer.writeUInt8(goldId, 8192 + 273);
      client.write('map_chunk', {
        x: 0,
        z: 0,
        groundUp: true,
        bitMap: parseInt('00111100', 2),
        chunkData: buffer
      });
    });
  });
  describe("physics", function() {
    var pos = vec3(1, 65, 1);
    var goldId = 41;
    it("gravity + land on solid block + jump", function(done) {
      var y = 80;
      var terminal = 10;
      var hitTerminal = false;
      bot.on('move', function() {
        assert.ok(bot.entity.position.y <= y);
        assert.ok(bot.entity.position.y >= pos.y);
        y = bot.entity.position.y;
        if (bot.entity.velocity.y > -terminal) hitTerminal = true;
        if (bot.entity.velocity.y === 0) {
          assert.ok(hitTerminal);
          assert.ok(bot.entity.onGround);
          assert.ok(bot.entity.position.y, pos.y);
          done();
        } else {
          assert.strictEqual(bot.entity.onGround, false);
        }
      });
      server.on('login', function(client) {
        var buffer = new Buffer((4096 + 2048 + 2048 + 2048) * 4 + 256);
        buffer.fill(0);
        buffer.writeUInt8(goldId, 8192 + 273);
        client.write('login', {
          entityId: 0,
          levelType: "fogetaboutit",
          gameMode: 0,
          dimension: 0,
          difficulty: 0,
          maxPlayers: 20,
          reducedDebugInfo:true
        });
        client.write('map_chunk', {
          x: 0,
          z: 0,
          groundUp: true,
          bitMap: parseInt('00111100', 2),
          chunkData: buffer
        });
        client.write('position', {
          x: 1.5,
          y: 80,
          z: 1.5,
          pitch: 0,
          yaw: 0,
          flags: 0
        });
      });
    });
  });
  describe("entities", function() {
    it("sets players[player].entity to null upon despawn", function(done) {
      var serverClient = null;
      bot.once('entitySpawn', function(entity) {
        serverClient.write('entity_destroy', {
          entityIds: [8],
        });
      });
      bot.once("entityGone", function(entity) {
        assert.equal(bot.players[entity.username], null);
        done();
      });
      server.on('login', function(client) {
        serverClient = client;

        client.write('player_info',{ id: 56,
          state: 'play',
          action: 0,
          length: 1,
          data:
            [ { UUID: [1,2,3,4],
              name: 'bot5',
              propertiesLength: 0,
              properties: [],
              gamemode: 0,
              ping: 0,
              hasDisplayName: false } ] });

        client.write('named_entity_spawn', {
          entityId: 56,
          playerUUID: [1,2,3,4],
          x: 1,
          y: 2,
          z: 3,
          yaw: 0,
          pitch: 0,
          currentItem: -1,
          metadata: [],
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>module.exports = function (grunt) {
    // Do grunt-related things in here
    grunt.initConfig({
            pkg: grunt.file.readJSON('package.json'), uglify: {
                options: {
                    banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
                },
                build: {
                    src: 'javascript-inheritance.js',
                    dest: 'build/<%= pkg.name %>.min.js'
                }
            }, jasmine: {
                prototypal: {
                    src: 'javascript-inheritance.js',
                    options: {
                        specs: 'specs/PrototypalInheritanceSpec.js',
                        helpers: 'specs/SpecHelper.js',
                        junit: {
                            path: 'junit'
                        }
                    }
                },
                classical: {
                    src: 'javascript-inheritance.js',
                    options: {
                        specs: 'specs/ClassicalInheritanceSpec.js',
                        helpers: 'specs/SpecHelper.js',
                        junit: {
                            path: 'junit'
                        }
                    }
                }
            },
            jasmine_node: {
                coverage: {
                },
                options: {
                    forceExit: true,
                    match: '.',
                    matchall: false,
                    extensions: 'js',
                    specNameMatcher: 'spec',
                    junitreport: {
                        report: false,
                        savePath: "./junit/coverage/",
                        useDotNotation: true,
                        consolidate: true
                    }
                }
            }
            , 'jasmine-server': {
                browser: false
            },
            jshint: {
                all: ['*.js', 'specs/*.js'], options: {
                    jshintrc: '.jshintrc'
                }
            }
            , watch: {
                scripts: {
                    files: ['javascript-inheritance.js', 'specs/*.js'],
                    tasks: ['jshint', 'jasmine'],
                    options: {
                        spawn: false
                    }
                }
            }
        }
    )
    ;
    grunt.loadNpmTasks('grunt-contrib-jasmine');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-jasmine-node-coverage');

    grunt.registerTask('test', 'jasmine') ;
    grunt.registerTask('build', 'uglify') ;

    grunt.registerTask('default', ['jasmine', 'jshint', 'jasmine_node']) ;
}
;<commit_msg>added grunt tasks<commit_after>module.exports = function (grunt) {
    // Do grunt-related things in here
    grunt.initConfig({
            pkg: grunt.file.readJSON('package.json'), uglify: {
                options: {
                    banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
                },
                build: {
                    src: 'javascript-inheritance.js',
                    dest: 'build/<%= pkg.name %>.min.js'
                }
            }, jasmine: {
                prototypal: {
                    src: 'javascript-inheritance.js',
                    options: {
                        specs: 'specs/PrototypalInheritanceSpec.js',
                        helpers: 'specs/SpecHelper.js',
                        junit: {
                            path: 'junit'
                        }
                    }
                },
                classical: {
                    src: 'javascript-inheritance.js',
                    options: {
                        specs: 'specs/ClassicalInheritanceSpec.js',
                        helpers: 'specs/SpecHelper.js',
                        junit: {
                            path: 'junit'
                        }
                    }
                }
            },
            jasmine_node: {
                coverage: {
                },
                options: {
                    forceExit: true,
                    match: '.',
                    matchall: false,
                    extensions: 'js',
                    specNameMatcher: 'spec',
                    junitreport: {
                        report: false,
                        savePath: "./junit/coverage/",
                        useDotNotation: true,
                        consolidate: true
                    }
                },
                all: ['specs/']
            }
            , 'jasmine-server': {
                browser: false
            },
            jshint: {
                all: ['*.js', 'specs/*.js'], options: {
                    jshintrc: '.jshintrc'
                }
            }
            , watch: {
                scripts: {
                    files: ['javascript-inheritance.js', 'specs/*.js'],
                    tasks: ['jshint', 'jasmine'],
                    options: {
                        spawn: false
                    }
                }
            }
        }
    )
    ;
    grunt.loadNpmTasks('grunt-contrib-jasmine');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-jasmine-node-coverage');

    grunt.registerTask('test', 'jasmine') ;
    grunt.registerTask('build', 'uglify') ;

    grunt.registerTask('default', ['jasmine', 'jshint', 'jasmine_node']) ;
}
;<|endoftext|>


<commit_before>var config = require('config');
var log = require('./client/log')('geocode');
var get = require('./client/request').get;

/**
 * Geocode
 */

module.exports = geocode;
module.exports.reverseAmigo = reverseAmigo;
module.exports.suggestAmigo = suggestAmigo;

/**
 * Geocode
 */

function geocode(address, callback) {
  log('--> geocoding %s', address);
  get('/geocode/' + address, function(err, res) {
    if (err) {
      log('<-- geocoding error %s', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Reverse geocode
 */

function reverseAmigo(ll, callback) {

  var parameter = {
      'token':config.realtime_access_token() ,
      'point.lon':ll[0],
      'point.lat':ll[1]
  };

  get('https://www.amigocloud.com/api/v1/me/geocoder/reverse', parameter, function(err, res) {

    if (err) {
      log('<-- geocoding error %e', err);

    } else {
      callback(false, res.body);
    }
  });
}

/**
 * Suggestions!
 */

function suggestAmigo(text, callback) {
    var databoundary = [];
    get('https://www.amigocloud.com/api/v1/users/1/projects/661/datasets/22492', {'token' : config.realtime_access_token()}, function(err, res) {

        if (err) {
            console.log("error");
        }else {
            console.log("data boundary ->" , res.body);
        }

    )};

    var list_address;
    var parameter = {
        'token': config.realtime_access_token() ,
        'boundary.rect.min_lat': '36.155617833819',
        'boundary.rect.min_lon': '-123.607177734375',
        'boundary.rect.max_lat': '38.826870521381',
        'boundary.rect.max_lon': '-120.701293945312',
        'sources':'osm,oa',
        'text': text
    };

    get('https://www.amigocloud.com/api/v1/me/geocoder/search', parameter, function(err, res) {

            if(err) {
                log("Amigo Cloud Response Error ->", err);

            }else{
                if(res.body.features) {

                    list_address = res.body.features;
                    if (list_address.length > 0) {
                         callback(
                            null,
                            list_address
                        );
                    }else {
                        callback(true, res);
                    }

                }
            }
    });
}
<commit_msg>agregando data<commit_after>var config = require('config');
var log = require('./client/log')('geocode');
var get = require('./client/request').get;

/**
 * Geocode
 */

module.exports = geocode;
module.exports.reverseAmigo = reverseAmigo;
module.exports.suggestAmigo = suggestAmigo;

/**
 * Geocode
 */

function geocode(address, callback) {
  log('--> geocoding %s', address);
  get('/geocode/' + address, function(err, res) {
    if (err) {
      log('<-- geocoding error %s', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Reverse geocode
 */

function reverseAmigo(ll, callback) {

  var parameter = {
      'token':config.realtime_access_token() ,
      'point.lon':ll[0],
      'point.lat':ll[1]
  };

  get('https://www.amigocloud.com/api/v1/me/geocoder/reverse', parameter, function(err, res) {

    if (err) {
      log('<-- geocoding error %e', err);

    } else {
      callback(false, res.body);
    }
  });
}

/**
 * Suggestions!
 */

function suggestAmigo(text, callback) {
    var databoundary = [];
    get('https://www.amigocloud.com/api/v1/users/1/projects/661/datasets/22492', {'token' : config.realtime_access_token()}, function(err, res) {

        if (err) {
            console.log("error");
        }else {
            console.log("data boundary ->" , res.body);
        }

    });

    var list_address;
    var parameter = {
        'token': config.realtime_access_token() ,
        'boundary.rect.min_lat': '36.155617833819',
        'boundary.rect.min_lon': '-123.607177734375',
        'boundary.rect.max_lat': '38.826870521381',
        'boundary.rect.max_lon': '-120.701293945312',
        'sources':'osm,oa',
        'text': text
    };

    get('https://www.amigocloud.com/api/v1/me/geocoder/search', parameter, function(err, res) {

            if(err) {
                log("Amigo Cloud Response Error ->", err);

            }else{
                if(res.body.features) {

                    list_address = res.body.features;
                    if (list_address.length > 0) {
                         callback(
                            null,
                            list_address
                        );
                    }else {
                        callback(true, res);
                    }

                }
            }
    });
}
<|endoftext|>


<commit_before>var expect = require('chai').expect;
var user = require('../lib/user');

describe('validate', function() {

  it('should return false for an invalid oauth token', function(done) {
    var aub = user.fromModel({
      login: 'aubhaze',
      token: 'fake',
      model: {}
    });
    aub.validate().then(function(res) {
      expect(res).to.be.false;
      done();
    }, done);
  });

});
<commit_msg>Add fromModel test<commit_after>var expect = require('chai').expect;
var user = require('../lib/user');

describe('fromModel', function() {
  it('should set correct params', function() {
    var model = {
      login: 'aubhaze',
      token: 'fake',
      avatar_url: 'asdf'
    };
    var res = user.fromModel(model);

    expect(res.login).to.equal(model.login);
    expect(res.model).to.eql(model);
  });
});

describe('validate', function() {

  it('should return false for an invalid oauth token', function(done) {
    var aub = user.fromModel({
      login: 'aubhaze',
      token: 'fake',
      model: {}
    });
    aub.validate().then(function(res) {
      expect(res).to.be.false;
      done();
    }, done);
  });

});
<|endoftext|>


<commit_before>'use strict';

var index = require('../../../lib/index');

describe('lib/index', sandbox(function () {
  var config, result, expected;

  beforeEach(function () {
    this.clipboard = {
      files: {
        'index.html': '123',
        schemas: {
          'bar.json': '123',
          bars: {
            'baz.json': '123'
          }
        },
        ignored: {
          foo: '123'
        }
      }
    };

    config = {
      index: {
        schemas: true
      }
    };

    expected = {
      files: {
        'index.html': 'index.html',
        schemas: {
          'bar.json': 'schemas/bar.json',
          bars: {
            'baz.json': 'schemas/bars/baz.json'
          }
        }
      }
    };

    result = index.call(this, config);
  });

  it('returns an object which indexes all the files from the clipboard', function () {
    result.should.deep.equal(expected);
  });

}));
<commit_msg>Fix index.test.js unit test for Windows devices<commit_after>'use strict';

var index = require('../../../lib/index');
var path = require('path');

describe('lib/index', sandbox(function () {
  var config, result, expected;

  beforeEach(function () {
    this.clipboard = {
      files: {
        'index.html': '123',
        schemas: {
          'bar.json': '123',
          bars: {
            'baz.json': '123'
          }
        },
        ignored: {
          foo: '123'
        }
      }
    };

    config = {
      index: {
        schemas: true
      }
    };

    expected = {
      files: {
        'index.html': 'index.html',
        schemas: {
          'bar.json': 'schemas' + path.sep + 'bar.json',
          bars: {
            'baz.json': 'schemas' + path.sep + 'bars' + path.sep + 'baz.json'
          }
        }
      }
    };

    result = index.call(this, config);
  });

  it('returns an object which indexes all the files from the clipboard', function () {
    result.should.deep.equal(expected);
  });

}));
<|endoftext|>


<commit_before>const months = ['January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'];
const weekdays = ['Sunday',
  'Monday',
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday',
  'Saturday'];

// -----

$('.datepicker').pickadate({
  // The title label to use for the month nav buttons
  labelMonthNext: pgettext('Datepicker option', 'Next month'),
  labelMonthPrev: pgettext('Datepicker option', 'Previous month'),

  // The title label to use for the dropdown selectors
  labelMonthSelect: pgettext('Datepicker option', 'Select a month'),
  labelYearSelect: pgettext('Datepicker option', 'Select a year'),

  // Months and weekdays
  monthsFull: months.map(month => pgettext('Datepicker month', month)),
  monthsShort: months.map(month => pgettext('Datepicker month shortcut', month.slice(0, 3))),
  weekdaysFull: weekdays.map(day => pgettext('Datepicker weekday', day)),
  weekdaysShort: weekdays.map(day => pgettext('Datepicker weekday shortcut', day.slice(0, 3))),

  // Materialize modified
  weekdaysLetter: weekdays.map(day => pgettext(`${day} shortcut`, day[0])),
  today: pgettext('Datepicker option', 'Today'),
  clear: pgettext('Datepicker option', 'Clear'),
  close: pgettext('Datepicker option', 'Close'),

  format: 'd mmmm yyyy',
  formatSubmit: 'yyyy-mm-dd',
  selectMonths: true,
  hiddenName: true,
  onClose: () => $(document.activeElement).blur()
});
<commit_msg>Fix translations<commit_after>// -----

$('.datepicker').pickadate({
  labelMonthNext: pgettext('Datepicker option', 'Next month'),
  labelMonthPrev: pgettext('Datepicker option', 'Previous month'),

  // The title label to use for the dropdown selectors
  labelMonthSelect: pgettext('Datepicker option', 'Select a month'),
  labelYearSelect: pgettext('Datepicker option', 'Select a year'),

  // Months and weekdays
  monthsFull: [
    pgettext('Datepicker month', 'January'),
    pgettext('Datepicker month', 'February'),
    pgettext('Datepicker month', 'March'),
    pgettext('Datepicker month', 'April'),
    pgettext('Datepicker month', 'May'),
    pgettext('Datepicker month', 'June'),
    pgettext('Datepicker month', 'July'),
    pgettext('Datepicker month', 'August'),
    pgettext('Datepicker month', 'September'),
    pgettext('Datepicker month', 'October'),
    pgettext('Datepicker month', 'November'),
    pgettext('Datepicker month', 'December')],
  monthsShort: [
    pgettext('Datepicker month shortcut', 'Jan'),
    pgettext('Datepicker month shortcut', 'Feb'),
    pgettext('Datepicker month shortcut', 'Mar'),
    pgettext('Datepicker month shortcut', 'Apr'),
    pgettext('Datepicker month shortcut', 'May'),
    pgettext('Datepicker month shortcut', 'Jun'),
    pgettext('Datepicker month shortcut', 'Jul'),
    pgettext('Datepicker month shortcut', 'Aug'),
    pgettext('Datepicker month shortcut', 'Sep'),
    pgettext('Datepicker month shortcut', 'Oct'),
    pgettext('Datepicker month shortcut', 'Nov'),
    pgettext('Datepicker month shortcut', 'Dec')],
  weekdaysFull: [
    pgettext('Datepicker weekday', 'Sunday'),
    pgettext('Datepicker weekday', 'Monday'),
    pgettext('Datepicker weekday', 'Tuesday'),
    pgettext('Datepicker weekday', 'Wednesday'),
    pgettext('Datepicker weekday', 'Thursday'),
    pgettext('Datepicker weekday', 'Friday'),
    pgettext('Datepicker weekday', 'Saturday')],
  weekdaysShort: [
    pgettext('Datepicker weekday shortcut', 'Sun'),
    pgettext('Datepicker weekday shortcut', 'Mon'),
    pgettext('Datepicker weekday shortcut', 'Tue'),
    pgettext('Datepicker weekday shortcut', 'Wed'),
    pgettext('Datepicker weekday shortcut', 'Thu'),
    pgettext('Datepicker weekday shortcut', 'Fri'),
    pgettext('Datepicker weekday shortcut', 'Sat')],

  // Materialize modified
  weekdaysLetter: [
    pgettext('Sunday shortcut', 'S'),
    pgettext('Monday shortcut', 'M'),
    pgettext('Tuesday shortcut', 'T'),
    pgettext('Wednesday shortcut', 'W'),
    pgettext('Thursday shortcut', 'T'),
    pgettext('Friday shortcut', 'F'),
    pgettext('Saturday shortcut', 'S')],
  today: pgettext('Datepicker option', 'Today'),
  clear: pgettext('Datepicker option', 'Clear'),
  close: pgettext('Datepicker option', 'Close'),

  format: 'd mmmm yyyy',
  formatSubmit: 'yyyy-mm-dd',
  selectMonths: true,
  hiddenName: true,
  onClose: () => $(document.activeElement).blur()
});
<|endoftext|>


<commit_before>const
  env = requireModule("env"),
  readLocalBranch = requireModule("read-local-branch");

module.exports = async function() {
  const fromEnv = env.resolve("GIT_BRANCH");
  if (fromEnv) {
    return fromEnv;
  }
  return await readLocalBranch();
}
<commit_msg>:bug: should import the correct module :/<commit_after>const
  env = requireModule("env"),
  readCurrentBranch = requireModule("read-current-branch");

module.exports = async function() {
  const fromEnv = env.resolve("GIT_BRANCH");
  if (fromEnv) {
    return fromEnv;
  }
  return await readCurrentBranch();
}
<|endoftext|>


<commit_before>const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PurifyCSSPlugin = require('purifycss-webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');

exports.devServer = function({ host, port }) {
  return {
    devServer: {
      // Enable history API fallback so HTML5 History API based
      // routing works. This is a good default that will come
      // in handy in more complicated setups.
      historyApiFallback: true,

      // Don't refresh if hot loading fails. If you want
      // refresh behavior, set hot: true instead.
      hotOnly: true,

      // Display only errors to reduce the amount of output.
      stats: 'errors-only',

      // Parse host and port from env to allow customization.
      //
      // If you use Vagrant or Cloud9, set
      // host: options.host || '0.0.0.0';
      //
      // 0.0.0.0 is available to all network devices
      // unlike default `localhost`.
      host: host, // Defaults to `localhost`
      port: port, // Defaults to 8080
    },
    plugins: [
      // Enable multi-pass compilation for enhanced performance
      // in larger projects. Good default.
      new webpack.HotModuleReplacementPlugin({
        // Disabled as this won't work with html-webpack-template
        //multiStep: true
      }),
    ],
  };
};

exports.lintJavaScript = function({ include, exclude, options }) {
  return {
    module: {
      rules: [
        {
          test: /\.js$/,
          include: include,
          exclude: exclude,
          enforce: 'pre',

          loader: 'eslint-loader',
          options: options,
        },
      ],
    },
  };
};

exports.loadCSS = function({ include, exclude } = {}) {
  return {
    module: {
      rules: [
        {
          test: /\.css$/,
          include: include,
          exclude: exclude,

          use: ['style-loader', 'css-loader'],
        },
      ],
    },
  };
};

exports.extractCSS = function({ include, exclude } = {}) {
  return {
    module: {
      rules: [
        // Extract CSS during build
        {
          test: /\.css$/,
          include: include,
          exclude: exclude,

          use: ExtractTextPlugin.extract({
            fallbackLoader: 'style-loader',
            loader: 'css-loader',
          }),
        },
      ],
    },
    plugins: [
      // Output extracted CSS to a file
      new ExtractTextPlugin('[name].[contenthash].css'),
    ],
  };
};

exports.purifyCSS = function(paths) {
  return {
    plugins: [
      new PurifyCSSPlugin({ paths: paths }),
    ],
  };
};

exports.lintCSS = function({ include, exclude, rules }) {
  return {
    module: {
      rules: [
        {
          test: /\.css$/,
          include: include,
          exclude: exclude,
          enforce: 'pre',

          loader: 'postcss-loader',
          options: {
            plugins: function () {
              return [
                require('stylelint')({
                  rules: rules,
                  // Ignore node_modules CSS
                  ignoreFiles: 'node_modules/**/*.css',
                }),
              ];
            },
          },
        },
      ],
    },
  };
};

exports.generateSourceMaps = function({ type }) {
  return {
    devtool: type,
  };
};

exports.extractBundles = function(bundles, options) {
  const entry = {};
  const names = [];

  // Set up entries and names.
  bundles.forEach(({ name, entries }) => {
    if (entries) {
      entry[name] = entries;
    }

    names.push(name);
  });

  return {
    // Define an entry point needed for splitting.
    entry,
    plugins: [
      // Extract bundles.
      new webpack.optimize.CommonsChunkPlugin(
        Object.assign({}, options, { names })
      ),
    ],
  };
};

exports.loadJavaScript = function({ include, exclude }) {
  return {
    module: {
      rules: [
        {
          test: /\.js$/,
          include: include,
          exclude: exclude,

          loader: 'babel-loader',
          options: {
            // Enable caching for improved performance during
            // development.
            // It uses default OS directory by default. If you need
            // something more custom, pass a path to it.
            // I.e., { cacheDirectory: '<path>' }
            cacheDirectory: true,
          },
        },
      ],
    },
  };
};

exports.clean = function(path) {
  return {
    plugins: [
      new CleanWebpackPlugin([path]),
    ],
  };
};

exports.minifyJavaScript = function({ useSourceMap }) {
  return {
    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: useSourceMap,
        compress: {
          warnings: false,
        },
      }),
    ],
  };
};

exports.setFreeVariable = function(key, value) {
  const env = {};
  env[key] = JSON.stringify(value);

  return {
    plugins: [
      new webpack.DefinePlugin(env),
    ],
  };
};

<commit_msg>Drop multi-pass comment<commit_after>const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PurifyCSSPlugin = require('purifycss-webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');

exports.devServer = function({ host, port }) {
  return {
    devServer: {
      // Enable history API fallback so HTML5 History API based
      // routing works. This is a good default that will come
      // in handy in more complicated setups.
      historyApiFallback: true,

      // Don't refresh if hot loading fails. If you want
      // refresh behavior, set hot: true instead.
      hotOnly: true,

      // Display only errors to reduce the amount of output.
      stats: 'errors-only',

      // Parse host and port from env to allow customization.
      //
      // If you use Vagrant or Cloud9, set
      // host: options.host || '0.0.0.0';
      //
      // 0.0.0.0 is available to all network devices
      // unlike default `localhost`.
      host: host, // Defaults to `localhost`
      port: port, // Defaults to 8080
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin({
        // Disabled as this won't work with html-webpack-template
        //multiStep: true
      }),
    ],
  };
};

exports.lintJavaScript = function({ include, exclude, options }) {
  return {
    module: {
      rules: [
        {
          test: /\.js$/,
          include: include,
          exclude: exclude,
          enforce: 'pre',

          loader: 'eslint-loader',
          options: options,
        },
      ],
    },
  };
};

exports.loadCSS = function({ include, exclude } = {}) {
  return {
    module: {
      rules: [
        {
          test: /\.css$/,
          include: include,
          exclude: exclude,

          use: ['style-loader', 'css-loader'],
        },
      ],
    },
  };
};

exports.extractCSS = function({ include, exclude } = {}) {
  return {
    module: {
      rules: [
        // Extract CSS during build
        {
          test: /\.css$/,
          include: include,
          exclude: exclude,

          use: ExtractTextPlugin.extract({
            fallbackLoader: 'style-loader',
            loader: 'css-loader',
          }),
        },
      ],
    },
    plugins: [
      // Output extracted CSS to a file
      new ExtractTextPlugin('[name].[contenthash].css'),
    ],
  };
};

exports.purifyCSS = function(paths) {
  return {
    plugins: [
      new PurifyCSSPlugin({ paths: paths }),
    ],
  };
};

exports.lintCSS = function({ include, exclude, rules }) {
  return {
    module: {
      rules: [
        {
          test: /\.css$/,
          include: include,
          exclude: exclude,
          enforce: 'pre',

          loader: 'postcss-loader',
          options: {
            plugins: function () {
              return [
                require('stylelint')({
                  rules: rules,
                  // Ignore node_modules CSS
                  ignoreFiles: 'node_modules/**/*.css',
                }),
              ];
            },
          },
        },
      ],
    },
  };
};

exports.generateSourceMaps = function({ type }) {
  return {
    devtool: type,
  };
};

exports.extractBundles = function(bundles, options) {
  const entry = {};
  const names = [];

  // Set up entries and names.
  bundles.forEach(({ name, entries }) => {
    if (entries) {
      entry[name] = entries;
    }

    names.push(name);
  });

  return {
    // Define an entry point needed for splitting.
    entry,
    plugins: [
      // Extract bundles.
      new webpack.optimize.CommonsChunkPlugin(
        Object.assign({}, options, { names })
      ),
    ],
  };
};

exports.loadJavaScript = function({ include, exclude }) {
  return {
    module: {
      rules: [
        {
          test: /\.js$/,
          include: include,
          exclude: exclude,

          loader: 'babel-loader',
          options: {
            // Enable caching for improved performance during
            // development.
            // It uses default OS directory by default. If you need
            // something more custom, pass a path to it.
            // I.e., { cacheDirectory: '<path>' }
            cacheDirectory: true,
          },
        },
      ],
    },
  };
};

exports.clean = function(path) {
  return {
    plugins: [
      new CleanWebpackPlugin([path]),
    ],
  };
};

exports.minifyJavaScript = function({ useSourceMap }) {
  return {
    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: useSourceMap,
        compress: {
          warnings: false,
        },
      }),
    ],
  };
};

exports.setFreeVariable = function(key, value) {
  const env = {};
  env[key] = JSON.stringify(value);

  return {
    plugins: [
      new webpack.DefinePlugin(env),
    ],
  };
};

<|endoftext|>


<commit_before>'use strict';

const St = imports.gi.St;
const Main = imports.ui.main;
const GnomeDesktop = imports.gi.GnomeDesktop;
const Lang = imports.lang;
const Shell = imports.gi.Shell;
const Util = imports.misc.util;
const Config = imports.misc.config;

const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
const Convenience = Me.imports.convenience;

let text, button, label;
let clock, clock_signal_id;
let settings;

let signals = [];

let format_params = {
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
}
let time_text = 'UTC';

let shellMinorVersion = parseInt(Config.PACKAGE_VERSION.split('.')[1]);

function init() {
    settings = Convenience.getSettings();

    clock = new GnomeDesktop.WallClock();
    button = new St.Bin({
        style_class: 'panel-button',
        reactive: true,
        can_focus: false,
        x_expand: true,
        y_expand: false,
        y_align: shellMinorVersion < 36 ? St.Align.MIDDLE : St.Align.END,
        track_hover: true
    });

    label = new St.Label({
        text: '00:00:00' + time_text,
        opacity: 200
    });

    button.set_child(label);
}

function enable() {
    log_this(`enabling...`);

    signals[0] = settings.connect('changed::show-seconds', Lang.bind(this, setSecondsDisplayed));
    signals[1] = settings.connect('changed::time-text', Lang.bind(this, setTimeText));
    signals[2] = settings.connect('changed::show-date', Lang.bind(this, setDateDisplayed));
    signals[3] = settings.connect('changed::light-opacity', Lang.bind(this, setLightOpacity));

    signals[4] = button.connect('button-press-event', showMenu);
    setSecondsDisplayed();
    setTimeText();
    setDateDisplayed();
    setLightOpacity();

    update_time();
    signals[5] = clock.connect('notify::clock', Lang.bind(this, this.update_time));
    Main.panel._centerBox.insert_child_at_index(button, 1);
    log_this(`enabled.`);
}

function disable() {
    log_this(`disabling...`);

    settings.disconnect(signals[0]);
    settings.disconnect(signals[1]);
    settings.disconnect(signals[2]);
    settings.disconnect(signals[3]);
    button.disconnect(signals[4]);

    Main.panel._centerBox.remove_child(button);
    clock.disconnect(signals[5]);
    log_this(`disabled.`);
}

function update_time() {
    var now = new Date();
    var utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
    label.set_text(new Intl.DateTimeFormat('default', format_params).format(utc) + ' ' + time_text);
}

function setSecondsDisplayed() {
    let secondsDisplayed = settings.get_boolean('show-seconds');
    if (secondsDisplayed) {
        format_params['second'] = '2-digit';
    } else {
        delete format_params['second'];
    }
    update_time();
}

function setTimeText() {
    time_text = settings.get_string('time-text');
    update_time();
}

function setDateDisplayed() {
    let dateDisplayed = settings.get_boolean('show-date');
    if (dateDisplayed) {
        format_params['weekday'] = 'short';
        format_params['month'] = 'short';
        format_params['day'] = 'numeric';
    } else {
        delete format_params['weekday'];
        delete format_params['month'];
        delete format_params['day'];
    }
    update_time();
}

function setLightOpacity() {
    label.opacity = settings.get_boolean('light-opacity') ? 255 : 200;
    update_time();
}

function showMenu() {
    Util.spawn([
        "gnome-shell-extension-prefs",
        Me.uuid
    ]);
}

function log_this(string) {
    log(`[${Me.metadata.name}-${Me.metadata.version}] ${string}`)
}<commit_msg>Code cleanup<commit_after>'use strict';

const St = imports.gi.St;
const Main = imports.ui.main;
const GnomeDesktop = imports.gi.GnomeDesktop;
const Lang = imports.lang;
const Shell = imports.gi.Shell;
const Util = imports.misc.util;
const Config = imports.misc.config;

const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
const Convenience = Me.imports.convenience;

let text, button, label;
let clock, clock_signal_id;
let settings;

let signals = [];

let format_params = {
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
}
let time_text = 'UTC';

let shellMinorVersion = parseInt(Config.PACKAGE_VERSION.split('.')[1]);

function init() {
    settings = Convenience.getSettings();

    clock = new GnomeDesktop.WallClock();
    button = new St.Bin({
        style_class: 'panel-button',
        reactive: true,
        can_focus: false,
        x_expand: true,
        y_expand: false,
        y_align: shellMinorVersion < 36 ? St.Align.MIDDLE : St.Align.END,
        track_hover: true
    });

    label = new St.Label({
        opacity: 200
    });

    button.set_child(label);
}

function enable() {
    log_this(`enabling...`);

    signals[0] = settings.connect('changed::show-seconds', Lang.bind(this, setSecondsDisplayed));
    signals[1] = settings.connect('changed::time-text', Lang.bind(this, setTimeText));
    signals[2] = settings.connect('changed::show-date', Lang.bind(this, setDateDisplayed));
    signals[3] = settings.connect('changed::light-opacity', Lang.bind(this, setLightOpacity));

    signals[4] = button.connect('button-press-event', showMenu);
    setSecondsDisplayed();
    setTimeText();
    setDateDisplayed();
    setLightOpacity();

    update_time();
    signals[5] = clock.connect('notify::clock', Lang.bind(this, this.update_time));
    Main.panel._centerBox.insert_child_at_index(button, 1);
    log_this(`enabled.`);
}

function disable() {
    log_this(`disabling...`);

    settings.disconnect(signals[0]);
    settings.disconnect(signals[1]);
    settings.disconnect(signals[2]);
    settings.disconnect(signals[3]);
    button.disconnect(signals[4]);

    Main.panel._centerBox.remove_child(button);
    clock.disconnect(signals[5]);
    log_this(`disabled.`);
}

function update_time() {
    var now = new Date();
    var utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
    label.set_text(new Intl.DateTimeFormat('default', format_params).format(utc) + ' ' + time_text);
}

function setSecondsDisplayed() {
    let secondsDisplayed = settings.get_boolean('show-seconds');
    if (secondsDisplayed) {
        format_params['second'] = '2-digit';
    } else {
        delete format_params['second'];
    }
    update_time();
}

function setTimeText() {
    time_text = settings.get_string('time-text');
    update_time();
}

function setDateDisplayed() {
    let dateDisplayed = settings.get_boolean('show-date');
    if (dateDisplayed) {
        format_params['weekday'] = 'short';
        format_params['month'] = 'short';
        format_params['day'] = 'numeric';
    } else {
        delete format_params['weekday'];
        delete format_params['month'];
        delete format_params['day'];
    }
    update_time();
}

function setLightOpacity() {
    label.opacity = settings.get_boolean('light-opacity') ? 255 : 200;
    update_time();
}

function showMenu() {
    Util.spawn([
        "gnome-shell-extension-prefs",
        Me.uuid
    ]);
}

function log_this(string) {
    log(`[${Me.metadata.name}-${Me.metadata.version}] ${string}`)
}<|endoftext|>


<commit_before>/**
 * SowerPHP: Minimalist Framework for PHP
 * Copyright (C) SowerPHP (http://sowerphp.org)
 *
 * Este programa es software libre: usted puede redistribuirlo y/o
 * modificarlo bajo los términos de la Licencia Pública General GNU
 * publicada por la Fundación para el Software Libre, ya sea la versión
 * 3 de la Licencia, o (a su elección) cualquier versión posterior de la
 * misma.
 *
 * Este programa se distribuye con la esperanza de que sea útil, pero
 * SIN GARANTÍA ALGUNA; ni siquiera la garantía implícita
 * MERCANTIL o de APTITUD PARA UN PROPÓSITO DETERMINADO.
 * Consulte los detalles de la Licencia Pública General GNU para obtener
 * una información más detallada.
 *
 * Debería haber recibido una copia de la Licencia Pública General GNU
 * junto a este programa.
 * En caso contrario, consulte <http://www.gnu.org/licenses/gpl.html>.
 */

/**
 * @file __.js
 * Biblioteca con métodos genéricos (bajo la clase __) para propósitos
 * genéricos
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
 * @version 2014-04-09
 */

/*jslint browser: true, devel: true, nomen: true, indent: 4 */

/**
 * Constructor de la clase
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
 * @version 2014-04-09
 */
function __() {
    'use strict';
    return;
}

/**
 * Método que determina si un objeto es/está vacío o no
 * @param obj Objeto que se está revisando
 * @return =true si es vacio
 */
__.empty = function (obj) {
    'use strict';
    if (obj === undefined || obj === null || obj === "") { return true; }
    if (typeof obj === "number" && isNaN(obj)) { return true; }
    if (obj instanceof Date && isNaN(Number(obj))) { return true; }
    return false;
};

/**
 * Método que determina si un string es la representación entera de un número
 * @param value Valor que se desea verificar si es una representación entera
 * @return =true valor pasado es un enero
 */
__.isInt = function (value) {
    'use strict';
    if ((parseFloat(value) === parseInt(value, 10)) && !isNaN(value)) {
        return true;
    }
    return false;
};

/**
 * Método que formatea un número usando separador de miles
 * @param n Número a formatear (ej: 1234)
 * @return Número formateado (ej: 1.234)
 * @author http://ur1.ca/h1cvs
 */
__.num = function (n) {
    'use strict';
    var number = n.toString(), result = "", isNegative = false;
    if (number.indexOf("-") > -1) {
        number = number.substr(1);
        isNegative = true;
    }
    while (number.length > 3) {
        result = "." + number.substr(number.length - 3) + result;
        number = number.substring(0, number.length - 3);
    }
    result = number + result;
    if (isNegative) { result = "-" + result; }
    return result;
};

/**
 * Método que remueve los tags <option> de un tag <select>
 * @param selectbox Elemento select que se quiere limpiar
 * @param from Desde que option limpiar el campo select
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
 * @version 2014-04-09
 */
__.removeOptions = function (selectbox, from) {
    'use strict';
    var i;
    from = from || 0;
    for (i = selectbox.options.length - 1; i >= from; i -= 1) {
        selectbox.remove(i);
    }
};

/**
 * Obtiene el dígito verificador a partir del rut sin este
 * @param numero Rut sin puntos ni digito verificador
 * @return char dígito verificador del rut ingresado
 * @author http://ur1.ca/h1d8v
 * @version 2011-04-21
 */
__.rutDV = function (numero) {
    'use strict';
    var nuevo_numero, i, j, suma, n_dv;
    nuevo_numero = numero.toString().split("").reverse().join("");
    for (i = 0, j = 2, suma = 0; i < nuevo_numero.length; i += 1, j = j === 7 ? 2 : j + 1) {
        suma += (parseInt(nuevo_numero.charAt(i), 10) * j);
    }
    n_dv = 11 - (suma % 11);
    return ((n_dv === 11) ? 0 : ((n_dv === 10) ? "K" : n_dv));
};

/**
 * Método que abre un popup
 * @param url Dirección web que se debe abrir en el popup
 * @param w Ancho de la ventana que se abrirá
 * @param h Alto de la ventana que se abrirá
 * @param s Si se muestran ("yes") o no ("no") los scrollbars
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
 * @version 2014-04-09
 */
__.popup = function (url, w, h, s) {
    'use strict';
    s = s || "no";
    window.open(
        url,
        window,
        "width=" + w + ",height=" + h + ",directories=no,location=no,menubar=no,scrollbars=" + s + ",status=no,toolbar=no,resizable=no"
    );
}

/**
 * Función para enviar un formulario por POST
 * @param url URL donde se debe enviar el formulario
 * @param variables Hash json con las variables a pasar al formulario
 * @param newWindow Si está asignado se abrirá el formulario en una nueva ventana
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
 * @version 2014-04-29
 */
__.post = function(url, variables, newWindow) {
    'use strict';
    var form, hiddenField, variable;
    form = document.createElement('form');
    form.setAttribute('method', 'post');
    form.setAttribute('action', url);
    if (typeof(newWindow) !== 'undefined') {
        form.setAttribute('target', '_blank');
    }
    for (variable in variables) {
        hiddenField = document.createElement('input');
        hiddenField.setAttribute('type', 'hidden');
        hiddenField.setAttribute('name', variable);
        hiddenField.setAttribute('value', variables[variable]);
        form.appendChild(hiddenField);
    }
    form.submit();
}

/**
 * Implementación sincrónica de $.getJSON, esto para poder recuperar el objeto
 * JSON fuera de la funcion que se ejecuta en success
 * @param url Url desde donde se obtendrá el JSON
 * @param data Datos que se deben enviar por la URL (como GET)
 * @return json Datos retornados por la página
 * @todo Migrar método para que use Javascript puro (sin JQuery)
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
 * @version 2014-05-10
 */
__.getJSON = function(url, data) {
    'use strict';
    var json;
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        success: function (result) {json = result;},
        data: data,
        async: false
    });
    return json;
}
<commit_msg>Cambios a comillas dobles<commit_after>/**
 * SowerPHP: Minimalist Framework for PHP
 * Copyright (C) SowerPHP (http://sowerphp.org)
 *
 * Este programa es software libre: usted puede redistribuirlo y/o
 * modificarlo bajo los términos de la Licencia Pública General GNU
 * publicada por la Fundación para el Software Libre, ya sea la versión
 * 3 de la Licencia, o (a su elección) cualquier versión posterior de la
 * misma.
 *
 * Este programa se distribuye con la esperanza de que sea útil, pero
 * SIN GARANTÍA ALGUNA; ni siquiera la garantía implícita
 * MERCANTIL o de APTITUD PARA UN PROPÓSITO DETERMINADO.
 * Consulte los detalles de la Licencia Pública General GNU para obtener
 * una información más detallada.
 *
 * Debería haber recibido una copia de la Licencia Pública General GNU
 * junto a este programa.
 * En caso contrario, consulte <http://www.gnu.org/licenses/gpl.html>.
 */

/**
 * @file __.js
 * Biblioteca con métodos genéricos (bajo la clase __) para propósitos
 * genéricos
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
 * @version 2014-04-09
 */

/*jslint browser: true, devel: true, nomen: true, indent: 4 */

/**
 * Constructor de la clase
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
 * @version 2014-04-09
 */
function __() {
    'use strict';
    return;
}

/**
 * Método que determina si un objeto es/está vacío o no
 * @param obj Objeto que se está revisando
 * @return =true si es vacio
 */
__.empty = function (obj) {
    'use strict';
    if (obj === undefined || obj === null || obj === "") { return true; }
    if (typeof obj === "number" && isNaN(obj)) { return true; }
    if (obj instanceof Date && isNaN(Number(obj))) { return true; }
    return false;
};

/**
 * Método que determina si un string es la representación entera de un número
 * @param value Valor que se desea verificar si es una representación entera
 * @return =true valor pasado es un enero
 */
__.isInt = function (value) {
    'use strict';
    if ((parseFloat(value) === parseInt(value, 10)) && !isNaN(value)) {
        return true;
    }
    return false;
};

/**
 * Método que formatea un número usando separador de miles
 * @param n Número a formatear (ej: 1234)
 * @return Número formateado (ej: 1.234)
 * @author http://ur1.ca/h1cvs
 */
__.num = function (n) {
    'use strict';
    var number = n.toString(), result = "", isNegative = false;
    if (number.indexOf("-") > -1) {
        number = number.substr(1);
        isNegative = true;
    }
    while (number.length > 3) {
        result = "." + number.substr(number.length - 3) + result;
        number = number.substring(0, number.length - 3);
    }
    result = number + result;
    if (isNegative) { result = "-" + result; }
    return result;
};

/**
 * Método que remueve los tags <option> de un tag <select>
 * @param selectbox Elemento select que se quiere limpiar
 * @param from Desde que option limpiar el campo select
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
 * @version 2014-04-09
 */
__.removeOptions = function (selectbox, from) {
    'use strict';
    var i;
    from = from || 0;
    for (i = selectbox.options.length - 1; i >= from; i -= 1) {
        selectbox.remove(i);
    }
};

/**
 * Obtiene el dígito verificador a partir del rut sin este
 * @param numero Rut sin puntos ni digito verificador
 * @return char dígito verificador del rut ingresado
 * @author http://ur1.ca/h1d8v
 * @version 2011-04-21
 */
__.rutDV = function (numero) {
    'use strict';
    var nuevo_numero, i, j, suma, n_dv;
    nuevo_numero = numero.toString().split("").reverse().join("");
    for (i = 0, j = 2, suma = 0; i < nuevo_numero.length; i += 1, j = j === 7 ? 2 : j + 1) {
        suma += (parseInt(nuevo_numero.charAt(i), 10) * j);
    }
    n_dv = 11 - (suma % 11);
    return ((n_dv === 11) ? 0 : ((n_dv === 10) ? "K" : n_dv));
};

/**
 * Método que abre un popup
 * @param url Dirección web que se debe abrir en el popup
 * @param w Ancho de la ventana que se abrirá
 * @param h Alto de la ventana que se abrirá
 * @param s Si se muestran ("yes") o no ("no") los scrollbars
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
 * @version 2014-04-09
 */
__.popup = function (url, w, h, s) {
    'use strict';
    s = s || "no";
    window.open(
        url,
        window,
        "width=" + w + ",height=" + h + ",directories=no,location=no,menubar=no,scrollbars=" + s + ",status=no,toolbar=no,resizable=no"
    );
}

/**
 * Función para enviar un formulario por POST
 * @param url URL donde se debe enviar el formulario
 * @param variables Hash json con las variables a pasar al formulario
 * @param newWindow Si está asignado se abrirá el formulario en una nueva ventana
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
 * @version 2014-04-29
 */
__.post = function(url, variables, newWindow) {
    'use strict';
    var form, hiddenField, variable;
    form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", url);
    if (typeof(newWindow) !== "undefined") {
        form.setAttribute("target", "_blank");
    }
    for (variable in variables) {
        hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", variable);
        hiddenField.setAttribute("value", variables[variable]);
        form.appendChild(hiddenField);
    }
    form.submit();
}

/**
 * Implementación sincrónica de $.getJSON, esto para poder recuperar el objeto
 * JSON fuera de la funcion que se ejecuta en success
 * @param url Url desde donde se obtendrá el JSON
 * @param data Datos que se deben enviar por la URL (como GET)
 * @return json Datos retornados por la página
 * @todo Migrar método para que use Javascript puro (sin JQuery)
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
 * @version 2014-05-10
 */
__.getJSON = function(url, data) {
    'use strict';
    var json;
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        success: function (result) {json = result;},
        data: data,
        async: false
    });
    return json;
}
<|endoftext|>


<commit_before>$(function(){
	disegnaBottoni();
});

function disegnaBottoni() {
	$('.buttonStyle').button();
}
<commit_msg>mappe di google<commit_after>$(function(){
	disegnaBottoni();
});

function disegnaBottoni() {
	$('.buttonStyle').button();
}

var geocoder;
var map;<|endoftext|>


<commit_before>module.exports = function(grunt) {
    require('load-grunt-tasks')(grunt);
    grunt.loadTasks('./grunt_tasks');
    grunt.loadTasks('./vendor/open-orchestra/open-orchestra-cms-bundle/OpenOrchestra/GruntTasks');
    grunt.loadTasks('./vendor/open-orchestra/open-orchestra-media-admin-bundle/OpenOrchestra/GruntTasks');

    var merge = require('merge');
    var config = {
        pkg: grunt.file.readJSON('package.json'),
        env: process.env
    };
    config = merge.recursive(true, config, loadDirConfig('./grunt_tasks/options/'));
    config = merge.recursive(true, config, loadDirConfig('./vendor/open-orchestra/open-orchestra-cms-bundle/OpenOrchestra/GruntTasks/Options/'));
    config = merge.recursive(true, config, loadDirConfig('./vendor/open-orchestra/open-orchestra-media-admin-bundle/OpenOrchestra/GruntTasks/Options/'));

    grunt.initConfig(config);
};

function loadDirConfig(path) {
    var glob = require('glob');
    var merge = require('merge');
    var dirConfig = {};

    glob.sync('*', {cwd: path}).forEach(function(filename) {
        var fileConfig = loadFileConfig(path, filename);
        dirConfig = merge.recursive(true, dirConfig, fileConfig);
    });

    return dirConfig;
}

function loadFileConfig(path, filename) {
    var keys =  filename.replace(/\.js$/,'').split('.');

    var buildFileConfig = function(keys, filepath) {
        if (keys.length == 0) {
            return require(filepath);
        } else {
            var subArray = {};
            var index = keys[0];
            keys.shift();
            subArray[index] = buildFileConfig(keys, filepath);
            return subArray;
        }
    }

    return buildFileConfig(keys, path + filename);
}
<commit_msg>add semicolon<commit_after>module.exports = function(grunt) {
    require('load-grunt-tasks')(grunt);
    grunt.loadTasks('./grunt_tasks');
    grunt.loadTasks('./vendor/open-orchestra/open-orchestra-cms-bundle/OpenOrchestra/GruntTasks');
    grunt.loadTasks('./vendor/open-orchestra/open-orchestra-media-admin-bundle/OpenOrchestra/GruntTasks');

    var merge = require('merge');
    var config = {
        pkg: grunt.file.readJSON('package.json'),
        env: process.env
    };
    config = merge.recursive(true, config, loadDirConfig('./grunt_tasks/options/'));
    config = merge.recursive(true, config, loadDirConfig('./vendor/open-orchestra/open-orchestra-cms-bundle/OpenOrchestra/GruntTasks/Options/'));
    config = merge.recursive(true, config, loadDirConfig('./vendor/open-orchestra/open-orchestra-media-admin-bundle/OpenOrchestra/GruntTasks/Options/'));

    grunt.initConfig(config);
};

function loadDirConfig(path) {
    var glob = require('glob');
    var merge = require('merge');
    var dirConfig = {};

    glob.sync('*', {cwd: path}).forEach(function(filename) {
        var fileConfig = loadFileConfig(path, filename);
        dirConfig = merge.recursive(true, dirConfig, fileConfig);
    });

    return dirConfig;
}

function loadFileConfig(path, filename) {
    var keys =  filename.replace(/\.js$/,'').split('.');

    var buildFileConfig = function(keys, filepath) {
        if (keys.length == 0) {
            return require(filepath);
        } else {
            var subArray = {};
            var index = keys[0];
            keys.shift();
            subArray[index] = buildFileConfig(keys, filepath);
            return subArray;
        }
    };

    return buildFileConfig(keys, path + filename);
}
<|endoftext|>


<commit_before>// Generated on 2014-09-30 using generator-angular 0.9.8
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: 'dist'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: './bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false,
        raw: 'Sass::Script::Number.precision = 10\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated'
        }
      },
      server: {
        options: {
          debugInfo: true
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: ['*.js', '!oldieshim.js'],
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'fonts/*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: '.',
          src: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
          dest: '<%= yeoman.dist %>'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass:server'
      ],
      test: [
        'compass'
      ],
      dist: [
        'compass:dist',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<commit_msg>Hardcoded copy of jquery-fullscreen and modernizr<commit_after>// Generated on 2014-09-30 using generator-angular 0.9.8
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: 'dist'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: './bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false,
        raw: 'Sass::Script::Number.precision = 10\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated'
        }
      },
      server: {
        options: {
          debugInfo: true
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: ['*.js', '!oldieshim.js'],
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'fonts/*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: '.',
          src: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
          dest: '<%= yeoman.dist %>'
        }, {
          expand: true,
          cwd: '.',
          src: 'bower_components/modernizr/*',
          dest: '<%= yeoman.dist %>'
        }, {
          expand: true,
          cwd: '.',
          src: 'bower_components/jquery-fullscreen/*',
          dest: '<%= yeoman.dist %>'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass:server'
      ],
      test: [
        'compass'
      ],
      dist: [
        'compass:dist',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<|endoftext|>


<commit_before>require('chai').should();

var jade = require('jade');
var jadeTraceur = require('..');

describe('compile', function(){
	var expected ='';
	it('should be the right compiled output', function(){
		var jadeT = jadeTraceur({}, jade);
		var compiled = jadeT.compileFile('./test/jade/test.jade');
		var result = compiled();
		result.should.be.equal(expected);
	});
});
<commit_msg>Fix test<commit_after>require('chai').should();

var jade = require('jade');
var jadeTraceur = require('..');

describe('compile', function(){
	var expected ='';
	it('should be the right compiled output', function(){
		var jadeT = jadeTraceur({ externalHelpers: true }, jade);
		var compiled = jadeT.compileFile('./test/jade/test.jade');
		var result = compiled();
		result.should.be.equal(expected);
	});
});
<|endoftext|>


<commit_before>import bridge from './bridge'
import server from './server'
import bundler from './bundler'
import builder from './builder'
import opts from './opts'
import disk from './disk'
import gulp from './gulp'
import cache from './cache'
import keys from './keys'
import watchDeletes from './lib/watchDeletes'
import { logError, handleError, path, log } from './lib/fns'
import Editor from './editor'

// welcome to motion!

let started = false

export async function startup(options = {}) {
  if (process.env.MOTION_DEBUG) {
    print('total startup time: ', Date.now() - process.env.startedat)
  }

  if (started) return
  started = true

  print()

  // order important!
  await opts.init(options)

  log.setLogging()
  await disk.init() // reads versions and sets up readers/writers
  await builder.clear.init() // ensures internal directories set up
  await Promise.all([
    opts.serialize(), // write out opts to state file
    cache.init(),
    bundler.init()
  ])

  watchDeletes()
}

async function gulpScripts(opts) {
  await gulp.init(opts)
  await gulp.afterBuild()
}

export async function build(opts = {}) {
  try {
    await startup({ ...opts, build: true })
    await Promise.all([
      bundler.remakeInstallDir(),
      builder.clear.buildDir()
    ])
    await Promise.all([
      gulp.assets(),
      gulpScripts({ once: opts.once })
    ])
    await bundler.all()
    await builder.build()
    if (opts.once) return
    print()
    process.exit()
  }
  catch(e) {
    handleError(e)
  }
}

export async function run(opts) {
  try {
    await startup(opts)
    if (opts.watch) gulp.assets()
    await server.run()
    await bridge.activate()
    activateEditor(bridge)
    await gulpScripts()
    cache.serialize() // write out cache
    await bundler.all()
    if (opts.watch) await builder.build()
    keys.init()
  }
  catch(e) {
    handleError(e)
  }
}

function activateEditor(bridge) {
  const editor = new Editor()
  editor.activate(bridge)
}
<commit_msg>:new: Properly relay broadcasts<commit_after>import bridge from './bridge'
import server from './server'
import bundler from './bundler'
import builder from './builder'
import opts from './opts'
import disk from './disk'
import gulp from './gulp'
import cache from './cache'
import keys from './keys'
import watchDeletes from './lib/watchDeletes'
import { logError, handleError, path, log } from './lib/fns'
import Editor from './editor'

// welcome to motion!

let started = false

export async function startup(options = {}) {
  if (process.env.MOTION_DEBUG) {
    print('total startup time: ', Date.now() - process.env.startedat)
  }

  if (started) return
  started = true

  print()

  // order important!
  await opts.init(options)

  log.setLogging()
  await disk.init() // reads versions and sets up readers/writers
  await builder.clear.init() // ensures internal directories set up
  await Promise.all([
    opts.serialize(), // write out opts to state file
    cache.init(),
    bundler.init()
  ])

  watchDeletes()
}

async function gulpScripts(opts) {
  await gulp.init(opts)
  await gulp.afterBuild()
}

export async function build(opts = {}) {
  try {
    await startup({ ...opts, build: true })
    await Promise.all([
      bundler.remakeInstallDir(),
      builder.clear.buildDir()
    ])
    await Promise.all([
      gulp.assets(),
      gulpScripts({ once: opts.once })
    ])
    await bundler.all()
    await builder.build()
    if (opts.once) return
    print()
    process.exit()
  }
  catch(e) {
    handleError(e)
  }
}

export async function run(opts) {
  try {
    await startup(opts)
    if (opts.watch) gulp.assets()
    await server.run()
    await activateBridge()
    activateEditor(bridge)
    await gulpScripts()
    cache.serialize() // write out cache
    await bundler.all()
    if (opts.watch) await builder.build()
    keys.init()
  }
  catch(e) {
    handleError(e)
  }
}

function activateEditor() {
  const editor = new Editor()
  editor.activate(bridge)
}

async function activateBridge() {
  await bridge.activate()
  bridge.onDidReceiveMessage('broadcast:editor', function(message) {
    bridge.broadcast('broadcast:editor', message)
  })
}
<|endoftext|>