<commit_before>// Plugin for using a local directory as a Library. Generates the payload for
// an AssetList REST endpoint consisting of asset models as well as pagination
// helpers.
var _ = require('underscore'),
    fs = require('fs'),
    url = require('url'),
    path = require('path'),
    querystring = require('querystring'),
    Step = require('step');

module.exports = function(app, options, callback) {
    // Recursive readdir. `callback(err, files)` is given a `files` array where
    // each file is an object with `filename` and `stat` properties.
    var lsR = function(basedir, callback) {
        var files = [];
        var ls = [];
        Step(
            function() {
                fs.readdir(basedir, this);
            },
            function(err, data) {
                if (data.length === 0) return this();

                var group = this.group();
                ls = _.map(data, function(v) {
                    return path.join(basedir, v);
                });
                _.each(ls, function(v) {
                    fs.stat(v, group());
                });
            },
            function(err, stats) {
                if (ls.length === 0) return this();

                var group = this.group();
                _.each(ls, function(v, k) {
                    var next = group();
                    if (stats[k].isDirectory()) {
                        lsR(v, next);
                    } else {
                        files.push({
                            filename: v,
                            stat: stats[k]
                        });
                        next();
                    }
                });
            },
            function(err, sub) {
                _.each(sub, function(v) {
                    v && (files = files.concat(v));
                });
                callback(err, files);
            }
        );
    }

    // Filter an array of files where filenames match regex `re`.
    var lsFilter = function(files, re) {
        return _.filter(files, function(f) {
            return f.filename.match(re);
        });
    };

    // Convert a list of files into asset models.
    var toAssets = function(files, base_dir, port) {
        return _.map(files, function(f) {
            return {
                url: url.format({
                    host: 'localhost:' + port,
                    protocol: 'http:',
                    pathname: path.join(
                        '/api/Library/'
                        + options.id
                        + '/files/'
                        // Ensure only one trailing slash
                        + querystring.escape(f.filename.replace(
                          base_dir.replace(/(\/)$/, '') + '/', ''))
                    )
                }),
                bytes: (Math.ceil(parseInt(f.stat.size) / 1048576)) + ' MB',
                id: path.basename(f.filename)
            };
        });
    };

    // Sort and slice to the specified page.
    var paginate = function(objects, page, limit) {
        return _.sortBy(objects, function(f) {
            return f.id;
        }).slice(page * limit, page * limit + limit);
    };

    // Generate the AssetList payload object.
    lsR(options.directory_path, function(err, files) {
        var assets = toAssets(
            lsFilter(files, /\.(zip|json|geojson|vrt|tiff?)$/i),
            options.directory_path,
            require('settings').port
        );
        callback({
            models: paginate(
                assets,
                options.page,
                options.limit
            ),
            page: options.page,
            pageTotal: Math.ceil(assets.length / options.limit)
        });
    });
};

<commit_msg>Make Library items URL relative. Fixes #267<commit_after>// Plugin for using a local directory as a Library. Generates the payload for
// an AssetList REST endpoint consisting of asset models as well as pagination
// helpers.
var _ = require('underscore'),
    fs = require('fs'),
    url = require('url'),
    path = require('path'),
    querystring = require('querystring'),
    Step = require('step');

module.exports = function(app, options, callback) {
    // Recursive readdir. `callback(err, files)` is given a `files` array where
    // each file is an object with `filename` and `stat` properties.
    var lsR = function(basedir, callback) {
        var files = [];
        var ls = [];
        Step(
            function() {
                fs.readdir(basedir, this);
            },
            function(err, data) {
                if (data.length === 0) return this();

                var group = this.group();
                ls = _.map(data, function(v) {
                    return path.join(basedir, v);
                });
                _.each(ls, function(v) {
                    fs.stat(v, group());
                });
            },
            function(err, stats) {
                if (ls.length === 0) return this();

                var group = this.group();
                _.each(ls, function(v, k) {
                    var next = group();
                    if (stats[k].isDirectory()) {
                        lsR(v, next);
                    } else {
                        files.push({
                            filename: v,
                            stat: stats[k]
                        });
                        next();
                    }
                });
            },
            function(err, sub) {
                _.each(sub, function(v) {
                    v && (files = files.concat(v));
                });
                callback(err, files);
            }
        );
    }

    // Filter an array of files where filenames match regex `re`.
    var lsFilter = function(files, re) {
        return _.filter(files, function(f) {
            return f.filename.match(re);
        });
    };

    // Convert a list of files into asset models.
    var toAssets = function(files, base_dir, port) {
        return _.map(files, function(f) {
            return {
                url: url.format({
                    pathname: path.join(
                        'api/Library/'
                        + options.id
                        + '/files/'
                        // Ensure only one trailing slash
                        + querystring.escape(f.filename.replace(
                          base_dir.replace(/(\/)$/, '') + '/', ''))
                    )
                }),
                bytes: (Math.ceil(parseInt(f.stat.size) / 1048576)) + ' MB',
                id: path.basename(f.filename)
            };
        });
    };

    // Sort and slice to the specified page.
    var paginate = function(objects, page, limit) {
        return _.sortBy(objects, function(f) {
            return f.id;
        }).slice(page * limit, page * limit + limit);
    };

    // Generate the AssetList payload object.
    lsR(options.directory_path, function(err, files) {
        var assets = toAssets(
            lsFilter(files, /\.(zip|json|geojson|vrt|tiff?)$/i),
            options.directory_path,
            require('settings').port
        );
        callback({
            models: paginate(
                assets,
                options.page,
                options.limit
            ),
            page: options.page,
            pageTotal: Math.ceil(assets.length / options.limit)
        });
    });
};

<|endoftext|>


<commit_before>import deepExtend from 'deep-extend';
import defaults from './defaults';
import Promise from 'bluebird';

import path from 'path';

/**
 * For relative pathing to work, let's convert all paths in src options to
 * absolute paths, if they are not already.
 * @param {Object} opts   Mutated in place.
 */
function normalizePaths (opts) {
  for (var srcKey in opts.src) {
    if (!path.isAbsolute(opts.src[srcKey].glob)) {
      opts.src[srcKey].glob = path.resolve(opts.src[srcKey].glob);
    }
    if (!path.isAbsolute(opts.src[srcKey].basedir)) {
      opts.src[srcKey].basedir = path.resolve(opts.src[srcKey].basedir);
    }
  }
}

/**
 * Merge defaults into passed options.
 * @param {Object} options
 * @param {Object} handlebars   Handlebars instance—it can be passed explicitly,
 *                              primarily for testing purposes.
 * @return {Promise} resolving to merged options
 */

function init (options = {}, handlebars) {
  const opts = deepExtend({}, defaults, options);
  normalizePaths(opts);
  opts.handlebars = handlebars || require('handlebars');
  return Promise.resolve(opts);
}

export default init;
<commit_msg>Change `init()` to use new Handlebars by default instead of singleton<commit_after>import deepExtend from 'deep-extend';
import defaults from './defaults';
import Promise from 'bluebird';
import Handlebars from 'handlebars';
import path from 'path';

/**
 * For relative pathing to work, let's convert all paths in src options to
 * absolute paths, if they are not already.
 * @param {Object} opts   Mutated in place.
 */
function normalizePaths (opts) {
  for (var srcKey in opts.src) {
    if (!path.isAbsolute(opts.src[srcKey].glob)) {
      opts.src[srcKey].glob = path.resolve(opts.src[srcKey].glob);
    }
    if (!path.isAbsolute(opts.src[srcKey].basedir)) {
      opts.src[srcKey].basedir = path.resolve(opts.src[srcKey].basedir);
    }
  }
}

/**
 * Merge defaults into passed options.
 * @param {Object} options
 * @param {Object} handlebars   Handlebars instance—it can be passed explicitly,
 *                              primarily for testing purposes.
 * @return {Promise} resolving to merged options
 */

function init (options = {}, handlebars) {
  const opts = deepExtend({}, defaults, options);
  normalizePaths(opts);
  opts.handlebars = handlebars || Handlebars.create();
  return Promise.resolve(opts);
}

export default init;
<|endoftext|>


<commit_before>var projectId = null;
var roomTypeId = null;
var roomsCount = null;
var roomCapacity = 0;

var roomsRows = null;
var rowPlaceholder = null;
var dlgEditRoomName = null;

function AddPeople(roomId)
{

}

function KickPeople(roomId)
{

}

function AddRoom()
{
    dlgEditRoomName.roomId = null;
    dlgEditRoomName.roomName = "";
    dlgEditRoomName.pnRoomNameTitle.innerHTML = "Добавление комнат";
    dlgEditRoomName.edRoomName.value = "";
    $(dlgEditRoomName).modal("show");
    dlgEditRoomName.edRoomName.focus();
}

function DeleteRoom(id)
{
    var row = roomsRows.GetRowById(id);
    var name = row.getElementsByTagName("td").item(0).innerHTML;
    if (confirm("Удалить комнату " + name + "?"))
    {
        $(row.bnDelete).prop("disabled", true);
        DoDeleteRoom(id);
    }
}

function RenameRoom(id)
{
    var row = roomsRows.GetRowById(id);
    if (row != null)
    {
        var name = row.getElementsByTagName("td").item(0).innerHTML;

        dlgEditRoomName.roomId = id;
        dlgEditRoomName.roomName = name;
        dlgEditRoomName.pnRoomNameTitle.innerHTML = "Изменение комнаты";
        dlgEditRoomName.edRoomName.value = name;
        $(dlgEditRoomName).modal("show");
        dlgEditRoomName.edRoomName.focus();
    }
}

function DoEditRoom(id, name)
{
    var row = null;
    if (id == null)
        id = "new";
    else
    {
        row = roomsRows.GetRowById(id);
        row.getElementsByTagName("td").item(0).innerHTML = name;
        $(row.bnRename).prop("disabled", true);
    }

    var url = "/" + projectId + "/rooms/editroom?roomTypeId=" + roomTypeId + "&room=" + id + "&name=" + name;

    var xr = $.ajax(url, { method: "GET" })
        .done(function (data, status, xr)
        {
            if (id != "new")
                $(row.bnRename).prop("disabled", false);

            if (xr.status == 200)
            {
                $(roomsRows).append(xr.responseText);
            }
            else if (xr.status == 500)
            {
                ErrorEdit();
            }
            else
            {
                // Unknown success code -- have to reload page
                location.reload();
            }
        })
        .fail(function (xr, status, error)
        {
            if (id != "new")
                $(row.bnRename).prop("disabled", false);

            ErrorEdit();
        });
}

function DoDeleteRoom(id)
{
    var url = "/" + projectId + "/rooms/deleteroom?roomTypeId=" + roomTypeId + "&roomId=" + id;
    var xr = $.ajax(url, { method: "DELETE" })
        .done(function (data, status, xr)
        {
            if (xr.status == 200)
            {
                var row = roomsRows.GetRowById(id);
                row.remove();
            }
            else if (xr.status == 500)
            {
                ErrorDelete();
            }
            else
            {
                // Unknown success code -- have to reload page
                location.reload();
            }
        })
        .fail(function (xr, status, error)
        {
            ErrorDelete();
        });
}

function ErrorEdit()
{
    alert("Произошла ошибка при добавлении или изменении комнат");
}

function ErrorDelete()
{
    alert("Произошла ошибка при попытке удаления комнаты")
}

function parseIntDef(value, def)
{
    value = parseInt(value);
    if (isNaN(value))
        value = def;
    return value;
}

$(function ()
{
    roomsRows = document.getElementById("roomsRows");
    rowPlaceholder = document.getElementById("rowPlaceholder");
    $(rowPlaceholder).toggle(roomsCount == 0);

    roomsRows.GetRowById = function (roomId)
    {
        return document.getElementById("room" + roomId);
    };

    // Rows initialization
    if (roomsCount > 0)
    {
        for (var i = 0; i < roomsRows.children.length - 1; i++)
        {
            room = roomsRows.children[i];
            if (room.id.startsWith("room"))
            {
                room.roomId = parseIntDef(room.getAttribute("roomId"), 0);
                room.occupancy = parseIntDef(room.getAttribute("occupancy"), 0);
                room.bnAddPeople = document.getElementById("add" + room.roomId);
                room.bnKickPeople = document.getElementById("kick" + room.roomId);
                room.bnRename = document.getElementById("rename" + room.roomId);
                room.bnDelete = document.getElementById("delete" + room.roomId);
                $(room.bnDelete).prop("disabled", room.occupancy > 0);
            }
        }
    }

    // Dialog initialization
    dlgEditRoomName = document.getElementById("dlgEditRoomName");
    dlgEditRoomName.pnRoomNameTitle = document.getElementById("pnRoomNameTitle");
    dlgEditRoomName.edRoomName = document.getElementById("edRoomName");
    dlgEditRoomName.bnEditRoomOk = document.getElementById("bnEditRoomOk");
    $(dlgEditRoomName.edRoomName).keypress(function ()
    {
        var newValue = String(dlgEditRoomName.edRoomName.value).trim();
        dlgEditRoomName.bnEditRoomOk.disabled =
            newValue.length == 0 || newValue == dlgEditRoomName.roomName;
    });
    $(dlgEditRoomName.bnEditRoomOk).click(function ()
    {
        var newValue = String(dlgEditRoomName.edRoomName.value).trim();
        if (newValue.length == 0 || newValue == dlgEditRoomName.roomName)
            return;
        $(dlgEditRoomName).modal("hide");
        DoEditRoom(dlgEditRoomName.roomId, newValue);
    });

})
<commit_msg>Edit room hints autohide<commit_after>var projectId = null;
var roomTypeId = null;
var roomsCount = null;
var roomCapacity = 0;

var roomsRows = null;
var rowPlaceholder = null;
var dlgEditRoomName = null;

function AddPeople(roomId)
{

}

function KickPeople(roomId)
{

}

function AddRoom()
{
    dlgEditRoomName.roomId = null;
    dlgEditRoomName.roomName = "";
    dlgEditRoomName.pnRoomNameTitle.innerHTML = "Добавление комнат";
    dlgEditRoomName.edRoomName.value = "";
    $(dlgEditRoomName.addComment).show();
    $(dlgEditRoomName).modal("show");
    dlgEditRoomName.edRoomName.focus();
}

function DeleteRoom(id)
{
    var row = roomsRows.GetRowById(id);
    var name = row.getElementsByTagName("td").item(0).innerHTML;
    if (confirm("Удалить комнату " + name + "?"))
    {
        $(row.bnDelete).prop("disabled", true);
        DoDeleteRoom(id);
    }
}

function RenameRoom(id)
{
    var row = roomsRows.GetRowById(id);
    if (row != null)
    {
        var name = row.getElementsByTagName("td").item(0).innerHTML;

        dlgEditRoomName.roomId = id;
        dlgEditRoomName.roomName = name;
        dlgEditRoomName.pnRoomNameTitle.innerHTML = "Изменение комнаты";
        dlgEditRoomName.edRoomName.value = name;
        $(dlgEditRoomName.addComment).hide();
        $(dlgEditRoomName).modal("show");
        dlgEditRoomName.edRoomName.focus();
    }
}

function DoEditRoom(id, name)
{
    var row = null;
    if (id == null)
        id = "new";
    else
    {
        row = roomsRows.GetRowById(id);
        row.getElementsByTagName("td").item(0).innerHTML = name;
        $(row.bnRename).prop("disabled", true);
    }

    var url = "/" + projectId + "/rooms/editroom?roomTypeId=" + roomTypeId + "&room=" + id + "&name=" + name;

    var xr = $.ajax(url, { method: "GET" })
        .done(function (data, status, xr)
        {
            if (id != "new")
                $(row.bnRename).prop("disabled", false);

            if (xr.status == 200)
            {
                $(roomsRows).append(xr.responseText);
            }
            else if (xr.status == 500)
            {
                ErrorEdit();
            }
            else
            {
                // Unknown success code -- have to reload page
                location.reload();
            }
        })
        .fail(function (xr, status, error)
        {
            if (id != "new")
                $(row.bnRename).prop("disabled", false);

            ErrorEdit();
        });
}

function DoDeleteRoom(id)
{
    var url = "/" + projectId + "/rooms/deleteroom?roomTypeId=" + roomTypeId + "&roomId=" + id;
    var xr = $.ajax(url, { method: "DELETE" })
        .done(function (data, status, xr)
        {
            if (xr.status == 200)
            {
                var row = roomsRows.GetRowById(id);
                row.remove();
            }
            else if (xr.status == 500)
            {
                ErrorDelete();
            }
            else
            {
                // Unknown success code -- have to reload page
                location.reload();
            }
        })
        .fail(function (xr, status, error)
        {
            ErrorDelete();
        });
}

function ErrorEdit()
{
    alert("Произошла ошибка при добавлении или изменении комнат");
}

function ErrorDelete()
{
    alert("Произошла ошибка при попытке удаления комнаты")
}

function parseIntDef(value, def)
{
    value = parseInt(value);
    if (isNaN(value))
        value = def;
    return value;
}

$(function ()
{
    roomsRows = document.getElementById("roomsRows");
    rowPlaceholder = document.getElementById("rowPlaceholder");
    $(rowPlaceholder).toggle(roomsCount == 0);

    roomsRows.GetRowById = function (roomId)
    {
        return document.getElementById("room" + roomId);
    };

    // Rows initialization
    if (roomsCount > 0)
    {
        for (var i = 0; i < roomsRows.children.length - 1; i++)
        {
            room = roomsRows.children[i];
            if (room.id.startsWith("room"))
            {
                room.roomId = parseIntDef(room.getAttribute("roomId"), 0);
                room.occupancy = parseIntDef(room.getAttribute("occupancy"), 0);
                room.bnAddPeople = document.getElementById("add" + room.roomId);
                room.bnKickPeople = document.getElementById("kick" + room.roomId);
                room.bnRename = document.getElementById("rename" + room.roomId);
                room.bnDelete = document.getElementById("delete" + room.roomId);
                $(room.bnDelete).prop("disabled", room.occupancy > 0);
            }
        }
    }

    // Dialog initialization
    dlgEditRoomName = document.getElementById("dlgEditRoomName");
    dlgEditRoomName.pnRoomNameTitle = document.getElementById("pnRoomNameTitle");
    dlgEditRoomName.edRoomName = document.getElementById("edRoomName");
    dlgEditRoomName.bnEditRoomOk = document.getElementById("bnEditRoomOk");
    dlgEditRoomName.addComment = document.getElementById("addComment");
    $(dlgEditRoomName.edRoomName).keypress(function ()
    {
        var newValue = String(dlgEditRoomName.edRoomName.value).trim();
        dlgEditRoomName.bnEditRoomOk.disabled =
            newValue.length == 0 || newValue == dlgEditRoomName.roomName;
    });
    $(dlgEditRoomName.bnEditRoomOk).click(function ()
    {
        var newValue = String(dlgEditRoomName.edRoomName.value).trim();
        if (newValue.length == 0 || newValue == dlgEditRoomName.roomName)
            return;
        $(dlgEditRoomName).modal("hide");
        DoEditRoom(dlgEditRoomName.roomId, newValue);
    });

})
<|endoftext|>


<commit_before>import {motionFile} from '../gulp/babel'
import {Scanner} from '../gulp/scanner'
import Cache from '../cache'

const NEWLINE_REGEX = /\r\n|\n|\r/g
export const POSITION_TYPE = {
  VIEW_TOP: 'VIEW_TOP',
  VIEW_JSX: 'VIEW_JSX',
  STYLE: 'STYLE'
}

export function collectViews(contents) {
  const filePath = '__editor__'
  try {
    let views = {}
    Scanner.pre(filePath, contents, function(contents) {
      motionFile({
        contents,
        path: filePath,
        relative: filePath,
        sourceMap: false
      })
    })
    return Cache.getFileMeta(filePath) || {}
  } catch (_) {
    if (typeof _.pos !== 'undefined') {
      // Syntax error
      return {}
    } else throw _
  }
}

export function pointWithinRange(point, range) {
  return point.isGreaterThan(range[0]) && point.isLessThan(range[1])
}

export function getObjectAtPosition(objects, position) {
  for (const key in objects) {
    const value = objects[key]
    if (pointWithinRange(position, value.location)) {
      return value
    }
  }
  return null
}

export function getRowFromText(text, row) {
  const rowText = text.split(NEWLINE_REGEX)[row]
  return rowText || ''
}
<commit_msg>:fire: Fix CI build<commit_after>const NEWLINE_REGEX = /\r\n|\n|\r/g
export const POSITION_TYPE = {
  VIEW_TOP: 'VIEW_TOP',
  VIEW_JSX: 'VIEW_JSX',
  STYLE: 'STYLE'
}

export function collectViews(contents) {
  throw new Error('To be rewritten')
}

export function pointWithinRange(point, range) {
  return point.isGreaterThan(range[0]) && point.isLessThan(range[1])
}

export function getObjectAtPosition(objects, position) {
  for (const key in objects) {
    const value = objects[key]
    if (pointWithinRange(position, value.location)) {
      return value
    }
  }
  return null
}

export function getRowFromText(text, row) {
  const rowText = text.split(NEWLINE_REGEX)[row]
  return rowText || ''
}
<|endoftext|>


<commit_before>// Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

// Integers in each row are sorted from left to right.
// The first integer of each row is greater than the last integer of the previous row.
// For example,

// Consider the following matrix:

// [
//   [1,   3,  5,  7],
//   [10, 11, 16, 20],
//   [23, 30, 34, 50]
// ]

// Given target = 3, return true.

/**
 * @param {array[][]} matrix
 * @param {number} target
 * @return {boolean}
 */

// create variables to keep track of
  // rLo: the lowest index of the current row
  // rHi: the highest index of the current row
  // cLo: the lowest index of the current column
  // cHi: the highest index of the current column
  // mid: the index of the current row

// create a while that breaks once low row index meets high row index
  // set mid by length of rows divided by 2
  // once mid is set, grab length of current row and set it as our highest column index
  // create 4 conditionals
    // if the first or last index of our current row is the target, return true
    // if target is greater than lowest index of row AND target is less than highest index of current row
      // we can check each element in current row to see if target exists
      // decrement and increment lowest and highest index till each element is covered to see if target exists
    // if the target is less than the lowest element on the current row we can check arrays before
    // case thats left is.. the target is greater than the highest element on the current row, so we check arrays after

var searchMatrix = function(matrix, target) {
    var rLo = 0,
        rHi = matrix.length-1,
        cLo = 0,
        cHi,
        mid;

    while( rHi>=rLo ){
        mid = Math.floor(rHi/2);
        cHi  = matrix[mid].length-1;
        if( matrix[mid][cLo] === target ||  matrix[mid][cHi] === target) return true;
        if( matrix[mid][cLo] < target && matrix[mid][cHi] > target ) return checkRow(matrix[mid], cLo, cHi); // in current array
        if( matrix[mid][cLo] > target ) return searchMatrix(  matrix.splice(rLo, mid), target ); //  check rows before current
        return searchMatrix(  matrix.splice(mid+1), target ); // check rows after current
    }

    function checkRow(arr, l, r){
        while( l<=r ){
            if( arr[l] === target || arr[r] === target ) return true;
            l++;
            r--;
        }
        return false;
    }
    return false;
};
<commit_msg>syntax<commit_after>// Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

// Integers in each row are sorted from left to right.
// The first integer of each row is greater than the last integer of the previous row.
// For example,

// Consider the following matrix:

// [
//   [1,   3,  5,  7],
//   [10, 11, 16, 20],
//   [23, 30, 34, 50]
// ]

// Given target = 3, return true.

/**
 * @param {array[][]} matrix
 * @param {number} target
 * @return {boolean}
 */

// create variables to keep track of
  // rLo: the lowest index of the current row
  // rHi: the highest index of the current row
  // cLo: the lowest index of the current column
  // cHi: the highest index of the current column
  // mid: the index of the current row

// create a while that breaks once low row index meets high row index
  // set mid by length of rows divided by 2
  // once mid is set, grab length of current row and set it as our highest column index
  // create 4 conditionals
    // if the first or last index of our current row is the target, return true
    // if target is greater than lowest index of row AND target is less than highest index of current row
      // we can check each element in current row to see if target exists
      // decrement and increment lowest and highest index till each element is covered to see if target exists
    // if the target is less than the lowest element on the current row we can check arrays before
    // case thats left is.. the target is greater than the highest element on the current row, so we check arrays after

var searchMatrix = function(matrix, target) {
    var rLo = 0,
        rHi = matrix.length-1,
        cLo = 0,
        cHi,
        mid;

    while( rHi>=rLo ){
        mid = Math.floor(rHi/2);
        cHi  = matrix[mid].length-1;
        if( matrix[mid][cLo] === target ||  matrix[mid][cHi] === target ) return true;
        if( matrix[mid][cLo] < target && matrix[mid][cHi] > target ) return checkRow(matrix[mid], cLo, cHi); // in current array
        if( matrix[mid][cLo] > target ) return searchMatrix(  matrix.splice(rLo, mid), target ); //  check rows before current
        return searchMatrix(  matrix.splice(mid+1), target ); // check rows after current
    }

    function checkRow(arr, l, r){
        while( l<=r ){
            if( arr[l] === target || arr[r] === target ) return true;
            l++;
            r--;
        }
        return false;
    }
    return false;
};
<|endoftext|>


<commit_before>import SetGameState from './SetGameStateAction.js';
import SetUiMessage from './SetUiMessageAction.js';
import { TakeResources } from './async/ExecutePlayerAction.js';
import CheckResponse from './async/CheckResponse.js';

export default function TakeResourcesFromStackAction() {
  return (dispatch, getState) => {
    let state = getState();

    let selection = state.gameState.board.selection;
    if (selection.type === 'RESOURCE_SELECTION') {
      CheckResponse(TakeResources(state.gameId, 0, state.gameState.board.selection.selection.join()))
      .then(
          gameState => { dispatch(SetGameState(gameState)); }
      )
      .catch(
          error => {
            dispatch(SetUiMessage(error.message, 'ERROR'));
          }
      );
    } else {
      dispatch(SetUiMessage("Wrong selection", 'ERROR'));
    }
  }
}
<commit_msg>Using gameRef.gameId instead of plain gameId.<commit_after>import SetGameState from './SetGameStateAction.js';
import SetUiMessage from './SetUiMessageAction.js';
import { TakeResources } from './async/ExecutePlayerAction.js';
import CheckResponse from './async/CheckResponse.js';

export default function TakeResourcesFromStackAction() {
  return (dispatch, getState) => {
    let state = getState();

    let selection = state.gameState.board.selection;
    if (selection.type === 'RESOURCE_SELECTION') {
      CheckResponse(
          TakeResources(
              state.gameRef.gameId,
              0,
              state.gameState.board.selection.selection.join()))
      .then(
          gameState => { dispatch(SetGameState(gameState)); }
      )
      .catch(
          error => {
            dispatch(SetUiMessage(error.message, 'ERROR'));
          }
      );
    } else {
      dispatch(SetUiMessage("Wrong selection", 'ERROR'));
    }
  }
}
<|endoftext|>


<commit_before>/* @flow */

import * as babylon from 'babylon';

import type Program from './elements/types/Program';
import type Location from './elements/Element';

import visitorKeys from './visitorKeys';
import elementIndex from './elements/elementIndex';
import Token from './elements/Token';

export type BabylonToken = {
    type: string,
    value: string,
    start: number,
    end: number,
    loc?: Location,
    sourceCode: string
};

/**
 * Creates CST using AST and token list.
 *
 * @param {Object} ast
 * @param {Array} tokens
 * @returns {Program}
 */
export function buildElementTree(ast: Object, tokens: Array<BabylonToken>): Program {
    var firstToken = tokens[0];
    ast.start = firstToken.start;
    ast.end = tokens[tokens.length - 1].end;
    return ((buildElementTreeItem(ast, {
        tokens,
        token: firstToken,
        pos: 0
    }): any): Program);
}

type ElementTreeItemState = {
    tokens: Array<BabylonToken>,
    token: BabylonToken,
    pos: number
};

/**
 * @param {Object} ast
 * @param {{tokens: Array, token: Object, pos: Number}} state
 * @returns {Element}
 */
function buildElementTreeItem(ast: Object, state: ElementTreeItemState): ?Element {
    var elementType = ast.type;
    let childProps = visitorKeys[elementType];

    if (!childProps) {
        let error = new SyntaxError(`Cannot iterate using ${elementType}`);
        error.loc = ast.loc.start;
        throw error;
    }

    let childElements = [];
    for (let i = 0; i < childProps.length; i++) {
        let childAst = ast[childProps[i]];
        if (childAst) {
            if (Array.isArray(childAst)) {
                for (let j = 0; j < childAst.length; j++) {
                    if (childAst[j] !== null) {
                        childElements[childElements.length] = childAst[j];
                    }
                }
            } else {
                childElements[childElements.length] = childAst;
            }
        }
    }

    childElements.sort((ast1, ast2) => {
        return ast1.start < ast2.start ? -1 : (ast1.start > ast2.start ? 1 : 0);
    });

    let NodeClass = elementIndex[elementType];

    if (!NodeClass) {
        throw new Error(`Cannot create ${elementType} instance`);
    }

    let children = [];
    let childElementIndex = 0;
    let childElement = childElements[0];
    let end = ast.end;

    do {
        if (childElement && state.token.start === childElement.start) {
            if (state.token.end > childElement.end) {
                let EmptyNodeClass = elementIndex[childElement.type];
                if (!EmptyNodeClass) {
                    throw new Error(`Cannot create ${childElement.type} instance`);
                }

                children[children.length] = new EmptyNodeClass([]);
                childElement = childElements[++childElementIndex];
            } else {
                let nextChild = childElements[childElementIndex + 1];

                // Skip first `Identifier` for ({ test = 1 } = {})
                // since it is already used in `AssignmentPattern`
                // Need to fix this one day (See https://github.com/babel/babylon/issues/49)
                if (
                    elementType === 'ObjectProperty' &&
                    nextChild && nextChild.type === 'AssignmentPattern'
                ) {
                    while (state.token.start !== nextChild.start) {
                        state.pos--;
                        state.token = state.tokens[state.pos];
                    }

                    childElement = childElements[++childElementIndex];

                    continue;
                }

                children[children.length] = buildElementTreeItem(childElement, state);
                childElement = childElements[++childElementIndex];

                if (!state.token ||
                    (state.token.start === end && (state.token.end !== end || elementType !== 'Program'))
                ) {
                    return new NodeClass(children);
                }
            }
        } else {
            let endOfAstReached = state.token.end === end;
            let addedTokenType = state.token.type;

            if (endOfAstReached && ast.type === 'Identifier' && addedTokenType === 'Keyword') {
                state.token.type = addedTokenType = 'Identifier';
            }

            children[children.length] = Token.createFromToken(state.token);

            state.pos++;
            state.token = state.tokens[state.pos];

            if (elementType === 'Program' && addedTokenType !== 'EOF') {
                continue;
            }

            if (endOfAstReached) {
                return new NodeClass(children);
            }
        }
    } while (state.token);
}

/**
 * Build single token list using code tokens, comments and whitespace.
 *
 * @param {Array} codeTokens
 * @param {String} code
 * @returns {Array}
 */
export function buildTokenList(codeTokens: Array<BabylonToken>, code: string): Array<BabylonToken> {
    let prevPos = 0;
    let result = [];

    for (var i = 0; i < codeTokens.length; i++) {
        let token = processToken(codeTokens[i], code);

        let pos = token.start;
        if (prevPos !== pos) {
            let value = code.substring(prevPos, pos);
            result[result.length] = {
                type: 'Whitespace',
                value,
                sourceCode: value,
                start: prevPos,
                end: pos
            };
        }
        result[result.length] = token;

        prevPos = token.end;
    }

    return result;
}

/**
 * Babylon token types.
 */
let tt = babylon.tokTypes;

/**
 * Transforms Babylon-style token to Esprima-style token.
 *
 * @param {Object} token
 * @param {String} source
 */
function processToken(token: Object, source: string): BabylonToken {
    var type = token.type;

    if (type === tt.name) {
        token.type = 'Identifier';
    } else if (type === tt.semi || type === tt.comma ||
        type === tt.parenL || type === tt.parenR ||
        type === tt.braceL || type === tt.braceR ||
        type === tt.slash || type === tt.dot ||
        type === tt.bracketL || type === tt.bracketR ||
        type === tt.ellipsis || type === tt.arrow ||
        type === tt.star || type === tt.incDec ||
        type === tt.colon || type === tt.question ||
        type === tt.backQuote ||
        type === tt.dollarBraceL || type === tt.at ||
        type === tt.logicalOR || type === tt.logicalAND ||
        type === tt.bitwiseOR || type === tt.bitwiseXOR ||
        type === tt.bitwiseAND || type === tt.equality ||
        type === tt.relational || type === tt.bitShift ||
        type === tt.plusMin || type === tt.modulo ||
        type === tt.exponent || type === tt.prefix ||
        type === tt.doubleColon ||
        type.isAssign) {
        token.type = 'Punctuator';
        if (!token.value) {
            token.sourceCode = token.value = type.label;
        }
    } else if (type === tt.template) {
        token.type = 'Template';
        token.sourceCode = token.value;
    } else if (type === tt.jsxTagStart) {
        token.type = 'Punctuator';
        token.sourceCode = token.value = '<';
    } else if (type === tt.jsxTagEnd) {
        token.type = 'Punctuator';
        token.sourceCode = token.value = '>';
    } else if (type === tt.jsxName) {
        token.type = 'JSXIdentifier';
    } else if (type === tt.jsxText) {
        token.type = 'JSXText';
    } else if (type.keyword === 'null') {
        token.type = 'Null';
        token.value = null;
    } else if (type.keyword === 'false' || type.keyword === 'true') {
        token.type = 'Boolean';
        token.value = type.keyword === 'true';
    } else if (type.keyword) {
        token.type = 'Keyword';
    } else if (type === tt.num) {
        token.type = 'Numeric';
    } else if (type === tt.string) {
        token.type = 'String';
    } else if (type === tt.regexp) {
        token.type = 'RegularExpression';
    } else if (type === 'CommentLine') {
        token.sourceCode = '//' + token.value;
    } else if (type === 'CommentBlock') {
        token.sourceCode = '/*' + token.value + '*/';
    } else if (type === tt.eof) {
        token.type = 'EOF';
        token.sourceCode = token.value = '';
    }

    if (!('sourceCode' in token)) {
        token.sourceCode = source.slice(token.start, token.end);
    }

    return token;
}
<commit_msg>Simplify `ObjectProperty` with `AssignmentPattern` hack one more time<commit_after>/* @flow */

import * as babylon from 'babylon';

import type Program from './elements/types/Program';
import type Location from './elements/Element';

import visitorKeys from './visitorKeys';
import elementIndex from './elements/elementIndex';
import Token from './elements/Token';

export type BabylonToken = {
    type: string,
    value: string,
    start: number,
    end: number,
    loc?: Location,
    sourceCode: string
};

/**
 * Creates CST using AST and token list.
 *
 * @param {Object} ast
 * @param {Array} tokens
 * @returns {Program}
 */
export function buildElementTree(ast: Object, tokens: Array<BabylonToken>): Program {
    var firstToken = tokens[0];
    ast.start = firstToken.start;
    ast.end = tokens[tokens.length - 1].end;
    return ((buildElementTreeItem(ast, {
        tokens,
        token: firstToken,
        pos: 0
    }): any): Program);
}

type ElementTreeItemState = {
    tokens: Array<BabylonToken>,
    token: BabylonToken,
    pos: number
};

/**
 * @param {Object} ast
 * @param {{tokens: Array, token: Object, pos: Number}} state
 * @returns {Element}
 */
function buildElementTreeItem(ast: Object, state: ElementTreeItemState): ?Element {
    var elementType = ast.type;
    let childProps = visitorKeys[elementType];

    if (!childProps) {
        let error = new SyntaxError(`Cannot iterate using ${elementType}`);
        error.loc = ast.loc.start;
        throw error;
    }

    let childElements = [];
    for (let i = 0; i < childProps.length; i++) {
        let childAst = ast[childProps[i]];

        if (!childAst) {
            continue;
        }

        if (Array.isArray(childAst)) {
            for (let j = 0; j < childAst.length; j++) {
                if (childAst[j] === null) {
                    continue;
                }

                // Skip first `Identifier` for ({ test = 1 } = {})
                // since it is already used in `AssignmentPattern`
                // Need to fix this one day (See https://github.com/babel/babylon/issues/49)
                if (
                    childAst[j].type === 'ObjectProperty' &&
                    childAst[j].value.type === 'AssignmentPattern'
                ) {
                    delete childAst[j].key;
                }

                childElements[childElements.length] = childAst[j];
            }
        } else {
            childElements[childElements.length] = childAst;
        }
    }

    childElements.sort((ast1, ast2) => {
        return ast1.start < ast2.start ? -1 : (ast1.start > ast2.start ? 1 : 0);
    });

    let NodeClass = elementIndex[elementType];

    if (!NodeClass) {
        throw new Error(`Cannot create ${elementType} instance`);
    }

    let children = [];
    let childElementIndex = 0;
    let childElement = childElements[0];
    let end = ast.end;

    do {
        if (childElement && state.token.start === childElement.start) {
            if (state.token.end > childElement.end) {
                let EmptyNodeClass = elementIndex[childElement.type];
                if (!EmptyNodeClass) {
                    throw new Error(`Cannot create ${childElement.type} instance`);
                }

                children[children.length] = new EmptyNodeClass([]);
                childElement = childElements[++childElementIndex];
            } else {
                let nextChild = childElements[childElementIndex + 1];

                children[children.length] = buildElementTreeItem(childElement, state);
                childElement = childElements[++childElementIndex];

                if (!state.token ||
                    (state.token.start === end && (state.token.end !== end || elementType !== 'Program'))
                ) {
                    return new NodeClass(children);
                }
            }
        } else {
            let endOfAstReached = state.token.end === end;
            let addedTokenType = state.token.type;

            if (endOfAstReached && ast.type === 'Identifier' && addedTokenType === 'Keyword') {
                state.token.type = addedTokenType = 'Identifier';
            }

            children[children.length] = Token.createFromToken(state.token);

            state.pos++;
            state.token = state.tokens[state.pos];

            if (elementType === 'Program' && addedTokenType !== 'EOF') {
                continue;
            }

            if (endOfAstReached) {
                return new NodeClass(children);
            }
        }
    } while (state.token);
}

/**
 * Build single token list using code tokens, comments and whitespace.
 *
 * @param {Array} codeTokens
 * @param {String} code
 * @returns {Array}
 */
export function buildTokenList(codeTokens: Array<BabylonToken>, code: string): Array<BabylonToken> {
    let prevPos = 0;
    let result = [];

    for (var i = 0; i < codeTokens.length; i++) {
        let token = processToken(codeTokens[i], code);

        let pos = token.start;
        if (prevPos !== pos) {
            let value = code.substring(prevPos, pos);
            result[result.length] = {
                type: 'Whitespace',
                value,
                sourceCode: value,
                start: prevPos,
                end: pos
            };
        }
        result[result.length] = token;

        prevPos = token.end;
    }

    return result;
}

/**
 * Babylon token types.
 */
let tt = babylon.tokTypes;

/**
 * Transforms Babylon-style token to Esprima-style token.
 *
 * @param {Object} token
 * @param {String} source
 */
function processToken(token: Object, source: string): BabylonToken {
    var type = token.type;

    if (type === tt.name) {
        token.type = 'Identifier';
    } else if (type === tt.semi || type === tt.comma ||
        type === tt.parenL || type === tt.parenR ||
        type === tt.braceL || type === tt.braceR ||
        type === tt.slash || type === tt.dot ||
        type === tt.bracketL || type === tt.bracketR ||
        type === tt.ellipsis || type === tt.arrow ||
        type === tt.star || type === tt.incDec ||
        type === tt.colon || type === tt.question ||
        type === tt.backQuote ||
        type === tt.dollarBraceL || type === tt.at ||
        type === tt.logicalOR || type === tt.logicalAND ||
        type === tt.bitwiseOR || type === tt.bitwiseXOR ||
        type === tt.bitwiseAND || type === tt.equality ||
        type === tt.relational || type === tt.bitShift ||
        type === tt.plusMin || type === tt.modulo ||
        type === tt.exponent || type === tt.prefix ||
        type === tt.doubleColon ||
        type.isAssign) {
        token.type = 'Punctuator';
        if (!token.value) {
            token.sourceCode = token.value = type.label;
        }
    } else if (type === tt.template) {
        token.type = 'Template';
        token.sourceCode = token.value;
    } else if (type === tt.jsxTagStart) {
        token.type = 'Punctuator';
        token.sourceCode = token.value = '<';
    } else if (type === tt.jsxTagEnd) {
        token.type = 'Punctuator';
        token.sourceCode = token.value = '>';
    } else if (type === tt.jsxName) {
        token.type = 'JSXIdentifier';
    } else if (type === tt.jsxText) {
        token.type = 'JSXText';
    } else if (type.keyword === 'null') {
        token.type = 'Null';
        token.value = null;
    } else if (type.keyword === 'false' || type.keyword === 'true') {
        token.type = 'Boolean';
        token.value = type.keyword === 'true';
    } else if (type.keyword) {
        token.type = 'Keyword';
    } else if (type === tt.num) {
        token.type = 'Numeric';
    } else if (type === tt.string) {
        token.type = 'String';
    } else if (type === tt.regexp) {
        token.type = 'RegularExpression';
    } else if (type === 'CommentLine') {
        token.sourceCode = '//' + token.value;
    } else if (type === 'CommentBlock') {
        token.sourceCode = '/*' + token.value + '*/';
    } else if (type === tt.eof) {
        token.type = 'EOF';
        token.sourceCode = token.value = '';
    }

    if (!('sourceCode' in token)) {
        token.sourceCode = source.slice(token.start, token.end);
    }

    return token;
}
<|endoftext|>


<commit_before>define(["Tone/core/Tone", "Tone/signal/Signal", "Tone/source/Source"],
function(Tone){

	"use strict";

	/**
	 *  @class Oscilator with start, pause, stop and sync to Transport methods
	 *
	 *  @constructor
	 *  @extends {Tone.Source}
	 *  @param {number|string} [frequency=440] starting frequency
	 *  @param {string} [type="sine"] type of oscillator (sine|square|triangle|sawtooth)
	 */
	Tone.Oscillator = function(){

		Tone.Source.call(this);
		var options = this.optionsObject(arguments, ["frequency", "type"], Tone.Oscillator.defaults);

		/**
		 *  the main oscillator
		 *  @type {OscillatorNode}
		 *  @private
		 */
		this._oscillator = null;

		/**
		 *  the frequency control signal
		 *  @type {Tone.Signal}
		 */
		this.frequency = new Tone.Signal(this.toFrequency(options.frequency));

		/**
		 *  the detune control signal
		 *  @type {Tone.Signal}
		 */
		this.detune = new Tone.Signal(options.detune);

		/**
		 *  callback which is invoked when the oscillator is stoped
		 *  @type {function()}
		 */
		this.onended = options.onended;

		/**
		 *  the periodic wave
		 *  @type {PeriodicWave}
		 *  @private
		 */
		this._wave = null;

		/**
		 *  the phase of the oscillator
		 *  between 0 - 360
		 *  @type {number}
		 *  @private
		 */
		this._phase = options.phase;

		/**
		 *  the type of the oscillator
		 *  @type {string}
		 *  @private
		 */
		this._type = options.type;

		//setup
		this.setPhase(this._phase);
	};

	Tone.extend(Tone.Oscillator, Tone.Source);

	/**
	 *  the default parameters
	 *
	 *  @static
	 *  @const
	 *  @type {Object}
	 */
	Tone.Oscillator.defaults = {
		"type" : "sine",
		"frequency" : 440,
		"onended" : function(){},
		"detune" : 0,
		"phase" : 0
	};

	/**
	 *  start the oscillator
	 *
	 *  @param  {Tone.Time} [time=now]
	 */
	Tone.Oscillator.prototype.start = function(time){
		if (this.state === Tone.Source.State.STOPPED){
			this.state = Tone.Source.State.STARTED;
			//get previous values
			//new oscillator with previous values
			this._oscillator = this.context.createOscillator();
			this._oscillator.setPeriodicWave(this._wave);
			//connect the control signal to the oscillator frequency & detune
			this._oscillator.connect(this.output);
			this.frequency.connect(this._oscillator.frequency);
			this.detune.connect(this._oscillator.detune);
			//start the oscillator
			this._oscillator.onended = this.onended;
			this._oscillator.start(this.toSeconds(time));
		}
	};

	/**
	 *  stop the oscillator
	 *  @param  {Tone.Time} [time=now] (optional) timing parameter
	 */
	Tone.Oscillator.prototype.stop = function(time){
		if (this.state === Tone.Source.State.STARTED){
			this.state = Tone.Source.State.STOPPED;
			this._oscillator.stop(this.toSeconds(time));
		}
	};

	/**
	 *  exponentially ramp the frequency of the oscillator over the rampTime
	 *
	 *  @param {Tone.Time}	val
	 *  @param {Tone.Time=} rampTime when the oscillator will arrive at the frequency
	 */
	Tone.Oscillator.prototype.setFrequency = function(val, rampTime){
		if (rampTime){
			this.frequency.exponentialRampToValueAtTime(this.toFrequency(val), this.toSeconds(rampTime));
		} else {
			this.frequency.setValue(this.toFrequency(val));
		}
	};

	/**
	 *  set the oscillator type
	 *
	 *  uses PeriodicWave even for native types so that it can set the phase
	 *
	 *  the the PeriodicWave equations are from the Web Audio Source code
	 *  here: https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp&sq=package:chromium
	 *
	 *  @param {string} type (sine|square|triangle|sawtooth)
	 */
	Tone.Oscillator.prototype.setType = function(type){
		var fftSize = 4096;
		var halfSize = fftSize / 2;

		var real = new Float32Array(halfSize);
		var imag = new Float32Array(halfSize);

		// Clear DC and Nyquist.
		real[0] = 0;
		imag[0] = 0;

		var shift = this._phase;
		for (var n = 1; n < halfSize; ++n) {
			var piFactor = 2 / (n * Math.PI);
			var b;
			switch (type) {
				case "sine":
					b = (n === 1) ? 1 : 0;
					break;
				case "square":
					b = (n & 1) ? 2 * piFactor : 0;
					break;
				case "sawtooth":
					b = piFactor * ((n & 1) ? 1 : -1);
					break;
				case "triangle":
					if (n & 1) {
						b = 2 * (piFactor * piFactor) * ((((n - 1) >> 1) & 1) ? -1 : 1);
					} else {
						b = 0;
					}
					break;
				default:
					throw new TypeError("invalid oscillator type: "+type);
			}
			if (b !== 0){
				real[n] = -b * Math.sin(shift);
				imag[n] = b * Math.cos(shift);
			} else {
				real[n] = 0;
				imag[n] = 0;
			}
		}
		var periodicWave = this.context.createPeriodicWave(real, imag);
		this._wave = periodicWave;
		if (this._oscillator !== null){
			this._oscillator.setPeriodicWave(this._wave);
		}
		this._type = type;
	};

	/**
	 *  @return {string} the type of oscillator
	 */
	Tone.Oscillator.prototype.getType = function() {
		return this._type;
	};

	/**
	 *  set the phase of the oscillator (in degrees)
	 *  @param {number} degrees the phase in degrees
	 */
	Tone.Oscillator.prototype.setPhase = function(phase) {
		this._phase = phase * Math.PI / 180;
		this.setType(this._type);
	};

	/**
	 *  set the parameters at once
	 *  @param {Object} params
	 */
	Tone.Oscillator.prototype.set = function(params){
		if (!this.isUndef(params.type)) this.setType(params.type);
		if (!this.isUndef(params.phase)) this.setPhase(params.phase);
		if (!this.isUndef(params.frequency)) this.frequency.setValue(params.frequency);
		if (!this.isUndef(params.onended)) this.onended = params.onended;
		if (!this.isUndef(params.detune)) this.detune.setValue(params.detune);
		Tone.Source.prototype.set.call(this, params);
	};

	/**
	 *  dispose and disconnect
	 */
	Tone.Oscillator.prototype.dispose = function(){
		Tone.Source.prototype.dispose.call(this);
		this.stop();
		if (this._oscillator !== null){
			this._oscillator.disconnect();
			this._oscillator = null;
		}
		this.frequency.dispose();
		this.detune.dispose();
		this._wave = null;
		this.detune = null;
		this.frequency = null;
	};

	return Tone.Oscillator;
});<commit_msg>Oscillator getter functions<commit_after>define(["Tone/core/Tone", "Tone/signal/Signal", "Tone/source/Source"],
function(Tone){

	"use strict";

	/**
	 *  @class Oscilator with start, pause, stop and sync to Transport methods
	 *
	 *  @constructor
	 *  @extends {Tone.Source}
	 *  @param {number|string} [frequency=440] starting frequency
	 *  @param {string} [type="sine"] type of oscillator (sine|square|triangle|sawtooth)
	 */
	Tone.Oscillator = function(){

		Tone.Source.call(this);
		var options = this.optionsObject(arguments, ["frequency", "type"], Tone.Oscillator.defaults);

		/**
		 *  the main oscillator
		 *  @type {OscillatorNode}
		 *  @private
		 */
		this._oscillator = null;

		/**
		 *  the frequency control signal
		 *  @type {Tone.Signal}
		 */
		this.frequency = new Tone.Signal(this.toFrequency(options.frequency));

		/**
		 *  the detune control signal
		 *  @type {Tone.Signal}
		 */
		this.detune = new Tone.Signal(options.detune);

		/**
		 *  callback which is invoked when the oscillator is stoped
		 *  @type {function()}
		 */
		this.onended = options.onended;

		/**
		 *  the periodic wave
		 *  @type {PeriodicWave}
		 *  @private
		 */
		this._wave = null;

		/**
		 *  the phase of the oscillator
		 *  between 0 - 360
		 *  @type {number}
		 *  @private
		 */
		this._phase = options.phase;

		/**
		 *  the type of the oscillator
		 *  @type {string}
		 *  @private
		 */
		this._type = options.type;

		//setup
		this.setPhase(this._phase);
	};

	Tone.extend(Tone.Oscillator, Tone.Source);

	/**
	 *  the default parameters
	 *
	 *  @static
	 *  @const
	 *  @type {Object}
	 */
	Tone.Oscillator.defaults = {
		"type" : "sine",
		"frequency" : 440,
		"onended" : function(){},
		"detune" : 0,
		"phase" : 0
	};

	/**
	 *  start the oscillator
	 *
	 *  @param  {Tone.Time} [time=now]
	 */
	Tone.Oscillator.prototype.start = function(time){
		if (this.state === Tone.Source.State.STOPPED){
			this.state = Tone.Source.State.STARTED;
			//get previous values
			//new oscillator with previous values
			this._oscillator = this.context.createOscillator();
			this._oscillator.setPeriodicWave(this._wave);
			//connect the control signal to the oscillator frequency & detune
			this._oscillator.connect(this.output);
			this.frequency.connect(this._oscillator.frequency);
			this.detune.connect(this._oscillator.detune);
			//start the oscillator
			this._oscillator.onended = this.onended;
			this._oscillator.start(this.toSeconds(time));
		}
	};

	/**
	 *  stop the oscillator
	 *  @param  {Tone.Time} [time=now] (optional) timing parameter
	 */
	Tone.Oscillator.prototype.stop = function(time){
		if (this.state === Tone.Source.State.STARTED){
			this.state = Tone.Source.State.STOPPED;
			this._oscillator.stop(this.toSeconds(time));
		}
	};

	/**
	 *  exponentially ramp the frequency of the oscillator over the rampTime
	 *
	 *  @param {Tone.Time}	val
	 *  @param {Tone.Time=} rampTime when the oscillator will arrive at the frequency
	 */
	Tone.Oscillator.prototype.setFrequency = function(val, rampTime){
		if (rampTime){
			this.frequency.exponentialRampToValueAtTime(this.toFrequency(val), this.toSeconds(rampTime));
		} else {
			this.frequency.setValue(this.toFrequency(val));
		}
	};

	/**
	 * @return {number} the current frequency
	 */
	Tone.Oscillator.prototype.getFrequency = function(){
		return this.frequency.getValue();
	};

	/**
	 *  set the oscillator type
	 *
	 *  uses PeriodicWave even for native types so that it can set the phase
	 *
	 *  the the PeriodicWave equations are from the Web Audio Source code
	 *  here: https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp&sq=package:chromium
	 *
	 *  @param {string} type (sine|square|triangle|sawtooth)
	 */
	Tone.Oscillator.prototype.setType = function(type){
		var fftSize = 4096;
		var halfSize = fftSize / 2;

		var real = new Float32Array(halfSize);
		var imag = new Float32Array(halfSize);

		// Clear DC and Nyquist.
		real[0] = 0;
		imag[0] = 0;

		var shift = this._phase;
		for (var n = 1; n < halfSize; ++n) {
			var piFactor = 2 / (n * Math.PI);
			var b;
			switch (type) {
				case "sine":
					b = (n === 1) ? 1 : 0;
					break;
				case "square":
					b = (n & 1) ? 2 * piFactor : 0;
					break;
				case "sawtooth":
					b = piFactor * ((n & 1) ? 1 : -1);
					break;
				case "triangle":
					if (n & 1) {
						b = 2 * (piFactor * piFactor) * ((((n - 1) >> 1) & 1) ? -1 : 1);
					} else {
						b = 0;
					}
					break;
				default:
					throw new TypeError("invalid oscillator type: "+type);
			}
			if (b !== 0){
				real[n] = -b * Math.sin(shift);
				imag[n] = b * Math.cos(shift);
			} else {
				real[n] = 0;
				imag[n] = 0;
			}
		}
		var periodicWave = this.context.createPeriodicWave(real, imag);
		this._wave = periodicWave;
		if (this._oscillator !== null){
			this._oscillator.setPeriodicWave(this._wave);
		}
		this._type = type;
	};

	/**
	 *  @return {string} the type of oscillator
	 */
	Tone.Oscillator.prototype.getType = function() {
		return this._type;
	};

	/**
	 *  set the phase of the oscillator (in degrees)
	 *  @param {number} degrees the phase in degrees
	 */
	Tone.Oscillator.prototype.setPhase = function(phase) {
		this._phase = phase * Math.PI / 180;
		this.setType(this._type);
	};

	/**
	 * @return {number} the current phase
	 */
	Tone.Oscillator.prototype.getPhase = function(){
		return this._phase / Math.PI * 180;
	};

	/**
	 *  set the parameters at once
	 *  @param {Object} params
	 */
	Tone.Oscillator.prototype.set = function(params){
		if (!this.isUndef(params.type)) this.setType(params.type);
		if (!this.isUndef(params.phase)) this.setPhase(params.phase);
		if (!this.isUndef(params.frequency)) this.frequency.setValue(params.frequency);
		if (!this.isUndef(params.onended)) this.onended = params.onended;
		if (!this.isUndef(params.detune)) this.detune.setValue(params.detune);
		Tone.Source.prototype.set.call(this, params);
	};

	/**
	 *  dispose and disconnect
	 */
	Tone.Oscillator.prototype.dispose = function(){
		Tone.Source.prototype.dispose.call(this);
		this.stop();
		if (this._oscillator !== null){
			this._oscillator.disconnect();
			this._oscillator = null;
		}
		this.frequency.dispose();
		this.detune.dispose();
		this._wave = null;
		this.detune = null;
		this.frequency = null;
	};

	return Tone.Oscillator;
});<|endoftext|>


<commit_before>const { AppSetting } = require('../../core/app_setting');
const log = require('../../core/log');
const path = require('path');
const request = require('request');

// Constants required for all repository plugins.
const name = "APTrust";
const description = "APTrust Repository";
const version = "0.1";

// These constants are specific to APTrust.
const apiVersion = 'v2';

class APTrust {

    // job is the job you want to query the remote repository
    // about. The Job object contains the bag name and other
    // info, including the etag or checksum returned by the
    // remote storage service after upload.
    //
    // emitter comes from plugins.newRepoEmitter()
    constructor(job, emitter) {
        this.job = job;
        this.emitter = emitter;

        this.uploadResult = job.operationResults.find(r => r.provider === "APTrust S3 uploader") || null;
    }

    describe() {
        return {
            name: name,
            description: description,
            version: version,
            url: this.url
        }
    }

    // getObjectInfo gets object info from the remote repository.
    // The dashboard calls this method to display info about the job.
    getObjectInfo() {
        this.emitter.emit('start');
        if (this.uploadResult == null) {
            this.emitter.emit('complete', this.job.id, this._notYetUploaded());
        }
        if (!this._canConnect) {
            this.emitter.emit('complete', this.job.id, '');
        }
        this._getIntellectualObject();
    }

    // -----------------------------------------------------------------
    // All methods below are private.
    // -----------------------------------------------------------------

    // Jobs run by early beta users do not have properties remoteChecksum
    // or remoteUrl on the OperationResult object, so we can't deduce
    // which repository they uploaded to. If we can't figure that out,
    // don't try to run a query.
    _canConnect(conn) {
        if (conn.url && conn.user && conn.apiKey) {
            return true;
        }
        return false;
    }

    _connectionInfo() {
        let conn = {
            url: null,
            user: null,
            apiKey: null
        };
        let instDomain = this._getSetting("Institution Domain")
        if (instDomain) {
            let demoBucketName = `aptrust.receiving.test.${instDomain}`
            if (this.uploadResult.remoteUrl == demoBucketName) {
                conn.url = this._getSetting("Pharos Demo URL");
                conn.user = this._getSetting("Pharos Demo API Login");
                conn.apiKey = this._getSetting("Pharos Demo API Key");
            } else {
                conn.url = this._getSetting("Pharos Production URL");
                conn.user = this._getSetting("Pharos Production API Login");
                conn.apiKey = this._getSetting("Pharos Production API Key");
            }
        }
        return conn;
    }

    _getHeaders(conn) {
        return {
            'User-Agent': 'DART / Node.js request',
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-Pharos-API-User': conn.user,
            'X-Pharos-API-Key': conn.apiKey
        }
    }

    _getSetting(settingName) {
        let setting = AppSetting.find(settingName);
        if (setting) {
            return setting.value;
        }
        return null;
    }

    _notYetUploaded() {
        let html =  '
This bag has not been uploaded to APTrust.
';
        this.emitter.emit('complete', this.job.id, html);
    }

    _getIntellectualObject() {
        let repo = this;
        let identifier = path.basename(this.job.packagedFile);
        let conn = this._connectionInfo();

        // if (this._canConnect(conn) === false) {
        //     console.log(`Cannot check Pharos for ${identifier}: not enough info`);
        //     return;
        // }
        if (identifier.includes('April')) {
            console.log(this.uploadResult)
        }

        let baseUrl = `${conn.url}/api/${apiVersion}`
        let encodedIdentifier = encodeURIComponent(identifier);
        let objectUrl = `${baseUrl}/objects/${encodedIdentifier}`;
        let etag = this.uploadResult.remoteChecksum;
        let workItemUrl = null;
        if (etag) {
            workItemUrl = `${baseUrl}/items/?name=${encodedIdentifier}&etag=${etag}&sort=date`;
        }
        let options = {
            url: objectUrl,
            headers: this._getHeaders(conn)
        };

        var workItemCallback = function (error, response, body) {
            if (response.statusCode == 404) {
                // No work item
            } else if (!error && response.statusCode == 200) {
                var data = JSON.parse(body);
                repo._formatWorkItemRecord(data);
            } else {
                repo._formatError(error, response, body);
            }
        }

        var getWorkItem = function() {
            if (workItemUrl === null) {
                repo._displayCantGetInfo(identifier);
            } else {
                options.url = workItemUrl;
                log.debug(`Requesting WorkItem: ${options.url}`);
                request(options, workItemCallback);
            }
        }

        var intelObjectCallback = function(error, response, body) {
            if (!error && response.statusCode == 404) {
                // Not ingested yet. Check for pending WorkItem.
                getWorkItem();
            } else if (!error && response.statusCode == 200) {
                var data = JSON.parse(body);
                repo._formatObjectRecord(data);
            } else {
                repo._formatError(error, response, body);
            }
        }

        // Try to get the intellectual object from Pharos.
        log.debug(`Requesting IntellectualObject: ${options.url}`);
        request(options, intelObjectCallback);
    }

    // _getWorkItem() {
    //     let conn = this._connectionInfo();
    //     let identifier = path.basename(this.job.packagedFile);
    //     let encodedIdentifier = encodeURIComponent(identifier);
    //     let etag = this.uploadResult.remoteChecksum;
    //     let url = `${this.apiUrl}/items/?name=${encodedIdentifier}&etag=${etag}&sort=date&page=1&per_page=1`;
    //     log.debug(`Requesting WorkItem: ${url}`);
    //     var options = {
    //         url: conn.url,
    //         headers: this._getHeaders(conn)
    //     };
    //     request(options, this._workItemCallback);
    // }

    // _intelObjectCallback(error, response, body) {
    //     if (!error && response.statusCode == 404) {
    //         // Not ingested yet. Check for pending WorkItem.
    //         this._getWorkItem();
    //     } else if (!error && response.statusCode == 200) {
    //         var data = JSON.parse(body);
    //         this._formatObjectRecord(data);
    //     } else {
    //         this._formatError(error, response, body);
    //     }
    // }

    // _workItemCallback(error, response, body) {
    //     if (response.statusCode == 404) {
    //         // No work item
    //     } else if (!error && response.statusCode == 200) {
    //         var data = JSON.parse(body);
    //         this._formatWorkItemRecord(data);
    //     } else {
    //         this._formatError(error, response, body);
    //     }
    // }

    _displayCantGetInfo(identifier) {
        console.log(`Can't get WorkItem info for ${identifier}`);  //'
    }

    _formatWorkItem(data) {
        console.log(data);
    }

    _formatObjectRecord(data) {
        console.log(data);
    }

    _formatError(error, response, body) {
        let message = `Error in request to APTrust: ${error}`;
        console.log(message);
        log.error(message);
        log.error(body);
        let html = `<div class="text-warning">${message}</div>`
        this.emitter.emit('complete', this.job.id, html);
    }
}

module.exports.Provider = APTrust;
module.exports.name = name;
module.exports.description = description;
module.exports.version = version;
<commit_msg>Working on Pharos integration<commit_after>const { AppSetting } = require('../../core/app_setting');
const log = require('../../core/log');
const path = require('path');
const request = require('request');

// Constants required for all repository plugins.
const name = "APTrust";
const description = "APTrust Repository";
const version = "0.1";

// These constants are specific to APTrust.
const apiVersion = 'v2';

class APTrust {

    // job is the job you want to query the remote repository
    // about. The Job object contains the bag name and other
    // info, including the etag or checksum returned by the
    // remote storage service after upload.
    //
    // emitter comes from plugins.newRepoEmitter()
    constructor(job, emitter) {
        this.job = job;
        this.emitter = emitter;

        this.uploadResult = job.operationResults.find(r => r.provider === "APTrust S3 uploader") || null;
    }

    describe() {
        return {
            name: name,
            description: description,
            version: version,
            url: this.url
        }
    }

    // getObjectInfo gets object info from the remote repository.
    // The dashboard calls this method to display info about the job.
    getObjectInfo() {
        this.emitter.emit('start');
        if (this.uploadResult == null) {
            this.emitter.emit('complete', this.job.id, this._notYetUploaded());
        }
        if (!this._canConnect) {
            this.emitter.emit('complete', this.job.id, '');
        }
        this._getIntellectualObject();
    }

    // -----------------------------------------------------------------
    // All methods below are private.
    // -----------------------------------------------------------------

    // Jobs run by early beta users do not have properties remoteChecksum
    // or remoteUrl on the OperationResult object, so we can't deduce
    // which repository they uploaded to. If we can't figure that out,
    // don't try to run a query.
    _canConnect(conn) {
        if (conn.url && conn.user && conn.apiKey) {
            return true;
        }
        return false;
    }

    _connectionInfo() {
        let conn = {
            url: null,
            user: null,
            apiKey: null
        };
        let instDomain = this._getSetting("Institution Domain")
        if (instDomain) {
            let demoBucketName = `aptrust.receiving.test.${instDomain}`
            if (this.uploadResult.remoteUrl && this.uploadResult.remoteUrl.includes(demoBucketName)) {
                conn.url = this._getSetting("Pharos Demo URL");
                conn.user = this._getSetting("Pharos Demo API Login");
                conn.apiKey = this._getSetting("Pharos Demo API Key");
            } else {
                conn.url = this._getSetting("Pharos Production URL");
                conn.user = this._getSetting("Pharos Production API Login");
                conn.apiKey = this._getSetting("Pharos Production API Key");
            }
        }
        return conn;
    }

    _getHeaders(conn) {
        return {
            'User-Agent': 'DART / Node.js request',
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-Pharos-API-User': conn.user,
            'X-Pharos-API-Key': conn.apiKey
        }
    }

    _getSetting(settingName) {
        let setting = AppSetting.findByName(settingName);
        if (setting) {
            return setting.value;
        }
        return null;
    }

    _notYetUploaded() {
        let html =  '
This bag has not been uploaded to APTrust.
';
        this.emitter.emit('complete', this.job.id, html);
    }

    _getIntellectualObject() {
        let repo = this;
        let identifier = path.basename(this.job.packagedFile);
        let conn = this._connectionInfo();

        // if (this._canConnect(conn) === false) {
        //     console.log(`Cannot check Pharos for ${identifier}: not enough info`);
        //     return;
        // }

        // if (identifier.includes('April')) {
        //     console.log(this.uploadResult)
        // }

        let baseUrl = `${conn.url}/api/${apiVersion}`
        let encodedIdentifier = encodeURIComponent(identifier);
        let objectUrl = `${baseUrl}/objects/${encodedIdentifier}`;
        let etag = this.uploadResult.remoteChecksum;
        let workItemUrl = null;
        if (etag) {
            workItemUrl = `${baseUrl}/items/?name=${encodedIdentifier}&etag=${etag}&sort=date`;
        }
        let options = {
            url: objectUrl,
            headers: this._getHeaders(conn)
        };

        var workItemCallback = function (error, response, body) {
            if (response.statusCode == 404) {
                // No work item
            } else if (!error && response.statusCode == 200) {
                var data = JSON.parse(body);
                repo._formatWorkItemRecord(data);
            } else {
                repo._formatError(error, response, body);
            }
        }

        var getWorkItem = function() {
            if (workItemUrl === null) {
                repo._displayCantGetInfo(identifier);
            } else {
                options.url = workItemUrl;
                log.debug(`Requesting WorkItem: ${options.url}`);
                request(options, workItemCallback);
            }
        }

        var intelObjectCallback = function(error, response, body) {
            if (!error && response.statusCode == 404) {
                // Not ingested yet. Check for pending WorkItem.
                getWorkItem();
            } else if (!error && response.statusCode == 200) {
                var data = JSON.parse(body);
                repo._formatObjectRecord(data);
            } else {
                repo._formatError(error, response, body);
            }
        }

        // Try to get the intellectual object from Pharos.
        log.debug(`Requesting IntellectualObject: ${options.url}`);
        request(options, intelObjectCallback);
    }

    // _getWorkItem() {
    //     let conn = this._connectionInfo();
    //     let identifier = path.basename(this.job.packagedFile);
    //     let encodedIdentifier = encodeURIComponent(identifier);
    //     let etag = this.uploadResult.remoteChecksum;
    //     let url = `${this.apiUrl}/items/?name=${encodedIdentifier}&etag=${etag}&sort=date&page=1&per_page=1`;
    //     log.debug(`Requesting WorkItem: ${url}`);
    //     var options = {
    //         url: conn.url,
    //         headers: this._getHeaders(conn)
    //     };
    //     request(options, this._workItemCallback);
    // }

    // _intelObjectCallback(error, response, body) {
    //     if (!error && response.statusCode == 404) {
    //         // Not ingested yet. Check for pending WorkItem.
    //         this._getWorkItem();
    //     } else if (!error && response.statusCode == 200) {
    //         var data = JSON.parse(body);
    //         this._formatObjectRecord(data);
    //     } else {
    //         this._formatError(error, response, body);
    //     }
    // }

    // _workItemCallback(error, response, body) {
    //     if (response.statusCode == 404) {
    //         // No work item
    //     } else if (!error && response.statusCode == 200) {
    //         var data = JSON.parse(body);
    //         this._formatWorkItemRecord(data);
    //     } else {
    //         this._formatError(error, response, body);
    //     }
    // }

    _displayCantGetInfo(identifier) {
        console.log(`Can't get WorkItem info for ${identifier}`);  //'
    }

    _formatWorkItem(data) {
        console.log(data);
    }

    _formatObjectRecord(data) {
        console.log(data);
    }

    _formatError(error, response, body) {
        let errMsg = error;
        if (errMsg == null) {
            try {
                let data = JSON.parse(body);
                errMsg = data.error;
            } catch(err) {
                log.error(`Cannot parse Pharos error message`);
            }
        }
        let message = `Error in request to APTrust: ${errMsg}`;
        console.log(message);
        log.error(message);
        log.error(body);
        let html = `<div class="text-warning">${message}</div>`
        this.emitter.emit('complete', this.job.id, html);
    }
}

module.exports.Provider = APTrust;
module.exports.name = name;
module.exports.description = description;
module.exports.version = version;
<|endoftext|>


<commit_before>/**
* kinship plotting using d3
* Isaak Y Tecle <iyt2@cornell.edu>
*
*/

var solGS = solGS || function solGS() {};

solGS.kinship = {

    getPopulationDetails: function () {

	var page = document.URL;
	var popId;

	if (page.match(/solgs\/trait\//)) {
	    popId = jQuery("#training_pop_id").val();
	} else {
	    popId = jQuery("#selection_pop_id").val();
	}

	var protocolId = jQuery("#genotyping_protocol_id").val();
	var traitId = jQuery("#trait_id").val();

	return {
	    'kinship_pop_id' : popId,
	    'genotyping_protocol_id': protocolId,
	    'trait_id': traitId,
	};
    },

    getKinshipData: function() {

	var popData = this.getPopulationDetails();

	jQuery("#kinship_message").html("Running kinship... please wait...");

	jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            data: popData,
            url: '/solgs/kinship/data/',
            success: function (res) {

                if (res.data_exists) {

                    solGS.kinship.plotKinship(res.data);
		    solGS.kinship.addDowloandLinks(res);

		    jQuery("#kinship_message").empty();
                } else {

                    jQuery("#kinship_message")
                        .css({"padding-left": '0px'})
                        .html("This population has no kinship data.");

		    jQuery("#run_kinship").show();
                }
            },
            error: function (res) {
                jQuery("#kinship_message")
                    .css({"padding-left": '0px'})
                    .html("Error occured preparing the kinship data.");

		jQuery("#run_kinship").show();
            }
	});
    },

    plotKinship: function (data) {

	var pop = this.getPopulationDetails();
	var popId = pop.kinship_pop_id;
	var protocolId = pop.genotyping_protocol_id;

        solGS.heatmap.plot(data, '#kinship_canvas');

    },

    addDowloandLinks: function(res) {

	var kinshipFile = res.kinship_table_file;
	console.log('kinshipFile ' + kinshipFile)
	var aveFile = res.kinship_averages_file;
	var inbreedingFile = res.inbreeding_file;

	var fileNameKinship = kinshipFile.split('/').pop();
	var fileNameAve = aveFile.split('/').pop();
	var fileNameInbreeding = inbreedingFile.split('/').pop();

	kinshipFile = "Kinship matrix";
	aveFile = "Average kinship";
	inbreedingFile = "Inbreeding Coefficients";

	jQuery("#kinship_canvas")
	    .append('
 Download: '
		     + kinshipFile + ' | '
		     + aveFile + ' | '
		     + inbreedingFile)
	    .show();

    },

///////
}

jQuery(document).ready( function () {

    jQuery("#run_kinship").click(function () {
        solGS.kinship.getKinshipData();
    	jQuery("#run_kinship").hide();
    });

});

<commit_msg>kinship for combined pops<commit_after>/**
* kinship plotting using d3
* Isaak Y Tecle <iyt2@cornell.edu>
*
*/

var solGS = solGS || function solGS() {};

solGS.kinship = {

    getPopulationDetails: function () {

	var page = document.URL;
	var popId;

	if (page.match(/solgs\/trait\/|solgs\/model\/combined\/populations\//)) {
	    popId = jQuery("#training_pop_id").val();
	} else {
	    popId = jQuery("#selection_pop_id").val();
	}

	var protocolId = jQuery("#genotyping_protocol_id").val();
	var traitId = jQuery("#trait_id").val();

	return {
	    'kinship_pop_id' : popId,
	    'genotyping_protocol_id': protocolId,
	    'trait_id': traitId,
	};
    },

    getKinshipData: function() {

	var popData = this.getPopulationDetails();

	jQuery("#kinship_message").html("Running kinship... please wait...");

	jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            data: popData,
            url: '/solgs/kinship/data/',
            success: function (res) {

                if (res.data_exists) {

                    solGS.kinship.plotKinship(res.data);
		    solGS.kinship.addDowloandLinks(res);

		    jQuery("#kinship_message").empty();
                } else {

                    jQuery("#kinship_message")
                        .css({"padding-left": '0px'})
                        .html("This population has no kinship data.");

		    jQuery("#run_kinship").show();
                }
            },
            error: function (res) {
                jQuery("#kinship_message")
                    .css({"padding-left": '0px'})
                    .html("Error occured preparing the kinship data.");

		jQuery("#run_kinship").show();
            }
	});
    },

    plotKinship: function (data) {

	var pop = this.getPopulationDetails();
	var popId = pop.kinship_pop_id;
	var protocolId = pop.genotyping_protocol_id;

        solGS.heatmap.plot(data, '#kinship_canvas');

    },

    addDowloandLinks: function(res) {

	var kinshipFile = res.kinship_table_file;
	console.log('kinshipFile ' + kinshipFile)
	var aveFile = res.kinship_averages_file;
	var inbreedingFile = res.inbreeding_file;

	var fileNameKinship = kinshipFile.split('/').pop();
	var fileNameAve = aveFile.split('/').pop();
	var fileNameInbreeding = inbreedingFile.split('/').pop();

	kinshipFile = "Kinship matrix";
	aveFile = "Average kinship";
	inbreedingFile = "Inbreeding Coefficients";

	jQuery("#kinship_canvas")
	    .append('
 Download: '
		     + kinshipFile + ' | '
		     + aveFile + ' | '
		     + inbreedingFile)
	    .show();

    },

///////
}

jQuery(document).ready( function () {

    jQuery("#run_kinship").click(function () {
        solGS.kinship.getKinshipData();
    	jQuery("#run_kinship").hide();
    });

});

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity
} from 'react-native';

class Button extends Component {
    static propTypes = {
        ...TouchableOpacity.propTypes,
        text: React.PropTypes.string.isRequired,
        backgroundColor: React.PropTypes.string,
        borderColor: React.PropTypes.string,
        borderRadius: React.PropTypes.number,
        shadowHeight: React.PropTypes.number,
        activeOpacity: React.PropTypes.number,
        containerStyle: View.propTypes.style,
        contentStyle: Text.propTypes.style
    }

    static defaultProps = {
        borderRadius: 8,
        shadowHeight: 4,
        activeOpacity: 0.9,
        backgroundColor: '#1abc9c',
        borderColor: '#16a085'
    }

    constructor(props){
        super(props)

        this._pressIn = this._pressIn.bind(this)
        this._pressOut = this._pressOut.bind(this)

        this.state = {
            borderBottomWidth: this.props.shadowHeight,
            borderColor: this.props.borderColor,
            borderRadius: this.props.borderRadius,
            borderLeftWidth: 0.5,
            borderRightWidth: 0.5
        }
    }

    _pressIn(){
        this.setState({
            borderBottomWidth: 0,
            borderColor: 'transparent',
            borderRadius: this.props.borderRadius,
            borderLeftWidth: 0,
            borderRightWidth: 0
        })
    }

    _pressOut(){
        this.setState({
            borderBottomWidth: this.props.shadowHeight,
            borderColor: this.props.borderColor,
            borderRadius: this.props.borderRadius,
            borderLeftWidth: 0.5,
            borderRightWidth: 0.5
        })
    }

  render() {
    return (
      <TouchableOpacity
        onPress={this.props.onPress}
        onPressIn={this._pressIn}
        onPressOut={this._pressOut}
        activeOpacity={this.props.activeOpacity}
        style={[styles.buttonContainer, this.props.containerStyle, {backgroundColor: this.props.backgroundColor, borderBottomWidth: this.state.borderBottomWidth, borderColor: this.state.borderColor, borderRadius: this.state.borderRadius, borderLeftWidth: this.state.borderLeftWidth, borderRightWidth: this.state.borderRightWidth}]}>
        <Text style={[styles.text, this.props.contentStyle]}>
            {this.props.text}
        </Text>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  buttonContainer: {
      justifyContent: 'center',
      alignItems: 'center',
  },
  text:{
      color: 'white',
      fontSize: 18,
      fontWeight: 'bold'
  }
});

export default Button;
<commit_msg>initialization of pre-defined types<commit_after>import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity
} from 'react-native';

class Button extends Component {
    static propTypes = {
        ...TouchableOpacity.propTypes,
        text: React.PropTypes.string.isRequired,
        backgroundColor: React.PropTypes.string,
        borderColor: React.PropTypes.string,
        borderRadius: React.PropTypes.number,
        shadowHeight: React.PropTypes.number,
        activeOpacity: React.PropTypes.number,
        containerStyle: View.propTypes.style,
        contentStyle: Text.propTypes.style,
        type: React.PropTypes.string
    }

    static defaultProps = {
        borderRadius: 8,
        shadowHeight: 4,
        activeOpacity: 0.9,
        backgroundColor: '#1abc9c',
        borderColor: '#16a085'
    }

    constructor(props){
        super(props)

        this._pressIn = this._pressIn.bind(this)
        this._pressOut = this._pressOut.bind(this)

        this.state = {
            borderBottomWidth: this.props.shadowHeight,
            borderColor: this.props.borderColor,
            borderRadius: this.props.borderRadius,
            borderLeftWidth: 0.5,
            borderRightWidth: 0.5
        }
    }

    _pressIn(){
        this.setState({
            borderBottomWidth: 0,
            borderColor: 'transparent',
            borderRadius: this.props.borderRadius,
            borderLeftWidth: 0,
            borderRightWidth: 0
        })
    }

    _pressOut(){
        this.setState({
            borderBottomWidth: this.props.shadowHeight,
            borderColor: this.props.borderColor,
            borderRadius: this.props.borderRadius,
            borderLeftWidth: 0.5,
            borderRightWidth: 0.5
        })
    }

  render() {
    return (
      <TouchableOpacity
        onPress={this.props.onPress}
        onPressIn={this._pressIn}
        onPressOut={this._pressOut}
        activeOpacity={this.props.activeOpacity}
        style={[styles.buttonContainer, this.props.containerStyle, {backgroundColor: this.props.backgroundColor, borderBottomWidth: this.state.borderBottomWidth, borderColor: this.state.borderColor, borderRadius: this.state.borderRadius, borderLeftWidth: this.state.borderLeftWidth, borderRightWidth: this.state.borderRightWidth}]}>
        <Text style={[styles.text, this.props.contentStyle]}>
            {this.props.text}
        </Text>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  buttonContainer: {
      justifyContent: 'center',
      alignItems: 'center',
  },
  text:{
      color: 'white',
      fontSize: 18,
      fontWeight: 'bold'
  }
});

export default Button;
<|endoftext|>


<commit_before>'use strict';

// ## Module Dependencies
var _ = require('lodash');
var User = require('./neo4j/user.js');
var UserProfile = require('./neo4j/userprofile.js');
var Architect = require('neo4j-architect');
var colog = require('colog');

Architect.init();

var Construct = Architect.Construct;
var Cypher = Architect.Cypher;

// ## Results Functions
// To be combined with queries using _.partial()

// return a single user
var _singleUser = function (results, callback) {
  if (results.length) {
    callback(null, new User(results[0].user));
  } else {
    callback(null, null);
  }
};
// return a single user
var _singleUserProfile = function (results, callback) {
  if (results.length) {
    // console.log(new UserProfile(results[0]));
    callback(null, new UserProfile(results[0]));
  } else {
    callback(null, null);
  }
};

// return many users
var _manyUsers = function (results, callback) {
  var users = _.map(results, function (result) {
    return new User(result.user);
  });

  callback(null, users);
};

// ## Query Functions
// Should be combined with results functions using _.partial()

var _matchBy = function (keys, params, callback) {
  var cypherParams = _.pick(params, keys);

  var query = [
    'MATCH (user:User)',
    Cypher.where('user', keys),
    'WITH user',
    'MATCH (user)-[:LIKES]->(like:Like)',
    'WITH user,like',
    'MATCH (user)-[:HAS_TAG]->(tag:Tag)',
    'WITH user,like,tag',
    'RETURN user,collect(like) as likes,collect(tag) as tags'
  ].join('\n');

  colog.info(query);

  callback(null, query, cypherParams);
};

var _matchByUUID = _.partial(_matchBy, ['id']);

var _matchAll = _.partial(_matchBy, []);

// creates the user with cypher
var _create = function (params, callback) {
  colog.info(params);
  var cypherParams = {
    id : params.id,
    firstname : params.firstname,
    lastname : params.lastname,
    profileImage : params.profileImage,
  };

  var query = [

    'MERGE (user:User{id: {id}})',
    'ON CREATE',
      'SET user.created = timestamp()',
    'SET user.lastLogin = timestamp()'
  ];

  if (cypherParams.firstname){
    query.push(
    'SET user.firstname ={firstname}');
  }
  if (cypherParams.lastname){
    query.push(
    'SET user.lastname= {lastname}');
  }
  if (cypherParams.profileImage){
    query.push(
    'SET user.profileImage = {profileImage}');
  }
  query.push(
    'RETURN user');

  query = query.join('\n');

  colog.info(query);

  callback(null, query, cypherParams);
};

// delete the user and any relationships with cypher
var _delete = function (params, callback) {
  var cypherParams = {
    id: params.id
  };

  var query = [
    'MATCH (user:User {id:{id}})',
    'OPTIONAL MATCH (user)-[r]-()',
    'DELETE user, r',
  ].join('\n');

  callback(null, query, cypherParams);
};

// delete all users
var _deleteAll = function (params, callback) {
  var cypherParams = {};

  var query = [
    'MATCH (user:User)',
    'OPTIONAL MATCH (user)-[r]-()',
    'DELETE user, r',
  ].join('\n');

  callback(null, query, cypherParams);
};

// create a new user

var getById = new Construct(_matchByUUID).query().then(_singleUserProfile);

var getAll = new Construct(_matchAll, _manyUsers);

var create = new Construct(_create, _singleUser);
// get a user by id and update their properties
// var update = new Construct(_update, _singleUser);

// delete a user by id
var deleteUser = new Construct(_delete);

// delete a user by id
var deleteAllUsers = new Construct(_deleteAll);

// export exposed functions
module.exports = {
  getById: getById.done(),
  create: create.done(),
  getAll: getAll.done(),
  deleteUser: deleteUser.done(),
  deleteAllUsers: deleteAllUsers.done(),
};
<commit_msg>Changed the query give distinct values<commit_after>'use strict';

// ## Module Dependencies
var _ = require('lodash');
var User = require('./neo4j/user.js');
var UserProfile = require('./neo4j/userprofile.js');
var Architect = require('neo4j-architect');
var colog = require('colog');

Architect.init();

var Construct = Architect.Construct;
var Cypher = Architect.Cypher;

// ## Results Functions
// To be combined with queries using _.partial()

// return a single user
var _singleUser = function (results, callback) {
  if (results.length) {
    callback(null, new User(results[0].user));
  } else {
    callback(null, null);
  }
};
// return a single user
var _singleUserProfile = function (results, callback) {
  if (results.length) {
    // console.log(new UserProfile(results[0]));
    callback(null, new UserProfile(results[0]));
  } else {
    callback(null, null);
  }
};

// return many users
var _manyUsers = function (results, callback) {
  var users = _.map(results, function (result) {
    return new User(result.user);
  });

  callback(null, users);
};

// ## Query Functions
// Should be combined with results functions using _.partial()

var _matchBy = function (keys, params, callback) {
  var cypherParams = _.pick(params, keys);

  var query = [
    'MATCH (user:User)',
    Cypher.where('user', keys),
    'WITH user',
    'MATCH (user)-[:LIKES]->(like:Like)',
    'WITH user,like',
    'MATCH (user)-[:HAS_TAG]->(tag:Tag)',
    'WITH user,like,tag',
    'RETURN user,COLLECT( DISTINCT like) as likes,COLLECT( DISTINCT tag) as tags'
  ].join('\n');

  colog.info(query);

  callback(null, query, cypherParams);
};

var _matchByUUID = _.partial(_matchBy, ['id']);

var _matchAll = _.partial(_matchBy, []);

// creates the user with cypher
var _create = function (params, callback) {
  colog.info(params);
  var cypherParams = {
    id : params.id,
    firstname : params.firstname,
    lastname : params.lastname,
    profileImage : params.profileImage,
  };

  var query = [

    'MERGE (user:User{id: {id}})',
    'ON CREATE',
      'SET user.created = timestamp()',
    'SET user.lastLogin = timestamp()'
  ];

  if (cypherParams.firstname){
    query.push(
    'SET user.firstname ={firstname}');
  }
  if (cypherParams.lastname){
    query.push(
    'SET user.lastname= {lastname}');
  }
  if (cypherParams.profileImage){
    query.push(
    'SET user.profileImage = {profileImage}');
  }
  query.push(
    'RETURN user');

  query = query.join('\n');

  colog.info(query);

  callback(null, query, cypherParams);
};

// delete the user and any relationships with cypher
var _delete = function (params, callback) {
  var cypherParams = {
    id: params.id
  };

  var query = [
    'MATCH (user:User {id:{id}})',
    'OPTIONAL MATCH (user)-[r]-()',
    'DELETE user, r',
  ].join('\n');

  callback(null, query, cypherParams);
};

// delete all users
var _deleteAll = function (params, callback) {
  var cypherParams = {};

  var query = [
    'MATCH (user:User)',
    'OPTIONAL MATCH (user)-[r]-()',
    'DELETE user, r',
  ].join('\n');

  callback(null, query, cypherParams);
};

// create a new user

var getById = new Construct(_matchByUUID).query().then(_singleUserProfile);

var getAll = new Construct(_matchAll, _manyUsers);

var create = new Construct(_create, _singleUser);
// get a user by id and update their properties
// var update = new Construct(_update, _singleUser);

// delete a user by id
var deleteUser = new Construct(_delete);

// delete a user by id
var deleteAllUsers = new Construct(_deleteAll);

// export exposed functions
module.exports = {
  getById: getById.done(),
  create: create.done(),
  getAll: getAll.done(),
  deleteUser: deleteUser.done(),
  deleteAllUsers: deleteAllUsers.done(),
};
<|endoftext|>


<commit_before>import {plugin} from 'postcss';
import has from 'has';
import browserslist from 'browserslist';
import {isSupported} from 'caniuse-api';
import fromInitial from '../data/fromInitial.json';
import toInitial from '../data/toInitial.json';

const initial = 'initial';

export default plugin('postcss-reduce-initial', () => {
    return (css, result) => {
        const {opts} = result;
        const browsers = browserslist(null, {
            stats: opts && opts.stats,
            path: opts && opts.from,
            env: opts && opts.env,
        });
        const initialSupport = isSupported('css-initial-value', browsers);
        css.walkDecls(decl => {
            const {prop} = decl;
            if (
                initialSupport &&
                has(toInitial, prop) &&
                decl.value === toInitial[prop]
            ) {
                decl.value = initial;
                return;
            }
            if (decl.value !== initial) {
                return;
            }
            if (fromInitial[prop]) {
                decl.value = fromInitial[decl.prop];
            }
        });
    };
});
<commit_msg>Consolidate exit logic for initial value conversion.<commit_after>import {plugin} from 'postcss';
import has from 'has';
import browserslist from 'browserslist';
import {isSupported} from 'caniuse-api';
import fromInitial from '../data/fromInitial.json';
import toInitial from '../data/toInitial.json';

const initial = 'initial';

export default plugin('postcss-reduce-initial', () => {
    return (css, result) => {
        const {opts} = result;
        const browsers = browserslist(null, {
            stats: opts && opts.stats,
            path: opts && opts.from,
            env: opts && opts.env,
        });
        const initialSupport = isSupported('css-initial-value', browsers);
        css.walkDecls(decl => {
            const {prop} = decl;
            if (
                initialSupport &&
                has(toInitial, prop) &&
                decl.value === toInitial[prop]
            ) {
                decl.value = initial;
                return;
            }
            if (decl.value !== initial || !fromInitial[prop]) {
                return;
            }
            decl.value = fromInitial[prop];
        });
    };
});
<|endoftext|>