<commit_before>

var ColorWheel = React.createClass({
  render: function() {
    var n = this.props.n == undefined ? 24 : this.props.n;
    var radius = this.props.radius == undefined ? 200 : this.props.radius;
    var thickness = this.props.thickness == undefined ? 40 : this.props.thickness;
    // radus is the outer radius

    var radius2 = radius - thickness;
    var colorDots = [];
    for(var i = 0; i < n; i++) {
      var a1 = Math.PI * 2 * i / n;
      var a2 = Math.PI * 2 * (i+1)/n;
      colorDots.push(<path
        d={
          "M" + (radius + Math.round(Math.cos(a1) * radius)) + "," + (radius - Math.round(Math.sin(a1) * radius)) + " " +
          "A" + radius + "," + radius + " 0 0,0 " + (radius + Math.round(Math.cos(a2) * radius)) + "," + (radius - Math.round(Math.sin(a2) * radius)) + " " +
          "L" + (radius + Math.round(Math.cos(a2) * radius2)) + "," + (radius - Math.round(Math.sin(a2) * radius2)) + " " +
          "A" + radius2 + "," + radius2 + " 0 0,1 " + (radius + Math.round(Math.cos(a1) * radius2)) + "," + (radius - Math.round(Math.sin(a1) * radius2)) + " " +
          "Z"
        }
        fill={i%2 == 0 ? "red" : "blue" }
        stroke = "black"
      >);
    }
    return (
      <svg height={radius*2+2} width={radius*2+2}>{colorDots}</svg>
    );
  }
})
<commit_msg>Update colorWheel.js<commit_after>

var ColorWheel = React.createClass({
  render: function() {
    var n = this.props.n == undefined ? 24 : this.props.n;
    var radius = this.props.radius == undefined ? 200 : this.props.radius;
    var thickness = this.props.thickness == undefined ? 40 : this.props.thickness;
    // radus is the outer radius

    var radius2 = radius - thickness;
    var colorDots = [];
    for(var i = 0; i < n; i++) {
      var a1 = Math.PI * 2 * i / n;
      var a2 = Math.PI * 2 * (i+1)/n;
      colorDots.push(<path
        d={
          "M" + (radius + Math.round(Math.cos(a1) * radius)) + "," + (radius - Math.round(Math.sin(a1) * radius)) + " " +
          "A" + radius + "," + radius + " 0 0,0 " + (radius + Math.round(Math.cos(a2) * radius)) + "," + (radius - Math.round(Math.sin(a2) * radius)) + " " +
          "L" + (radius + Math.round(Math.cos(a2) * radius2)) + "," + (radius - Math.round(Math.sin(a2) * radius2)) + " " +
          "A" + radius2 + "," + radius2 + " 0 0,1 " + (radius + Math.round(Math.cos(a1) * radius2)) + "," + (radius - Math.round(Math.sin(a1) * radius2)) + " " +
          "Z"
        }
        fill={i%2 == 0 ? "red" : "blue" }
        stroke = "black"
      >);
    }
    return (
      <svg height={radius*2+2} width={radius*2+2}> {colorDots} </svg>
    );
  }
})
<|endoftext|>


<commit_before>$(function(){
    var VOTING = {{ VOTING|lower }};

    var IS_LOGGED_IN = false;
    var USER = [];
    var USER_VOTES = [];
    var loginHost = '/api/';
    var cookie_namespace = 'nicar15lightningtalks-';
    var fingerprint = new Fingerprint({canvas: true}).get();

    var $loggedIn = $('#logged-in');
    var $loggedOut = $('#logged-out');
    var $userId = $('#user-id');
    var $submitLogin = $('#submit-login');
    var $submitLogout = $('#submit-logout');
    var $password = $('#password-login');
    var $email = $('#email-login');
    var $name = $('#name-login');
    var $session = $('div.session.unvoted .thumbs');
    var $votedSession = $('div.session.voted .thumbs');

    var $createSession = $('#submit-create-session');
    var $loginMessage = $('#please-login');
    var $proposeForm = $('#propose');

    var set_login_status = function(logged_in, user, votes) {
        IS_LOGGED_IN = logged_in;
        USER = user;

        if (votes.length > 0) {
            // If there are new votes incoming, merge them.
            USER_VOTES = USER_VOTES.concat(votes);
        }

        if (logged_in) {
            $userId.html(user[1]);
            $loggedOut.hide();
            $loggedIn.show();
            $('div.'+USER[0]).addClass('mine');
            if (VOTING) {
                $('div.session.unvoted .thumbs').css('cursor', 'pointer');
                votes_show();
            } else {
                $loginMessage.hide();
                $proposeForm.show();
            }
        } else {
            $loggedIn.hide();
            $loggedOut.show();
            $('div').removeClass('mine');
            if (VOTING) {
                votes_remove();
            } else {
                $loginMessage.show();
                $proposeForm.hide();
            }
        }
    }

    var votes_show = function() {
        $.each(USER_VOTES, function(idx, v){
            $('#' + v).removeClass('unvoted').addClass('voted');
        });
    }

    var votes_remove = function() {
        $.each($('div.session'), function(idx, v){
            $(v).removeClass('voted').addClass('unvoted');
        });
    }

    var session_vote = function() {
        if (IS_LOGGED_IN && USER) {
            var thisSession = $(this).parent('.votes-box').parent('.session');
            var url = loginHost + 'vote/action/';
            var session_id = $(thisSession).attr('id');
            url += '?user=' + USER[0];
            url += '&session=' + session_id;
            $.ajax(url, {
                async: true,
                cache: true,
                crossDomain: false,
                dataType: 'json',
                jsonp: false,
                success: function(data) {
                    if (data['success'] === true) {

                        // Update the array of votes and serialize to pipe-separated for the cookie.
                        USER_VOTES.push(session_id);
                        $.cookie(cookie_namespace + 'votes', USER_VOTES.join("|"));

                        // Increment the count while we wait for the server to do this automatically.
                        var $count_container = $('#' + session_id + ' .votes-box .count .num');
                        var old_count = parseInt($count_container.html()) + 1;
                        $count_container.html(old_count);

                        // Percolate the changes.
                        set_login_status(true, USER, USER_VOTES);
                    }
                }
            });
        }
    }

    var session_unvote = function() {
        if (IS_LOGGED_IN && USER) {
            var thisSession = $(this).parent('.votes-box').parent('.session');
            // Jeremy HALP

            // var url = loginHost + 'vote/action/';
            // var session_id = $(thisSession).attr('id');
            // url += '?user=' + USER[0];
            // url += '&session=' + session_id;
            // $.ajax(url, {
            //     async: true,
            //     cache: true,
            //     crossDomain: false,
            //     dataType: 'json',
            //     jsonp: false,
            //     success: function(data) {
            //         if (data['success'] === true) {

            //             // Update the array of votes and serialize to pipe-separated for the cookie.
            //             USER_VOTES.push(session_id);
            //             $.cookie(cookie_namespace + 'votes', USER_VOTES.join("|"));

            //             // Increment the count while we wait for the server to do this automatically.
            //             var $count_container = $('#' + session_id + ' .votes-box .count .num');
            //             var old_count = parseInt($count_container.html()) + 1;
            //             $count_container.html(old_count);

            //             // Percolate the changes.
            //             set_login_status(true, USER, USER_VOTES);
            //         }
            //     }
            // });
        }
    }

    var user_login = function() {
        var url = loginHost + 'user/action/';
        url += '?email=' + $email.val();
        url += '&password=' + $password.val();
        url += '&fingerprint=' + fingerprint;
        if ($name) { url += '&name=' + $name.val(); }

        $.ajax(url, {
            async: true,
            cache: true,
            crossDomain: false,
            dataType: 'json',
            jsonp: false,
            success: function(data) {
                if (data['success'] === true) {
                    $.cookie(cookie_namespace + 'user', data['_id'] + '|' + data['name']);

                    // Votes come back as pipe-delimited from the server.
                    $.cookie(cookie_namespace + 'votes', data['votes']);
                    set_login_status(true, [data['_id'],data['name']], data['votes'].split("|"));
                }
            }
        });
    }

    var user_logout = function() {
      $.removeCookie(cookie_namespace + 'user');
      $.removeCookie(cookie_namespace + 'votes');
      set_login_status(false, null, []);
    }

    var init = function() {
      if ($.cookie(cookie_namespace + 'user') !== undefined){
          if ($.cookie(cookie_namespace + 'votes') !== undefined) {
              set_login_status(true, $.cookie(cookie_namespace + 'user').split("|"), $.cookie(cookie_namespace + 'votes').split("|"));
          }
      } else {
          set_login_status(false, null, []);
      }
    }

    var session_create = function() {
        if (IS_LOGGED_IN && USER) {
            var s = {}
            s['title'] = $proposeForm.find('input').val();
            s['description'] = $proposeForm.find('textarea').val();
            s['user'] = USER[0];

            if ($.trim(s.title) == "" || $.trim(s.description) == "") {
                alert('Please fill out the title and the description fields.')
            } else {
                var url = loginHost + 'session/action/';
                url += '?user=' + s.user;
                url += '&title=' + s.title;
                url += '&description=' + s.description;
                $.ajax(url, {
                    async: true,
                    cache: true,
                    crossDomain: false,
                    dataType: 'json',
                    jsonp: false,
                    success: function(data) {
                        if (data['success'] === true) {
                            $proposeForm.find('input').val('');
                            $proposeForm.find('textarea').val('');
                            alert('Your session "'+s.title+'" has been submitted.');
                        }
                    }
                });

            }
        } else {
            alert('Please log in or create an account.');
        }
    }

    $submitLogin.on('click', user_login);
    $submitLogout.on('click', user_logout);
    $createSession.on('click', session_create);
    $session.on('click', session_vote);
    $votedSession.on('click', session_unvote);
    init();
});<commit_msg>some type of unvoted bug, fixing<commit_after>$(function(){
    var VOTING = {{ VOTING|lower }};

    var IS_LOGGED_IN = false;
    var USER = [];
    var USER_VOTES = [];
    var loginHost = '/api/';
    var cookie_namespace = 'nicar15lightningtalks-';
    var fingerprint = new Fingerprint({canvas: true}).get();

    var $loggedIn = $('#logged-in');
    var $loggedOut = $('#logged-out');
    var $userId = $('#user-id');
    var $submitLogin = $('#submit-login');
    var $submitLogout = $('#submit-logout');
    var $password = $('#password-login');
    var $email = $('#email-login');
    var $name = $('#name-login');
    var $session = $('div.session .thumbs');

    var $createSession = $('#submit-create-session');
    var $loginMessage = $('#please-login');
    var $proposeForm = $('#propose');

    var set_login_status = function(logged_in, user, votes) {
        IS_LOGGED_IN = logged_in;
        USER = user;

        if (votes.length > 0) {
            // If there are new votes incoming, merge them.
            USER_VOTES = USER_VOTES.concat(votes);
        }

        if (logged_in) {
            $userId.html(user[1]);
            $loggedOut.hide();
            $loggedIn.show();
            $('div.'+USER[0]).addClass('mine');
            if (VOTING) {
                $('div.session.unvoted .thumbs').css('cursor', 'pointer');
                votes_show();
            } else {
                $loginMessage.hide();
                $proposeForm.show();
            }
        } else {
            $loggedIn.hide();
            $loggedOut.show();
            $('div').removeClass('mine');
            if (VOTING) {
                votes_remove();
            } else {
                $loginMessage.show();
                $proposeForm.hide();
            }
        }
    }

    var votes_show = function() {
        $.each(USER_VOTES, function(idx, v){
            $('#' + v).removeClass('unvoted').addClass('voted');
        });
    }

    var votes_remove = function() {
        $.each($('div.session'), function(idx, v){
            $(v).removeClass('voted').addClass('unvoted');
        });
    }

    var session_vote = function() {

        if (IS_LOGGED_IN && USER) {
            var thisSession = $(this).parent('.votes-box').parent('.session');
            var voted = $(thisSession).hasClass('voted');
            var session_id = $(thisSession).attr('id');

            if (!voted){
                var url = loginHost + 'vote/action/';
                url += '?user=' + USER[0];
                url += '&session=' + session_id;
                $.ajax(url, {
                    async: true,
                    cache: true,
                    crossDomain: false,
                    dataType: 'json',
                    jsonp: false,
                    success: function(data) {
                        if (data['success'] === true) {

                            // Update the array of votes and serialize to pipe-separated for the cookie.
                            USER_VOTES.push(session_id);
                            $.cookie(cookie_namespace + 'votes', USER_VOTES.join("|"));

                            // Increment the count while we wait for the server to do this automatically.
                            // SOME TYPE OF BUG HERE.
                            $(thisSession).removeClass('unvoted').addClass('voted');
                            var $count_container = $('#' + session_id + ' .votes-box .count .num');
                            var old_count = parseInt($count_container.html()) + 1;
                            $count_container.html(old_count);

                            // Percolate the changes.
                            set_login_status(true, USER, USER_VOTES);
                        }
                    }
                });
            } else {
                $(thisSession).removeClass('voted').addClass('unvoted');
                var $count_container = $('#' + session_id + ' .votes-box .count .num');
                var old_count = parseInt($count_container.html()) - 1;
                $count_container.html(old_count);
            }
        }
    }

    var user_login = function() {
        var url = loginHost + 'user/action/';
        url += '?email=' + $email.val();
        url += '&password=' + $password.val();
        url += '&fingerprint=' + fingerprint;
        if ($name) { url += '&name=' + $name.val(); }

        $.ajax(url, {
            async: true,
            cache: true,
            crossDomain: false,
            dataType: 'json',
            jsonp: false,
            success: function(data) {
                if (data['success'] === true) {
                    $.cookie(cookie_namespace + 'user', data['_id'] + '|' + data['name']);

                    // Votes come back as pipe-delimited from the server.
                    $.cookie(cookie_namespace + 'votes', data['votes']);
                    set_login_status(true, [data['_id'],data['name']], data['votes'].split("|"));
                }
            }
        });
    }

    var user_logout = function() {
      $.removeCookie(cookie_namespace + 'user');
      $.removeCookie(cookie_namespace + 'votes');
      set_login_status(false, null, []);
    }

    var init = function() {
      if ($.cookie(cookie_namespace + 'user') !== undefined){
          if ($.cookie(cookie_namespace + 'votes') !== undefined) {
              set_login_status(true, $.cookie(cookie_namespace + 'user').split("|"), $.cookie(cookie_namespace + 'votes').split("|"));
          }
      } else {
          set_login_status(false, null, []);
      }
    }

    var session_create = function() {
        if (IS_LOGGED_IN && USER) {
            var s = {}
            s['title'] = $proposeForm.find('input').val();
            s['description'] = $proposeForm.find('textarea').val();
            s['user'] = USER[0];

            if ($.trim(s.title) == "" || $.trim(s.description) == "") {
                alert('Please fill out the title and the description fields.')
            } else {
                var url = loginHost + 'session/action/';
                url += '?user=' + s.user;
                url += '&title=' + s.title;
                url += '&description=' + s.description;
                $.ajax(url, {
                    async: true,
                    cache: true,
                    crossDomain: false,
                    dataType: 'json',
                    jsonp: false,
                    success: function(data) {
                        if (data['success'] === true) {
                            $proposeForm.find('input').val('');
                            $proposeForm.find('textarea').val('');
                            alert('Your session "'+s.title+'" has been submitted.');
                        }
                    }
                });

            }
        } else {
            alert('Please log in or create an account.');
        }
    }

    $submitLogin.on('click', user_login);
    $submitLogout.on('click', user_logout);
    $createSession.on('click', session_create);
    $session.on('click', session_vote);
    init();
});<|endoftext|>


<commit_before>//
// Communicate with cscript via stdin/stderr
//
// For using vm-commands must be run from 32-bit cscript (true if Ruby is 32-bit)
//
+function(){

var
  w = WScript,
  i = w.StdIn,
  o = w.StdErr,
  vms = {}

loadShivs('json2 es5')

while(!i.AtEndOfStream)
  o.WriteLine(wrap(i.ReadLine()))

function wrap(s)
{
  try { s=compile(s) }
  catch(e) { s={err: e.message || 'General error'} }

  try { return JSON.stringify(s) }
  catch(e) { return '{"err":"JSON.stringify error"}' }
}

function compile(s)
{
  s = JSON.parse(s)
  switch(typeof s)
  {
    case 'string':
      return ok(new Function(s)())
    case 'object':
      return vmCmd(s)
    default:
      throw Error('String expected!')
  }
}

function ok(v)
{
  return 'undefined'==typeof v ? {} : {ok: v}
}

function loadJS(name)
{
  var
    fso = new ActiveXObject("Scripting.FileSystemObject")
  name = fso.GetParentFolderName(w.ScriptFullName)+"/"+name+".js"
  new Function(fso.OpenTextFile(name).ReadAll())()
}

function loadShivs(names)
{
  names = names.split(' ')
  for(var i in names)
    loadJS(names[i])
}

function vmCmd(s)
{
  if(!('vm' in s))
    throw Error('VM command expected!')
  if('js' in s)
    return vmEval(s)
  if(!s.vm)
    return {vm: vmNew()}
  delete vms[s.vm]
  return {}
}

function vmNew()
{
  var i, r
  for(i = 10; i>0; i--)
    if((r = /\d{3,}/.exec(Math.random())) && !vms[r = r[0]])
    {
      vms[r] = i = new ActiveXObject('ScriptControl')
      i.Language = 'JScript'
      return r
    }
  throw Error('Cannot generate random number')
}

function vmEval(s)
{
  var z = vms[s.vm]
  if(!z)
    throw Error('VM not found')
  if('string'!=typeof s.js)
    throw Error('String expected!')
  return ok(z.eval('new Function('+JSON.stringify(s.js)+')()'))
}

}()
<commit_msg>Patch Wvm with ES5 shims<commit_after>//
// Communicate with cscript via stdin/stderr
//
// For using vm-commands must be run from 32-bit cscript (true if Ruby is 32-bit)
//
+function(){

var
  w = WScript,
  i = w.StdIn,
  o = w.StdErr,
  vms = {},
  lastShim

loadShivs('json2 es5')

while(!i.AtEndOfStream)
  o.WriteLine(wrap(i.ReadLine()))

function wrap(s)
{
  try { s=compile(s) }
  catch(e) { s={err: e.message || 'General error'} }

  try { return JSON.stringify(s) }
  catch(e) { return '{"err":"JSON.stringify error"}' }
}

function compile(s)
{
  s = JSON.parse(s)
  switch(typeof s)
  {
    case 'string':
      return ok(new Function(s)())
    case 'object':
      return vmCmd(s)
    default:
      throw Error('String expected!')
  }
}

function ok(v)
{
  return 'undefined'==typeof v ? {} : {ok: v}
}

function jsText(name)
{
  var
    fso = new ActiveXObject("Scripting.FileSystemObject")
  name = fso.GetParentFolderName(w.ScriptFullName)+"/"+name+".js"
  return fso.OpenTextFile(name).ReadAll()
}

function loadShivs(names)
{
  names = names.split(' ')
  for(var i in names)
    new Function(lastShim = jsText(names[i]))()
}

function vmCmd(s)
{
  if(!('vm' in s))
    throw Error('VM command expected!')
  if('js' in s)
    return vmEval(s)
  if(!s.vm)
    return {vm: vmNew()}
  delete vms[s.vm]
  return {}
}

function vmNew()
{
  var i, r
  for(i = 10; i>0; i--)
    if((r = /\d{3,}/.exec(Math.random())) && !vms[r = r[0]])
    {
      vms[r] = i = new ActiveXObject('ScriptControl')
      i.Language = 'JScript'
      i.addCode(lastShim)
      return r
    }
  throw Error('Cannot generate random number')
}

function vmEval(s)
{
  var z = vms[s.vm]
  if(!z)
    throw Error('VM not found')
  if('string'!=typeof s.js)
    throw Error('String expected!')
  return ok(z.eval('new Function('+JSON.stringify(s.js)+')()'))
}

}()
<|endoftext|>


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

'use strict';

describe('DeviceManagerSmokeTest', () => {
  if (!process.env.GCLOUD_PROJECT) {
    throw new Error("Usage: GCLOUD_PROJECT=<project_id> node #{$0}");
  }
  var projectId = process.env.GCLOUD_PROJECT;

  it('successfully makes a call to the service using promises', done => {
    const iot = require('../src');

    var client = new iot.v1.DeviceManagerClient({
      // optional auth parameters.
    });

    // Iterate over all elements.
    var formattedParent = client.locationPath(projectId, "us-central1");

    client.listDeviceRegistries({parent: formattedParent})
      .then(responses => {
        var resources = responses[0];
        for (let i = 0; i < resources.length; i += 1) {
          console.log(resources[i]);
        }
      })
      .then(done)
      .catch(done);
  });

  it('successfully makes a call to the service using callbacks', done => {
    const iot = require('../src');

    var client = new iot.v1.DeviceManagerClient({
      // optional auth parameters.
    });

    // Or obtain the paged response.
    var formattedParent = client.locationPath(projectId, "us-central1");

    var options = {autoPaginate: false};
    var callback = responses => {
      // The actual resources in a response.
      var resources = responses[0];
      // The next request if the response shows that there are more responses.
      var nextRequest = responses[1];
      // The actual response object, if necessary.
      // var rawResponse = responses[2];
      for (let i = 0; i < resources.length; i += 1) {
        console.log(resources[i]);
      }
      if (nextRequest) {
        // Fetch the next page.
        return client.listDeviceRegistries(nextRequest, options).then(callback);
      }
    }
    client.listDeviceRegistries({parent: formattedParent}, options)
      .then(callback)
      .then(done)
      .catch(done);
  });

  it('successfully makes a call to the service using streaming', done => {
    const iot = require('../src');

    var client = new iot.v1.DeviceManagerClient({
      // optional auth parameters.
    });

    var formattedParent = client.locationPath(projectId, "us-central1");
    client.listDeviceRegistriesStream({parent: formattedParent})
      .on('data', element => {
        console.log(element);
      })
      .on('error', done)
      .on('end', done);
  });
});
<commit_msg>quiet some linting issues on sample<commit_after>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

/* global describe, it */

describe('DeviceManagerSmokeTest', () => {
  if (!process.env.GCLOUD_PROJECT) {
    throw new Error('Usage: GCLOUD_PROJECT=<project_id> node #{$0}');
  }
  var projectId = process.env.GCLOUD_PROJECT;

  it('successfully makes a call to the service using promises', done => {
    const iot = require('../src');

    var client = new iot.v1.DeviceManagerClient({
      // optional auth parameters.
    });

    // Iterate over all elements.
    var formattedParent = client.locationPath(projectId, 'us-central1');

    client
      .listDeviceRegistries({parent: formattedParent})
      .then(responses => {
        var resources = responses[0];
        for (let i = 0; i < resources.length; i += 1) {
          console.log(resources[i]);
        }
      })
      .then(done)
      .catch(done);
  });

  it('successfully makes a call to the service using callbacks', done => {
    const iot = require('../src');

    var client = new iot.v1.DeviceManagerClient({
      // optional auth parameters.
    });

    // Or obtain the paged response.
    var formattedParent = client.locationPath(projectId, 'us-central1');

    var options = {autoPaginate: false};
    var callback = responses => {
      // The actual resources in a response.
      var resources = responses[0];
      // The next request if the response shows that there are more responses.
      var nextRequest = responses[1];
      // The actual response object, if necessary.
      // var rawResponse = responses[2];
      for (let i = 0; i < resources.length; i += 1) {
        console.log(resources[i]);
      }
      if (nextRequest) {
        // Fetch the next page.
        return client.listDeviceRegistries(nextRequest, options).then(callback);
      }
    };
    client
      .listDeviceRegistries({parent: formattedParent}, options)
      .then(callback)
      .then(done)
      .catch(done);
  });

  it('successfully makes a call to the service using streaming', done => {
    const iot = require('../src');

    var client = new iot.v1.DeviceManagerClient({
      // optional auth parameters.
    });

    var formattedParent = client.locationPath(projectId, 'us-central1');
    client
      .listDeviceRegistriesStream({parent: formattedParent})
      .on('data', element => {
        console.log(element);
      })
      .on('error', done)
      .on('end', done);
  });
});
<|endoftext|>


<commit_before>$(document).ready(function() {

  module("underscore.object.selectors");

  test("accessor", function() {
    var a = [{a: 1, b: 2}, {c: 3}];

    equal(_.accessor('a')(a[0]), 1, 'should return a function that plucks');
    equal(_.accessor('a')(a[1]), undefined, 'should return a function that plucks, or returns undefined');
    deepEqual(_.map(a, _.accessor('a')), [1, undefined], 'should return a function that plucks');
  });

  test("dictionary", function() {
    var a = [{a: 1, b: 2}, {c: 3}];

    equal(_.dictionary(a[0])('a'), 1, 'should return a function that acts as a dictionary');
    equal(_.dictionary(a[1])('a'), undefined, 'should return a function that acts as a dictionary, or returns undefined');
  });

  test("selectKeys", function() {
    deepEqual(_.selectKeys({'a': 1, 'b': 2}, ['a']), {'a': 1}, 'shold return a map of the desired keys');
    deepEqual(_.selectKeys({'a': 1, 'b': 2}, ['z']), {}, 'shold return an empty map if the desired keys are not present');
  });

  test("kv", function() {
    deepEqual(_.kv({'a': 1, 'b': 2}, 'a'), ['a', 1], 'should return the key/value pair at the desired key');
    equal(_.kv({'a': 1, 'b': 2}, 'z'), undefined, 'shold return undefined if the desired key is not present');
  });

  test("getPath", function() {
    var deepObject = { a: { b: { c: "c" } }, falseVal: false, nullVal: null, undefinedVal: undefined, arrayVal: ["arr"] };
    var deepArr = [[["thirdLevel"]]];
    var ks = ["a", "b", "c"];

    strictEqual(_.getPath(deepObject, ks), "c", "should get a deep property's value from objects");
    deepEqual(ks, ["a", "b", "c"], "should not have mutated ks argument");
    strictEqual(_.getPath(deepArr, [0, 0, 0]), "thirdLevel", "should get a deep property's value from arrays");
    strictEqual(_.getPath(deepObject, ["arrayVal", 0]), "arr", "should get a deep property's value from nested arrays and objects");

    strictEqual(_.getPath(deepObject, ["undefinedVal"]), undefined, "should return undefined for undefined properties");
    strictEqual(_.getPath(deepObject, ["a", "notHere"]), undefined, "should return undefined for non-existent properties");
    strictEqual(_.getPath(deepObject, ["nullVal"]), null, "should return null for null properties");
    strictEqual(_.getPath(deepObject, ["nullVal", "notHere", "notHereEither"]), undefined, "should return undefined for non-existent descendents of null properties");
  });

  test("hasPath", function() {
    var deepObject = { a: { b: { c: "c" } }, falseVal: false, nullVal: null, undefinedVal: undefined, arrayVal: ["arr"] };
    var ks = ["a", "b", "c"];

    strictEqual(_.hasPath(deepObject, ["notHere", "notHereEither"]), false, "should return false if the path doesn't exist");
    strictEqual(_.hasPath(deepObject, ks), true, "should return true if the path exists");
    deepEqual(ks, ["a", "b", "c"], "should not have mutated ks argument");

    strictEqual(_.hasPath(deepObject, ["arrayVal", 0]), true, "should return true for an array's index if it is defined");
    strictEqual(_.hasPath(deepObject, ["arrayVal", 999]), false, "should return false for an array's index if it is not defined");

    strictEqual(_.hasPath(deepObject, ["nullVal"]), true, "should return true for null properties");
    strictEqual(_.hasPath(deepObject, ["undefinedVal"]), true, "should return true for properties that were explicitly assigned undefined");

    strictEqual(_.hasPath(deepObject, ["nullVal", "notHere"]), false, "should return false for descendants of null properties");
    strictEqual(_.hasPath(deepObject, ["undefinedVal", "notHere"]), false, "should return false for descendants of undefined properties");
  });

});
<commit_msg>Added preliminary tests for _.pick|omitWhen<commit_after>$(document).ready(function() {

  module("underscore.object.selectors");

  test("accessor", function() {
    var a = [{a: 1, b: 2}, {c: 3}];

    equal(_.accessor('a')(a[0]), 1, 'should return a function that plucks');
    equal(_.accessor('a')(a[1]), undefined, 'should return a function that plucks, or returns undefined');
    deepEqual(_.map(a, _.accessor('a')), [1, undefined], 'should return a function that plucks');
  });

  test("dictionary", function() {
    var a = [{a: 1, b: 2}, {c: 3}];

    equal(_.dictionary(a[0])('a'), 1, 'should return a function that acts as a dictionary');
    equal(_.dictionary(a[1])('a'), undefined, 'should return a function that acts as a dictionary, or returns undefined');
  });

  test("selectKeys", function() {
    deepEqual(_.selectKeys({'a': 1, 'b': 2}, ['a']), {'a': 1}, 'shold return a map of the desired keys');
    deepEqual(_.selectKeys({'a': 1, 'b': 2}, ['z']), {}, 'shold return an empty map if the desired keys are not present');
  });

  test("kv", function() {
    deepEqual(_.kv({'a': 1, 'b': 2}, 'a'), ['a', 1], 'should return the key/value pair at the desired key');
    equal(_.kv({'a': 1, 'b': 2}, 'z'), undefined, 'shold return undefined if the desired key is not present');
  });

  test("getPath", function() {
    var deepObject = { a: { b: { c: "c" } }, falseVal: false, nullVal: null, undefinedVal: undefined, arrayVal: ["arr"] };
    var deepArr = [[["thirdLevel"]]];
    var ks = ["a", "b", "c"];

    strictEqual(_.getPath(deepObject, ks), "c", "should get a deep property's value from objects");
    deepEqual(ks, ["a", "b", "c"], "should not have mutated ks argument");
    strictEqual(_.getPath(deepArr, [0, 0, 0]), "thirdLevel", "should get a deep property's value from arrays");
    strictEqual(_.getPath(deepObject, ["arrayVal", 0]), "arr", "should get a deep property's value from nested arrays and objects");

    strictEqual(_.getPath(deepObject, ["undefinedVal"]), undefined, "should return undefined for undefined properties");
    strictEqual(_.getPath(deepObject, ["a", "notHere"]), undefined, "should return undefined for non-existent properties");
    strictEqual(_.getPath(deepObject, ["nullVal"]), null, "should return null for null properties");
    strictEqual(_.getPath(deepObject, ["nullVal", "notHere", "notHereEither"]), undefined, "should return undefined for non-existent descendents of null properties");
  });

  test("hasPath", function() {
    var deepObject = { a: { b: { c: "c" } }, falseVal: false, nullVal: null, undefinedVal: undefined, arrayVal: ["arr"] };
    var ks = ["a", "b", "c"];

    strictEqual(_.hasPath(deepObject, ["notHere", "notHereEither"]), false, "should return false if the path doesn't exist");
    strictEqual(_.hasPath(deepObject, ks), true, "should return true if the path exists");
    deepEqual(ks, ["a", "b", "c"], "should not have mutated ks argument");

    strictEqual(_.hasPath(deepObject, ["arrayVal", 0]), true, "should return true for an array's index if it is defined");
    strictEqual(_.hasPath(deepObject, ["arrayVal", 999]), false, "should return false for an array's index if it is not defined");

    strictEqual(_.hasPath(deepObject, ["nullVal"]), true, "should return true for null properties");
    strictEqual(_.hasPath(deepObject, ["undefinedVal"]), true, "should return true for properties that were explicitly assigned undefined");

    strictEqual(_.hasPath(deepObject, ["nullVal", "notHere"]), false, "should return false for descendants of null properties");
    strictEqual(_.hasPath(deepObject, ["undefinedVal", "notHere"]), false, "should return false for descendants of undefined properties");
  });

  test("pickWhen", function() {
    var a = {foo: true, bar: false, baz: 42};

    deepEqual(_.pickWhen(a, _.truthy), {foo: true, baz: 42}, "should return an object with kvs that return a truthy value for the given predicate");
  });

  test("omitWhen", function() {
    var a = {foo: [], bar: "", baz: "something", quux: ['a']};

    deepEqual(_.omitWhen(a, _.isEmpty), {baz: "something", quux: ['a']}, "should return an object with kvs that return a falsey value for the given predicate");
  });
});
<|endoftext|>


<commit_before>module.exports = function(app) {
  var helpers = require('express-helpers')();
  var widgets = {};
  if (app) {
    var express = require('express');
  }

  var clone = function(original){
    var copy, target = {};
    for ( var name in original ) {
      if ( original[ name ] !== undefined )
        target[ name ] = original[ name ];
    }
    return target;
  }

  //can be strongly typed or not depending if it gives a value_type
  var getHtmlOptions = function(){
    var value_type, in_args;
    if(type.of(arguments[0]) == 'string'){
      value_type = arguments[0];
      in_args = arguments[1];
    }else
      in_args = arguments[0];

    var args = Array.prototype.slice.call(in_args),
      i = 0,
      value, html_options = {};

    if(args.length > 1){
      args.shift();//get rid of first arg
      if((value_type && type.of(args[0]) == value_type) ||
        (!value_type && type.of(args[0]) != 'object'
              && type.of(args[0]) != 'function'
              && type.of(args[0]) != 'array')){
        value = args[0];
        i++;
      }
      while(args[i]){
        if(type.of(args[i]) == 'object') html_options = args[i];
        i++;
      }
    }
    if(value) html_options.value = html_options.value || value;
    return html_options;
  }

  var is=
  {
    Null:function(a){return a===null;},
    Undefined:function(a){return a===undefined;},
    nt:function(a){return(a===null||a===undefined);},
    Function:function(a){return(typeof(a)==='function')?a.constructor.toString().match(/Function/)!==null:false;},
    String:function(a){return(typeof(a)==='string')?true:(typeof(a)==='object')?a.constructor.toString().match(/string/i)!==null:false;    },
    Array:function(a){return(typeof(a)==='object')?a.constructor.toString().match(/array/i)!==null||a.length!==undefined:false;},
    Boolean:function(a){return(typeof(a)==='boolean')?true:(typeof(a)==='object')?a.constructor.toString().match(/boolean/i)!==null:false;},
    Date:function(a){return(typeof(a)==='date')?true:(typeof(a)==='object')?a.constructor.toString().match(/date/i)!==null:false;},
    HTML:function(a){return(typeof(a)==='object')?a.constructor.toString().match(/html/i)!==null:false;},
    Number:function(a){return(typeof(a)==='number')?true:(typeof(a)==='object')?a.constructor.toString().match(/Number/)!==null:false;},
    Object:function(a){return(typeof(a)==='object')?a.constructor.toString().match(/object/i)!==null:false;},
    RegExp:function(a){return(typeof(a)==='function')?a.constructor.toString().match(/regexp/i)!==null:false;}
  };

  var type={
    of:function(a){
      for(var i in is){
        if(is[i](a))
          return i.toLowerCase();
      }
    }
  };

  widgets.cmenu = function (menuData, menuOutput) {
    if (typeof menuOutput == "undefined")
      menuOutput = "";
    if (!menuData['items']) {
      menuOutput += (menuOutput) ? helpers.end_tag('ul') : "";
      return menuOutput;
    }
    var menuItems = menuData['items'];
    menuOutput += helpers.start_tag_for('ul', menuData['htmlOptions']);
    for(var i = 0; i < menuItems.length; i++) {
      menuOutput += helpers.start_tag_for("li", menuItems[i]['listHtmlOptions']);
      menuOutput += helpers.link_to(menuItems[i]['label'], menuItems[i]['url'], menuItems[i]['linkHtmlOptions']);
      menuOutput += widgets.cmenu(menuItems[i], menuOutput);
      menuOutput += helpers.end_tag("li");
    }
  };

  if(app){
    //3.x support
    if(type.of(app) == 'function'){
      for (var name in widgets) {
        app.locals[name] = widgets[name];
      }

      //add dynamic widgets
      app.use(function(req, res, next){
        res.locals.is_current_page = function(url){
          var current_page = req.url,
              httpregex = /http:\/\/|https:\/\/|www\./g;
          return url === current_page ||  url.replace(httpregex,'')  === req.headers.host.replace(httpregex,'') + current_page
        }

        res.locals.link_to_unless_current = function(name, url, html_options){
          var current_page = req.url,
              httpregex = /http:\/\/|https:\/\/|www\./g;
          if(url != current_page && url.replace(httpregex,'')  != req.headers.host.replace(httpregex,'') + current_page)
            return link_to(name, url, html_options)
        }

        next();
      })
    }
    //2.x support
    else if ((express.Server && app instanceof express.Server) || app instanceof express.HTTPServer || app instanceof express.HTTPSServer) {
      var obj = {};
      if ((express.Server && app instanceof express.Server) || app instanceof express.HTTPServer || app instanceof express.HTTPSServer) {
        for (name in widgets) {
          obj[name] = widgets[name];
        }
      }
      app.widgets(obj);

      //add dynamic widgets
      app.dynamicWidgets({
        is_current_page: function(req, res, next){
          var func = function(url){
            var current_page = req.url,
                httpregex = /http:\/\/|https:\/\/|www\./g;
            return url === current_page ||  url.replace(httpregex,'')  === req.headers.host.replace(httpregex,'') + current_page
          }
          return func
        },
        link_to_unless_current: function(req, res, next){
          var func = function(name, url, html_options){
            var current_page = req.url,
                httpregex = /http:\/\/|https:\/\/|www\./g;
            if(url != current_page && url.replace(httpregex,'')  != req.headers.host.replace(httpregex,'') + current_page)
              return link_to(name, url, html_options)
          }
          return func;
        }
      })
    }
  }

  return widgets;
}
<commit_msg>Fixing CMenu<commit_after>module.exports = function(app) {
  var helpers = require('express-helpers')();
  var widgets = {};
  if (app) {
    var express = require('express');
  }

  var clone = function(original){
    var copy, target = {};
    for ( var name in original ) {
      if ( original[ name ] !== undefined )
        target[ name ] = original[ name ];
    }
    return target;
  }

  //can be strongly typed or not depending if it gives a value_type
  var getHtmlOptions = function(){
    var value_type, in_args;
    if(type.of(arguments[0]) == 'string'){
      value_type = arguments[0];
      in_args = arguments[1];
    }else
      in_args = arguments[0];

    var args = Array.prototype.slice.call(in_args),
      i = 0,
      value, html_options = {};

    if(args.length > 1){
      args.shift();//get rid of first arg
      if((value_type && type.of(args[0]) == value_type) ||
        (!value_type && type.of(args[0]) != 'object'
              && type.of(args[0]) != 'function'
              && type.of(args[0]) != 'array')){
        value = args[0];
        i++;
      }
      while(args[i]){
        if(type.of(args[i]) == 'object') html_options = args[i];
        i++;
      }
    }
    if(value) html_options.value = html_options.value || value;
    return html_options;
  }

  var is=
  {
    Null:function(a){return a===null;},
    Undefined:function(a){return a===undefined;},
    nt:function(a){return(a===null||a===undefined);},
    Function:function(a){return(typeof(a)==='function')?a.constructor.toString().match(/Function/)!==null:false;},
    String:function(a){return(typeof(a)==='string')?true:(typeof(a)==='object')?a.constructor.toString().match(/string/i)!==null:false;    },
    Array:function(a){return(typeof(a)==='object')?a.constructor.toString().match(/array/i)!==null||a.length!==undefined:false;},
    Boolean:function(a){return(typeof(a)==='boolean')?true:(typeof(a)==='object')?a.constructor.toString().match(/boolean/i)!==null:false;},
    Date:function(a){return(typeof(a)==='date')?true:(typeof(a)==='object')?a.constructor.toString().match(/date/i)!==null:false;},
    HTML:function(a){return(typeof(a)==='object')?a.constructor.toString().match(/html/i)!==null:false;},
    Number:function(a){return(typeof(a)==='number')?true:(typeof(a)==='object')?a.constructor.toString().match(/Number/)!==null:false;},
    Object:function(a){return(typeof(a)==='object')?a.constructor.toString().match(/object/i)!==null:false;},
    RegExp:function(a){return(typeof(a)==='function')?a.constructor.toString().match(/regexp/i)!==null:false;}
  };

  var type={
    of:function(a){
      for(var i in is){
        if(is[i](a))
          return i.toLowerCase();
      }
    }
  };

  widgets.cmenu = function (menuData) {
    var menuOutput = "";
    if (!menuData['items']) {
      menuOutput += (menuOutput) ? helpers.end_tag('ul') : "";
      return menuOutput;
    }
    var menuItems = menuData['items'];
    menuOutput += helpers.start_tag_for('ul', menuData['htmlOptions'] || {});
    for(var i = 0; i < menuItems.length; i++) {
      menuOutput += helpers.start_tag_for("li", menuItems[i]['listHtmlOptions'] || {});
      menuOutput += helpers.link_to(menuItems[i]['label'], menuItems[i]['url'], menuItems[i]['linkHtmlOptions'] || {});
      menuOutput += widgets.cmenu(menuItems[i]);
      menuOutput += helpers.end_tag("li");
    }
    menuOutput += (menuOutput) ? helpers.end_tag('ul') : "";
    return menuOutput;
  };

  if(app){
    //3.x support
    if(type.of(app) == 'function'){
      for (var name in widgets) {
        app.locals[name] = widgets[name];
      }

      //add dynamic widgets
      app.use(function(req, res, next){
        res.locals.is_current_page = function(url){
          var current_page = req.url,
              httpregex = /http:\/\/|https:\/\/|www\./g;
          return url === current_page ||  url.replace(httpregex,'')  === req.headers.host.replace(httpregex,'') + current_page
        }

        res.locals.link_to_unless_current = function(name, url, html_options){
          var current_page = req.url,
              httpregex = /http:\/\/|https:\/\/|www\./g;
          if(url != current_page && url.replace(httpregex,'')  != req.headers.host.replace(httpregex,'') + current_page)
            return link_to(name, url, html_options)
        }

        next();
      })
    }
    //2.x support
    else if ((express.Server && app instanceof express.Server) || app instanceof express.HTTPServer || app instanceof express.HTTPSServer) {
      var obj = {};
      if ((express.Server && app instanceof express.Server) || app instanceof express.HTTPServer || app instanceof express.HTTPSServer) {
        for (name in widgets) {
          obj[name] = widgets[name];
        }
      }
      app.widgets(obj);

      //add dynamic widgets
      app.dynamicWidgets({
        is_current_page: function(req, res, next){
          var func = function(url){
            var current_page = req.url,
                httpregex = /http:\/\/|https:\/\/|www\./g;
            return url === current_page ||  url.replace(httpregex,'')  === req.headers.host.replace(httpregex,'') + current_page
          }
          return func
        },
        link_to_unless_current: function(req, res, next){
          var func = function(name, url, html_options){
            var current_page = req.url,
                httpregex = /http:\/\/|https:\/\/|www\./g;
            if(url != current_page && url.replace(httpregex,'')  != req.headers.host.replace(httpregex,'') + current_page)
              return link_to(name, url, html_options)
          }
          return func;
        }
      })
    }
  }

  return widgets;
}
<|endoftext|>


<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class coinmate extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'coinmate',
            'name': 'CoinMate',
            'countries': [ 'GB', 'CZ', 'EU' ], // UK, Czech Republic
            'rateLimit': 1000,
            'has': {
                'CORS': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27811229-c1efb510-606c-11e7-9a36-84ba2ce412d8.jpg',
                'api': 'https://coinmate.io/api',
                'www': 'https://coinmate.io',
                'fees': 'https://coinmate.io/fees',
                'doc': [
                    'https://coinmate.docs.apiary.io',
                    'https://coinmate.io/developers',
                ],
                'referral': 'https://coinmate.io?referral=YTFkM1RsOWFObVpmY1ZjMGREQmpTRnBsWjJJNVp3PT0',
            },
            'requiredCredentials': {
                'apiKey': true,
                'secret': true,
                'uid': true,
            },
            'api': {
                'public': {
                    'get': [
                        'orderBook',
                        'ticker',
                        'transactions',
                    ],
                },
                'private': {
                    'post': [
                        'balances',
                        'bitcoinWithdrawal',
                        'bitcoinDepositAddresses',
                        'buyInstant',
                        'buyLimit',
                        'cancelOrder',
                        'cancelOrderWithInfo',
                        'createVoucher',
                        'openOrders',
                        'redeemVoucher',
                        'sellInstant',
                        'sellLimit',
                        'transactionHistory',
                        'unconfirmedBitcoinDeposits',
                    ],
                },
            },
            'markets': {
                'BTC/EUR': { 'id': 'BTC_EUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR', 'precision': { 'amount': 4, 'price': 2 }, 'maker': 0.25 / 100, 'taker': 0.12 / 100 },
                'BTC/CZK': { 'id': 'BTC_CZK', 'symbol': 'BTC/CZK', 'base': 'BTC', 'quote': 'CZK', 'precision': { 'amount': 4, 'price': 2 }, 'maker': 0.25 / 100, 'taker': 0.12 / 100 },
                'LTC/EUR': { 'id': 'LTC_EUR', 'symbol': 'LTC/EUR', 'base': 'LTC', 'quote': 'EUR', 'precision': { 'amount': 4, 'price': 2 }, 'maker': 0.25 / 100, 'taker': 0.12 / 100 },
                'LTC/CZK': { 'id': 'LTC_CZK', 'symbol': 'LTC/CZK', 'base': 'LTC', 'quote': 'CZK', 'precision': { 'amount': 4, 'price': 2 }, 'maker': 0.25 / 100, 'taker': 0.12 / 100 },
                'LTC/BTC': { 'id': 'LTC_BTC', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC', 'precision': { 'amount': 4, 'price': 5 }, 'maker': 0.25 / 100, 'taker': 0.12 / 100 },
                'ETH/EUR': { 'id': 'ETH_CZK', 'symbol': 'ETH/EUR', 'base': 'ETH', 'quote': 'EUR', 'precision': { 'amount': 4, 'price': 2 }},
                'ETH/CZK': { 'id': 'ETH_CZK', 'symbol': 'ETH/CZK', 'base': 'ETH', 'quote': 'CZK', 'precision': { 'amount': 4, 'price': 2 }},
                'ETH/BTC': { 'id': 'ETH_BTC', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC', 'precision': { 'amount': 4, 'price': 5 }},
                'XRP/EUR': { 'id': 'XRP_EUR', 'symbol': 'XRP/EUR', 'base': 'XRP', 'quote': 'EUR', 'precision': { 'amount': 4, 'price': 5 }},
                'XRP/CZK': { 'id': 'XRP_CZK', 'symbol': 'XRP/CZK', 'base': 'XRP', 'quote': 'CZK', 'precision': { 'amount': 4, 'price': 5 }},
                'XRP/BTC': { 'id': 'XRP_BTC', 'symbol': 'XRP/BTC', 'base': 'XRP', 'quote': 'BTC', 'precision': { 'amount': 4, 'price': 8 }},
                'BCH/EUR': { 'id': 'BCH_EUR', 'symbol': 'BCH/EUR', 'base': 'BCH', 'quote': 'EUR', 'precision': { 'amount': 4, 'price': 2 }},
                'BCH/CZK': { 'id': 'BCH_CZK', 'symbol': 'BCH/CZK', 'base': 'BCH', 'quote': 'CZK', 'precision': { 'amount': 4, 'price': 2 }},
                'BCH/BTC': { 'id': 'BCH_BTC', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC', 'precision': { 'amount': 4, 'price': 5 }},
            },
            'fees': {
                'trading': {
                    'maker': 0.05 / 100,
                    'taker': 0.15 / 100,
                },
            },
        });
    }

    async fetchBalance (params = {}) {
        let response = await this.privatePostBalances ();
        let balances = response['data'];
        let result = { 'info': balances };
        let currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let account = this.account ();
            if (currency in balances) {
                account['free'] = balances[currency]['available'];
                account['used'] = balances[currency]['reserved'];
                account['total'] = balances[currency]['balance'];
            }
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        let response = await this.publicGetOrderBook (this.extend ({
            'currencyPair': this.marketId (symbol),
            'groupByPriceLimit': 'False',
        }, params));
        let orderbook = response['data'];
        let timestamp = orderbook['timestamp'] * 1000;
        return this.parseOrderBook (orderbook, timestamp, 'bids', 'asks', 'price', 'amount');
    }

    async fetchTicker (symbol, params = {}) {
        let response = await this.publicGetTicker (this.extend ({
            'currencyPair': this.marketId (symbol),
        }, params));
        let ticker = response['data'];
        let timestamp = ticker['timestamp'] * 1000;
        let last = this.safeFloat (ticker, 'last');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'high'),
            'low': this.safeFloat (ticker, 'low'),
            'bid': this.safeFloat (ticker, 'bid'),
            'bidVolume': undefined,
            'ask': this.safeFloat (ticker, 'ask'),
            'vwap': undefined,
            'askVolume': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': this.safeFloat (ticker, 'amount'),
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    parseTrade (trade, market = undefined) {
        if (!market)
            market = this.markets_by_id[trade['currencyPair']];
        return {
            'id': trade['transactionId'],
            'info': trade,
            'timestamp': trade['timestamp'],
            'datetime': this.iso8601 (trade['timestamp']),
            'symbol': market['symbol'],
            'type': undefined,
            'side': undefined,
            'price': trade['price'],
            'amount': trade['amount'],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        let market = this.market (symbol);
        let response = await this.publicGetTransactions (this.extend ({
            'currencyPair': market['id'],
            'minutesIntoHistory': 10,
        }, params));
        return this.parseTrades (response['data'], market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        let method = 'privatePost' + this.capitalize (side);
        let order = {
            'currencyPair': this.marketId (symbol),
        };
        if (type === 'market') {
            if (side === 'buy')
                order['total'] = amount; // amount in fiat
            else
                order['amount'] = amount; // amount in fiat
            method += 'Instant';
        } else {
            order['amount'] = amount; // amount in crypto
            order['price'] = price;
            method += this.capitalize (type);
        }
        let response = await this[method] (this.extend (order, params));
        return {
            'info': response,
            'id': response['data'].toString (),
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return await this.privatePostCancelOrder ({ 'orderId': id });
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + path;
        if (api === 'public') {
            if (Object.keys (params).length)
                url += '?' + this.urlencode (params);
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            let auth = nonce + this.uid + this.apiKey;
            let signature = this.hmac (this.encode (auth), this.encode (this.secret));
            body = this.urlencode (this.extend ({
                'clientId': this.uid,
                'nonce': nonce,
                'publicKey': this.apiKey,
                'signature': signature.toUpperCase (),
            }, params));
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if ('error' in response)
            if (response['error'])
                throw new ExchangeError (this.id + ' ' + this.json (response));
        return response;
    }
};
<commit_msg>[coinmate] fixed currency mapping<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class coinmate extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'coinmate',
            'name': 'CoinMate',
            'countries': [ 'GB', 'CZ', 'EU' ], // UK, Czech Republic
            'rateLimit': 1000,
            'has': {
                'CORS': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27811229-c1efb510-606c-11e7-9a36-84ba2ce412d8.jpg',
                'api': 'https://coinmate.io/api',
                'www': 'https://coinmate.io',
                'fees': 'https://coinmate.io/fees',
                'doc': [
                    'https://coinmate.docs.apiary.io',
                    'https://coinmate.io/developers',
                ],
                'referral': 'https://coinmate.io?referral=YTFkM1RsOWFObVpmY1ZjMGREQmpTRnBsWjJJNVp3PT0',
            },
            'requiredCredentials': {
                'apiKey': true,
                'secret': true,
                'uid': true,
            },
            'api': {
                'public': {
                    'get': [
                        'orderBook',
                        'ticker',
                        'transactions',
                    ],
                },
                'private': {
                    'post': [
                        'balances',
                        'bitcoinWithdrawal',
                        'bitcoinDepositAddresses',
                        'buyInstant',
                        'buyLimit',
                        'cancelOrder',
                        'cancelOrderWithInfo',
                        'createVoucher',
                        'openOrders',
                        'redeemVoucher',
                        'sellInstant',
                        'sellLimit',
                        'transactionHistory',
                        'unconfirmedBitcoinDeposits',
                    ],
                },
            },
            'markets': {
                'BTC/EUR': { 'id': 'BTC_EUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR', 'precision': { 'amount': 4, 'price': 2 }, 'maker': 0.25 / 100, 'taker': 0.12 / 100 },
                'BTC/CZK': { 'id': 'BTC_CZK', 'symbol': 'BTC/CZK', 'base': 'BTC', 'quote': 'CZK', 'precision': { 'amount': 4, 'price': 2 }, 'maker': 0.25 / 100, 'taker': 0.12 / 100 },
                'LTC/EUR': { 'id': 'LTC_EUR', 'symbol': 'LTC/EUR', 'base': 'LTC', 'quote': 'EUR', 'precision': { 'amount': 4, 'price': 2 }, 'maker': 0.25 / 100, 'taker': 0.12 / 100 },
                'LTC/CZK': { 'id': 'LTC_CZK', 'symbol': 'LTC/CZK', 'base': 'LTC', 'quote': 'CZK', 'precision': { 'amount': 4, 'price': 2 }, 'maker': 0.25 / 100, 'taker': 0.12 / 100 },
                'LTC/BTC': { 'id': 'LTC_BTC', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC', 'precision': { 'amount': 4, 'price': 5 }, 'maker': 0.25 / 100, 'taker': 0.12 / 100 },
                'ETH/EUR': { 'id': 'ETH_EUR', 'symbol': 'ETH/EUR', 'base': 'ETH', 'quote': 'EUR', 'precision': { 'amount': 4, 'price': 2 }},
                'ETH/CZK': { 'id': 'ETH_CZK', 'symbol': 'ETH/CZK', 'base': 'ETH', 'quote': 'CZK', 'precision': { 'amount': 4, 'price': 2 }},
                'ETH/BTC': { 'id': 'ETH_BTC', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC', 'precision': { 'amount': 4, 'price': 5 }},
                'XRP/EUR': { 'id': 'XRP_EUR', 'symbol': 'XRP/EUR', 'base': 'XRP', 'quote': 'EUR', 'precision': { 'amount': 4, 'price': 5 }},
                'XRP/CZK': { 'id': 'XRP_CZK', 'symbol': 'XRP/CZK', 'base': 'XRP', 'quote': 'CZK', 'precision': { 'amount': 4, 'price': 5 }},
                'XRP/BTC': { 'id': 'XRP_BTC', 'symbol': 'XRP/BTC', 'base': 'XRP', 'quote': 'BTC', 'precision': { 'amount': 4, 'price': 8 }},
                'BCH/EUR': { 'id': 'BCH_EUR', 'symbol': 'BCH/EUR', 'base': 'BCH', 'quote': 'EUR', 'precision': { 'amount': 4, 'price': 2 }},
                'BCH/CZK': { 'id': 'BCH_CZK', 'symbol': 'BCH/CZK', 'base': 'BCH', 'quote': 'CZK', 'precision': { 'amount': 4, 'price': 2 }},
                'BCH/BTC': { 'id': 'BCH_BTC', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC', 'precision': { 'amount': 4, 'price': 5 }},
            },
            'fees': {
                'trading': {
                    'maker': 0.05 / 100,
                    'taker': 0.15 / 100,
                },
            },
        });
    }

    async fetchBalance (params = {}) {
        let response = await this.privatePostBalances ();
        let balances = response['data'];
        let result = { 'info': balances };
        let currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let account = this.account ();
            if (currency in balances) {
                account['free'] = balances[currency]['available'];
                account['used'] = balances[currency]['reserved'];
                account['total'] = balances[currency]['balance'];
            }
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        let response = await this.publicGetOrderBook (this.extend ({
            'currencyPair': this.marketId (symbol),
            'groupByPriceLimit': 'False',
        }, params));
        let orderbook = response['data'];
        let timestamp = orderbook['timestamp'] * 1000;
        return this.parseOrderBook (orderbook, timestamp, 'bids', 'asks', 'price', 'amount');
    }

    async fetchTicker (symbol, params = {}) {
        let response = await this.publicGetTicker (this.extend ({
            'currencyPair': this.marketId (symbol),
        }, params));
        let ticker = response['data'];
        let timestamp = ticker['timestamp'] * 1000;
        let last = this.safeFloat (ticker, 'last');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'high'),
            'low': this.safeFloat (ticker, 'low'),
            'bid': this.safeFloat (ticker, 'bid'),
            'bidVolume': undefined,
            'ask': this.safeFloat (ticker, 'ask'),
            'vwap': undefined,
            'askVolume': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': this.safeFloat (ticker, 'amount'),
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    parseTrade (trade, market = undefined) {
        if (!market)
            market = this.markets_by_id[trade['currencyPair']];
        return {
            'id': trade['transactionId'],
            'info': trade,
            'timestamp': trade['timestamp'],
            'datetime': this.iso8601 (trade['timestamp']),
            'symbol': market['symbol'],
            'type': undefined,
            'side': undefined,
            'price': trade['price'],
            'amount': trade['amount'],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        let market = this.market (symbol);
        let response = await this.publicGetTransactions (this.extend ({
            'currencyPair': market['id'],
            'minutesIntoHistory': 10,
        }, params));
        return this.parseTrades (response['data'], market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        let method = 'privatePost' + this.capitalize (side);
        let order = {
            'currencyPair': this.marketId (symbol),
        };
        if (type === 'market') {
            if (side === 'buy')
                order['total'] = amount; // amount in fiat
            else
                order['amount'] = amount; // amount in fiat
            method += 'Instant';
        } else {
            order['amount'] = amount; // amount in crypto
            order['price'] = price;
            method += this.capitalize (type);
        }
        let response = await this[method] (this.extend (order, params));
        return {
            'info': response,
            'id': response['data'].toString (),
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return await this.privatePostCancelOrder ({ 'orderId': id });
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + path;
        if (api === 'public') {
            if (Object.keys (params).length)
                url += '?' + this.urlencode (params);
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            let auth = nonce + this.uid + this.apiKey;
            let signature = this.hmac (this.encode (auth), this.encode (this.secret));
            body = this.urlencode (this.extend ({
                'clientId': this.uid,
                'nonce': nonce,
                'publicKey': this.apiKey,
                'signature': signature.toUpperCase (),
            }, params));
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if ('error' in response)
            if (response['error'])
                throw new ExchangeError (this.id + ' ' + this.json (response));
        return response;
    }
};
<|endoftext|>


<commit_before>$(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
        },
        submitSuccess: function($form, event) {
            var firstHackathon;
            $("#Field6").is(':checked') ? firstHackathon = true : firstHackathon = false;
            console.log($('#Field5').get(0).files[0]);
            var data = {"firstName": $('#Field1').val(), "lastName": $('#Field2').val(), "email": $('#Field3').val(), "school": $('#Field4').val(), "resume": $('#Field5').val(), "first": firstHackathon}

            $.ajax({
                url:    "./scripts/register.php",
                type:   "POST",
                data:   {
                    data: data
                },
                success: function(data) {
                    $('#success').empty();
                    if(data.indexOf("user-exists") > -1){
                        $('#success').append('
Hey, '+$('#Field1').val()+'! Looks like we already have that email registered!
').hide().fadeIn(750);
                    }
                    if(data.indexOf("added-user") > -1){
                        $('#success').append('
Thanks for registering, '+$('#Field1').val()+'!
').hide().fadeIn(750);
                        $('#submitButton').prop("disabled",true);
                    }
                },
                error: function(data) {
                    $('#success').append('
Sorry, '+$('#Field1').val()+', but it looks like we are having trouble right now. Try again later!
').hide().fadeIn(750);
                }
            });
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

$('#name').focus(function() {
    $('#success').html('');
});<commit_msg>Added file support for resume upload<commit_after>$(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
        },
        submitSuccess: function($form, event) {
            var reader = new FileReader();
            var firstHackathon;
            $("#Field6").is(':checked') ? firstHackathon = true : firstHackathon = false;
            console.log(reader.readAsArrayBuffer($('#Field5').get(0).files[0]));
            var data = {"firstName": $('#Field1').val(), "lastName": $('#Field2').val(), "email": $('#Field3').val(), "school": $('#Field4').val(), "resume": $('#Field5').val(), "first": firstHackathon}

            $.ajax({
                url:    "./scripts/register.php",
                type:   "POST",
                data:   {
                    data: data
                },
                success: function(data) {
                    $('#success').empty();
                    if(data.indexOf("user-exists") > -1){
                        $('#success').append('
Hey, '+$('#Field1').val()+'! Looks like we already have that email registered!
').hide().fadeIn(750);
                    }
                    if(data.indexOf("added-user") > -1){
                        $('#success').append('
Thanks for registering, '+$('#Field1').val()+'!
').hide().fadeIn(750);
                        $('#submitButton').prop("disabled",true);
                    }
                },
                error: function(data) {
                    $('#success').append('
Sorry, '+$('#Field1').val()+', but it looks like we are having trouble right now. Try again later!
').hide().fadeIn(750);
                }
            });
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

$('#name').focus(function() {
    $('#success').html('');
});<|endoftext|>


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

'use strict';

function synthesizeText(text, outputFile) {
  // [START tts_synthesize_text]
  const textToSpeech = require('@google-cloud/text-to-speech');
  const fs = require('fs');

  const client = new textToSpeech.TextToSpeechClient();

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const text = 'Text to synthesize, eg. hello';
  // const outputFile = 'Local path to save audio file to, e.g. output.mp3';

  const request = {
    input: {text: text},
    voice: {languageCode: 'en-US', ssmlGender: 'FEMALE'},
    audioConfig: {audioEncoding: 'MP3'},
  };

  client
    .synthesizeSpeech(request)
    .then(results => {
      const audioContent = results[0].audioContent;

      fs.writeFileSync(outputFile, audioContent, 'binary');
      console.log(`Audio content written to file: ${outputFile}`);
    })
    .catch(err => {
      console.error('ERROR:', err);
    });
  // [END tts_synthesize_text]
}

function synthesizeSsml(ssml, outputFile) {
  // [START tts_synthesize_ssml]
  const textToSpeech = require('@google-cloud/text-to-speech');
  const fs = require('fs');

  const client = new textToSpeech.TextToSpeechClient();

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const ssml = '<speak>Hello there.</speak>';
  // const outputFile = 'Local path to save audio file to, e.g. output.mp3';

  const request = {
    input: {ssml: ssml},
    voice: {languageCode: 'en-US', ssmlGender: 'FEMALE'},
    audioConfig: {audioEncoding: 'MP3'},
  };

  client
    .synthesizeSpeech(request)
    .then(results => {
      const audioContent = results[0].audioContent;

      fs.writeFileSync(outputFile, audioContent, 'binary');
      console.log(`Audio content written to file: ${outputFile}`);
    })
    .catch(err => {
      console.error('ERROR:', err);
    });
  // [END tts_synthesize_ssml]
}

function synthesizeTextFile(textFile, outputFile) {
  // [START tts_synthesize_text_file]
  const textToSpeech = require('@google-cloud/text-to-speech');
  const fs = require('fs');

  const client = new textToSpeech.TextToSpeechClient();

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const textFile = 'Local path to text file, eg. input.txt';
  // const outputFile = 'Local path to save audio file to, e.g. output.mp3';

  const request = {
    input: {text: fs.readFileSync(textFile)},
    voice: {languageCode: 'en-US', ssmlGender: 'FEMALE'},
    audioConfig: {audioEncoding: 'MP3'},
  };

  client
    .synthesizeSpeech(request)
    .then(results => {
      const audioContent = results[0].audioContent;

      fs.writeFileSync(outputFile, audioContent, 'binary');
      console.log(`Audio content written to file: ${outputFile}`);
    })
    .catch(err => {
      console.error('ERROR:', err);
    });
  // [END tts_synthesize_text_file]
}

function synthesizeSsmlFile(ssmlFile, outputFile) {
  // [START tts_synthesize_ssml_file]
  const textToSpeech = require('@google-cloud/text-to-speech');
  const fs = require('fs');

  const client = new textToSpeech.TextToSpeechClient();

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const ssmlFile = 'Local path to SSML file, eg. input.ssml';
  // const outputFile = 'Local path to save audio file to, e.g. output.mp3';

  const request = {
    input: {ssml: fs.readFileSync(ssmlFile)},
    voice: {languageCode: 'en-US', ssmlGender: 'FEMALE'},
    audioConfig: {audioEncoding: 'MP3'},
  };

  client
    .synthesizeSpeech(request)
    .then(results => {
      const audioContent = results[0].audioContent;

      fs.writeFileSync(outputFile, audioContent, 'binary');
      console.log(`Audio content written to file: ${outputFile}`);
    })
    .catch(err => {
      console.error('ERROR:', err);
    });
  // [END tts_synthesize_ssml_file]
}

require(`yargs`) // eslint-disable-line
  .demand(1)
  .command(`text <text>`, `Synthesizes audio file from text`, {}, opts =>
    synthesizeText(opts.text, opts.outputFile)
  )
  .command(`ssml <ssml>`, `Synthesizes audio file from SSML`, {}, opts =>
    synthesizeSsml(opts.ssml, opts.outputFile)
  )
  .command(
    `text-file <textFile>`,
    `Synthesizes audio file from text in a file`,
    {},
    opts => synthesizeTextFile(opts.textFile, opts.outputFile)
  )
  .command(
    `ssml-file <ssmlFile>`,
    `Synthesizes audio file from SSML in a file`,
    {},
    opts => synthesizeSsmlFile(opts.ssmlFile, opts.outputFile)
  )
  .options({
    outputFile: {
      alias: 'o',
      default: 'output.mp3',
      global: true,
      requiresArg: true,
      type: 'string',
    },
  })
  .example(`node $0 text "hello" -o hello.mp3`)
  .example(`node $0 ssml "<speak>Hello there.</speak>" -o hello.mp3`)
  .example(`node $0 text-file resources/hello.txt -o output.mp3`)
  .example(`node $0 ssml-file resources/hello.ssml -o output.mp3`)
  .wrap(120)
  .recommendCommands()
  .epilogue(
    `For more information, see https://cloud.google.com/text-to-speech/docs`
  )
  .help()
  .strict().argv;
<commit_msg>Samples: update writing bytes to mp3 files to be async<commit_after>/**
 * Copyright 2018, Google, Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

function synthesizeText(text, outputFile) {
  // [START tts_synthesize_text]
  const textToSpeech = require('@google-cloud/text-to-speech');
  const fs = require('fs');

  const client = new textToSpeech.TextToSpeechClient();

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const text = 'Text to synthesize, eg. hello';
  // const outputFile = 'Local path to save audio file to, e.g. output.mp3';

  const request = {
    input: {text: text},
    voice: {languageCode: 'en-US', ssmlGender: 'FEMALE'},
    audioConfig: {audioEncoding: 'MP3'},
  };

  client
    .synthesizeSpeech(request)
    .then(async results => {
      const audioContent = results[0].audioContent;

      await fs.writeFile(outputFile, audioContent, 'binary');
      console.log(`Audio content written to file: ${outputFile}`);
    })
    .catch(err => {
      console.error('ERROR:', err);
    });
  // [END tts_synthesize_text]
}

function synthesizeSsml(ssml, outputFile) {
  // [START tts_synthesize_ssml]
  const textToSpeech = require('@google-cloud/text-to-speech');
  const fs = require('fs');

  const client = new textToSpeech.TextToSpeechClient();

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const ssml = '<speak>Hello there.</speak>';
  // const outputFile = 'Local path to save audio file to, e.g. output.mp3';

  const request = {
    input: {ssml: ssml},
    voice: {languageCode: 'en-US', ssmlGender: 'FEMALE'},
    audioConfig: {audioEncoding: 'MP3'},
  };

  client
    .synthesizeSpeech(request)
    .then(async results => {
      const audioContent = results[0].audioContent;

      await fs.writeFile(outputFile, audioContent, 'binary');
      console.log(`Audio content written to file: ${outputFile}`);
    })
    .catch(err => {
      console.error('ERROR:', err);
    });
  // [END tts_synthesize_ssml]
}

function synthesizeTextFile(textFile, outputFile) {
  // [START tts_synthesize_text_file]
  const textToSpeech = require('@google-cloud/text-to-speech');
  const fs = require('fs');

  const client = new textToSpeech.TextToSpeechClient();

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const textFile = 'Local path to text file, eg. input.txt';
  // const outputFile = 'Local path to save audio file to, e.g. output.mp3';

  const request = {
    input: {text: fs.readFileSync(textFile)},
    voice: {languageCode: 'en-US', ssmlGender: 'FEMALE'},
    audioConfig: {audioEncoding: 'MP3'},
  };

  client
    .synthesizeSpeech(request)
    .then(async results => {
      const audioContent = results[0].audioContent;

      await fs.writeFile(outputFile, audioContent, 'binary');
      console.log(`Audio content written to file: ${outputFile}`);
    })
    .catch(err => {
      console.error('ERROR:', err);
    });
  // [END tts_synthesize_text_file]
}

function synthesizeSsmlFile(ssmlFile, outputFile) {
  // [START tts_synthesize_ssml_file]
  const textToSpeech = require('@google-cloud/text-to-speech');
  const fs = require('fs');

  const client = new textToSpeech.TextToSpeechClient();

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const ssmlFile = 'Local path to SSML file, eg. input.ssml';
  // const outputFile = 'Local path to save audio file to, e.g. output.mp3';

  const request = {
    input: {ssml: fs.readFileSync(ssmlFile)},
    voice: {languageCode: 'en-US', ssmlGender: 'FEMALE'},
    audioConfig: {audioEncoding: 'MP3'},
  };

  client
    .synthesizeSpeech(request)
    .then(async results => {
      const audioContent = results[0].audioContent;

      await fs.writeFile(outputFile, audioContent, 'binary');
      console.log(`Audio content written to file: ${outputFile}`);
    })
    .catch(err => {
      console.error('ERROR:', err);
    });
  // [END tts_synthesize_ssml_file]
}

require(`yargs`) // eslint-disable-line
  .demand(1)
  .command(`text <text>`, `Synthesizes audio file from text`, {}, opts =>
    synthesizeText(opts.text, opts.outputFile)
  )
  .command(`ssml <ssml>`, `Synthesizes audio file from SSML`, {}, opts =>
    synthesizeSsml(opts.ssml, opts.outputFile)
  )
  .command(
    `text-file <textFile>`,
    `Synthesizes audio file from text in a file`,
    {},
    opts => synthesizeTextFile(opts.textFile, opts.outputFile)
  )
  .command(
    `ssml-file <ssmlFile>`,
    `Synthesizes audio file from SSML in a file`,
    {},
    opts => synthesizeSsmlFile(opts.ssmlFile, opts.outputFile)
  )
  .options({
    outputFile: {
      alias: 'o',
      default: 'output.mp3',
      global: true,
      requiresArg: true,
      type: 'string',
    },
  })
  .example(`node $0 text "hello" -o hello.mp3`)
  .example(`node $0 ssml "<speak>Hello there.</speak>" -o hello.mp3`)
  .example(`node $0 text-file resources/hello.txt -o output.mp3`)
  .example(`node $0 ssml-file resources/hello.ssml -o output.mp3`)
  .wrap(120)
  .recommendCommands()
  .epilogue(
    `For more information, see https://cloud.google.com/text-to-speech/docs`
  )
  .help()
  .strict().argv;
<|endoftext|>


<commit_before>var sizeof = require('object-sizeof');
var cppMsg = require('../node_modules/cppmsg/cppMsg.js');
var reverse = require("buffer-reverse");

var weathermsg = new cppMsg.msg(
	[
		['ProtocolVersion', 'int16'],
		['MessageType', 'int16'],
		['Data', 'object']
	]
);

var weatherDatamsg = new cppMsg.msg(
	[
		['Temperature', 'int16'],
		['Humidty', 'int16'],
		['BaroPressure', 'int16'],
		['BaroTemperature', 'int16'],
		['Lux', 'uint16'],
		['test', 'bool']
	]
);

var weathercontrolmsg = new cppMsg.msg(
	[
		['sleepTime', 'int16'],
		['lightningIndoors', 'bool'],
		['lightningTune', 'int16'],
		['lightningNoiseFloor', 'int16'],
		['radioPower', 'int16']
	]
	);

var NRF24 = require('nrf'),
	spiDev = "/dev/spidev0.0",
	cePin = 24,
	irqPin = 25, //var ce = require("./gpio").connect(cePin)
	pipes = [0xF0F0F0F0E1, 0xF0F0F0F0D2];
var nrf = NRF24.connect(spiDev, cePin, irqPin);
//nrf._debug = true;git
nrf.channel(0x4c); // Set channel to 76
nrf.transmitPower('PA_MAX');
nrf.dataRate('1Mbps') // Set data rate to 1Mbps
nrf.crcBytes(2) // Set the CRC to 2
nrf.autoRetransmit({
	count: 500,
	delay: 15
});

nrf.begin(function() {
	console.log("Radio recevier listening.");
	var rx = nrf.openPipe('rx', pipes[1]),
		tx = nrf.openPipe('tx', pipes[0]);

	rx.on('data', function(d) {
		console.log(d);
		var data = weathermsg.decodeMsg(reverse(d));
		console.log(data);

		var response = {sleeptime: 10, lightningIndoors: true, lightningTune: 4, lightningNoiseFloor: 4, radioPower: 3};
		              var responseBuf = weathercontrolmsg.encodeMsg(response);

		               tx.write(reverse(responseBuf), sizeof(responseBuf));

	});
	tx.on('error', function(e) {
		console.warn("Error sending reply.", e);
		process.exit();
	});
});

//function reverse(s) {
//	return s.split("").reverse().join("");
//}
<commit_msg>Working double struct<commit_after>var sizeof = require('object-sizeof');
var cppMsg = require('../node_modules/cppmsg/cppMsg.js');
var reverse = require("buffer-reverse");

var weatherdatamsg = new cppMsg.msg(
                [
                ['MessageType', 'int8'],
		['Temperature', 'int16'],
		['Humidty', 'int16'],
		['BaroPressure', 'int16'],
		['BaroTemperature', 'int16'],
		['Lux', 'uint16']
	]
);

var weathercontrolmsg = new cppMsg.msg(
	[
		['sleepTime', 'int16'],
		['lightningIndoors', 'bool'],
		['lightningTune', 'int16'],
		['lightningNoiseFloor', 'int16'],
		['radioPower', 'int16']
	]
	);

var lightningMsg = new cppMsg.msg(
    [
    ['MessageType','int8'],
    ['EventType','int16'],
    ['Distance','int16'],
    ['Intensity','int16']
    ]
);
var NRF24 = require('nrf'),
	spiDev = "/dev/spidev0.0",
	cePin = 24,
	irqPin = 25, //var ce = require("./gpio").connect(cePin)
	pipes = [0xF0F0F0F0E1, 0xF0F0F0F0D2];
var nrf = NRF24.connect(spiDev, cePin, irqPin);
//nrf._debug = true;git
nrf.channel(0x4c); // Set channel to 76
nrf.transmitPower('PA_MAX');
nrf.dataRate('1Mbps') // Set data rate to 1Mbps
nrf.crcBytes(2) // Set the CRC to 2
nrf.autoRetransmit({
	count: 500,
	delay: 15
});

nrf.begin(function() {
	console.log("Radio recevier listening.");
	var rx = nrf.openPipe('rx', pipes[1]),
		tx = nrf.openPipe('tx', pipes[0]);

	rx.on('data', function(d) {

                var typeCode = reverse(d).readUIntBE(0, 1);;
                console.log(typeCode);
                if(typeCode === 1){
		var data = weatherdatamsg.decodeMsg(reverse(d));
console.log(data);

                }else{
                var otherdata = lightningMsg.decodeMsg(reverse(d));
console.log(otherdata);
}
		var response = {sleeptime: 10, lightningIndoors: true, lightningTune: 4, lightningNoiseFloor: 4, radioPower: 3};
		              var responseBuf = weathercontrolmsg.encodeMsg(response);

		               tx.write(reverse(responseBuf), sizeof(responseBuf));

	});
	tx.on('error', function(e) {
		console.warn("Error sending reply.", e);
		process.exit();
	});
});

//function reverse(s) {
//	return s.split("").reverse().join("");
//}
<|endoftext|>


<commit_before>var request = require('request');
var settings = require('../settings');
var settings_local = require('../settings_local');
var _ = require('lodash');
var Promise = require('es6-promise').Promise;

const API_ENDPOINT = 'http://localhost:5000';
const PERSONA_ENDPOINT = 'http://localhost:9001';
const USER_COUNT = 100;

function createUsers() {
    function createUser(email) {
        return new Promise(function(resolve,reject){
            request.post({
                url: PERSONA_ENDPOINT+'/generate',
                form: {
                    email: email
                }
            }, function(err, resp, body) {
                if (err) {
                    reject('Connection to assertion generator failed');
                    return;
                }

                var json_resp = JSON.parse(body);
                resolve({email:email, assertion:json_resp.assertion});
            });
        });
    };

    function login(emailAssertion){
        var email = emailAssertion.email;
        var assertion = emailAssertion.assertion;

        return new Promise(function(resolve,reject){
            request.post({
                url: API_ENDPOINT+'/user/login',
                form: {
                    assertion: assertion,
                    audience: API_ENDPOINT
                }
            }, function(err, resp, body) {
                if (err) {
                    reject('Galaxy login failed.');
                    return;
                }

                var json_resp = JSON.parse(body);
                if (json_resp.error) {
                    reject('Galaxy login failed: ' + json_resp.error);
                    return;
                }

                resolve({email:email, token:json_resp.token});
            });
        });
    };

    var promises = [];
    for (var i = 0; i < USER_COUNT; i++){
        promises.push(createUser('test' + i + '@test.com').then(login));
    }
    return Promise.all(promises);
}

function createGames() {
    // do stuff
}

function createGames() {
    var default_params = {
        icons: '128',
        screenshots: 'yes'
    };
    var fake_games = [
        {
            name: 'Mario Broskis',
            app_url: 'http://mario.broskis'
        },
        {
            name: 'Halo 718',
            app_url: 'http://halo.com'
        },
        {
            name: 'Left 5 Dead',
            app_url: 'http://dead.left'
        }
    ];

    var promises = [];
    _.each(fake_games, function(game) {
        promises.push(new Promise(function(resolve, reject) {
            request.post({
                url: API_ENDPOINT + '/game/submit',
                form: _.defaults(game, default_params)
            }, function(err, resp, body) {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(body);
            });
        }));
    });
    return Promise.all(promises);
}

createUsers().then(function(result){
    console.log('user creation done!');
}, function(err) {
    console.log('user creation error', err);
});

createGames().then(function(result){
    console.log('game creation done! result:', result);
}, function(err) {
    console.log('game creation error:', err);
});<commit_msg>added more stored attributes for created users<commit_after>var request = require('request');
var settings = require('../settings');
var settings_local = require('../settings_local');
var _ = require('lodash');
var Promise = require('es6-promise').Promise;

const API_ENDPOINT = 'http://localhost:5000';
const PERSONA_ENDPOINT = 'http://localhost:9001';
const USER_COUNT = 100;

function createUsers() {
    function createUser(email) {
        return new Promise(function(resolve,reject){
            request.post({
                url: PERSONA_ENDPOINT+'/generate',
                form: {
                    email: email
                }
            }, function(err, resp, body) {
                if (err) {
                    reject('Connection to assertion generator failed');
                    return;
                }

                var json_resp = JSON.parse(body);
                resolve({email:email, assertion:json_resp.assertion});
            });
        });
    };

    function login(emailAssertion){
        var email = emailAssertion.email;
        var assertion = emailAssertion.assertion;

        return new Promise(function(resolve,reject){
            request.post({
                url: API_ENDPOINT+'/user/login',
                form: {
                    assertion: assertion,
                    audience: API_ENDPOINT
                }
            }, function(err, resp, body) {
                if (err) {
                    reject('Galaxy login failed.');
                    return;
                }

                var json_resp = JSON.parse(body);
                if (json_resp.error) {
                    reject('Galaxy login failed: ' + json_resp.error);
                    return;
                }
                resolve({
                    email:email,
                    token:json_resp.token,
                    username:json_resp.public.username,
                    id:json_resp.public.id
                });
            });
        });
    };

    var promises = [];
    for (var i = 0; i < USER_COUNT; i++){
        promises.push(createUser('test' + i + '@test.com').then(login));
    }
    return Promise.all(promises);
}

function createGames() {
    var default_params = {
        icons: '128',
        screenshots: 'yes'
    };
    var fake_games = [
        {
            name: 'Mario Broskis',
            app_url: 'http://mario.broskis'
        },
        {
            name: 'Halo 718',
            app_url: 'http://halo.com'
        },
        {
            name: 'Left 5 Dead',
            app_url: 'http://dead.left'
        }
    ];

    var promises = [];
    _.each(fake_games, function(game) {
        promises.push(new Promise(function(resolve, reject) {
            request.post({
                url: API_ENDPOINT + '/game/submit',
                form: _.defaults(game, default_params)
            }, function(err, resp, body) {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(body);
            });
        }));
    });
    return Promise.all(promises);
}

createUsers().then(function(result){
    console.log('user creation done!', result);
}, function(err) {
    console.log('user creation error', err);
});

createGames().then(function(result){
    console.log('game creation done! result:', result);
}, function(err) {
    console.log('game creation error:', err);
});<|endoftext|>