<commit_before>// Truth table functions and view
'use strict';

var m = require('mithril');
var _ = require('underscore');
var classNames = require('classnames');

var Table = {};

// Iterate through all possible true/false values for the given collection of
// variables
Table.forEachRow = function (variables, callback) {
  var currentVarValues = {};
  variables.forEach(function (variable) {
    // Variable values should be initialized to true because they will be
    // inverted before the callback is called for the first table row, making
    // the first permutation of variable values all false
    currentVarValues[variable.name] = true;
  });
  // If n corresponds to the number of variables, then there will always be 2^n
  // rows in the truth table (excluding the table head, of course)
  return _.times(Math.pow(2, variables.length), function (rowIndex) {
    variables.forEach(function (variable, varIndex) {
      // Alternate current variable values as needed
      if (rowIndex % Math.pow(2, variables.length - varIndex - 1) === 0) {
        currentVarValues[variable.name] = !currentVarValues[variable.name];
      }
    });
    return callback(currentVarValues);
  });
};

// Get the string value of the given boolean for display in the truth table
Table.getBoolStr = function (boolean) {
  if (boolean === true) {
    return 'T';
  } else if (boolean === false) {
    return 'F';
  } else {
    // Display U for null/undefined values
    return 'U';
  }
};

Table.Component = {};

Table.Component.controller = function () {
  return {
    getExpressionIndex: function (expressionElem) {
      var currentElem = expressionElem.parentNode.parentNode;
      var expressionIndex = -1;
      do {
        currentElem = currentElem.previousElementSibling;
        expressionIndex += 1;
      } while (currentElem !== null && currentElem.className === 'expression');
      return expressionIndex;
    },
    updateExpressionString: function (ctrl, expressions, event) {
      var expression = expressions.get(ctrl.getExpressionIndex(event.target));
      expression.string = event.target.value;
    }
  };
};

Table.Component.view = function (ctrl, variables, expressions) {
  // A cache to store expressions which are known to be invalid (so as to avoid
  // re-evaluating them later)
  var invalidExpressionCache = {};
  return m('table#truth-table', [
    m('thead', m('tr', {
      oninput: _.partial(ctrl.updateExpressionString, ctrl, expressions)
    }, [
      variables.map(function (variable) {
        return m('th.variable', variable.name);
      }),
      expressions.map(function (expression) {
        return m('th.expression', m('div.has-controls', [
          m('div.control.add'),
          m('div.control.remove'),
          m('input', {
            type: 'text',
            size: Math.max(1, expression.string.length),
            value: expression.string,
            autocapitalize: 'off',
            autocomplete: 'off',
            autocorrect: 'off',
            spellcheck: false
          })
        ]));
      })
    ])
  ),
  m('tbody', Table.forEachRow(variables, function (varValues) {
    return m('tr', [
      variables.map(function(variable) {
        var varValue = varValues[variable.name];
        return m('td', {
          class: classNames(
            {true: varValue === true},
            {false: varValue === false}
          )
        },
        Table.getBoolStr(varValue));
      }),
      expressions.map(function(expression) {
        var exprValue;
        // Don't re-evaluate expression if it is known to be invalid
        if (expression.string in invalidExpressionCache) {
          exprValue = null;
        } else {
          exprValue = expression.evaluate(varValues);
          if (exprValue === null) {
            // The value stored with the key in the cache doesn't really matter;
            // the cache itself functions more as a set than a dictionary
            invalidExpressionCache[expression.string] = true;
          }
        }
        return m('td', {
          class: classNames(
            {true: exprValue === true},
            {false: exprValue === false}
          )
        }, Table.getBoolStr(exprValue));
      })
    ]);
  }))
]);
};

module.exports = Table;
<commit_msg>Implement add/remove functionality for expressions<commit_after>// Truth table functions and view
'use strict';

var m = require('mithril');
var _ = require('underscore');
var classNames = require('classnames');

var Table = {};

// Iterate through all possible true/false values for the given collection of
// variables
Table.forEachRow = function (variables, callback) {
  var currentVarValues = {};
  variables.forEach(function (variable) {
    // Variable values should be initialized to true because they will be
    // inverted before the callback is called for the first table row, making
    // the first permutation of variable values all false
    currentVarValues[variable.name] = true;
  });
  // If n corresponds to the number of variables, then there will always be 2^n
  // rows in the truth table (excluding the table head, of course)
  return _.times(Math.pow(2, variables.length), function (rowIndex) {
    variables.forEach(function (variable, varIndex) {
      // Alternate current variable values as needed
      if (rowIndex % Math.pow(2, variables.length - varIndex - 1) === 0) {
        currentVarValues[variable.name] = !currentVarValues[variable.name];
      }
    });
    return callback(currentVarValues);
  });
};

// Get the string value of the given boolean for display in the truth table
Table.getBoolStr = function (boolean) {
  if (boolean === true) {
    return 'T';
  } else if (boolean === false) {
    return 'F';
  } else {
    // Display U for null/undefined values
    return 'U';
  }
};

Table.Component = {};

Table.Component.controller = function () {
  return {
    getExpressionIndex: function (expressionElem) {
      var currentElem = expressionElem.parentNode.parentNode;
      var expressionIndex = -1;
      do {
        currentElem = currentElem.previousElementSibling;
        expressionIndex += 1;
      } while (currentElem !== null && currentElem.className === 'expression');
      return expressionIndex;
    },
    updateExpressionString: function (ctrl, expressions, event) {
      var expression = expressions.get(ctrl.getExpressionIndex(event.target));
      expression.string = event.target.value;
    },
    addExpression: function (ctrl, expressions, event) {
      var expressionIndex = ctrl.getExpressionIndex(event.target);
      var expression = expressions.get(expressionIndex);
      expressions.insert(expressionIndex + 1, {
        string: expression.string
      });
      // Redraw the view to ensire the new expression element exists
      m.redraw();
      event.target
        .parentNode
        .parentNode
        .nextElementSibling
        .querySelector('input').focus();
    },
    removeExpression: function (ctrl, expressions, event) {
      expressions.remove(ctrl.getExpressionIndex(event.target));
    },
    handleClick: function (ctrl, expressions, event) {
      if (event.target.classList.contains('control')) {
        if (event.target.classList.contains('add')) {
          ctrl.addExpression(ctrl, expressions, event);
        } else if (event.target.classList.contains('remove')) {
          ctrl.removeExpression(ctrl, expressions, event);
        }
      }
    }
  };
};

Table.Component.view = function (ctrl, variables, expressions) {
  // A cache to store expressions which are known to be invalid (so as to avoid
  // re-evaluating them later)
  var invalidExpressionCache = {};
  return m('table#truth-table', [
    m('thead', m('tr', {
      onclick: _.partial(ctrl.handleClick, ctrl, expressions),
      oninput: _.partial(ctrl.updateExpressionString, ctrl, expressions)
    }, [
      variables.map(function (variable) {
        return m('th.variable', variable.name);
      }),
      expressions.map(function (expression) {
        return m('th.expression', m('div.has-controls', [
          m('div.control.add'),
          m('div.control.remove'),
          m('input', {
            type: 'text',
            size: Math.max(1, expression.string.length),
            value: expression.string,
            autocapitalize: 'off',
            autocomplete: 'off',
            autocorrect: 'off',
            spellcheck: false
          })
        ]));
      })
    ])
  ),
  m('tbody', Table.forEachRow(variables, function (varValues) {
    return m('tr', [
      variables.map(function(variable) {
        var varValue = varValues[variable.name];
        return m('td', {
          class: classNames(
            {true: varValue === true},
            {false: varValue === false}
          )
        },
        Table.getBoolStr(varValue));
      }),
      expressions.map(function(expression) {
        var exprValue;
        // Don't re-evaluate expression if it is known to be invalid
        if (expression.string in invalidExpressionCache) {
          exprValue = null;
        } else {
          exprValue = expression.evaluate(varValues);
          if (exprValue === null) {
            // The value stored with the key in the cache doesn't really matter;
            // the cache itself functions more as a set than a dictionary
            invalidExpressionCache[expression.string] = true;
          }
        }
        return m('td', {
          class: classNames(
            {true: exprValue === true},
            {false: exprValue === false}
          )
        }, Table.getBoolStr(exprValue));
      })
    ]);
  }))
]);
};

module.exports = Table;
<|endoftext|>


<commit_before>import Ember from 'ember';

import config from '../config/environment';

export default Ember.Service.extend({
    host: config.HOST,
    namespace: 'solr',
    core: 'dina',

    parseResponse (data) {
        return data.response.docs.mapBy('primary_id');
    },

    select (query, {entityType, fq, rows}) {
        const service = this;
        let url = `${this.host}/${this.namespace}/${this.core}/select?q=${query}&fl=primary_id&wt=json&indent=true`;

        if (entityType) {
            fq['entity_type'] = entityType;
        }

        let fqString = '';
        for(let key in fq) {
            fqString += `&fq=${key}%3D${fq[key]}`;
        }

        url += fqString;

        if (rows) {
            url += `&rows=${rows}`;
        }

        return new Ember.RSVP.Promise(function (resolve, reject) {
            Ember.$.getJSON(url).success((data)=>{
                resolve(service.parseResponse(data));
            }).fail((error)=>{
                reject(error);
            });
        });
    },
    updateIndex () {
        const url = `${this.host}/${this.namespace}/${this.core}/dataimport?command=delta-import&commit=1&wt=json`;
        Ember.$.getJSON(url);
    }
});
<commit_msg>Update how filter query is applied<commit_after>import Ember from 'ember';

import config from '../config/environment';

export default Ember.Service.extend({
    host: config.HOST,
    namespace: 'solr',
    core: 'dina',

    parseResponse (data) {
        return data.response.docs.mapBy('primary_id');
    },

    select (query, {entityType, fq, rows}) {
        const service = this;
        let url = `${this.host}/${this.namespace}/${this.core}/select?q=${query}&fl=primary_id&wt=json&indent=true`;

        if (entityType) {
            fq['entity_type'] = entityType;
        }

        let fqString = '';
        for(let key in fq) {
            fqString += `&fq=${key}%3A${fq[key]}`;
        }

        url += fqString;

        if (rows) {
            url += `&rows=${rows}`;
        }

        return new Ember.RSVP.Promise(function (resolve, reject) {
            Ember.$.getJSON(url).success((data)=>{
                resolve(service.parseResponse(data));
            }).fail((error)=>{
                reject(error);
            });
        });
    },
    updateIndex () {
        const url = `${this.host}/${this.namespace}/${this.core}/dataimport?command=delta-import&commit=1&wt=json`;
        Ember.$.getJSON(url);
    }
});
<|endoftext|>


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

    var SERVER = "http://cib-bolivia.com"
    // var SERVER = "http://localhost:5000"

    var REG_ENDPOINT = "/api/registro";
    var SUS_ENDPOINT = "/api/suscriptors";
    var QUERY_ENDPOINT = "/api/contacts";

    var MESSAGE = {
        contacto_ok: "Cracias por contactarse con nosotros.",
        contacto_fail: "No se pudo establecer conexion",
        suscripcion_ok: "Gracias por suscribirse a nuestro boletin.",
        suscripcion_fail: "Su suscripcion no se completo.",
        registro_ok: "Gracias por registrarse al evento.",
        registro_fail: "Su registro no pudo concretarse."
    }

    var REG_EXP = {
        name : /^[A-Za-z0-9 ]{3,20}$/,
        email : /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i,
        username : /^[A-Za-z0-9_]{1,20}$/,
        password :  /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/,
        filled :  /.+/,
    }

    toastr.options = {
      "closeButton": false,
      "debug": false,
      "newestOnTop": false,
      "progressBar": false,
      "positionClass": "toast-top-center",
      "preventDuplicates": false,
      "onclick": null,
      "showDuration": "500",
      "hideDuration": "1200",
      "timeOut": "5000",
      "extendedTimeOut": "500",
      "showEasing": "swing",
      "hideEasing": "linear",
      "showMethod": "fadeIn",
      "hideMethod": "fadeOut",
      "preventDuplicates" : true,
      "closeButton" : true
    };

    var Loader = {
        open: function(){
            document.getElementById('modalLoader').style.display = 'block';
            document.getElementById('fade').style.display = 'block';
        },
        close: function(){
            document.getElementById('modalLoader').style.display = 'none';
            document.getElementById('fade').style.display = 'none';
        }
    }

    // using jQuery
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

    // FORMULARIO DE CONTACTO
    var $contacForm = $('.contact-form form');
    $contacForm.find('#sendContact').click(function(e) {

        e.preventDefault();
        e.stopPropagation();

        console.log("guardando Conta");

        var $name = $( $contacForm.get(0).name );
        var $email = $( $contacForm.get(0).email );
        var $message = $contacForm.find('textarea');

        $('.contact-form p.error').show();
        $('input[name="name"], input[name="email"], textarea').removeClass('error');

        // e.stopPropagation();
        e.preventDefault();

        var validate = true;
        if ($name.val() == '') {
            $('.contact-form p.error').addClass('active').html(' Please enter your name.');
            $name.addClass('error').focus();
            validate = false;
        }

        function IsEmail(email) {
            var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            return regex.test(email);
        }

        if ($email.val() == '') {
            $('p.error').addClass('active').html(' Please enter your email.');
            $email.addClass('error').focus();
            validate = false;
        }

        console.log("IsEmail"+ IsEmail($email.val()) );

        if(!IsEmail($email.val())) {
            $('.contact-form p.error').addClass('active').html(' Looks like that email address is not correct. Try again.');
            $email.addClass('error').focus();
            validate = false;
        }

        if ($message.val() == "") {
            $('.contact-form p.error').addClass('active').html(' Please enter your message.');
            $message.addClass('error').focus();
            validate = false;
        }

        if(validate){
            var consulta = {
                name: $name.val(),
                email: $email.val(),
                message: $message.val()
            }
            var request = $.ajax({
                url: QUERY_ENDPOINT,
                method: 'POST',
                data: consulta
            });

            Loader.open();

            request.done(function (response, textStatus, jqXHR){
                $('.contact-form p.error').hide();
                $('.contact-form p.message').html('Consulta enviado, muchas gracias.').fadeOut(2000);
                Loader.close();
                toastr["success"](MESSAGE.contacto_ok);
            });
            request.fail(function (jqXHR, textStatus, errorThrown){
                console.error('The following error occured: '+ textStatus, errorThrown);
                Loader.close();
                toastr["error"](MESSAGE.contacto_fail);

            });
        }
    });

    //  FORMULARIO DE REGISTRO
    var $regForm = $("#regForm");
    $regForm.name = $( $regForm.get(0).name );
    $regForm.surname = $( $regForm.get(0).surname );
    $regForm.email = $( $regForm.get(0).email );
    $regForm.address = $( $regForm.get(0).address );
    $regForm.depot = $( $regForm.get(0).depot );
    $regForm.city = $( $regForm.get(0).city );
    $regForm.package = $("#package");
    $regForm.submit = $( $regForm.get(0).submit );

    $regForm.submit.click(function(e){
        e.stopPropagation();
        e.preventDefault()

        var validate = true;
        if( !REG_EXP.name.test($regForm.city.val()) ){
            $regForm.city.addClass("error");
            $regForm.city.focus();
            validate = false;
        } else $regForm.city.removeClass("error");

        if( !REG_EXP.filled.test($regForm.package.val()) ){
            $regForm.package.addClass("error");
            $regForm.package.focus();
            validate = false;
        } else $regForm.package.removeClass("error");

        if( !REG_EXP.filled.test($regForm.depot.val()) ){
            $regForm.depot.addClass("error");
            $regForm.depot.focus();
            validate = false;
        } else $regForm.depot.removeClass("error");

        if( !REG_EXP.filled.test($regForm.address.val()) ){
            $regForm.address.addClass("error");
            $regForm.address.focus();
            validate = false;
        } else $regForm.address.removeClass("error");

        if( !REG_EXP.email.test($regForm.email.val()) ){
            $regForm.email.addClass("error");
            $regForm.email.focus();
            validate = false;
        } else $regForm.email.removeClass("error");

        if( !REG_EXP.name.test($regForm.surname.val()) ){
            $regForm.surname.addClass("error");
            $regForm.surname.focus();
            validate = false;
        } else $regForm.surname.removeClass("error");

        if( !REG_EXP.name.test($regForm.name.val()) ){
            $regForm.name.addClass("error");
            $regForm.name.focus();
            validate = false;
        } else $regForm.name.removeClass("error");

        if(validate) {
            var person = {
                name: $regForm.name.val(),
                surname: $regForm.surname.val(),
                email: $regForm.email.val(),
                address: $regForm.address.val(),
                depot: $regForm.depot.val(),
                city: $regForm.city.val(),
                package: $regForm.package.val()
            }

            Loader.open();

            $.ajax({
                url: REG_ENDPOINT,
                data: person,
                method: "POST",
                success: function(data){
                    console.log(data);
                    Loader.close();
                    toastr["success"](MESSAGE.registro_ok);
                },
                error: function(a,b,c){
                    console.log(a,b,c);
                    Loader.close();
                    toastr["error"](MESSAGE.registro_fail);
                }
            })
        }
    });

    // FORMULARIO DE SUSCRIPCION
    var $susForm = $("#suscriptorForm");

    $susForm.email = $( $susForm.get(0).email );
    $susForm.submit = $susForm.find("button");

    $susForm.submit.click(function(e){
        e.preventDefault();
        e.stopPropagation();

        var validate = true;
        if( !REG_EXP.email.test($susForm.email.val()) ){
            $susForm.email.addClass("error'");
            $susForm.email.focus();
            validate = false;
        } else $susForm.email.removeClass("error");

        if(validate) {
            var suscriptor = { email: $susForm.email.val() }

            Loader.open();

            $.ajax({
                url: SUS_ENDPOINT,
                data: suscriptor,
                method: "POST",
                success: function(data){
                    console.log(data);
                    Loader.close();
                    toastr["success"](MESSAGE.suscripcion_ok);
                },
                error: function(a,b,c){
                    console.log(a,b,c);
                    Loader.close();
                    toastr["error"](MESSAGE.suscripcion_fail);
                }
            })
        }
    });

});<commit_msg>clean<commit_after>$(document).ready(function(){

    var SERVER = "http://cib-bolivia.com"
    // var SERVER = "http://localhost:5000"

    var REG_ENDPOINT = "/api/registro";
    var SUS_ENDPOINT = "/api/suscriptors";
    var QUERY_ENDPOINT = "/api/contacts";

    var MESSAGE = {
        contacto_ok: "Cracias por contactarse con nosotros.",
        contacto_fail: "No se pudo establecer conexion",
        suscripcion_ok: "Gracias por suscribirse a nuestro boletin.",
        suscripcion_fail: "Su suscripcion no se completo.",
        registro_ok: "Gracias por registrarse al evento.",
        registro_fail: "Su registro no pudo concretarse."
    }

    var REG_EXP = {
        name : /^[A-Za-z0-9 ]{3,20}$/,
        email : /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i,
        username : /^[A-Za-z0-9_]{1,20}$/,
        password :  /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/,
        filled :  /.+/,
    }

    toastr.options = {
      "closeButton": false,
      "debug": false,
      "newestOnTop": false,
      "progressBar": false,
      "positionClass": "toast-top-center",
      "preventDuplicates": false,
      "onclick": null,
      "showDuration": "500",
      "hideDuration": "1200",
      "timeOut": "5000",
      "extendedTimeOut": "500",
      "showEasing": "swing",
      "hideEasing": "linear",
      "showMethod": "fadeIn",
      "hideMethod": "fadeOut",
      "preventDuplicates" : true,
      "closeButton" : true
    };

    var Loader = {
        open: function(){
            document.getElementById('modalLoader').style.display = 'block';
            document.getElementById('fade').style.display = 'block';
        },
        close: function(){
            document.getElementById('modalLoader').style.display = 'none';
            document.getElementById('fade').style.display = 'none';
        }
    }

    // using jQuery
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

    // FORMULARIO DE CONTACTO
    var $contacForm = $('.contact-form form');
    $contacForm.find('#sendContact').click(function(e) {

        e.preventDefault();
        e.stopPropagation();

        console.log("guardando Conta");

        var $name = $( $contacForm.get(0).name );
        var $email = $( $contacForm.get(0).email );
        var $message = $contacForm.find('textarea');

        $('.contact-form p.error').show();
        $('input[name="name"], input[name="email"], textarea').removeClass('error');

        // e.stopPropagation();
        e.preventDefault();

        var validate = true;
        if ($name.val() == '') {
            $('.contact-form p.error').addClass('active').html(' Please enter your name.');
            $name.addClass('error').focus();
            validate = false;
        }

        function IsEmail(email) {
            var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            return regex.test(email);
        }

        if ($email.val() == '') {
            $('p.error').addClass('active').html(' Please enter your email.');
            $email.addClass('error').focus();
            validate = false;
        }

        console.log("IsEmail"+ IsEmail($email.val()) );

        if(!IsEmail($email.val())) {
            $('.contact-form p.error').addClass('active').html(' Looks like that email address is not correct. Try again.');
            $email.addClass('error').focus();
            validate = false;
        }

        if ($message.val() == "") {
            $('.contact-form p.error').addClass('active').html(' Please enter your message.');
            $message.addClass('error').focus();
            validate = false;
        }

        if(validate){
            var consulta = {
                name: $name.val(),
                email: $email.val(),
                message: $message.val()
            }
            var request = $.ajax({
                url: QUERY_ENDPOINT,
                method: 'POST',
                data: consulta
            });

            Loader.open();

            request.done(function (response, textStatus, jqXHR){
                $('.contact-form p.error').hide();
                $('.contact-form p.message').html('Consulta enviado, muchas gracias.').fadeOut(2000);
                Loader.close();
                toastr["success"](MESSAGE.contacto_ok);
                $contacForm.get(0).reset();
                $name.focus();
            });
            request.fail(function (jqXHR, textStatus, errorThrown){
                console.error('The following error occured: '+ textStatus, errorThrown);
                Loader.close();
                toastr["error"](MESSAGE.contacto_fail);

            });
        }
    });

    //  FORMULARIO DE REGISTRO
    var $regForm = $("#regForm");
    $regForm.name = $( $regForm.get(0).name );
    $regForm.surname = $( $regForm.get(0).surname );
    $regForm.email = $( $regForm.get(0).email );
    $regForm.address = $( $regForm.get(0).address );
    $regForm.depot = $( $regForm.get(0).depot );
    $regForm.city = $( $regForm.get(0).city );
    $regForm.package = $("#package");
    $regForm.submit = $( $regForm.get(0).submit );

    $regForm.submit.click(function(e){
        e.stopPropagation();
        e.preventDefault()

        var validate = true;
        if( !REG_EXP.name.test($regForm.city.val()) ){
            $regForm.city.addClass("error");
            $regForm.city.focus();
            validate = false;
        } else $regForm.city.removeClass("error");

        if( !REG_EXP.filled.test($regForm.package.val()) ){
            $regForm.package.addClass("error");
            $regForm.package.focus();
            validate = false;
        } else $regForm.package.removeClass("error");

        if( !REG_EXP.filled.test($regForm.depot.val()) ){
            $regForm.depot.addClass("error");
            $regForm.depot.focus();
            validate = false;
        } else $regForm.depot.removeClass("error");

        if( !REG_EXP.filled.test($regForm.address.val()) ){
            $regForm.address.addClass("error");
            $regForm.address.focus();
            validate = false;
        } else $regForm.address.removeClass("error");

        if( !REG_EXP.email.test($regForm.email.val()) ){
            $regForm.email.addClass("error");
            $regForm.email.focus();
            validate = false;
        } else $regForm.email.removeClass("error");

        if( !REG_EXP.name.test($regForm.surname.val()) ){
            $regForm.surname.addClass("error");
            $regForm.surname.focus();
            validate = false;
        } else $regForm.surname.removeClass("error");

        if( !REG_EXP.name.test($regForm.name.val()) ){
            $regForm.name.addClass("error");
            $regForm.name.focus();
            validate = false;
        } else $regForm.name.removeClass("error");

        if(validate) {
            var person = {
                name: $regForm.name.val(),
                surname: $regForm.surname.val(),
                email: $regForm.email.val(),
                address: $regForm.address.val(),
                depot: $regForm.depot.val(),
                city: $regForm.city.val(),
                package: $regForm.package.val()
            }

            Loader.open();

            $.ajax({
                url: REG_ENDPOINT,
                data: person,
                method: "POST",
                success: function(data){
                    console.log(data);
                    Loader.close();
                    toastr["success"](MESSAGE.registro_ok);
                    $regForm.get(0).reset();
                    $regForm.name.focus();
                },
                error: function(a,b,c){
                    console.log(a,b,c);
                    Loader.close();
                    toastr["error"](MESSAGE.registro_fail);
                }
            })
        }
    });

    // FORMULARIO DE SUSCRIPCION
    var $susForm = $("#suscriptorForm");

    $susForm.email = $( $susForm.get(0).email );
    $susForm.submit = $susForm.find("button");

    $susForm.submit.click(function(e){
        e.preventDefault();
        e.stopPropagation();

        var validate = true;
        if( !REG_EXP.email.test($susForm.email.val()) ){
            $susForm.email.addClass("error'");
            $susForm.email.focus();
            validate = false;
        } else $susForm.email.removeClass("error");

        if(validate) {
            var suscriptor = { email: $susForm.email.val() }

            Loader.open();

            $.ajax({
                url: SUS_ENDPOINT,
                data: suscriptor,
                method: "POST",
                success: function(data){
                    console.log(data);
                    Loader.close();
                    toastr["success"](MESSAGE.suscripcion_ok);
                    $susForm.get(0).reset();
                    $susForm.email.focus();
                },
                error: function(a,b,c){
                    console.log(a,b,c);
                    Loader.close();
                    toastr["error"](MESSAGE.suscripcion_fail);
                }
            })
        }
    });

});<|endoftext|>


<commit_before>/*!
 * Copyright (c) 2010 Andrew Watts
 *
 * Dual licensed under the MIT (MIT_LICENSE.txt)
 * and GPL (GPL_LICENSE.txt) licenses
 *
 * http://github.com/andrewwatts/ui.tabs.closable
 */
(function() {

var ui_tabs_tabify = $.ui.tabs.prototype._tabify;

$.extend($.ui.tabs.prototype, {

    _tabify: function() {
        var self = this;

        ui_tabs_tabify.apply(this, arguments);

        // if closable tabs are enable, add a close button
        if (self.options.closable === true) {

            var unclosable_lis = this.lis.filter(function() {
                // return the lis that do not have a close button
                return $('span.ui-icon-circle-close', this).length === 0;
            });

            // append the close button and associated events
            unclosable_lis.each(function() {
                $(this)
                    .append('')
                    .find('a:last')
                        .hover(
                            function() {
                                $(this).css('cursor', 'pointer');
                            },
                            function() {
                                $(this).css('cursor', 'default');
                            }
                        )
                        .click(function() {
                            var index = self.lis.index($(this).parent());
                            if (index > -1) {
                                // remove this tab
                                self.remove(index)
                            }

                            // don't follow the link
                            return false;
                        })
                    .end();
            });
        }
    }
});

})(jQuery);
<commit_msg>Adding a callback for closing the tab<commit_after>/*!
 * Copyright (c) 2010 Andrew Watts
 *
 * Dual licensed under the MIT (MIT_LICENSE.txt)
 * and GPL (GPL_LICENSE.txt) licenses
 *
 * http://github.com/andrewwatts/ui.tabs.closable
 */
(function() {

var ui_tabs_tabify = $.ui.tabs.prototype._tabify;

$.extend($.ui.tabs.prototype, {

    _tabify: function() {
        var self = this;

        ui_tabs_tabify.apply(this, arguments);

        // if closable tabs are enable, add a close button
        if (self.options.closable === true) {

            var unclosable_lis = this.lis.filter(function() {
                // return the lis that do not have a close button
                return $('span.ui-icon-circle-close', this).length === 0;
            });

            // append the close button and associated events
            unclosable_lis.each(function() {
                $(this)
                    .append('')
                    .find('a:last')
                        .hover(
                            function() {
                                $(this).css('cursor', 'pointer');
                            },
                            function() {
                                $(this).css('cursor', 'default');
                            }
                        )
                        .click(function() {
                            var index = self.lis.index($(this).parent());
                            if (index > -1) {
                                // call _trigger to see if remove is allowed
                                if (false === self._trigger("closableClick", null, self._ui( $(self.lis[index]).find( "a" )[ 0 ], self.panels[index] ))) return;

                                // remove this tab
                                self.remove(index)
                            }

                            // don't follow the link
                            return false;
                        })
                    .end();
            });
        }
    }
});

})(jQuery);
<|endoftext|>


<commit_before>import angular from 'angular'
import 'angular-ui-bootstrap'
import 'angular-ui-router'
import 'angular-moment'
import 'angular-socket-io'
import routerAdder from './helpers/add-route'
import authInterceptor from './helpers/auth-interceptor'
import controllers from './controllers'

const app = angular.module('mission-control', [
  'ui.router',
  'ui.bootstrap',
  'angularMoment',
  'btford.socket-io'
])
const addRoute = routerAdder(app)

// Configure router with default route
app.config(['$urlRouterProvider', ($urlRouterProvider) => {

  // For any unmatched url, redirect to /dashboard
  $urlRouterProvider.otherwise('/dashboard')

}])

// Configure default $http request options and catch 401s with interceptor
app.config(['$httpProvider', ($httpProvider) => {

  // Automatically send credentials (cookies)
  $httpProvider.defaults.withCredentials = true
  // Register $http middleware/"interceptor" for re-authenticating
  $httpProvider.interceptors.push(authInterceptor)

}])

// Configure socket-io
app.factory('socket', function(socketFactory) {
  return socketFactory()
})

app.run(controllers.socketManager)
app.run(controllers.user)
app.run(controllers.login)
app.run(controllers.modals)
app.run(controllers.helpers)

// Routes
addRoute('dashboard', '/dashboard', 'dashboard.html', controllers.dashboard)

addRoute('projects', '/projects', 'projects.html', controllers.projects)
// addRoute('project', '/project/:project', '/project/project.html', controllers.project)

addRoute('pipelines', '/pipelines', 'pipelines.html', controllers.pipelines)
addRoute('pipeline-execution-details', '/pipelines/executions/{id}', 'pipeline-execution-details.html', controllers.pipelineExecutionDetails)
// addRoute('pipeline', '/project/:project/:pipeline', '/project/pipeline.html', controllers.pipeline)

addRoute('health', '/health', 'health.html', controllers.health)

addRoute('applications', '/resources/applications', '/resources/applications.html', controllers.applications)
addRoute('application-builds', '/resources/application-builds', '/resources/application-builds.html', controllers.applicationBuilds)
addRoute('servers', '/resources/servers', '/resources/servers.html', controllers.servers)
addRoute('files', '/resources/files', '/resources/files.html', controllers.files)
addRoute('credentials', '/resources/credentials', '/resources/credentials.html', controllers.credentials)
addRoute('github-repositories', '/resources/github-repositories', '/resources/github-repositories.html', controllers.githubRepositories)

addRoute('configuration', '/settings/general/configuration', '/settings/general/configuration.html', controllers.configuration)
addRoute('users', '/settings/general/users', '/settings/general/users.html', controllers.users)

addRoute('slack', '/settings/notifications/slack', '/settings/notifications/slack.html', controllers.slack)
addRoute('email', '/settings/notifications/email', '/settings/notifications/email.html', controllers.email)
<commit_msg>Noting refactor reasoning<commit_after>import angular from 'angular'
import 'angular-ui-bootstrap'
import 'angular-ui-router'
import 'angular-moment'
import 'angular-socket-io'
import routerAdder from './helpers/add-route'
import authInterceptor from './helpers/auth-interceptor'
import controllers from './controllers'

const app = angular.module('mission-control', [
  'ui.router',
  'ui.bootstrap',
  'angularMoment',
  'btford.socket-io'
])
const addRoute = routerAdder(app)

// Configure router with default route
app.config(['$urlRouterProvider', ($urlRouterProvider) => {

  // For any unmatched url, redirect to /dashboard
  $urlRouterProvider.otherwise('/dashboard')

}])

// Configure default $http request options and catch 401s with interceptor
app.config(['$httpProvider', ($httpProvider) => {

  // Automatically send credentials (cookies)
  $httpProvider.defaults.withCredentials = true
  // Register $http middleware/"interceptor" for re-authenticating
  $httpProvider.interceptors.push(authInterceptor)

}])

// Configure socket-io
app.factory('socket', function(socketFactory) {
  return socketFactory({
    ioSocket: io.connect() // using this syntax here in case we need to set options for socket.io later
  })
})

app.run(controllers.socketManager)
app.run(controllers.user)
app.run(controllers.login)
app.run(controllers.modals)
app.run(controllers.helpers)

// Routes
addRoute('dashboard', '/dashboard', 'dashboard.html', controllers.dashboard)

addRoute('projects', '/projects', 'projects.html', controllers.projects)
// addRoute('project', '/project/:project', '/project/project.html', controllers.project)

addRoute('pipelines', '/pipelines', 'pipelines.html', controllers.pipelines)
addRoute('pipeline-execution-details', '/pipelines/executions/{id}', 'pipeline-execution-details.html', controllers.pipelineExecutionDetails)
// addRoute('pipeline', '/project/:project/:pipeline', '/project/pipeline.html', controllers.pipeline)

addRoute('health', '/health', 'health.html', controllers.health)

addRoute('applications', '/resources/applications', '/resources/applications.html', controllers.applications)
addRoute('application-builds', '/resources/application-builds', '/resources/application-builds.html', controllers.applicationBuilds)
addRoute('servers', '/resources/servers', '/resources/servers.html', controllers.servers)
addRoute('files', '/resources/files', '/resources/files.html', controllers.files)
addRoute('credentials', '/resources/credentials', '/resources/credentials.html', controllers.credentials)
addRoute('github-repositories', '/resources/github-repositories', '/resources/github-repositories.html', controllers.githubRepositories)

addRoute('configuration', '/settings/general/configuration', '/settings/general/configuration.html', controllers.configuration)
addRoute('users', '/settings/general/users', '/settings/general/users.html', controllers.users)

addRoute('slack', '/settings/notifications/slack', '/settings/notifications/slack.html', controllers.slack)
addRoute('email', '/settings/notifications/email', '/settings/notifications/email.html', controllers.email)
<|endoftext|>


<commit_before>'use strict'

exports.fn = function (gulp, paths, mode, done) {
  var watch = require('gulp-watch')
  var batch = require('gulp-batch')

  watch([paths.src + '**/*.ts', '!' + paths.jspmPackages], batch(function (events, done) {
    gulp.start('lint:ts', done)
    gulp.start('tscompile', done)
    done()
  }))
}
<commit_msg>Fix task name.<commit_after>'use strict'

exports.fn = function (gulp, paths, mode, done) {
  var watch = require('gulp-watch')
  var batch = require('gulp-batch')

  watch([paths.src + '**/*.ts', '!' + paths.jspmPackages], batch(function (events, done) {
    gulp.start('lint:ts', done)
    gulp.start('bundle:tscompile', done)
    done()
  }))
}
<|endoftext|>


<commit_before>jQuery.getScript = function(url, callback, cache) {
    jQuery.ajax({ type: "GET", url: url, success: callback, dataType: "script", cache: cache });
};

function tubepress_init(baseUrl) {
	tubepress_load_embedded_js(baseUrl);
    tubepress_load_players(baseUrl);
    tubepress_attach_listeners();
}

function tubepress_attach_listeners()
{
	jQuery("a[id^='tubepress_']").click(function () {
		var rel_split    = jQuery(this).attr("rel").split("_");
		var galleryId    = rel_split[3];
		var playerName   = rel_split[2];
		var embeddedName = rel_split[1];
		var videoId = jQuery(this).attr("id").substring(16, 27);

        _tubepress_swap_embedded(galleryId, videoId, embeddedName);
        _tubepress_call_player_js(galleryId, videoId, embeddedName, playerName);
    });
}

/**
 * This function is very carefully constructed to work with both IE 7-8 and FF.
 * Modify at your own risk!!
 *
 * @param galleryId    The unique gallery ID containing the embedded object
 *                      to swap
 * @param videoId      The "new" YouTube video ID
 * @param embeddedName Longtail, YouTube, etc
 * @return void
 */
function _tubepress_swap_embedded(galleryId, videoId, embeddedName) {

	var wrapperId = "#tubepress_embedded_object_" + galleryId;
    var wrapper = jQuery(wrapperId);
    if (wrapper.html() != "") {

    	/* grab the matcher for the embedded player */
    	var matcher = window["tubepress_" + embeddedName + "_matcher"]();
    	var paramName = window["tubepress_" + embeddedName + "_param"]();
    	var obj = jQuery(wrapperId + " > object");
    	var oldVideoId = obj.children("param[name='" + paramName + "']").attr("value").match(matcher)[1];

    	/* save the params but remove them from the DOM for now */
    	var params = obj.children("param");
    	params.remove();

    	/* replace the video ID inside the object tag */
    	var newHtml = wrapper.html().replace(oldVideoId, videoId);

    	/* chop off the closing </object> */
    	newHtml = newHtml.substring(0, newHtml.length - 9);

    	/* now add back the params, but this time with the new video ID */
    	params.each(function() {
        	newHtml += '<param name="' + this.name + '" value="' + this.value.replace(oldVideoId, videoId) + '" />';
        });

    	/* re-close the object */
    	newHtml += '</object>';

    	/* add it back in */
    	wrapper.html(newHtml);
    }
}

function _tubepress_call_player_js(galleryId, videoId, embeddedName, playerName) {
    var playerFunctionName = "tubepress_" + playerName + "_player";
    window[playerFunctionName](galleryId, videoId);
}

function tubepress_load_players(baseUrl) {
	var playerNames = _tubepress_rel_parser(2);
    for(var i = 0; i < playerNames.length; i++) {
    	var name = playerNames[i];
        jQuery.getScript(baseUrl + "/ui/players/" + name + "/" + name + ".js",
        	_tubepress_player_loaded(name, baseUrl) , true);
    }
}

function _tubepress_player_loaded(playerName, baseUrl) {
	var funcName = 'tubepress_' + playerName + '_player_init';
	var f = function() { window[funcName](baseUrl); }
	_tubepress_call_when_true(function() { return typeof window[funcName] == 'function'; }, f);
}

function tubepress_load_embedded_js(baseUrl) {
    var embeddedNames = _tubepress_rel_parser(1);
    for(var i = 0; i < embeddedNames.length; i++) {
        jQuery.getScript(baseUrl + "/ui/embedded/" + embeddedNames[i] + "/" + embeddedNames[i] + ".js", function() {}, true);
    }
}

/**
 * Utility function to do some DOM parsing for other functions here
 * @param index
 * @return
 */
function _tubepress_rel_parser(index) {
    var returnValue = [];
    jQuery("a[rel^='tubepress_']").each( function() {
        var thisName = jQuery(this).attr("rel").split("_")[index];
        if (jQuery.inArray(thisName, returnValue) == -1) {
            returnValue.push(thisName);
        }
    });
    return returnValue;
}

/**
 * Waits until the given test is true (tests every .4 seconds),
 * and then executes the given callback.
 * @param test
 * @param callback
 * @return
 */
function _tubepress_call_when_true(test, callback) {
	if (!test()) {
		setTimeout(function() {_tubepress_call_when_true(test, callback);}, 400);
		return;
	}
	callback();
}

/**
 * Convenience method to wait for a script to load, then call some function
 * from that script.
 * @param scriptPath
 * @param test
 * @param callback
 * @return
 */
function _tubepress_get_wait_call(scriptPath, test, callback) {
	jQuery.getScript(scriptPath, function() {
		_tubepress_call_when_true(test, callback);
    }, true);
}
<commit_msg>Adding some comments to tubepress.js. Helping YUI compressor by reducing 'var' statements.<commit_after>jQuery.getScript = function(url, callback, cache) {
    jQuery.ajax({ type: "GET", url: url, success: callback, dataType: "script", cache: cache });
};

function tubepress_init(baseUrl) {
	tubepress_load_embedded_js(baseUrl);
    tubepress_load_players(baseUrl);
    tubepress_attach_listeners();
}

function tubepress_attach_listeners()
{
    /* any link with an id that starts with "tubepress_" */
	jQuery("a[id^='tubepress_']").click(function () {
		var rel_split    = jQuery(this).attr("rel").split("_"),
            galleryId    = rel_split[3],
		    playerName   = rel_split[2],
		    embeddedName = rel_split[1],
            videoId = jQuery(this).attr("id").substring(16, 27);

        /* swap the gallery's embedded object */
        _tubepress_swap_embedded(galleryId, videoId, embeddedName);

        /* then call the player to load up / play the video */
        _tubepress_call_player_js(galleryId, videoId, embeddedName, playerName);
    });
}

/**
 * This function is very carefully constructed to work with both IE 7-8 and FF.
 * Modify at your own risk!!
 *
 * @param galleryId    The unique gallery ID containing the embedded object
 *                      to swap
 * @param videoId      The "new" YouTube video ID
 * @param embeddedName Longtail, YouTube, etc
 * @return void
 */
function _tubepress_swap_embedded(galleryId, videoId, embeddedName) {

	var wrapperId = "#tubepress_embedded_object_" + galleryId,
        wrapper = jQuery(wrapperId);

    /* if we can't find the embedded object, just bail */
    if (wrapper.length == 0) {
        return;
    }

    /* grab the matcher for the embedded player */
    var matcher    = window["tubepress_" + embeddedName + "_matcher"](),
        paramName  = window["tubepress_" + embeddedName + "_param"](),
        obj        = jQuery(wrapperId + " > object"),
        oldVideoId = obj.children("param[name='" + paramName + "']").attr("value").match(matcher)[1];

    /* save the params but remove them from the DOM for now */
   	var params = obj.children("param");
   	params.remove();

   	/* replace the video ID inside the object tag */
   	var newHtml = wrapper.html().replace(oldVideoId, videoId);

   	/* chop off the closing </object> */
   	newHtml = newHtml.substring(0, newHtml.length - 9);

   	/* now add back the params, but this time with the new video ID */
   	params.each(function() {
       	newHtml += '<param name="' + this.name + '" value="' + this.value.replace(oldVideoId, videoId) + '" />';
    });

   	/* re-close the object */
   	newHtml += '</object>';

   	/* add it back in */
   	wrapper.html(newHtml);

    /* now pat yourself on the back */
}

function _tubepress_call_player_js(galleryId, videoId, embeddedName, playerName) {
    var playerFunctionName = "tubepress_" + playerName + "_player";
    window[playerFunctionName](galleryId, videoId);
}

function tubepress_load_players(baseUrl) {
	var playerNames = _tubepress_rel_parser(2), i;
    for(i = 0; i < playerNames.length; i++) {
    	var name = playerNames[i];
        jQuery.getScript(baseUrl + "/ui/players/" + name + "/" + name + ".js",
        	_tubepress_player_loaded(name, baseUrl) , true);
    }
}

function _tubepress_player_loaded(playerName, baseUrl) {
	var funcName = 'tubepress_' + playerName + '_player_init',
        f = function() { window[funcName](baseUrl); }
	_tubepress_call_when_true(function() { return typeof window[funcName] == 'function'; }, f);
}

function tubepress_load_embedded_js(baseUrl) {
    var embeddedNames = _tubepress_rel_parser(1), i;
    for(i = 0; i < embeddedNames.length; i++) {
        jQuery.getScript(baseUrl + "/ui/embedded/" + embeddedNames[i] + "/" + embeddedNames[i] + ".js", function() {}, true);
    }
}

/**
 * Utility function to do some DOM parsing for other functions here
 * @param index
 * @return
 */
function _tubepress_rel_parser(index) {
    var returnValue = [];
    jQuery("a[rel^='tubepress_']").each( function() {
        var thisName = jQuery(this).attr("rel").split("_")[index];
        if (jQuery.inArray(thisName, returnValue) == -1) {
            returnValue.push(thisName);
        }
    });
    return returnValue;
}

/**
 * Waits until the given test is true (tests every .4 seconds),
 * and then executes the given callback.
 * @param test
 * @param callback
 * @return
 */
function _tubepress_call_when_true(test, callback) {
    /* if the test doesn't pass, try again in .4 seconds */
    if (!test()) {
		setTimeout(function() {_tubepress_call_when_true(test, callback);}, 400);
		return;
	}
    /* the test passed, so call the callback */
	callback();
}

/**
 * Convenience method to wait for a script to load, then call some function
 * from that script.
 * @param scriptPath
 * @param test
 * @param callback
 * @return
 */
function _tubepress_get_wait_call(scriptPath, test, callback) {
	jQuery.getScript(scriptPath, function() {
		_tubepress_call_when_true(test, callback);
    }, true);
}
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs'),
  https = require('https'),
  util = require('util');

var semver = require('semver'),
  tarball = require('tarball-extract');

var REGISTRY_ROOT = 'https://registry.npmjs.org/';

var VERBOSE = 1;

function _log(msg) {
  if (VERBOSE) {
    console.log(msg);
  }
}

/**
 * Represent a package version
 */
var Version = function(name, version, dependencies) {
  this.name = name;
  this.version = version;
  this.dependencies = dependencies;
}

Version.prototype.get_dependencies = function(callback, errback, _currents, _for) {
  var self = this;
  var result = _currents;

  if (self.name in result) {
    if (result[self.name].indexOf(self.version) >= 0) {
      callback(result);
      return
    }
    result[self.name].push(self.version)
  }
  else {
    result[self.name] = [self.version];
  }

  var dependencies = [];
  Object.keys(self.dependencies).forEach(function(depname) {
    var depver = self.dependencies[depname];
    if (depname in Package.instances) {
      var pkg = Package.instances[depname];
      pkg.push_required_version(depver);
      dependencies.push(pkg);
    }
    else {
      dependencies.push(new Package(depname, depver))
    }
  });

  function build_dependency(dependencies) {
    if (dependencies.length > 0) {
      var pkg = dependencies.pop();
      if (_for) {
        var __for = self.name + '==' + self.version + ' <- ' + _for;
      }
      else {
        var __for = self.name + '==' + self.version;
      }
      pkg._get_dependencies(
        function(dep_result) {
          Object.keys(dep_result).forEach(function(key) {
            if (key in result) {
              dep_result[key].forEach(function(version) {
                if (result[key].indexOf(version) < 0) {
                  result[key].push(version);
                }
              });
            }
            else {
              result[key] = dep_result[key];
            }
          });
          build_dependency(dependencies);
        },
        errback,
        result,
        __for);
    }
    else {
      //if (result.indexOf((self.name + '==' + self.version)) < 0) {
      //  result.push(self.name + '==' + self.version);
      //}
      callback(result);
    }
  }
  build_dependency(dependencies);
}

/**
 * Represent a package
 */
var Package = function(name, required_version) {
  this.name = name;
  required_version = required_version || '*';
  this.required_versions = [required_version];
  this.versions = [];
  Package.instances[this.name] = this;
}

Package.metadatas = {}
Package.instances = {}

Package.prototype.push_required_version = function(version) {
  if (this.required_versions.indexOf(version) < 0) {
    this.required_versions.push(version);
  }
}

Package.prototype.get_metadata = function(callback, errback) {

  _log('GET ' + REGISTRY_ROOT + this.name + '/');
  https.get(REGISTRY_ROOT + this.name + '/', function(res) {
    var response = '';
    res.on('data', function (chunk) {
      response += chunk;
    });

    res.on('end', function () {
      // console.log('Got response: ' + res.statusCode);
      var json = null;
      try {
        json = JSON.parse(response);
      }
      catch (exc) {
        errback(exc);
      }
      if (json  !== null) {
        callback(json);
      }

    });

  }).on('error', function(e) {
    _log('Got error: ' + e.message);
    throw Error('Package {} deleted from {}'.format(this.name, REGISTRY_ROOT))
  });

}

Package.prototype.build_versions = function() {
  var self = this;
  var metadata = Package.metadatas[this.name];
  var versions = [];

  Object.keys(metadata['versions']).forEach(function(version) {
    self.required_versions.forEach(function(required_version) {
      if (semver.satisfies(version, required_version)) {
        var ver_data = metadata['versions'][version];
        versions.push([version, ver_data['dependencies'] || {}]);
      }
    });
  });

  if (versions.length == 0) {
    throw Error(util.format('%s has no valid version', this.name));
  }

  // newest version first
  versions.sort(function(el0, el1) { return semver.compare(el1[0], el0[0]) });
  var self = this;
  versions.forEach(function(version) {
    self.versions.push(new Version(self.name, version[0], version[1]));
  });
}

Package.prototype._get_dependencies = function(callback, errback, _currents, _for) {

  var self = this;

  _log(util.format('\n\nLoading dependencies of %s for %s', self.name, _for));

  var on_version_loaded = function(result) {
    // _log(util.format('Dependencies of %s are loaded: %s', self.name));
    callback(result);
  }

  var build_with_next_version = function(versions) {
    var version = versions.shift();
    if (version) {
      _log(util.format('Build %s with %s',
                  version.name, version.version));
      version.get_dependencies(on_version_loaded,
                               function (error) {
                                 // test errors
                                 build_with_next_version(versions);
                               },
                               _currents || {},
                               _for || '');
    }
    else {
      throw Error(util.format('No available version for %s %s',
                  self.name, self.required_version));
    }
  }

  var on_metadata = function() {
    self.build_versions();
    // self.versions is initialized with the on_metadata
    build_with_next_version(self.versions.slice());
  }

  if (self.name in Package.metadatas) {
    on_metadata();
  }
  else {
    this.get_metadata(
      function(metadata) {
        Package.metadatas[self.name] = metadata;
        on_metadata();
      },
      errback);
  }
}

Package.prototype.get_dependencies = function(callback, errback) {
  var self = this;

  self._get_dependencies(
      function(result) {
        var cb_result = {};
        var conflicts = {}
        Object.keys(result).forEach(function(key) {

          var no_conflict = true;
          var versions = result[key];
          for ( var i = 0; i < versions.length; i++ ) {
            var version = versions[i];
            Package.instances[key].required_versions.forEach(function(required_version) {
              no_conflict = no_conflict && semver.satisfies(version, required_version);
            })
            if (no_conflict) {
              break;
            }
          }
          if (no_conflict) {
            cb_result[key] = version;
          }
          else {
            conflicts[key] = Package.instances[key].required_versions;
          }
        })
        if (Object.keys(conflicts) == 0) {
          callback(cb_result);
        }
        else {
          Object.keys(conflicts).forEach(function(key) {
            console.log(util.format('Conflict with %s==%s: %s', key,
                result[key], conflicts[key]))
          });
          errback(Error('Conflicts not resolved'));
        }
      },
      errback, {}, self.name);
}

Package.install = function(name, version, callback, errback) {
  _log(util.format('Installing %s==%s', name, version));

  var metadata = Package.metadatas[name]['versions'][version];
  var url = metadata['dist']['tarball'].replace(/^http:/, 'https:')

  var local_tarball = util.format('./node_modules/%s-%s.tar.gz', name, version);

  var extract_tarball = function() {
    // XXX does not check the SHA1 SUM metadata['dist']['shasum']!!!
    // tarball and wget lib does not implement that kind of check
    tarball.extractTarballDownload(url,
        local_tarball,
        util.format('./node_modules/%s-%s', name, version),
        {},
        function(err, result) {
          fs.unlink(local_tarball, function (err2) {
            if (err2) {
              console.log(util.format('Problem while deleting file %s', local_tarball));
            }
            fs.rename(
                util.format('./node_modules/%s-%s/package', name, version),
                util.format('./node_modules/%s', name),
                function() {
                  fs.rmdir(util.format('./node_modules/%s-%s', name, version),
                    function() {
                      if (err) {
                        errback(err);
                      }
                      else {
                        callback();
                      }
                    });
                });
          });
        });
  }

  fs.exists('./node_modules', function(exists) {
    if (exists) {
      extract_tarball();
    }
    else {
      fs.mkdir('./node_modules', '0750', extract_tarball);
    }
  })

}

module.exports = {'Package': Package};
<commit_msg>Fix indentation<commit_after>'use strict';

var fs = require('fs'),
  https = require('https'),
  util = require('util');

var semver = require('semver'),
  tarball = require('tarball-extract');

var REGISTRY_ROOT = 'https://registry.npmjs.org/';

var VERBOSE = 1;

function _log(msg) {
  if (VERBOSE) {
    console.log(msg);
  }
}

/**
 * Represent a package version
 */
var Version = function(name, version, dependencies) {
  this.name = name;
  this.version = version;
  this.dependencies = dependencies;
}

Version.prototype.get_dependencies = function(callback, errback, _currents, _for) {
  var self = this;
  var result = _currents;

  if (self.name in result) {
    if (result[self.name].indexOf(self.version) >= 0) {
      callback(result);
      return
    }
    result[self.name].push(self.version)
  }
  else {
    result[self.name] = [self.version];
  }

  var dependencies = [];
  Object.keys(self.dependencies).forEach(function(depname) {
    var depver = self.dependencies[depname];
    if (depname in Package.instances) {
      var pkg = Package.instances[depname];
      pkg.push_required_version(depver);
      dependencies.push(pkg);
    }
    else {
      dependencies.push(new Package(depname, depver))
    }
  });

  function build_dependency(dependencies) {
    if (dependencies.length > 0) {
      var pkg = dependencies.pop();
      if (_for) {
        var __for = self.name + '==' + self.version + ' <- ' + _for;
      }
      else {
        var __for = self.name + '==' + self.version;
      }
      pkg._get_dependencies(
        function(dep_result) {
          Object.keys(dep_result).forEach(function(key) {
            if (key in result) {
              dep_result[key].forEach(function(version) {
                if (result[key].indexOf(version) < 0) {
                  result[key].push(version);
                }
              });
            }
            else {
              result[key] = dep_result[key];
            }
          });
          build_dependency(dependencies);
        },
        errback,
        result,
        __for);
    }
    else {
      //if (result.indexOf((self.name + '==' + self.version)) < 0) {
      //  result.push(self.name + '==' + self.version);
      //}
      callback(result);
    }
  }
  build_dependency(dependencies);
}

/**
 * Represent a package
 */
var Package = function(name, required_version) {
  this.name = name;
  required_version = required_version || '*';
  this.required_versions = [required_version];
  this.versions = [];
  Package.instances[this.name] = this;
}

Package.metadatas = {}
Package.instances = {}

Package.prototype.push_required_version = function(version) {
  if (this.required_versions.indexOf(version) < 0) {
    this.required_versions.push(version);
  }
}

Package.prototype.get_metadata = function(callback, errback) {

  _log('GET ' + REGISTRY_ROOT + this.name + '/');
  https.get(REGISTRY_ROOT + this.name + '/', function(res) {
    var response = '';
    res.on('data', function (chunk) {
      response += chunk;
    });

    res.on('end', function () {
      // console.log('Got response: ' + res.statusCode);
      var json = null;
      try {
        json = JSON.parse(response);
      }
      catch (exc) {
        errback(exc);
      }
      if (json  !== null) {
        callback(json);
      }

    });

  }).on('error', function(e) {
    _log('Got error: ' + e.message);
    throw Error('Package {} deleted from {}'.format(this.name, REGISTRY_ROOT))
  });

}

Package.prototype.build_versions = function() {
  var self = this;
  var metadata = Package.metadatas[this.name];
  var versions = [];

  Object.keys(metadata['versions']).forEach(function(version) {
    self.required_versions.forEach(function(required_version) {
      if (semver.satisfies(version, required_version)) {
        var ver_data = metadata['versions'][version];
        versions.push([version, ver_data['dependencies'] || {}]);
      }
    });
  });

  if (versions.length == 0) {
    throw Error(util.format('%s has no valid version', this.name));
  }

  // newest version first
  versions.sort(function(el0, el1) { return semver.compare(el1[0], el0[0]) });
  var self = this;
  versions.forEach(function(version) {
    self.versions.push(new Version(self.name, version[0], version[1]));
  });
}

Package.prototype._get_dependencies = function(callback, errback, _currents, _for) {

  var self = this;

  _log(util.format('\n\nLoading dependencies of %s for %s', self.name, _for));

  var on_version_loaded = function(result) {
    // _log(util.format('Dependencies of %s are loaded: %s', self.name));
    callback(result);
  }

  var build_with_next_version = function(versions) {
    var version = versions.shift();
    if (version) {
      _log(util.format('Build %s with %s',
                  version.name, version.version));
      version.get_dependencies(on_version_loaded,
                               function (error) {
                                 // test errors
                                 build_with_next_version(versions);
                               },
                               _currents || {},
                               _for || '');
    }
    else {
      throw Error(util.format('No available version for %s %s',
                  self.name, self.required_version));
    }
  }

  var on_metadata = function() {
    self.build_versions();
    // self.versions is initialized with the on_metadata
    build_with_next_version(self.versions.slice());
  }

  if (self.name in Package.metadatas) {
    on_metadata();
  }
  else {
    this.get_metadata(
      function(metadata) {
        Package.metadatas[self.name] = metadata;
        on_metadata();
      },
      errback);
  }
}

Package.prototype.get_dependencies = function(callback, errback) {
  var self = this;

  self._get_dependencies(
      function(result) {
        var cb_result = {};
        var conflicts = {}
        Object.keys(result).forEach(function(key) {

          var no_conflict = true;
          var versions = result[key];
          for ( var i = 0; i < versions.length; i++ ) {
            var version = versions[i];
            Package.instances[key].required_versions.forEach(function(required_version) {
              no_conflict = no_conflict && semver.satisfies(version, required_version);
            })
            if (no_conflict) {
              break;
            }
          }
          if (no_conflict) {
            cb_result[key] = version;
          }
          else {
            conflicts[key] = Package.instances[key].required_versions;
          }
        })
        if (Object.keys(conflicts) == 0) {
          callback(cb_result);
        }
        else {
          Object.keys(conflicts).forEach(function(key) {
            console.log(util.format('Conflict with %s==%s: %s', key,
                result[key], conflicts[key]))
          });
          errback(Error('Conflicts not resolved'));
        }
      },
      errback, {}, self.name);
}

Package.install = function(name, version, callback, errback) {
  _log(util.format('Installing %s==%s', name, version));

  var metadata = Package.metadatas[name]['versions'][version];
  var url = metadata['dist']['tarball'].replace(/^http:/, 'https:')

  var local_tarball = util.format('./node_modules/%s-%s.tar.gz', name, version);

  var extract_tarball = function() {
    // XXX does not check the SHA1 SUM metadata['dist']['shasum']!!!
    // tarball and wget lib does not implement that kind of check
    tarball.extractTarballDownload(url,
      local_tarball,
      util.format('./node_modules/%s-%s', name, version),
      {},
      function(err, result) {
        fs.unlink(local_tarball, function (err2) {
          if (err2) {
            console.log(util.format('Problem while deleting file %s', local_tarball));
          }
          fs.rename(
            util.format('./node_modules/%s-%s/package', name, version),
            util.format('./node_modules/%s', name),
            function() {
              fs.rmdir(util.format('./node_modules/%s-%s', name, version),
                    function() {
                      if (err) {
                        errback(err);
                      }
                      else {
                        callback();
                      }
                });
            });
        });
      });
  }

  fs.exists('./node_modules', function(exists) {
    if (exists) {
      extract_tarball();
    }
    else {
      fs.mkdir('./node_modules', '0750', extract_tarball);
    }
  })

}

module.exports = {'Package': Package};
<|endoftext|>


<commit_before>'use strict';

angular.module('its110App')
  .directive('questionInstructions', function () {
    return {
      templateUrl: 'app/lessons/questionInstructions/question-instructions.html',
      restrict: 'EA',
      link: function (scope, element, attrs) {
      }
    };
  });
<commit_msg>WebPack question instructions<commit_after>import angular from 'angular';

import template from 'question-instructions.html';
import 'questionInstructions.css;'

angular.module('bitfit.lessons.instructions')
  .directive('questionInstructions', function () {
    return {
      template: template,
      restrict: 'EA',
      link: function (scope, element, attrs) {
      }
    };
  });
<|endoftext|>


<commit_before>import forEach from './forEach'

export default function sendRequest(params, cb) {
  return new Promise(function(resolve, reject) {
    var method = (params.method || 'GET').toUpperCase()
    var url = params.url
    if (['GET', 'POST', 'PUT', 'DELETE'].indexOf(method) < 0) {
      throw new Error("Parameter 'method' must be 'GET', 'POST', 'PUT', or 'DELETE'.")
    }
    if (!url) {
      throw new Error("Parameter 'url' is required.")
    }
    var xmlhttp = new XMLHttpRequest()
    xmlhttp.onreadystatechange = function() {
      // TODO: we could support more states here to give feedback
      // e.g. about progress of an upload
      if (xmlhttp.readyState === 4) return _done()
    }
    xmlhttp.open(method, url, true)
    if (params.header) {
      forEach(params.header, function(val, key) {
        xmlhttp.setRequestHeader(key, val)
      })
    }
    if (params.data) {
      xmlhttp.send(JSON.stringify(params.data))
    } else {
      xmlhttp.send()
    }

    function _done() {
      if (xmlhttp.status === 200) {
        var response = xmlhttp.responseText
        if (cb) cb(null, response)
        resolve(response)
      } else {
        console.error(xmlhttp.statusText)
        if (cb) cb(xmlhttp.status)
        reject(xmlhttp.statusText, xmlhttp.status)
      }
    }
  })
}

<commit_msg>Add option for sendRequest helper to send form data.<commit_after>import forEach from './forEach'

export default function sendRequest(params, cb) {
  return new Promise(function(resolve, reject) {
    var method = (params.method || 'GET').toUpperCase()
    var url = params.url
    if (['GET', 'POST', 'PUT', 'DELETE'].indexOf(method) < 0) {
      throw new Error("Parameter 'method' must be 'GET', 'POST', 'PUT', or 'DELETE'.")
    }
    if (!url) {
      throw new Error("Parameter 'url' is required.")
    }
    var xmlhttp = new XMLHttpRequest()
    xmlhttp.onreadystatechange = function() {
      // TODO: we could support more states here to give feedback
      // e.g. about progress of an upload
      if (xmlhttp.readyState === 4) return _done()
    }
    xmlhttp.open(method, url, true)
    if (params.header) {
      forEach(params.header, function(val, key) {
        xmlhttp.setRequestHeader(key, val)
      })
    }
    if (params.data instanceof FormData) {
      xmlhttp.send(params.data)
    } else if (params.data) {
      xmlhttp.send(JSON.stringify(params.data))
    } else {
      xmlhttp.send()
    }

    function _done() {
      if (xmlhttp.status === 200) {
        var response = xmlhttp.responseText
        if (cb) cb(null, response)
        resolve(response)
      } else {
        console.error(xmlhttp.statusText)
        if (cb) cb(xmlhttp.status)
        reject(xmlhttp.statusText, xmlhttp.status)
      }
    }
  })
}

<|endoftext|>


<commit_before>define(["jquery", "bootstrap", "data-table"], function($){
    $(function(){

        $('#manus-grid').DataTable( {
            "processing": true,
            "serverSide": true,
            "order": [[ 0, "desc" ]],
            "ajax":{
                url : site_url + 'tlhp/manus/get_all_user', // json data
                type: "post",
                error: function(){  // error handling
                    $(".data-grid-error").html("");
                    $("#data-grid").append('

No data found in the server

');
                    $("#data-grid_processing").css("display","none");
                }
            },
            "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
                $('td:eq(1)', nRow).html('' + aData[1] + '');
                return nRow;
            },
            "aoColumnDefs": [{
                    "aTargets": [7],
                    mRender: function ( data, type, row ) {
                            //return '
 Edit    Delete
';
                            return '
 Edit    Delete
';

                    }
            }]
        });
    });

    $('.user-modal').on('click', function(e){
        $('#userModal').modal('show');
        return false;
    });
 });<commit_msg>bug fixing edit user<commit_after>define(["jquery", "bootstrap", "data-table"], function($){

	window.userEdit = function userEdit(id) {
    	var body = site_url + 'tlhp/manus/update/'+ id;
    	$('#userModal').modal('show').find('.modal-body').load(body);
    }

    $(function(){
        $('#manus-grid').DataTable( {
            "processing": true,
            "serverSide": true,
            "order": [[ 0, "desc" ]],
            "ajax":{
                url : site_url + 'tlhp/manus/get_all_user', // json data
                type: "post",
                error: function(){  // error handling
                    $(".data-grid-error").html("");
                    $("#data-grid").append('

No data found in the server

');
                    $("#data-grid_processing").css("display","none");
                }
            },
            "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
                $('td:eq(1)', nRow).html('' + aData[1] + '');
                return nRow;
            },
            "aoColumnDefs": [{
                    "aTargets": [7],
                    mRender: function ( data, type, row ) {
                            //return '
 Edit    Delete
';
                            return '
 Edit    Delete
';

                    }
            }]
        });
    });

    $('.user-modal').on('click', function(e){
        $('#userModal').modal('show');
        return false;
    });

 });<|endoftext|>


<commit_before>var path = require("path");
var createPic = ((info, cb) => {
    try {
        let gd = require('node-gd');
        let f = path.join(__dirname, '../fonts/RegencieLight.ttf');
        let c = {
            black: 0x000000, white: 0xffffff, red: 0xff0000, green: 0x00ff00,
            blue: 0x0000ff, gray: 0xc6c6c6, dgray: 0x555555, lgray: 0xdcdcdc
        };
        console.log(path.join(__dirname, './assets/template.png'));
        let t = gd.createFromPng(path.join(__dirname, './assets/template.png'));
        let a = gd.createFromJpeg(path.join(__dirname, './assets/hide.jpg'));
        a.copyResampled(t, 21, 22, 0, 0, 76, 76, a.width, a.height).destroy();
// Name
        t.stringFT(c.dgray, f, 14, 0, 122, 33, info.user.username);
// EXP
        let cexp = info.xp;
        let tnexp = info.needed;
        let exp = Math.floor(cexp / tnexp * 159) + 126;
        t.filledRectangle(126, 43, exp, 55, c.gray);
        t.stringFT(c.dgray, f, 8, 0, 189, 54, `${cexp}/${tnexp}`);

// Level
        let lv = info.level.toString();
        t.stringFT(c.dgray, f, 14, 0, 130, 80, `LEVEL`);
        t.stringFT(c.dgray, f, 14, 0, 155 - (lv.length * lv.length), 100, `${lv}`);

// Rank
        let rn = info.totalXp.toString();
        t.stringFT(c.dgray, f, 14, 0, 230, 80, `RANK`);
        t.stringFT(c.dgray, f, 14, 0, 252 - (rn.length * rn.length), 100, `${rn}`);
        t.savePng(path.join(__dirname, '../temp/output.png'), 0, function (err) {
            if (err) return cb(err);
            cb(null, '../temp/output.png');
        });
        t.destroy()
    } catch (e) {
        console.log(e);
    }
});
module.exports = createPic;
<commit_msg>sffdsdfsdf<commit_after>var path = require("path");
var request = require('request');
var createPic = ((info, cb) => {
    try {
        let gd = require('node-gd');
        let f = path.join(__dirname, '../fonts/RegencieLight.ttf');
        let c = {
            black: 0x000000, white: 0xffffff, red: 0xff0000, green: 0x00ff00,
            blue: 0x0000ff, gray: 0xc6c6c6, dgray: 0x555555, lgray: 0xdcdcdc
        };
        console.log(path.join(__dirname, './assets/template.png'));
        let t = gd.createFromPng(path.join(__dirname, './assets/template.png'));
        let a = gd.createFromJpegPtr(request.get(info.user.avatarURL));
        a.copyResampled(t, 21, 22, 0, 0, 76, 76, a.width, a.height).destroy();
// Name
        t.stringFT(c.dgray, f, 14, 0, 122, 33, info.user.username);
// EXP
        let cexp = info.xp;
        let tnexp = info.needed;
        let exp = Math.floor(cexp / tnexp * 159) + 126;
        t.filledRectangle(126, 43, exp, 55, c.gray);
        t.stringFT(c.dgray, f, 8, 0, 189, 54, `${cexp}/${tnexp}`);

// Level
        let lv = info.level.toString();
        t.stringFT(c.dgray, f, 14, 0, 130, 80, `LEVEL`);
        t.stringFT(c.dgray, f, 14, 0, 155 - (lv.length * lv.length), 100, `${lv}`);

// Rank
        let rn = info.totalXp.toString();
        t.stringFT(c.dgray, f, 14, 0, 230, 80, `XP`);
        t.stringFT(c.dgray, f, 14, 0, 252 - (rn.length * rn.length), 100, `${rn}`);
        t.savePng(path.join(__dirname, '../temp/output.png'), 0, function (err) {
            if (err) return cb(err);
            cb(null, '../temp/output.png');
        });
        t.destroy()
    } catch (e) {
        console.log(e);
    }
});
module.exports = createPic;
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs'),
request = require('request'),
_ = require('lodash'),
loginRoutePath = null,
additionalArgs = null,
authCheckFnc = null,
authCookieName = null;

function objToQueryString(obj) {
  var query = '?';
  for(let prop in obj) {
    query += prop + '=' + obj[prop].toString() + '&';
  }
  return query;
}

function fixRequirePath(path) {
  return '/' + path.replace('../', '').replace('./', '').replace('\\..', '').replace('\\.', '');
}

function findControllerMethod(fncName, allControllers) {
  if(fncName) {
    for(let cPath in allControllers) {
      let c = allControllers[cPath];
      for(let cFnc in c) {
        if(cFnc.toLowerCase() == fncName.toLowerCase()) {
          return c[cFnc];
        }
      }
    }
  }
  return null;
}

function bindConfig(server,config, url,  loginRoutePath, allControllers){
  debugger
  if(!config) {
    throw new Error('No config object found for route "' + fullPath + '".');
  }
  if(!config.actionMethod && !config.redirectTo) {
    throw new Error('No actionMethod name found on the route config for "' + fullPath + '"');
  }
  let controllerMethod = findControllerMethod(config.actionMethod, allControllers);
  if(!controllerMethod && !config.redirectTo) {
    throw new Error('No controller actionMethod found for "' + fullPath + '".');
  }
  if(additionalArgs.verbose) {
    console.log('Binding "' + url + '" to "' + config.verb.toUpperCase() + '".');
    if(config.headers) {
      console.log('Will set additional headers: ');
      console.log(JSON.stringify(config.headers));
    }
    if(config.requiresAuth) {
      console.log('"' + url + '" requires authorization.');
    }
    if(config.redirectTo) {
      console.log('"' + url + '" will redirect to "' + config.redirectTo + '", and the URL will ' + (config.keepOldURL ? ('remain "' + url + '"') : ('will change to "' + config.redirectTo + '"')));
    }
  }

  switch(config.verb.toLowerCase()) {
    case 'post':
    server.post(url, (req, res) => {
      if(config.requiresAuth && ((authCookieName && req.cookies && !req.cookies[authCookieName])) || !authCheckFnc(req, res)) {
        res.status(401).end();
      }
      else {
        res.set(config.headers || {});
        controllerMethod(req, res);
      }
    });
    break;
    case 'put':
    server.put(url, (req, res) => {
      if(config.requiresAuth && ((authCookieName && req.cookies && !req.cookies[authCookieName])) || !authCheckFnc(req, res)) {
        res.status(401).end();
      }
      else {
        res.set(config.headers || {});
        controllerMethod(req, res);
      }
    });
    break;
    case 'delete':
    server.delete(url, (req, res) => {
      if(config.requiresAuth && ((authCookieName && req.cookies && !req.cookies[authCookieName])) || !authCheckFnc(req, res)) {
        res.status(401).end();
      }
      else {
        res.set(config.headers || {});
        controllerMethod(req, res);
      }
    });
    break;
    case 'options':
    server.options(url, (req, res) => {
      if(config.requiresAuth && ((authCookieName && req.cookies && !req.cookies[authCookieName])) || !authCheckFnc(req, res)) {
        res.status(401).end();
      }
      else {
        res.set(config.headers || {});
        controllerMethod(req, res);
      }
    });
    break;
    case 'get':
    default:
    server.get(url, (req, res) => {
      if(config.redirectTo) {
        if(config.keepOldURL) {
          // Will request the page manually here via request library
          // and pipe it through as if it were coming from this request instance
          request({
            uri: req.protocol + '://' + req.hostname + ':' + (additionalArgs.serverPort || 80) + config.redirectTo + objToQueryString(req.query),
            method: 'GET',
            headers: req.headers
          }, (err, response) => {
            res.set(config.headers || {});
            if(err) {
              res.send(err);
            }
            else {
              res.send(response.body);
            }
          });
        }
        else {
          res.redirect(config.redirectTo + objToQueryString(req.query));
        }
      }
      else if(config.requiresAuth && (!authCheckFnc(req, res) || (authCookieName && req.cookies && !req.cookies[authCookieName]))) {
        // The user-provided authCheckFnc returns false, or the authCookie doesn't exist (if cookieParser() middleware is being used)
        if(loginRoutePath) {
          res.redirect(loginRoutePath + objToQueryString(req.query) + 'returnUrl=' + encodeURIComponent(req.url));
        }
        else {
          res.status(401).end();
        }
      }
      else {
        res.set(config.headers || {});
        controllerMethod(req, res);
      }
    });
    break;
  }
}

function bindRoutes(server, routesConfig, allControllers, args) {
  additionalArgs = args || {};
  authCheckFnc = additionalArgs.authCheckFnc || function () { return true; };
  authCookieName = additionalArgs.authCookieName || null;
  var loginRoutePath =null
  additionalArgs.verbose = additionalArgs.verbose || false;
  for(let r in routesConfig)     {
    let url = r;
    let config = routesConfig[r];
    if(_.isArray(config)){
      for (let c of config) {
        if(config.isLogin && !loginRoutePath) {
          // You can only have one login route per app. Does it make sense to have more than one? I don't think
          loginRoutePath = url;
        }
        bindConfig(server,c, url, loginRoutePath, allControllers)
        }
      }else{
        if(config.isLogin && !loginRoutePath) {
          // You can only have one login route per app. Does it make sense to have more than one? I don't think
          loginRoutePath = url;
        }
        bindConfig(server,config, url,loginRoutePath, allControllers)
      }

    }
  }

  module.exports = function (server, pathToRouteConfig, pathToControllers, args) {
    pathToRouteConfig = fixRequirePath(pathToRouteConfig);
    pathToControllers = fixRequirePath(pathToControllers);
    if(!server) {
      throw new Error('Why did\'nt you give EasyPeasy an Express app?');
    }
    if(!pathToRouteConfig) {
      throw new Error('No path to route config.json provided. Look, the whole point of EasyPeasy was to, well, be easy peasy. I can\'nt do this without a route config!');
    }
    if(!pathToControllers) {
      throw new Error('Sorry, Holmes. You did\'nt tell me about any of your controllers, so how am I supposed to wire these routes up?');
    }
    var allControllers = {},
    routesConfig = require(process.cwd() + pathToRouteConfig);

    pathToControllers = process.cwd() + pathToControllers;
    var allControllerPaths = fs.readdirSync(pathToControllers);
    allControllerPaths.forEach((c) => {
      let pathToController = pathToControllers + '/' + c;
      let theController = require(pathToControllers + '/' + c);
      allControllers[pathToController] = theController;
    });
    bindRoutes(server, routesConfig, allControllers, args);
  };
<commit_msg>removing debugger<commit_after>'use strict';

var fs = require('fs'),
request = require('request'),
_ = require('lodash'),
loginRoutePath = null,
additionalArgs = null,
authCheckFnc = null,
authCookieName = null;

function objToQueryString(obj) {
  var query = '?';
  for(let prop in obj) {
    query += prop + '=' + obj[prop].toString() + '&';
  }
  return query;
}

function fixRequirePath(path) {
  return '/' + path.replace('../', '').replace('./', '').replace('\\..', '').replace('\\.', '');
}

function findControllerMethod(fncName, allControllers) {
  if(fncName) {
    for(let cPath in allControllers) {
      let c = allControllers[cPath];
      for(let cFnc in c) {
        if(cFnc.toLowerCase() == fncName.toLowerCase()) {
          return c[cFnc];
        }
      }
    }
  }
  return null;
}

function bindConfig(server,config, url,  loginRoutePath, allControllers){
  if(!config) {
    throw new Error('No config object found for route "' + fullPath + '".');
  }
  if(!config.actionMethod && !config.redirectTo) {
    throw new Error('No actionMethod name found on the route config for "' + fullPath + '"');
  }
  let controllerMethod = findControllerMethod(config.actionMethod, allControllers);
  if(!controllerMethod && !config.redirectTo) {
    throw new Error('No controller actionMethod found for "' + fullPath + '".');
  }
  if(additionalArgs.verbose) {
    console.log('Binding "' + url + '" to "' + config.verb.toUpperCase() + '".');
    if(config.headers) {
      console.log('Will set additional headers: ');
      console.log(JSON.stringify(config.headers));
    }
    if(config.requiresAuth) {
      console.log('"' + url + '" requires authorization.');
    }
    if(config.redirectTo) {
      console.log('"' + url + '" will redirect to "' + config.redirectTo + '", and the URL will ' + (config.keepOldURL ? ('remain "' + url + '"') : ('will change to "' + config.redirectTo + '"')));
    }
  }

  switch(config.verb.toLowerCase()) {
    case 'post':
    server.post(url, (req, res) => {
      if(config.requiresAuth && ((authCookieName && req.cookies && !req.cookies[authCookieName])) || !authCheckFnc(req, res)) {
        res.status(401).end();
      }
      else {
        res.set(config.headers || {});
        controllerMethod(req, res);
      }
    });
    break;
    case 'put':
    server.put(url, (req, res) => {
      if(config.requiresAuth && ((authCookieName && req.cookies && !req.cookies[authCookieName])) || !authCheckFnc(req, res)) {
        res.status(401).end();
      }
      else {
        res.set(config.headers || {});
        controllerMethod(req, res);
      }
    });
    break;
    case 'delete':
    server.delete(url, (req, res) => {
      if(config.requiresAuth && ((authCookieName && req.cookies && !req.cookies[authCookieName])) || !authCheckFnc(req, res)) {
        res.status(401).end();
      }
      else {
        res.set(config.headers || {});
        controllerMethod(req, res);
      }
    });
    break;
    case 'options':
    server.options(url, (req, res) => {
      if(config.requiresAuth && ((authCookieName && req.cookies && !req.cookies[authCookieName])) || !authCheckFnc(req, res)) {
        res.status(401).end();
      }
      else {
        res.set(config.headers || {});
        controllerMethod(req, res);
      }
    });
    break;
    case 'get':
    default:
    server.get(url, (req, res) => {
      if(config.redirectTo) {
        if(config.keepOldURL) {
          // Will request the page manually here via request library
          // and pipe it through as if it were coming from this request instance
          request({
            uri: req.protocol + '://' + req.hostname + ':' + (additionalArgs.serverPort || 80) + config.redirectTo + objToQueryString(req.query),
            method: 'GET',
            headers: req.headers
          }, (err, response) => {
            res.set(config.headers || {});
            if(err) {
              res.send(err);
            }
            else {
              res.send(response.body);
            }
          });
        }
        else {
          res.redirect(config.redirectTo + objToQueryString(req.query));
        }
      }
      else if(config.requiresAuth && (!authCheckFnc(req, res) || (authCookieName && req.cookies && !req.cookies[authCookieName]))) {
        // The user-provided authCheckFnc returns false, or the authCookie doesn't exist (if cookieParser() middleware is being used)
        if(loginRoutePath) {
          res.redirect(loginRoutePath + objToQueryString(req.query) + 'returnUrl=' + encodeURIComponent(req.url));
        }
        else {
          res.status(401).end();
        }
      }
      else {
        res.set(config.headers || {});
        controllerMethod(req, res);
      }
    });
    break;
  }
}

function bindRoutes(server, routesConfig, allControllers, args) {
  additionalArgs = args || {};
  authCheckFnc = additionalArgs.authCheckFnc || function () { return true; };
  authCookieName = additionalArgs.authCookieName || null;
  var loginRoutePath =null
  additionalArgs.verbose = additionalArgs.verbose || false;
  for(let r in routesConfig)     {
    let url = r;
    let config = routesConfig[r];
    if(_.isArray(config)){
      for (let c of config) {
        if(config.isLogin && !loginRoutePath) {
          // You can only have one login route per app. Does it make sense to have more than one? I don't think
          loginRoutePath = url;
        }
        bindConfig(server,c, url, loginRoutePath, allControllers)
        }
      }else{
        if(config.isLogin && !loginRoutePath) {
          // You can only have one login route per app. Does it make sense to have more than one? I don't think
          loginRoutePath = url;
        }
        bindConfig(server,config, url,loginRoutePath, allControllers)
      }

    }
  }

  module.exports = function (server, pathToRouteConfig, pathToControllers, args) {
    pathToRouteConfig = fixRequirePath(pathToRouteConfig);
    pathToControllers = fixRequirePath(pathToControllers);
    if(!server) {
      throw new Error('Why did\'nt you give EasyPeasy an Express app?');
    }
    if(!pathToRouteConfig) {
      throw new Error('No path to route config.json provided. Look, the whole point of EasyPeasy was to, well, be easy peasy. I can\'nt do this without a route config!');
    }
    if(!pathToControllers) {
      throw new Error('Sorry, Holmes. You did\'nt tell me about any of your controllers, so how am I supposed to wire these routes up?');
    }
    var allControllers = {},
    routesConfig = require(process.cwd() + pathToRouteConfig);

    pathToControllers = process.cwd() + pathToControllers;
    var allControllerPaths = fs.readdirSync(pathToControllers);
    allControllerPaths.forEach((c) => {
      let pathToController = pathToControllers + '/' + c;
      let theController = require(pathToControllers + '/' + c);
      allControllers[pathToController] = theController;
    });
    bindRoutes(server, routesConfig, allControllers, args);
  };
<|endoftext|>


<commit_before>import Typography from 'typography'
import ms from 'modularscale'
import { MOBILE_MEDIA_QUERY, TABLET_MEDIA_QUERY } from 'typography-breakpoint-constants'

const options = {
  baseFontSize: '18px',
  baseLineHeight: '27px',
  googleFonts: [
    {
      name: 'Alegreya Sans',
      styles: [
        '400',
        '400i',
        '700',
      ],
    },
    {
      name: 'Alegreya SC',
      styles: [
        '400',
      ],
    },
    {
      name: 'Alegreya',
      styles: [
        '400',
      ],
    },
  ],
  headerFontFamily: [
    'Alegreya',
    'Georgia',
    'serif',
  ],
  bodyFontFamily: ['Alegreya Sans', 'sans-serif'],
  bodyWeight: 400,
  headerWeight: 400,
  boldWeight: 700,
  headerGray: 15,
  bodyGray: 30,
  overrideStyles: ({ adjustFontSizeTo, rhythm }, options) => ({
    body: {
      background: '#fffdf8',
    },
    '.title-display': {
      ...adjustFontSizeTo(`${ms(9/5, 'octave') * options.baseFontSize.slice(0, -2)}px`),
      fontFamily: '"Alegreya SC",sans-serif',
    },
    [TABLET_MEDIA_QUERY]: {
      'h1.title-display': {
        ...adjustFontSizeTo(`${ms(7/5, 'golden') * options.baseFontSize.slice(0, -2)}px`),
      },
      h4: {
        lineHeight: 1.45,
      },
    },
    [MOBILE_MEDIA_QUERY]: {
      blockquote: {
        marginLeft: rhythm(1.5),
        marginRight: 0,
      },
    },
    h4: {
      lineHeight: 1.5,
    },
    'h5,h6': {
      marginBottom: rhythm(1/2),
    },
    a: {
      color: '#9E5757',
      fontWeight: 600,
      textDecoration: 'none',
    },
    'a:hover': {
      textDecoration: 'underline',
    },
    blockquote: {
      ...adjustFontSizeTo('16px'),
      marginLeft: rhythm(3),
      marginRight: rhythm(1),
      marginTop: rhythm(1.5),
      marginBottom: rhythm(1.5),
    },
    'p > img': {
      marginBottom: 0,
    },
  }),
}
const typography = new Typography(options)

// Hot reload typography in development.
if (process.env.NODE_ENV !== 'production') {
  typography.injectStyles()
}

export default typography
<commit_msg>Decided against bold links<commit_after>import Typography from 'typography'
import ms from 'modularscale'
import { MOBILE_MEDIA_QUERY, TABLET_MEDIA_QUERY } from 'typography-breakpoint-constants'

const options = {
  baseFontSize: '18px',
  baseLineHeight: '27px',
  googleFonts: [
    {
      name: 'Alegreya Sans',
      styles: [
        '400',
        '400i',
        '700',
      ],
    },
    {
      name: 'Alegreya SC',
      styles: [
        '400',
      ],
    },
    {
      name: 'Alegreya',
      styles: [
        '400',
      ],
    },
  ],
  headerFontFamily: [
    'Alegreya',
    'Georgia',
    'serif',
  ],
  bodyFontFamily: ['Alegreya Sans', 'sans-serif'],
  bodyWeight: 400,
  headerWeight: 400,
  boldWeight: 700,
  headerGray: 15,
  bodyGray: 30,
  overrideStyles: ({ adjustFontSizeTo, rhythm }, options) => ({
    body: {
      background: '#fffdf8',
    },
    '.title-display': {
      ...adjustFontSizeTo(`${ms(9/5, 'octave') * options.baseFontSize.slice(0, -2)}px`),
      fontFamily: '"Alegreya SC",sans-serif',
    },
    [TABLET_MEDIA_QUERY]: {
      'h1.title-display': {
        ...adjustFontSizeTo(`${ms(7/5, 'golden') * options.baseFontSize.slice(0, -2)}px`),
      },
      h4: {
        lineHeight: 1.45,
      },
    },
    [MOBILE_MEDIA_QUERY]: {
      blockquote: {
        marginLeft: rhythm(1.5),
        marginRight: 0,
      },
    },
    h4: {
      lineHeight: 1.5,
    },
    'h5,h6': {
      marginBottom: rhythm(1/2),
    },
    a: {
      color: '#9E5757',
      textDecoration: 'underline',
    },
    'a:hover': {
      textDecoration: 'none',
    },
    blockquote: {
      ...adjustFontSizeTo('16px'),
      marginLeft: rhythm(3),
      marginRight: rhythm(1),
      marginTop: rhythm(1.5),
      marginBottom: rhythm(1.5),
    },
    'p > img': {
      marginBottom: 0,
    },
  }),
}
const typography = new Typography(options)

// Hot reload typography in development.
if (process.env.NODE_ENV !== 'production') {
  typography.injectStyles()
}

export default typography
<|endoftext|>