<commit_before>import { Component, PropTypes } from "react";
import { graphql } from "react-apollo";
import { connect } from "react-redux"
import gql from "graphql-tag";

import Loading from "../../components/loading";
import MiniCard from "../../components/cards/cards.MiniCard";

// XXX add skip if no tags

const RELATED_CONTENT_QUERY = gql`
  query GetRelatedContent($tags: [String], $includeChannels: [String], $limit: Int, $excludedIds: [String]) {
    taggedContent(tags: $tags, limit: $limit, includeChannels: $includeChannels, excludedIds: $excludedIds) {
      entryId: id
      id
      title
      channelName
      parent {
        entryId: id
        content {
          images(sizes: ["medium"]) {
            url
            label
            fileLabel
            id
          }
        }
      }
      content {
        images(sizes: ["medium"]) {
          url
          label
          fileLabel
          id
        }
      }
    }
  }
`;

const defaultArray = [];
const withContent = graphql(RELATED_CONTENT_QUERY, {
  name: "content",
  options: ownProps => ({
    variables: {
      tags: ownProps.tags || defaultArray,
      includeChannels: ownProps.includeChannels || defaultArray,
      limit: ownProps.limit || 3,
      excludedIds: ownProps.excludedIds || defaultArray,
    },
  }),
});

@connect()
@withContent
export default class RelatedContent extends Component {

  static defaultProps = {
    title: "More Like This",
  }

  static propTypes = {
    content: PropTypes.object,
    title: PropTypes.string,
  }

  render() {
    const { taggedContent, loading } = this.props.content;
    if (!loading && (taggedContent && !taggedContent.length)) return null;
    return (

{this.props.title}

          {(() => {
            if (!this.props.content.loading) return null;
            return (

                <Loading />

            );
          })()}
          {taggedContent && taggedContent.map((content, key) => (

              <MiniCard
                title={content.title}
                images={content.content.images}
                type={content.channel}
                content={content}
              />

          ))}

    );
  }
}
<commit_msg>linted changes<commit_after>import { Component, PropTypes } from "react";
import { graphql } from "react-apollo";
import { connect } from "react-redux";
import gql from "graphql-tag";

import Loading from "../../components/loading";
import MiniCard from "../../components/cards/cards.MiniCard";

// XXX add skip if no tags

/* eslint-disable max-len */
const RELATED_CONTENT_QUERY = gql`
  query GetRelatedContent($tags: [String], $includeChannels: [String], $limit: Int, $excludedIds: [String]) {
    taggedContent(tags: $tags, limit: $limit, includeChannels: $includeChannels, excludedIds: $excludedIds) {
      entryId: id
      id
      title
      channelName
      parent {
        entryId: id
        content {
          images(sizes: ["medium"]) {
            url
            label
            fileLabel
            id
          }
        }
      }
      content {
        images(sizes: ["medium"]) {
          url
          label
          fileLabel
          id
        }
      }
    }
  }
`;

const defaultArray = [];
const withContent = graphql(RELATED_CONTENT_QUERY, {
  name: "content",
  options: ownProps => ({
    variables: {
      tags: ownProps.tags || defaultArray,
      includeChannels: ownProps.includeChannels || defaultArray,
      limit: ownProps.limit || 3,
      excludedIds: ownProps.excludedIds || defaultArray,
    },
  }),
});

@connect()
@withContent
export default class RelatedContent extends Component {

  static defaultProps = {
    title: "More Like This",
  }

  static propTypes = {
    content: PropTypes.object,
    title: PropTypes.string,
  }

  render() {
    const { taggedContent, loading } = this.props.content;
    if (!loading && (taggedContent && !taggedContent.length)) return null;
    return (

{this.props.title}

          {(() => {
            if (!this.props.content.loading) return null;
            return (

                <Loading />

            );
          })()}
          {taggedContent && taggedContent.map((content, key) => (

              <MiniCard
                title={content.title}
                images={content.content.images}
                type={content.channel}
                content={content}
              />

          ))}

    );
  }
}
<|endoftext|>


<commit_before>// deferrer helps you to emulate a jQuery.Deferrer object
define(["vendors/go-phantomizer/queuer","vendors/go-phantomizer/template","vendors/utils/dfrer"],function (queuer, template, dfrer) {
    var phantomizer = function(){
    }
    phantomizer.prototype.template = new template();
    phantomizer.prototype.queuer = new queuer(window.phantomatic || false);

    phantomizer.prototype.before_render = [];
    phantomizer.prototype.after_static_render = [];
    phantomizer.prototype.after_client_render = [];
    phantomizer.prototype.after_render = [];

    function add_to_queuer(queuer,render_list){
        for(var n in render_list ){
            var render = render_list[n].render;
            if(render=="client"){
                queuer.render(render_list[n].fn);
            }else if(render=="static"){
                queuer.render_static(render_list[n].fn);
            }else{
                queuer.render(render_list[n].fn);
            }
        }
    }
    phantomizer.prototype.render = function(main_fn){
        var that = this;
        add_to_queuer(that.queuer, that.before_render);
// During the build, the static template are loaded and built in
        that.queuer.render_static(function(next){
            that.template.render_build(next);
        });
        add_to_queuer(that.queuer, that.after_static_render);
// during client side rendeering, render JIT template items
        that.queuer.render(function(next){
            that.template.render_client(next);
        });
        that.queuer.render(main_fn);

        add_to_queuer(that.queuer, that.after_client_render);
// inject template scripts
        that.queuer.render(function(next){
            that.template.inject_scripts();
            next();
        });
        add_to_queuer(that.queuer, that.after_render);

        that.queuer.run();
    };
    phantomizer.prototype.afterStaticRender = function(fn,render){
        render= render?render:"static";
        this.after_static_render.push({fn:fn,render:render});
    }
    phantomizer.prototype.afterClientRender = function(fn,render){
        render= render?render:"render";
        this.after_client_render.push({fn:fn,render:render});
    }
    phantomizer.prototype.afterRender = function(fn,render){
        render= render?render:"render";
        this.after_render.push({fn:fn,render:render});
    }
    phantomizer.prototype.beforeRender = function(fn,render){
        render= render?render:"render";
        this.before_render.push({fn:fn,render:render});
    }
    phantomizer.prototype.when = function(){
        var dfd = new dfrer();
        var dfrers = arguments;
        var cb_args = [];
        var todo_cnt = dfrers.length;
        var done_cnt = 0;
        for( var n=0;n<todo_cnt;n++){
            (function(df_index){
                dfrers[df_index].always(function(){
                    done_cnt++;
                    cb_args[df_index] = arguments;
                    if( done_cnt == todo_cnt ){
                        dfd.resolve.apply(dfd,cb_args);
                    }
                });
            })(n);
        }
        return dfd;
    }
    return new phantomizer();
});
<commit_msg>"use strict"; everywhere<commit_after>"use strict";

// deferrer helps you to emulate a jQuery.Deferrer object
define(["vendors/go-phantomizer/queuer","vendors/go-phantomizer/template","vendors/utils/dfrer"],function (queuer, template, dfrer) {
    var phantomizer = function(){
    }
    phantomizer.prototype.template = new template();
    phantomizer.prototype.queuer = new queuer(window.phantomatic || false);

    phantomizer.prototype.before_render = [];
    phantomizer.prototype.after_static_render = [];
    phantomizer.prototype.after_client_render = [];
    phantomizer.prototype.after_render = [];

    function add_to_queuer(queuer,render_list){
        for(var n in render_list ){
            var render = render_list[n].render;
            if(render=="client"){
                queuer.render(render_list[n].fn);
            }else if(render=="static"){
                queuer.render_static(render_list[n].fn);
            }else{
                queuer.render(render_list[n].fn);
            }
        }
    }
    phantomizer.prototype.render = function(main_fn){
        var that = this;
        add_to_queuer(that.queuer, that.before_render);
// During the build, the static template are loaded and built in
        that.queuer.render_static(function(next){
            that.template.render_build(next);
        });
        add_to_queuer(that.queuer, that.after_static_render);
// during client side rendeering, render JIT template items
        that.queuer.render(function(next){
            that.template.render_client(next);
        });
        that.queuer.render(main_fn);

        add_to_queuer(that.queuer, that.after_client_render);
// inject template scripts
        that.queuer.render(function(next){
            that.template.inject_scripts();
            next();
        });
        add_to_queuer(that.queuer, that.after_render);

        that.queuer.run();
    };
    phantomizer.prototype.afterStaticRender = function(fn,render){
        render= render?render:"static";
        this.after_static_render.push({fn:fn,render:render});
    }
    phantomizer.prototype.afterClientRender = function(fn,render){
        render= render?render:"render";
        this.after_client_render.push({fn:fn,render:render});
    }
    phantomizer.prototype.afterRender = function(fn,render){
        render= render?render:"render";
        this.after_render.push({fn:fn,render:render});
    }
    phantomizer.prototype.beforeRender = function(fn,render){
        render= render?render:"render";
        this.before_render.push({fn:fn,render:render});
    }
    phantomizer.prototype.when = function(){
        var dfd = new dfrer();
        var dfrers = arguments;
        var cb_args = [];
        var todo_cnt = dfrers.length;
        var done_cnt = 0;
        for( var n=0;n<todo_cnt;n++){
            (function(df_index){
                dfrers[df_index].always(function(){
                    done_cnt++;
                    cb_args[df_index] = arguments;
                    if( done_cnt == todo_cnt ){
                        dfd.resolve.apply(dfd,cb_args);
                    }
                });
            })(n);
        }
        return dfd;
    }
    return new phantomizer();
});
<|endoftext|>


<commit_before>/**
 * Validation for LegalForm
 */
(function($) {
    function LegalFormValidation() {
        this.ractive = null;
        this.el = null;
        this.container = null;

        //Fields for custom validation
        var textFields = 'input[type="text"], input[type="number"], input[type="email"], textarea';
        var stateFields = 'input[type="radio"], input[type="checkbox"], select';

        /**
         * Initialize validation
         *
         * @param {Ractive} ractive
         */
        this.init = function(ractive) {
            this.ractive = ractive;
            this.el = ractive.el;
            this.container = $(ractive.el).parent()[0];

            this.initDatePicker();
            this.initCustomValidation();
            this.initTextFields();
            this.initStateFields();

            this.initShowTooltip();
            this.initHideTooltipOnBlur();
            this.initHideTooltipOnScroll();

            this.initBootstrapValidation();
            this.initOnStep();
        }

        /**
         * Init validation for date picker
         */
        this.initDatePicker = function ()
        {
            $(this.container).on('dp.change', $.proxy(function(e) {
                var input = $(e.target).find(':input').get(0);
                this.validateField(input);
            }, this));
        }

        /**
         * Init custom validation
         */
        this.initCustomValidation = function ()
        {
            $(this.container).on('change', ':input', $.proxy(function(e) {
                this.validateField(e.target);
            }, this));
        }

        /**
         * Launch validation when interacting with text field
         */
        this.initTextFields = function ()
        {
            $(this.container).on('focus keyup', textFields, $.proxy(function(e) {
                this.handleValidation(e.target);
            }, this));
        }

        /**
         * Launch validation when interacting with "state" field
         */
        this.initStateFields = function ()
        {
            $(this.container).on('click', stateFields, $.proxy(function(e) {
                this.handleValidation(e.target);
            }, this));
        }

        /**
         * Init and show tooltips
         */
        this.initShowTooltip = function ()
        {
            $(this.container).on('mouseover click', '[rel=tooltip]', $.proxy(function(e) {
                this.initTooltip(e.target);
            }, this));
        }

        /**
         * Close programaticaly opened tooltip when leaving field
         */
        this.initHideTooltipOnBlur = function()
        {
            $(this.container).on('blur', textFields + ', ' + stateFields, $.proxy(function(e) {
                var help = $(e.target).closest('.form-group').find('[rel="tooltip"]');
                var tooltip = $(help).data('bs.tooltip');
                if (tooltip && tooltip.$tip.hasClass('in')) $(help).tooltip('hide');
            }, this));
        }

        /**
         * Close programaticaly opened tooltips on form scroll
         */
        this.initHideTooltipOnScroll = function ()
        {
            $(this.container).on('scroll', function(e) {
                $('[rel="tooltip"]').each(function() {
                    var tooltip = $(e.target).data('bs.tooltip');

                    if (tooltip && tooltip.$tip.hasClass('in')) {
                        $(this).tooltip('hide');
                    }
                });
            });
        }

        /**
         * Initialize the bootrap vaidation for the forms
         */
        this.initBootstrapValidation = function ()
        {
            $(this.container).find('form').validator();
        }

        /**
         * Initialize validation on step event
         */
        this.initOnStep = function ()
        {
            var ractive = this.ractive;
            var el = this.el;

            $(this.container).on('step.bs.wizard done.bs.wizard', '', $.proxy(function(e) {
                if (e.direction === 'back' || ractive.get('validation_enabled') === false) return;

                var validator = $(el).find('.wizard-step.active form').data('bs.validator');
                validator.validate();

                $(this.el).find(':not(.selectize-input)>:input:not(.btn)').each(function() {
                    this.validateField(e.target);
                    $(e.target).change();
                });

                if (validator.isIncomplete() || validator.hasErrors()) {
                    e.preventDefault();
                    return;
                }

                if (e.type === 'done') {
                    $(this.el).trigger('done.completed');
                }
            }));
        };

        /**
         * Launch validation and tooltips
         *
         * @param {Element} input
         */
        this.handleValidation = function(input) {
            var self = this;
            this.validateField(input);

            //This is needed to immediately mark field as invalid on type
            $(input).change();

            var help = $(input).closest('.form-group').find('[rel="tooltip"]');
            if (!$(help).length) return;

            var isValid = $(input).is(':valid');
            var tooltip = $(help).data('bs.tooltip');
            var isShown = tooltip && tooltip.$tip.hasClass('in');

            if (!isValid && !isShown) {
                //Timeout is needed for radio-checkboxes, when both blur and focus can work on same control
                setTimeout(function() {
                    self.initTooltip(help, true);
                }, $(input).is(stateFields) ? 300 : 0);
            } else if (isValid && isShown) {
                $(help).tooltip('hide');
            }
        }

        /**
         * Perform custom field validation
         *
         * @param {Element} input
         */
        this.validateField = function(input) {
            var error = 'Value is not valid';
            var name = $(input).attr('name') ? $(input).attr('name') : $(input).attr('data-id');
            if (!name) return;

            var value = $(input).val();
            if (value.length === 0) {
                $(input).get(0).setCustomValidity(
                    $(input).attr('required') ? 'Field is required' : ''
                );
                return;
            }

            var keypath = name.replace(/\{\{\s*/, '').replace(/\}\}\s*/, '').split('.');
            var meta = this.ractive.get('meta')[keypath[0]];
            name = keypath[0];

            if (keypath.length > 1) {
                for (var i = 1; i < keypath.length; i++) {
                    if (!meta[keypath[i]]) break;

                    meta = meta[keypath[i]];
                    name += '.' + keypath[i];
                }
            }

            // Implement validation for numbers
            if (meta.type === 'number') {
                var min = $(input).attr('min');
                var max = $(input).attr('max');
                var valid = $.isNumeric(value) && (!$.isNumeric(min) || Number(value) >= Number(min)) && (!$.isNumeric(max) || Number(value) <= Number(max));
                if (!valid) {
                    $(input).get(0).setCustomValidity(error);
                    return;
                }
            }

            var validation = meta.validation;

            if ($.trim(validation).length > 0) {
                var result = this.ractive.get(name + '-validation');
                if (!result) {
                    $(input).get(0).setCustomValidity(error);
                    return;
                }
            }

            $(input).get(0).setCustomValidity('');
        }

        //Init and show tooltip for the first time
        this.initTooltip = function(element, show) {
            var inited = $(element).data('bs.tooltip');
            if (!inited) {
                $(element).tooltip({
                    placement: $('#doc').css('position') === 'absolute' ? 'left' : 'right',
                    container: 'body'
                });
            }

            if (!inited || show) $(element).tooltip('show');
        }
    }

    window.LegalFormValidation = LegalFormValidation;
})(jQuery);
<commit_msg>Fixed datepicker<commit_after>/**
 * Validation for LegalForm
 */
(function($) {
    function LegalFormValidation() {
        this.ractive = null;
        this.el = null;
        this.container = null;

        //Fields for custom validation
        var textFields = 'input[type="text"], input[type="number"], input[type="email"], textarea';
        var stateFields = 'input[type="radio"], input[type="checkbox"], select';

        /**
         * Initialize validation
         *
         * @param {Ractive} ractive
         */
        this.init = function(ractive) {
            this.ractive = ractive;
            this.el = ractive.el;
            this.container = $(ractive.el).parent()[0];

            this.initDatePicker();
            this.initCustomValidation();
            this.initTextFields();
            this.initStateFields();

            this.initShowTooltip();
            this.initHideTooltipOnBlur();
            this.initHideTooltipOnScroll();

            this.initBootstrapValidation();
            this.initOnStep();
        }

        /**
         * Init validation for date picker
         */
        this.initDatePicker = function ()
        {
            $(this.container).on('click', '[data-picker="date"]', function(e) {
                if ($(this).data('DateTimePicker')) return;

                $(this).datetimepicker({ locale: 'nl', format: 'DD-MM-YYYY' });
                $(e.target).closest('.input-group-addon').trigger('click');
            });

            $(this.container).on('dp.change', $.proxy(function(e) {
                var input = $(e.target).find(':input').get(0);
                var name = $(input).attr('name');

                this.validateField(input);

                this.ractive.updateModel(name);

                //Fix material design
                if (ractive.get(name) !== '') {
                    $(e.target).parent().removeClass('is-empty');
                }
            }, this));

        }

        /**
         * Init custom validation
         */
        this.initCustomValidation = function ()
        {
            $(this.container).on('change', ':input', $.proxy(function(e) {
                this.validateField(e.target);
            }, this));
        }

        /**
         * Launch validation when interacting with text field
         */
        this.initTextFields = function ()
        {
            $(this.container).on('focus keyup', textFields, $.proxy(function(e) {
                this.handleValidation(e.target);
            }, this));
        }

        /**
         * Launch validation when interacting with "state" field
         */
        this.initStateFields = function ()
        {
            $(this.container).on('click', stateFields, $.proxy(function(e) {
                this.handleValidation(e.target);
            }, this));
        }

        /**
         * Init and show tooltips
         */
        this.initShowTooltip = function ()
        {
            $(this.container).on('mouseover click', '[rel=tooltip]', $.proxy(function(e) {
                this.initTooltip(e.target);
            }, this));
        }

        /**
         * Close programaticaly opened tooltip when leaving field
         */
        this.initHideTooltipOnBlur = function()
        {
            $(this.container).on('blur', textFields + ', ' + stateFields, $.proxy(function(e) {
                var help = $(e.target).closest('.form-group').find('[rel="tooltip"]');
                var tooltip = $(help).data('bs.tooltip');
                if (tooltip && tooltip.$tip.hasClass('in')) $(help).tooltip('hide');
            }, this));
        }

        /**
         * Close programaticaly opened tooltips on form scroll
         */
        this.initHideTooltipOnScroll = function ()
        {
            $(this.container).on('scroll', function(e) {
                $('[rel="tooltip"]').each(function() {
                    var tooltip = $(e.target).data('bs.tooltip');

                    if (tooltip && tooltip.$tip.hasClass('in')) {
                        $(this).tooltip('hide');
                    }
                });
            });
        }

        /**
         * Initialize the bootrap vaidation for the forms
         */
        this.initBootstrapValidation = function ()
        {
            $(this.container).find('form').validator();
        }

        /**
         * Initialize validation on step event
         */
        this.initOnStep = function ()
        {
            var ractive = this.ractive;
            var el = this.el;

            $(this.container).on('step.bs.wizard done.bs.wizard', '', $.proxy(function(e) {
                if (e.direction === 'back' || ractive.get('validation_enabled') === false) return;

                var validator = $(el).find('.wizard-step.active form').data('bs.validator');
                validator.validate();

                $(this.el).find(':not(.selectize-input)>:input:not(.btn)').each(function() {
                    this.validateField(e.target);
                    $(e.target).change();
                });

                if (validator.isIncomplete() || validator.hasErrors()) {
                    e.preventDefault();
                    return;
                }

                if (e.type === 'done') {
                    $(this.el).trigger('done.completed');
                }
            }));
        };

        /**
         * Launch validation and tooltips
         *
         * @param {Element} input
         */
        this.handleValidation = function(input) {
            var self = this;
            this.validateField(input);

            //This is needed to immediately mark field as invalid on type
            $(input).change();

            var help = $(input).closest('.form-group').find('[rel="tooltip"]');
            if (!$(help).length) return;

            var isValid = $(input).is(':valid');
            var tooltip = $(help).data('bs.tooltip');
            var isShown = tooltip && tooltip.$tip.hasClass('in');

            if (!isValid && !isShown) {
                //Timeout is needed for radio-checkboxes, when both blur and focus can work on same control
                setTimeout(function() {
                    self.initTooltip(help, true);
                }, $(input).is(stateFields) ? 300 : 0);
            } else if (isValid && isShown) {
                $(help).tooltip('hide');
            }
        }

        /**
         * Perform custom field validation
         *
         * @param {Element} input
         */
        this.validateField = function(input) {
            var error = 'Value is not valid';
            var name = $(input).attr('name') ? $(input).attr('name') : $(input).attr('data-id');
            if (!name) return;

            var value = $(input).val();
            if (value.length === 0) {
                $(input).get(0).setCustomValidity(
                    $(input).attr('required') ? 'Field is required' : ''
                );
                return;
            }

            var keypath = name.replace(/\{\{\s*/, '').replace(/\}\}\s*/, '').split('.');
            var meta = this.ractive.get('meta')[keypath[0]];
            name = keypath[0];

            if (keypath.length > 1) {
                for (var i = 1; i < keypath.length; i++) {
                    if (!meta[keypath[i]]) break;

                    meta = meta[keypath[i]];
                    name += '.' + keypath[i];
                }
            }

            // Implement validation for numbers
            if (meta.type === 'number') {
                var min = $(input).attr('min');
                var max = $(input).attr('max');
                var valid = $.isNumeric(value) && (!$.isNumeric(min) || Number(value) >= Number(min)) && (!$.isNumeric(max) || Number(value) <= Number(max));
                if (!valid) {
                    $(input).get(0).setCustomValidity(error);
                    return;
                }
            }

            var validation = meta.validation;

            if ($.trim(validation).length > 0) {
                var result = this.ractive.get(name + '-validation');
                if (!result) {
                    $(input).get(0).setCustomValidity(error);
                    return;
                }
            }

            $(input).get(0).setCustomValidity('');
        }

        //Init and show tooltip for the first time
        this.initTooltip = function(element, show) {
            var inited = $(element).data('bs.tooltip');
            if (!inited) {
                $(element).tooltip({
                    placement: $('#doc').css('position') === 'absolute' ? 'left' : 'right',
                    container: 'body'
                });
            }

            if (!inited || show) $(element).tooltip('show');
        }
    }

    window.LegalFormValidation = LegalFormValidation;
})(jQuery);
<|endoftext|>


<commit_before>Package.describe({
  name: 'gbrunner:packmeteor',
  version: '0.1.10',
  summary: "Rig the basics for packmeteor",
  git: 'https://github.com/Vilango/packmeteor'
});

Package.onUse(function (api) {
  api.versionsFrom('METEOR@0.9.4');
  api.use('webapp', 'server');
  api.use('reload', 'client');
  api.use('routepolicy', 'server');
  api.use('underscore', 'server');
  api.use('autoupdate', 'server', {weak: true});

  api.export('Packmeteor');
  api.use('deps', 'client');
  api.add_files('meteor/packmeteor-client.js', 'client');
  api.add_files('meteor/packmeteor-server.js', 'server');
});
<commit_msg>updated package<commit_after>Package.describe({
  name: 'gbrunner:packmeteor',
  version: '0.1.11',
  summary: "Rig the basics for packmeteor",
  git: 'https://github.com/Vilango/packmeteor'
});

Package.onUse(function (api) {
  api.versionsFrom('METEOR@1.1.0.3');
  api.use('webapp', 'server');
  api.use('reload', 'client');
  api.use('routepolicy', 'server');
  api.use('underscore', 'server');
  api.use('autoupdate', 'server', {weak: true});

  api.export('Packmeteor');
  api.use('deps', 'client');
  api.add_files('meteor/packmeteor-client.js', 'client');
  api.add_files('meteor/packmeteor-server.js', 'server');
});
<|endoftext|>


<commit_before>/* eslint-disable consistent-return */
'use strict';
const async = require('async');
const boom = require('boom');
const creds = require('./credentials');
const whitelist = {
    nkatzman: true,
    d2lam: true,
    cynthiax: true,
    dvdizon: true,
    FenrirUnbound: true,
    Filbird: true,
    jer: true,
    minz1027: true,
    petey: true,
    'shruthi-venkateswaran': true,
    stjohnjohnson: true,
    tkyi: true
};
const Model = require('screwdriver-models');

/**
 * Login to Screwdriver API
 * @method login
 * @param  {Hapi.Server} server          The Hapi Server we're on
 * @param  {Object}      config          Configuration from the user
 * @param  {String}      config.password Password to encrypt/decrypt data in Iron
 * @return {Object}                      Hapi Plugin Route
 */
module.exports = (server, config) => ({
    method: ['GET', 'POST'],
    path: '/login',
    config: {
        description: 'Login route',
        notes: 'Authenticate user with github oauth provider',
        tags: ['api', 'login'],
        auth: {
            strategy: 'oauth'
        },
        handler: (request, reply) => {
            if (!request.auth.isAuthenticated) {
                const message = `Authentication failed due to: ${request.auth.error.message}`;

                return reply(boom.unauthorized(message));
            }
            const username = request.auth.credentials.profile.username;

            if (!whitelist[username]) {
                const message = `User ${username} is not whitelisted to use the api`;

                return reply(boom.forbidden(message));
            }

            const profile = creds.generateProfile(username, ['user']);
            const token = request.server.plugins.login.generateToken(username, ['user']);

            request.cookieAuth.set(profile);

            const user = new Model.User(server.settings.app.datastore, config.password);
            const id = user.generateId({ username });
            const githubToken = request.auth.credentials.token;

            user.sealToken(githubToken, (err, sealed) => {
                async.waterfall([
                    (next) => user.get(id, next),
                    (userData, cb) => {
                        if (!userData) {
                            return user.create({
                                username,
                                token: sealed
                            }, cb);
                        }

                        return user.update({
                            id: userData.id,
                            data: {
                                token: sealed
                            }
                        }, cb);
                    }
                ], (error) => {
                    if (error) {
                        return reply(boom.wrap(error));
                    }

                    return reply({ token });
                });
            });
        }
    }
});
<commit_msg>Plz add Nico to whitelist<commit_after>/* eslint-disable consistent-return */
'use strict';
const async = require('async');
const boom = require('boom');
const creds = require('./credentials');
const whitelist = {
    nkatzman: true,
    d2lam: true,
    cynthiax: true,
    dvdizon: true,
    FenrirUnbound: true,
    Filbird: true,
    jer: true,
    minz1027: true,
    petey: true,
    'shruthi-venkateswaran': true,
    stjohnjohnson: true,
    tkyi: true,
    nicolaifsf: true
};
const Model = require('screwdriver-models');

/**
 * Login to Screwdriver API
 * @method login
 * @param  {Hapi.Server} server          The Hapi Server we're on
 * @param  {Object}      config          Configuration from the user
 * @param  {String}      config.password Password to encrypt/decrypt data in Iron
 * @return {Object}                      Hapi Plugin Route
 */
module.exports = (server, config) => ({
    method: ['GET', 'POST'],
    path: '/login',
    config: {
        description: 'Login route',
        notes: 'Authenticate user with github oauth provider',
        tags: ['api', 'login'],
        auth: {
            strategy: 'oauth'
        },
        handler: (request, reply) => {
            if (!request.auth.isAuthenticated) {
                const message = `Authentication failed due to: ${request.auth.error.message}`;

                return reply(boom.unauthorized(message));
            }
            const username = request.auth.credentials.profile.username;

            if (!whitelist[username]) {
                const message = `User ${username} is not whitelisted to use the api`;

                return reply(boom.forbidden(message));
            }

            const profile = creds.generateProfile(username, ['user']);
            const token = request.server.plugins.login.generateToken(username, ['user']);

            request.cookieAuth.set(profile);

            const user = new Model.User(server.settings.app.datastore, config.password);
            const id = user.generateId({ username });
            const githubToken = request.auth.credentials.token;

            user.sealToken(githubToken, (err, sealed) => {
                async.waterfall([
                    (next) => user.get(id, next),
                    (userData, cb) => {
                        if (!userData) {
                            return user.create({
                                username,
                                token: sealed
                            }, cb);
                        }

                        return user.update({
                            id: userData.id,
                            data: {
                                token: sealed
                            }
                        }, cb);
                    }
                ], (error) => {
                    if (error) {
                        return reply(boom.wrap(error));
                    }

                    return reply({ token });
                });
            });
        }
    }
});
<|endoftext|>


<commit_before>// Teste padrão das rotas
var assert = require('assert');
var server = require(__dirname + '/../../lib/http');
var loader = require(__dirname + '/../mock/loader');
var dropper = require(__dirname + '/../mock/dropper');
var request = require('supertest');

loader.routes();
loader.models();

describe('Rota /api/v1/news', function(){
  // Limpando o banco de dados antes e depois dos testes
  before(dropper);
  after(dropper);

  it('POST de notícias deve aceitar um documento bem formatado', function(cb){
    var data = {
      title : 'Testing news',
      link : 'http://nodebr.org',
      description: 'This is a testing news for testing purposes.',
      user: {
        name: 'Travis CI',
        email: 'support@travis-ci.com'
      }
    };

    request(server.listener)
      .post('/api/v1/news')
      .set('Content-Type', 'application/json')
      .send(data)
      .expect(200)
      .expect('Content-Type', 'application/json; charset=utf-8')
      .end(function(err){
        assert.ifError(err);
        cb();
      });
  });

  it('GET de notícias deve retornar as notícias', function(cb){
    request(server.listener)
      .get('/api/v1/news')
      .expect(200)
      .expect('Content-Type', 'application/json; charset=utf-8')
      .end(function(err, res){
        assert.ifError(err);
        assert.ok(res.body.result.length === 1);
        cb();
      });
  });

});
<commit_msg>testing api<commit_after>// Teste padrão das rotas
var assert = require('assert');
var server = require(__dirname + '/../../lib/http');
var loader = require(__dirname + '/../mock/loader');
var dropper = require(__dirname + '/../mock/dropper');
var request = require('supertest');
var db = require(__dirname + '/../../lib/db');
var news = require(__dirname + '/../../model/news-model');

loader.routes();
loader.models();

describe('Rota /api/v1/news', function(){
  // Limpando o banco de dados antes e depois dos testes
  before(dropper);
  after(dropper);

  it('POST de notícias deve aceitar um documento bem formatado', function(cb){
    var data = {
      title : 'Testing news',
      link : 'http://nodebr.org',
      description: 'This is a testing news for testing purposes.',
      user: {
        name: 'Travis CI',
        email: 'support@travis-ci.com'
      }
    };

    request(server.listener)
      .post('/api/v1/news')
      .set('Content-Type', 'application/json')
      .send(data)
      .expect(200)
      .expect('Content-Type', 'application/json; charset=utf-8')
      .end(function(err){
        assert.ifError(err);
        cb();
      });
  });

  it('GET de notícias deve retornar as notícias', function(cb){
    request(server.listener)
      .get('/api/v1/news')
      .expect(200)
      .expect('Content-Type', 'application/json; charset=utf-8')
      .end(function(err, res){
        assert.ifError(err);
        assert.ok(res.body.result.length === 1);
        cb();
      });
  });

  it('PUT aumentanto o Karma score de uma noticia '+
        'deve retornar a noticia', function(cb){

          db.model('news',news);

          news.findOne({'title' : 'Testing news'}, function(err, not){
            if(err)
              throw err;
            request(server.listener)
              .put('/api/v1/news/'+not.slug+'/karma')
              .send({karma : 1})
              .expect(200)
              .expect('Content-Type', 'application/json; charset=utf-8')
              .end(function(err, res){
                assert.ifError(err);
                assert.ok(res.body.karma === 1);
                cb();
              });
          });

        });

});
<|endoftext|>


<commit_before>'use strict';
import config from './config';

console.log.apply(console, config.consoleMessage);
console.log('Environment', config.environment);

mapboxgl.accessToken = config.mapboxToken;

if (!mapboxgl.supported()) {
  document.getElementById('map').innerHTML = 'Your browser does not support Mapbox GL';
} else {
  var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v9',
    center: [60, 2.867],
    zoom: 1.5
  });
  attachDataToMap(map, config.energydataDataset);
}

function attachDataToMap (theMap, dataset) {
  theMap.on('load', function () {
    // get the dataset JSON
    fetch(`https://energydata.info/api/3/action/package_show?id=${dataset}`)
    .then(function (response) {
      return response.json();
    }).then(function (datasetJSON) {
      // The tilejson is assumed to be on the first resource of the dataset
      return datasetJSON.result.resources[0].tilejson;
    }).then(function (tilejson) {
      // Fetch the tilejson
      return fetch(tilejson);
    }).then(function (response) {
      return response.json();
    }).then(function (tilejson) {
      var layer = tilejson;
      layer.type = 'vector';
      layer.attribution = 'energydata.info';
      theMap.addSource('data', layer);
      theMap.fitBounds([[layer.bounds[0], layer.bounds[1]], [layer.bounds[2], layer.bounds[3]]], {padding: 20});
      theMap.addControl(new mapboxgl.NavigationControl(), 'top-left');
      theMap.addLayer({
        'id': 'data',
        'type': 'line',
        'source': 'data',
        'source-layer': 'data_layer',
        'layout': {
          'line-join': 'round',
          'line-cap': 'round'
        },
        'paint': {
          'line-color': {
            'property': 'voltage_kV',
            'type': 'interval',
            'stops': [
              // a 0 value is missing data, and is likely to be Medium Voltage (66+)
              [0, '#002f54'],
              // LV & MV
              [0.001, '#22a6f5'],
              // HV
              [66, '#002f54']
            ]
          },
          'line-width': {
            'stops': [
              [0, 1],
              [5, 2],
              [10, 3],
              [15, 5]
            ]
          },
          'line-opacity': {
            'property': 'status',
            'type': 'categorical',
            'stops': [
              ['Planned', 0.7],
              ['Construction', 0.7]
            ]
          }
        }
      }, 'poi-scalerank2');

      // When a click event occurs near a feature, open a popup.
      theMap.on('click', function (e) {
        var features = map.queryRenderedFeatures(e.point, { layers: ['data'] });
        if (!features.length) {
          return;
        }
        var feature = features[0];

        var popup = new mapboxgl.Popup()
          .setLngLat(map.unproject(e.point))
          .setHTML(`

Status

${feature.properties.status}

Voltage

${feature.properties.voltage_kV}kV

`)
        .addTo(theMap);
      });
      // Use the same approach as above to indicate that the symbols are clickable
      // by changing the cursor style to 'pointer'.
      theMap.on('mousemove', function (e) {
        var features = map.queryRenderedFeatures(e.point, { layers: ['data'] });
        theMap.getCanvas().style.cursor = (features.length) ? 'pointer' : '';
      });

      // Filter the map data by property
      document.getElementById('filter').addEventListener('click', function (e) {
        if (e.target && e.target.className === 'status-filter') {
          var clickedOption = e.target.innerText.toLowerCase();
          e.preventDefault();

          switch (clickedOption) {
            case 'all':
              map.setFilter('data', ['!=', 'status', 'Decommissioned']);
              break;
            case 'planned':
              map.setFilter('data', ['in', 'status', 'Planned', 'Construction']);
              break;
            case 'existing':
              map.setFilter('data', ['==', 'status', 'Existing']);
          }

          // Remove .active from all items
          document.querySelectorAll('.status-filter').forEach(function (o) { o.classList.remove('active'); });
          e.target.classList.add('active');
        }
      });
    });
  });
}

// Open the modal
document.getElementById('modal-open').addEventListener('click', function (e) {
  e.preventDefault();
  let modal = document.getElementById('about-modal');
  modal.classList.remove('modal-leave', 'modal-leave-active');
  modal.classList.add('modal-enter', 'modal-enter-active');
});

// Close the modal when somebody clicks the Dismiss icon, or outside the modal
document.querySelectorAll('#about-modal, #modal-dismiss').forEach(function (o) {
  o.addEventListener('click', function (e) {
    e.preventDefault();
    let modal = document.getElementById('about-modal');
    modal.classList.remove('modal-enter', 'modal-enter-active');
    modal.classList.add('modal-leave', 'modal-leave-active');
  });
});

// Don't close if somebody clicks on the model itself
document.getElementById('about-modal-inner').addEventListener('click', function (e) {
  e.stopPropagation();
});
<commit_msg>Improve layer styles and correct modal behaviour on IE. Fix #8 #9<commit_after>/* global mapboxgl */
'use strict';
import config from './config';

console.log.apply(console, config.consoleMessage);
console.log('Environment', config.environment);

mapboxgl.accessToken = config.mapboxToken;

if (!mapboxgl.supported()) {
  document.getElementById('map').innerHTML = 'Your browser does not support Mapbox GL';
} else {
  var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v9',
    center: [60, 2.867],
    zoom: 1.5
  });
  attachDataToMap(map, config.energydataDataset);
}

function attachDataToMap (theMap, dataset) {
  theMap.on('load', function () {
    // get the dataset JSON
    fetch(`https://energydata.info/api/3/action/package_show?id=${dataset}`)
    .then(function (response) {
      return response.json();
    }).then(function (datasetJSON) {
      // The tilejson is assumed to be on the first resource of the dataset
      return datasetJSON.result.resources[0].tilejson;
    }).then(function (tilejson) {
      // Fetch the tilejson
      return fetch(tilejson);
    }).then(function (response) {
      return response.json();
    }).then(function (tilejson) {
      var layer = tilejson;
      layer.type = 'vector';
      layer.attribution = 'energydata.info';
      theMap.addSource('data', layer);
      theMap.fitBounds([[layer.bounds[0], layer.bounds[1]], [layer.bounds[2], layer.bounds[3]]], {padding: 20});
      theMap.addControl(new mapboxgl.NavigationControl(), 'top-left');

      theMap.addLayer({
        'id': 'existing',
        'type': 'line',
        'source': 'data',
        'source-layer': 'data_layer',
        'layout': {
          'visibility': 'visible',
          'line-join': 'round',
          'line-cap': 'round'
        },
        filter: ['==', 'status', 'Existing'],
        'paint': {
          'line-color': {
            'property': 'voltage_kV',
            'type': 'interval',
            'stops': [
              // a 0 value is missing data, and is likely to be Medium Voltage (66+)
              [0, '#002f54'],
              // LV & MV
              [0.001, '#22a6f5'],
              // HV
              [66, '#002f54']
            ]
          },
          'line-width': {
            'stops': [
              [0, 1],
              [5, 2],
              [10, 3],
              [15, 5]
            ]
          }
        }
      }, 'poi-scalerank2');

      theMap.addLayer({
        'id': 'planned',
        'type': 'line',
        'source': 'data',
        'source-layer': 'data_layer',
        'layout': {
          'visibility': 'visible',
          'line-join': 'round',
          'line-cap': 'round'
        },
        'filter': ['in', 'status', 'Planned', 'Construction'],
        'paint': {
          // 'line-color': '#FF0000',
          'line-opacity': 0.7,
          'line-dasharray': [2, 5],
          'line-color': {
            'property': 'voltage_kV',
            'type': 'interval',
            'stops': [
              // a 0 value is missing data, and is likely to be Medium Voltage (66+)
              [0, '#002f54'],
              // LV & MV
              [0.001, '#22a6f5'],
              // HV
              [66, '#002f54']
            ]
          },
          'line-width': {
            'stops': [
              [0, 1],
              [5, 2],
              [10, 3],
              [15, 5]
            ]
          }
        }
      }, 'poi-scalerank2');

      // When a click event occurs near a feature, open a popup.
      theMap.on('click', function (e) {
        var features = map.queryRenderedFeatures(e.point, { layers: ['existing', 'planned'] });
        if (!features.length) {
          return;
        }
        var feature = features[0];

        new mapboxgl.Popup()
          .setLngLat(map.unproject(e.point))
          .setHTML(`

Status

${feature.properties.status}

Voltage

${feature.properties.voltage_kV}kV

`)
        .addTo(theMap);
      });
      // Use the same approach as above to indicate that the symbols are clickable
      // by changing the cursor style to 'pointer'.
      theMap.on('mousemove', function (e) {
        var features = map.queryRenderedFeatures(e.point, { layers: ['existing', 'planned'] });
        theMap.getCanvas().style.cursor = (features.length) ? 'pointer' : '';
      });

      // Filter the map data by property
      document.getElementById('filter').addEventListener('click', function (e) {
        if (e.target && e.target.className === 'status-filter') {
          var clickedOption = e.target.innerText.toLowerCase();
          e.preventDefault();

          switch (clickedOption) {
            case 'all':
              map.setLayoutProperty('existing', 'visibility', 'visible');
              map.setLayoutProperty('planned', 'visibility', 'visible');
              break;
            case 'planned':
              map.setLayoutProperty('existing', 'visibility', 'none');
              map.setLayoutProperty('planned', 'visibility', 'visible');
              break;
            case 'existing':
              map.setLayoutProperty('existing', 'visibility', 'visible');
              map.setLayoutProperty('planned', 'visibility', 'none');
          }

          // Remove .active from all items
          document.querySelectorAll('.status-filter').forEach(function (o) { o.classList.remove('active'); });
          e.target.classList.add('active');
        }
      });
    });
  });
}

// Open the modal
document.getElementById('modal-open').addEventListener('click', function (e) {
  e.preventDefault();
  var modal = document.getElementById('about-modal');
  modal.classList.remove('modal-leave');
  modal.classList.remove('modal-leave-active');
  modal.classList.add('modal-enter');
  modal.classList.add('modal-enter-active');
});

// Close the modal when somebody clicks the Dismiss icon, or outside the modal
var modals = Array.prototype.slice.call(document.querySelectorAll('#about-modal, #modal-dismiss'));
modals.forEach(function (o) {
  o.addEventListener('click', function (e) {
    e.preventDefault();
    var modal = document.getElementById('about-modal');
    modal.classList.remove('modal-enter');
    modal.classList.remove('modal-enter-active');
    modal.classList.add('modal-leave');
    modal.classList.add('modal-leave-active');
  });
});

// Don't close if somebody clicks on the model itself
document.getElementById('about-modal-inner').addEventListener('click', function (e) {
  e.stopPropagation();
});<|endoftext|>


<commit_before>"use strict";

/* import-globals-from common.js */

// Detect an active review request on the bug page.
function submitter() {
  const flags = document.querySelectorAll(`div.attach-flag .vcard_${user.id}`);

  for (const f of flags) {
    const type = f.previousElementSibling;
    const vcard = f.parentNode.firstElementChild.className.match(/vcard_\d+/);
    if (vcard && type && type.textContent.endsWith("review?")) {
      return vcard[0];
    }
  }
}

// Augment any mention of the author across the bug page.
function augment(author) {
  const vcards = document.querySelectorAll(`.${author}`);
  for (const vcard of vcards) {
    const img = icon();
    vcard.parentElement.insertBefore(img, vcard);
    vcard.classList.toggle("br-vcard", true);
  }
}

async function init() {
  const author = submitter();
  const visible = await storage(bug_id);
  if (author) {
    augment(author);
    setVisible(visible);

    // The people module summary reveals assignee.
    document.getElementById("module-people-subtitle").innerHTML = "";
  }
}

init();
<commit_msg>Handle mozreview box on show_bug page<commit_after>"use strict";

/* import-globals-from common.js */

// Detect an active review request on the bug page.
function submitter() {
  const flags = document.querySelectorAll(`div.attach-flag .vcard_${user.id}`);

  for (const f of flags) {
    const type = f.previousElementSibling;
    const vcard = f.parentNode.firstElementChild.className.match(/vcard_\d+/);
    if (vcard && type && type.textContent.endsWith("review?")) {
      return vcard[0];
    }
  }
}

// Augment any mention of the author across the bug page.
function augment(author) {
  const vcards = document.querySelectorAll(`.${author}`);
  for (const vcard of vcards) {
    const img = icon();
    vcard.parentElement.insertBefore(img, vcard);
    vcard.classList.toggle("br-vcard", true);
  }
}

async function mozreview(records) {
  const visible = await storage(bug_id);
  for (const record of records) {
    for (const tr of record.addedNodes) {
      const td = tr.firstElementChild;
      if (td && td.textContent && !visible) {
        td.textContent = "";
      }
    }
  }
}

async function init() {
  const author = submitter();
  const visible = await storage(bug_id);
  if (author) {
    augment(author);
    setVisible(visible);

    // The people module summary reveals assignee.
    document.getElementById("module-people-subtitle").innerHTML = "";

    const tbody = document.querySelector("tbody.mozreview-request");
    const observer = new MutationObserver(mozreview);
    observer.observe(tbody, {childList: true});
  }
}

init();
<|endoftext|>


<commit_before>'use strict';

angular.module('app')
    .controller('rgiAnswerCtrl', function (
        $scope,
        $routeParams,
        $q,
        $timeout,
        $route,
        rgiNotifier,
        ngDialog,
        rgiAnswerSrvc,
        rgiDocumentSrvc,
        rgiDialogFactory,
        rgiIdentitySrvc,
        rgiAssessmentSrvc
    ) {
        $scope.identity = rgiIdentitySrvc;
        $scope.current_user = rgiIdentitySrvc.currentUser;
        $scope.page_type = 'answer';
        $scope.isCollapsed = false;

        rgiAnswerSrvc.get({answer_ID: $routeParams.answer_ID, assessment_ID: $routeParams.answer_ID.substring(0, 2)}, function (answer) {
            $scope.answer = answer;
            $scope.assessment = rgiAssessmentSrvc.get({assessment_ID: answer.assessment_ID});
            $scope.flags = answer.flags;
            $scope.references = answer.references;
            $scope.question = answer.question_ID;
            if (answer[$scope.current_user.role + '_score']) {
                $scope.question.question_criteria.forEach(function (opt, i) {
                    if (i===answer[$scope.current_user.role + '_score'].order-1) {
                        opt.selected = true;
                        $scope.answer.new_answer_selection = i;
                    } else {
                        opt.selected = false;
                    }
                });
            };

            if (answer.guidance_dialog) {
                rgiDialogFactory.guidanceDialog($scope);
            }
        });

        var resetReference = function() {
            rgiAnswerSrvc.get({answer_ID: $routeParams.answer_ID, assessment_ID: $routeParams.answer_ID.substring(0, 2)}, function (answer) {
                $scope.references = answer.references;
            });
        };
        var resetAnswer = function() {
            rgiAnswerSrvc.get({answer_ID: $routeParams.answer_ID, assessment_ID: $routeParams.answer_ID.substring(0, 2)}, function (answer) {
                $scope.answer = answer;
                $scope.flags = answer.flags;
            });
        };

        resetReference();
        $scope.$on('RESET_REFERENCE_ACTION', resetReference);
        $scope.$on('RESET_ANSWER_ACTION', resetAnswer);

    });<commit_msg>clean up the answer controller<commit_after>'use strict';

angular.module('app')
    .controller('rgiAnswerCtrl', function (
        $scope,
        $routeParams,
        rgiAnswerSrvc,
        rgiDialogFactory,
        rgiIdentitySrvc,
        rgiAssessmentSrvc
    ) {
        $scope.identity = rgiIdentitySrvc;
        $scope.current_user = rgiIdentitySrvc.currentUser;
        $scope.page_type = 'answer';
        $scope.isCollapsed = false;

        rgiAnswerSrvc.get({answer_ID: $routeParams.answer_ID, assessment_ID: $routeParams.answer_ID.substring(0, 2)}, function (answer) {
            $scope.answer = answer;
            $scope.assessment = rgiAssessmentSrvc.get({assessment_ID: answer.assessment_ID});
            $scope.flags = answer.flags;
            $scope.references = answer.references;
            $scope.question = answer.question_ID;
            if (answer[$scope.current_user.role + '_score']) {
                $scope.question.question_criteria.forEach(function (opt, i) {
                    if (i===answer[$scope.current_user.role + '_score'].order-1) {
                        opt.selected = true;
                        $scope.answer.new_answer_selection = i;
                    } else {
                        opt.selected = false;
                    }
                });
            }

            if (answer.guidance_dialog) {
                rgiDialogFactory.guidanceDialog($scope);
            }
        });

        var resetReference = function() {
            rgiAnswerSrvc.get({answer_ID: $routeParams.answer_ID, assessment_ID: $routeParams.answer_ID.substring(0, 2)}, function (answer) {
                $scope.references = answer.references;
            });
        };

        var resetAnswer = function() {
            rgiAnswerSrvc.get({answer_ID: $routeParams.answer_ID, assessment_ID: $routeParams.answer_ID.substring(0, 2)}, function (answer) {
                $scope.answer = answer;
                $scope.flags = answer.flags;
            });
        };

        resetReference();
        $scope.$on('RESET_REFERENCE_ACTION', resetReference);
        $scope.$on('RESET_ANSWER_ACTION', resetAnswer);

    });
<|endoftext|>


<commit_before><commit_msg>Fix regions<commit_after><|endoftext|>


<commit_before>import { sha3 } from 'web3-utils';
import axios from 'axios';
const API = 'https://mainnet.mewwallet.dev';

export default class MoonPayHandler {
  constructor() {}
  /*
   ** MoonPay
   */
  buy(tokenSymbol, fiatCurrency, amount, address) {
    const hash = sha3(address);
    const id = `WEB|${hash.substring(0, 42)}`;
    return new Promise(resolve => {
      let link = `${API}/v3/purchase/moonpay/order?address=${address}&id=${id}&cryptoCurrency=${tokenSymbol}&fiatCurrency=${fiatCurrency}`;
      if (amount) {
        link += `&requestedAmount=${amount}`;
      }
      const parsedUrl = encodeURI(link);
      // eslint-disable-next-line
      window.open(parsedUrl, '_blank');
      resolve();
    });
  }

  sell(tokenSymbol, amount, address) {
    const hash = sha3(address);
    const id = `WEB|${hash.substring(0, 42)}`;
    return new Promise(resolve => {
      const parsedUrl = encodeURI(
        `${API}/v3/sell/moonpay/order?address=${address}&id=${id}&cryptoCurrency=${tokenSymbol}&requestedAmount=${amount}`
      );
      // eslint-disable-next-line
      window.open(parsedUrl, '_blank');
      resolve();
    });
  }

  getSupportedFiatToBuy(symbol) {
    return new Promise((resolve, reject) => {
      axios
        .get(`${API}/v3/purchase/providers/web?iso=us&cryptoCurrency=${symbol}`)
        .then(res => {
          const supportedFiat = res.data;
          resolve(supportedFiat);
        })
        .catch(reject);
    });
  }

  getFiatRatesForBuy() {
    return new Promise((resolve, reject) => {
      axios
        .get(`${API}/v3/purchase/moonpay/quotes`)
        .then(res => {
          resolve(res.data);
        })
        .catch(reject);
    });
  }

  getSupportedFiatToSell(symbol) {
    return new Promise((resolve, reject) => {
      axios
        .get(`${API}/v3/sell/providers/web?iso=us&cryptoCurrency=${symbol}`)
        .then(res => {
          const supportedFiat = res.data;
          resolve(supportedFiat);
        })
        .catch(reject);
    });
  }

  /*
   ** Simplex
   */
  simplexBuy(tokenSymbol, fiatCurrency, amount, address) {
    const hash = sha3(address);
    const id = `WEB|${hash.substring(0, 42)}`;
    return new Promise(resolve => {
      const parsedUrl = encodeURI(
        `${API}/v2/purchase/simplex/order?address=${address}&id=${id}&requestedCurrency=${fiatCurrency}&fiatCurrency=${fiatCurrency}&requestedAmount=${amount}&cryptoCurrency=${tokenSymbol}`
      );
      // eslint-disable-next-line
      window.open(parsedUrl, '_blank');
      resolve();
    });
  }

  /* Simplex Quotes
  Parameters:
    PurchaseOrderReferenceId,
    FiatCurrency,
    PurchaseOrderRequestedCurrency,
    RequestedAmount, // Must be ETH amount ~0.027 - ~9
    PurchaseOrderCryptoCurrency
  Returns:
    payment_id: string,
    crypto_amount: number,
    crypto_currency: string,
    fiat_currency: string,
    fiat_amount: number,
    fiat_base_amount: number
  */
  getSimplexQuote(tokenSymbol, fiatCurrency, amount, address) {
    const hash = sha3(address);
    const id = `WEB|${hash.substring(0, 42)}`;
    return new Promise((resolve, reject) => {
      axios
        .get(
          encodeURI(
            `${API}/purchase/simplex/quote?id=${id}&requestedCurrency=${fiatCurrency}&fiatCurrency=${fiatCurrency}&requestedAmount=${amount}&cryptoCurrency=${tokenSymbol}`
          )
        )
        .then(res => {
          resolve(res.data);
        })
        .catch(reject);
    });
  }

  // this won't be used for awhile but is setup here
  getHistory() {}
}
<commit_msg>devop: 🔧 remove comments<commit_after>import { sha3 } from 'web3-utils';
import axios from 'axios';
const API = 'https://mainnet.mewwallet.dev';

export default class MoonPayHandler {
  constructor() {}
  /*
   ** MoonPay
   */
  buy(tokenSymbol, fiatCurrency, amount, address) {
    const hash = sha3(address);
    const id = `WEB|${hash.substring(0, 42)}`;
    return new Promise(resolve => {
      let link = `${API}/v3/purchase/moonpay/order?address=${address}&id=${id}&cryptoCurrency=${tokenSymbol}&fiatCurrency=${fiatCurrency}`;
      if (amount) {
        link += `&requestedAmount=${amount}`;
      }
      const parsedUrl = encodeURI(link);
      // eslint-disable-next-line
      window.open(parsedUrl, '_blank');
      resolve();
    });
  }

  sell(tokenSymbol, amount, address) {
    const hash = sha3(address);
    const id = `WEB|${hash.substring(0, 42)}`;
    return new Promise(resolve => {
      const parsedUrl = encodeURI(
        `${API}/v3/sell/moonpay/order?address=${address}&id=${id}&cryptoCurrency=${tokenSymbol}&requestedAmount=${amount}`
      );
      // eslint-disable-next-line
      window.open(parsedUrl, '_blank');
      resolve();
    });
  }

  getSupportedFiatToBuy(symbol) {
    return new Promise((resolve, reject) => {
      axios
        .get(`${API}/v3/purchase/providers/web?iso=us&cryptoCurrency=${symbol}`)
        .then(res => {
          const supportedFiat = res.data;
          resolve(supportedFiat);
        })
        .catch(reject);
    });
  }

  getFiatRatesForBuy() {
    return new Promise((resolve, reject) => {
      axios
        .get(`${API}/v3/purchase/moonpay/quotes`)
        .then(res => {
          resolve(res.data);
        })
        .catch(reject);
    });
  }

  getSupportedFiatToSell(symbol) {
    return new Promise((resolve, reject) => {
      axios
        .get(`${API}/v3/sell/providers/web?iso=us&cryptoCurrency=${symbol}`)
        .then(res => {
          const supportedFiat = res.data;
          resolve(supportedFiat);
        })
        .catch(reject);
    });
  }

  /*
   ** Simplex
   */
  simplexBuy(tokenSymbol, fiatCurrency, amount, address) {
    const hash = sha3(address);
    const id = `WEB|${hash.substring(0, 42)}`;
    return new Promise(resolve => {
      const parsedUrl = encodeURI(
        `${API}/v2/purchase/simplex/order?address=${address}&id=${id}&requestedCurrency=${fiatCurrency}&fiatCurrency=${fiatCurrency}&requestedAmount=${amount}&cryptoCurrency=${tokenSymbol}`
      );
      // eslint-disable-next-line
      window.open(parsedUrl, '_blank');
      resolve();
    });
  }

  getSimplexQuote(tokenSymbol, fiatCurrency, amount, address) {
    const hash = sha3(address);
    const id = `WEB|${hash.substring(0, 42)}`;
    return new Promise((resolve, reject) => {
      axios
        .get(
          encodeURI(
            `${API}/purchase/simplex/quote?id=${id}&requestedCurrency=${fiatCurrency}&fiatCurrency=${fiatCurrency}&requestedAmount=${amount}&cryptoCurrency=${tokenSymbol}`
          )
        )
        .then(res => {
          resolve(res.data);
        })
        .catch(reject);
    });
  }

  // this won't be used for awhile but is setup here
  getHistory() {}
}
<|endoftext|>


<commit_before>// Find help here:  https://themeteorchef.com/snippets/using-the-browser-policy-package/

import { BrowserPolicy } from 'meteor/browser-policy-common';

// Allow all content to be served from the current domain
BrowserPolicy.content.allowSameOriginForAll();

// Recommended settings
BrowserPolicy.content.disallowEval();

// Maps
BrowserPolicy.content.allowImageOrigin( 'api.tiles.mapbox.com' );
BrowserPolicy.content.allowImageOrigin( 'api.mapbox.com' );

// Mapbox Geocoding
BrowserPolicy.content.allowImageOrigin( 'api.tiles.mapbox.com' );

// Fonts
BrowserPolicy.content.allowStyleOrigin( 'fonts.googleapis.com' );
BrowserPolicy.content.allowFontOrigin( 'fonts.gstatic.com' );
BrowserPolicy.content.allowFontDataUrl();

// Image CDN
BrowserPolicy.content.allowImageOrigin( 'res.cloudinary.com' );

// Avatars
BrowserPolicy.content.allowImageOrigin( 'secure.gravatar.com' );
BrowserPolicy.content.allowImageOrigin( 'graph.facebook.com' );
BrowserPolicy.content.allowImageOrigin( '*.fbcdn.net' );
BrowserPolicy.content.allowImageOrigin( '*.akamaihd.net' );
BrowserPolicy.content.allowImageOrigin( '*.googleusercontent.com' );

// Google Analytics
BrowserPolicy.content.allowOriginForAll( 'https://www.google-analytics.com' );

// iubenda Privacy Policy
BrowserPolicy.content.allowScriptOrigin( 'cdn.iubenda.com' );
BrowserPolicy.content.allowStyleOrigin( 'cdn.iubenda.com' );
BrowserPolicy.content.allowImageOrigin( 'cdn.iubenda.com' );
BrowserPolicy.content.allowImageOrigin( 'www.iubenda.com' );
BrowserPolicy.content.allowFrameOrigin( 'www.iubenda.com' );
<commit_msg>Added browser policy for GA doubleclick.net<commit_after>// Find help here:  https://themeteorchef.com/snippets/using-the-browser-policy-package/

import { BrowserPolicy } from 'meteor/browser-policy-common';

// Allow all content to be served from the current domain
BrowserPolicy.content.allowSameOriginForAll();

// Recommended settings
BrowserPolicy.content.disallowEval();

// Maps
BrowserPolicy.content.allowImageOrigin( 'api.tiles.mapbox.com' );
BrowserPolicy.content.allowImageOrigin( 'api.mapbox.com' );

// Mapbox Geocoding
BrowserPolicy.content.allowImageOrigin( 'api.tiles.mapbox.com' );

// Fonts
BrowserPolicy.content.allowStyleOrigin( 'fonts.googleapis.com' );
BrowserPolicy.content.allowFontOrigin( 'fonts.gstatic.com' );
BrowserPolicy.content.allowFontDataUrl();

// Image CDN
BrowserPolicy.content.allowImageOrigin( 'res.cloudinary.com' );

// Avatars
BrowserPolicy.content.allowImageOrigin( 'secure.gravatar.com' );
BrowserPolicy.content.allowImageOrigin( 'graph.facebook.com' );
BrowserPolicy.content.allowImageOrigin( '*.fbcdn.net' );
BrowserPolicy.content.allowImageOrigin( '*.akamaihd.net' );
BrowserPolicy.content.allowImageOrigin( '*.googleusercontent.com' );

// Google Analytics
BrowserPolicy.content.allowOriginForAll( 'https://www.google-analytics.com' );
BrowserPolicy.content.allowImageOrigin( 'https://stats.g.doubleclick.net' );

// iubenda Privacy Policy
BrowserPolicy.content.allowScriptOrigin( 'cdn.iubenda.com' );
BrowserPolicy.content.allowStyleOrigin( 'cdn.iubenda.com' );
BrowserPolicy.content.allowImageOrigin( 'cdn.iubenda.com' );
BrowserPolicy.content.allowImageOrigin( 'www.iubenda.com' );
BrowserPolicy.content.allowFrameOrigin( 'www.iubenda.com' );
<|endoftext|>


<commit_before>'use strict';

//Native modules
import fs from 'fs';
import path from 'path';

//Vendor modules
import normalizePath from 'normalize-path';
import recursive from 'tail-call/core';
import {
  existsAsync,
  mkdirAsync,
  writeFileAsync,
  removeAsync
} from 'fs-extra-promise';

//Source modules
import Validations from './lines-validations';

const validator = new Validations();
const tailCall = recursive.recur;

let structureCreation = {
  generated: 0,
  notGenerated: 0
};

const logNonGenerated = tailCall((lineInfo, structureCreation) => {

  structureCreation.notGenerated = structureCreation.notGenerated + 1;
  console.log("structureCreation", structureCreation);
  console.log(">>>>>>>>>>>in logNonGenerated");
  //
  // if (lineInfo.children.length > 0) {
  //   lineInfo.children.forEach((line) => {
  //     if (line.inferType === 'file') {
  //       structureCreation.notGenerated = structureCreation.notGenerated + 1;
  //     } else {
  //       logNonGenerated(line);
  //     }
  //   });
  // } else {
  //   structureCreation.notGenerated = structureCreation.notGenerated + 1;
  // }
});

//Convert createStructure into a tail recursive function
let createStructureTC = null;
const createStructure = (lineInfo, rootPath,
  contentLineCount, resolve) => {
  console.log("\n\n----");
  console.log("lineInfo.structureName", lineInfo.structureName);
  console.log("lineInfo.isTopLine", lineInfo.isTopLine);

  let {
    structureName,
    inferType,
    nameDetails,
    isTopLine,
    childRepeatedLine
  } = lineInfo;

  let name = nameDetails.sanitizedName ||
    structureName,
    structureRoughPath = path.join(rootPath, name),
    structureCreatePath = normalizePath(structureRoughPath);

  if (inferType === 'file') {

    console.log("inferType", inferType);
    console.log("childRepeatedLine", childRepeatedLine);

    if (!childRepeatedLine) {
      structureCreation.generated = structureCreation.generated + 1;
      console.log("file structureCreation", structureCreation);
      //Create the file type
      (async function () {
        await writeFileAsync(structureCreatePath);
      })();

    } else {
      logNonGenerated(lineInfo, structureCreation);
    }

  } else {

    //TODO: check for childRepeatedLine before actual folder generation
    console.log("//////////folder childRepeatedLine", childRepeatedLine);
    let parentPath = path.join(rootPath, (nameDetails.sanitizedName || structureName));

    console.log("folder parentPath", parentPath);

    let genFolder = false;

    //Only generate folder if it is not a repeat
    if ((typeof childRepeatedLine ===
      'undefined' && lineInfo.repeatedLine !== true) ||
       (typeof lineInfo.repeatedLine === 'undefined' && childRepeatedLine !== true)) {
      genFolder = true;
      (async function () {
        await mkdirAsync(parentPath);
      })();

      structureCreation.generated = structureCreation.generated + 1;
      // console.log("lineInfo", lineInfo);
      console.log("created folder");
    } else {
      logNonGenerated(lineInfo, structureCreation);
    }

    console.log("structureCreation after wait folder gen", structureCreation);
    console.log("--------------------------\n\n");

    if (!genFolder) {

      lineInfo.children.forEach((line) => {
        logNonGenerated(line, structureCreation);
      });

    } else if (lineInfo.children.length > 0) {
      lineInfo.children.forEach((line) => {

        console.log("line name", line.structureName);
        console.log("right after structureCreation.notGenerated", structureCreation.notGenerated);
        // console.log("line", line);
        console.log("line.isTopLine", line.isTopLine);
        console.log("lineInfo.nameDetails.line", lineInfo.nameDetails.line);

        //&&  !isTopLine
        if (typeof lineInfo.childRepeatedLine === 'undefined') {
          createStructureTC(line, parentPath,
            contentLineCount, resolve);
        } else {
          // structureCreation.notGenerated = structureCreation.notGenerated + 1;
          console.log("+++++++++++++++++++++++folder structureCreation", structureCreation);
          logNonGenerated(line, structureCreation);
        }

      });
    }
  }

  if (structureCreation.generated + structureCreation.notGenerated
=== contentLineCount) {
    console.log("resolved");
    resolve();
  }

};

createStructureTC = tailCall(createStructure);

export default (linesInfo, rootPath) => {

  //The total number of lines that are possible to generate
  let contentLineCount = linesInfo.contentLineCount;

  let structureGenerating = new Promise((resolve, reject) => {

    //Take the outer-most level of elements which
    //serves as the initial generation set
    console.log("``````````````contentLineCount", contentLineCount);
    for (let i = 0; i < contentLineCount; i++) {
      console.log("linesInfo.topLevel[i].structureName", linesInfo.topLevel[i].structureName);
      // if (typeof linesInfo.topLevel[i].repeatedLine === 'undefined') {
        let topLevelLine = linesInfo.topLevel[i];
        createStructureTC(topLevelLine, rootPath,
          contentLineCount, resolve);
      // }

      // else {
      //
      //   console.log("last non-gen structureCreation", structureCreation);
      //   logNonGenerated(line, structureCreation);
      // }

    }
  });

  return structureGenerating;
};
<commit_msg>Clean up comments on the generate file<commit_after>'use strict';

//Native modules
import fs from 'fs';
import path from 'path';

//Vendor modules
import normalizePath from 'normalize-path';
import recursive from 'tail-call/core';
import {
  existsAsync,
  mkdirAsync,
  writeFileAsync,
  removeAsync
} from 'fs-extra-promise';

//Source modules
import Validations from './lines-validations';

const validator = new Validations();
const tailCall = recursive.recur;

//Log the lines that are not generated due to repeats
let structureCreation = {
  generated: 0,
  notGenerated: 0
};

const logNonGenerated = tailCall((structureCreation) => {
  structureCreation.notGenerated = structureCreation.notGenerated + 1;
});

//Convert createStructure into a tail recursive function
let createStructureTC = null;
const createStructure = (lineInfo, rootPath,
  contentLineCount, resolve) => {

  let {
    structureName,
    inferType,
    nameDetails,
    isTopLine,
    childRepeatedLine
  } = lineInfo;

  let name = nameDetails.sanitizedName ||
    structureName,
    structureRoughPath = path.join(rootPath, name),
    structureCreatePath = normalizePath(structureRoughPath);

  if (inferType === 'file') {

    if (!childRepeatedLine) {
      structureCreation.generated = structureCreation.generated + 1;

      //Create the file type
      (async function () {
        await writeFileAsync(structureCreatePath);
      })();

    } else {
      logNonGenerated(structureCreation);
    }
  } else {
    let parentPath = path.join(rootPath, (nameDetails.sanitizedName || structureName));

    let genFolder = false;

    //Only generate folder if it is not a repeat
    //Top level lines record repeats with only 'repeatedLine' while
    //child level lines repeats possess the 'repeatedLine' key
    if ((typeof childRepeatedLine ===
      'undefined' && lineInfo.repeatedLine !== true) ||
       (typeof lineInfo.repeatedLine === 'undefined' &&
        childRepeatedLine !== true)) {
      genFolder = true;

      //Create the folder
      (async function () {
        await mkdirAsync(parentPath);
      })();
      structureCreation.generated = structureCreation.generated + 1;
    } else {

      //folder will be logged as one that is not generated
      logNonGenerated(structureCreation);
    }

    //Ungenerated folder means a repeated line, but still attempt
    //to record the nested child of the repeated line
    if (!genFolder) {
      lineInfo.children.forEach((line) => {
        logNonGenerated(line, structureCreation);
      });
    } else if (lineInfo.children.length > 0) {
      lineInfo.children.forEach((line) => {

        //Again check for repeated lines in the child level lines
        //for the parent folder that is not repeated
        if (typeof lineInfo.childRepeatedLine === 'undefined') {
          createStructureTC(line, parentPath,
            contentLineCount, resolve);
        } else {
          logNonGenerated(line, structureCreation);
        }
      });
    }
  }

  //When all generated structures are created with the non-generated
  //structures ignored, signifies that the generation process comes to
  //an end
  if (structureCreation.generated + structureCreation.notGenerated
=== contentLineCount) {
    resolve();
  }
};

//Tail call wrapper
createStructureTC = tailCall(createStructure);

export default (linesInfo, rootPath) => {

  //The total number of lines that are possible to generate
  let contentLineCount = linesInfo.contentLineCount;
  let structureGenerating = new Promise((resolve, reject) => {

    //Take the outer-most level of elements which
    //serves as the initial generation set
    for (let i = 0; i < contentLineCount; i++) {
        let topLevelLine = linesInfo.topLevel[i];
        createStructureTC(topLevelLine, rootPath,
          contentLineCount, resolve);
    }
  });

  return structureGenerating;
};
<|endoftext|>


<commit_before>Package.describe({
    name: 'justinrvt:contact-form',
    summary: 'French contact form for METEOR',
    version: '1.3.3',
    git: 'https://github.com/JustinRvt/Meteor-French-Contact-Form',
    documentation: 'README.md'
});

Package.onUse(function(api) {
    api.versionsFrom('1.3.3');
    api.use('email', 'server');
    api.use([
        'templating',
        'mquandalle:jade@0.4.9'
    ]);
    api.use([
      'templating',
      'coffeescript'
    ]);
    api.use('aldeed:autoform@5.3.0');
    api.addFiles('contact-form.coffee');
    api.addFiles([
            'client/views/contact-form.jade',
            'client/views/contact-form.coffee'
        ],
        'client');
    api.addFiles('server/contact-form.coffee', 'server');
});

Package.onTest(function(api) {
    api.use('tinytest');
    api.use('templating', 'client');
    api.use('aldeed:autoform@5.3.0');
    api.addFiles('contact-form.coffee');
    api.addFiles([
      'client/views/contact-form.jade',
      'client/views/contact-form.coffee'
    ],
    'client');
    api.addFiles('server/contact-form.coffee', 'server');
    api.addFiles('contact-form-tests.coffee');
});
<commit_msg>fix package.js issue with Coffeescript & Jade<commit_after>Package.describe({
    name: 'justinrvt:contact-form',
    summary: 'French contact form for METEOR',
    version: '1.3.3',
    git: 'https://github.com/JustinRvt/Meteor-French-Contact-Form',
    documentation: 'README.md'
});

Package.onUse(function(api) {
    api.versionsFrom('1.3.3');
    api.use('email', 'server');
    api.use([
        'templating',
        'mquandalle:jade@0.4.9'
    ]);
    api.use([
      'templating',
      'coffeescript'
    ]);
    api.use('aldeed:autoform@5.3.0');
    api.addFiles('contact-form.coffee');
    api.addFiles([
            'client/views/contact-form.jade',
            'client/views/contact-form.coffee'
        ],
        'client');
    api.addFiles('server/contact-form.coffee', 'server');
});

Package.onTest(function(api) {
    api.use('tinytest');
    api.use([
        'templating',
        'mquandalle:jade@0.4.9'
    ]);
    api.use([
      'templating',
      'coffeescript'
    ]);
    api.use('aldeed:autoform@5.3.0');
    api.addFiles('contact-form.coffee');
    api.addFiles([
      'client/views/contact-form.jade',
      'client/views/contact-form.coffee'
    ],
    'client');
    api.addFiles('server/contact-form.coffee', 'server');
    api.addFiles('contact-form-tests.coffee');
});
<|endoftext|>