<commit_before>// custom functions
$(function(){

//Video events and functions
$('#vid,#vid2').click(function(){
  this.paused?this.play():this.pause();
  //class de parent
  $(this).parent().toggleClass('paused');
});

//Facebook global variables

var url_l = String((window.location != window.parent.location) ? document.referrer: document.location.href),
    body = $('body'),
    dominio = "datapola.com/",
    movil = false,
    ios =  iOS(),
    ref = document.referrer,
    fb_valid = false;

function faceConnect(){

  (function(d, s, id){

     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    window.fbAsyncInit = function() {
        FB.init({
          appId: '1660712804256395',
          status: true,
          xfbml: true,
          cookie: true,
          version    : 'v2.7',
          channelUrl: url_l+'/channelUrl.html'
        });

        FB.getLoginStatus(function(response) {

          // Check login status on load, and if the user is

          // already logged in, go directly to the welcome message.

          if (response.status == 'connected') {

            //Autoplay video if is connected
            var video = $("#vid, #vid2").get(0);
                video.play();

            //Draw Hidden Canvas
            function drawHidden(url) {

              var can = document.getElementById('can_hidden'),

                ctx = can.getContext('2d'),
                imgUrl = url;

                var img = new Image();
                img.src = url;

                var img2 = new Image();
                img2.src = 'https://'+dominio+'img/bg-canvas.jpg';

                ctx.drawImage(img2, 0, 0);
                ctx.drawImage(img, 30, 80);

                $('#can_hidden').hide();

            }

            //Draw image profile on video
            FB.api(
              '/me',
              'GET',
              {

                "fields":
                "context,first_name,last_name,name,id,picture.width(290).height(390).type(large)"},

              function(response) {

                  //Get profile photo if is refered
                  if(body.hasClass('refered')){
                    document.getElementById('profile-thumb').innerHTML = "";
                  }
              }

            );

            //Login for perimisions
            FB.login(function(response) {
              FB.api(
                '/me/friends',
                'GET',
                {

                  "fields":
                  "context,first_name,last_name,name,id,picture.width(290).height(390).type(large)"},

                function(response) {

                    var boxContainer = $('.box_amigos_facebook');

                    for(y=0; y<response.data.length; y++) {

                      $('.hidden').hide();

                      //Load images
                       boxContainer.append("
" + response.data[y].name + ""+ response.data[y].id +"
");

                      //Action for input
                      boxContainer.hide();

                      $('#search_friend').unbind('click').click(function(event) {
                          $(this).siblings('.box_amigos_facebook').toggle(400);
                      });

                      //Action box profile item
                      $('.box_perfil').click(function(event) {

                        var img = $(this).children('img').attr('src'),
                            nombre = $(this).children('.nombre').text(),
                            id_user = $(this).children('.id_man').text();

                            $('#search_friend').val(nombre);
                            $('#photo_friend').val(img);
                            $('#id_friend').val(id_user);
                            $(this).parent().hide(400);
                      });
                    }

                  //Click for publish BS
                  $('#push_public').click(function(e){

                      //Create canvas

                      function drawHidden(url) {

                        var canvas = document.getElementById('can_hidden');
                        var ctx = canvas.getContext("2d");

                        var img1 = loadImage(url, main);
                        var img2 = loadImage('https://datapola.com/img/pub2.jpg', main);

                        var imagesLoaded = 0;
                        function main() {
                            imagesLoaded += 1;

                            if(imagesLoaded == 2) {
                              console.log('yes');
                                // composite now
                                ctx.drawImage(img1, 0, 0);
                                ctx.drawImage(img2, 0, 0);
                            }
                            else{
                              console.log('nope');
                            }
                        }

                        function loadImage(src, onload) {
                            // http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called
                            var img = new Image();

                            img.onload = onload;
                            img.src = src;

                            return img;
                        }

                        $('#can_hidden').hide();

                    }

                    //Share action

                      FB.ui(

                      {

                          method: "feed",

                          to: $('#id_friend').val(),

                          link: 'https://datapola.tk/?id='+$('#id_friend').val(),

                          name: $('#search_friend').val() + ' debes '+ $('#beers_input').val() + ' Polas',

                          app_id: '1660712804256395',

                          description: 'Ingresa y reporta a los amigos que te deben las polas',

                          caption: 'Datapola',

                          //source: downloadURL,

                          type: 'photo',

                          picture: $('#photo_friend').val()

                      }, function(response){});

                      //Launch canvas
                      setTimeout(drawHidden($('#photo_friend').val()), 500);

                      return false;

                  });

                }

              );

            }, {scope: 'publish_actions'});

          } else {

            // Otherwise, show Login dialog first.

            FB.login(function(response) {

            }, {scope: 'publish_actions'});

          }

        });
    }
}//End of face connect

  //Agegate validation

    function getUrlVars() {
      // Find the params in the URL, Used when linking from another site that has already screened for age
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }

    $(window).load(function() {
      // If There is no Age Cookie or Cookie is set to Failed Hide Contents of Page and display Age Gate PopUp
          if($.cookie('age_verify') == 'underage') {
           window.location.href = "http://www.talkingalcohol.com/espanol/";
          }
          var gateParam = getUrlVars()["agegate"];
          // If Cookie is found and True Show Contents of Page and Remove Age Gate modal
          if($.cookie('age_verify') == 'legal' ||  gateParam == 'valid' ) {
           $.cookie('age_verify' , 'legal' , { expires: 1, path:'/'});
            $('body').addClass('ageGateActive');
            $('.content_ingresar').hide();
            //if is legal show video
            $('.content_video').show();
          }
        else {
            //window.location.href = "http://www.talkingalcohol.com/espanol/";
        }
    });
    // Calculate your age based on inputs

      var day = $("#birthDay").val();
      var month = $("#birthMonth").val();
      var year = $("#birthYear").val();

      // Disallow Letters into the Age Gate Input Fields
      $('#ageGateForm input.date').on('input', function() {
       this.value = this.value.replace(/[\s\D]/g, '', function(){
       });
       if ($(this).val().length == $(this).attr('maxlength'))  {
        if($('#birthDay').val() > 31 || $('#birthMonth').val() > 12 || $('#birthYear').val() > 2014) {
          $(this).val('');
          }
        if($('html').hasClass('no-touch')) {
          $(this).parent().next().find('input.date').focus();}
        };
      });

  // FORM Submit
  $("#ageGateForm").submit(function(){

      var day = $("#birthDay").val();
      var month = $("#birthMonth").val();
      var year = $("#birthYear").val();
      var age  = $("#requiredAge").val();

      // If Input Fields are left empty or not Formatted Correctly Display Message
      if (day == "" || month == "" || year == "" || month.length < 2 || day.length < 2 || year.length < 4){
        $('li.errors').html("Por favor llene los campos con el formato Correcto").slideDown(300);

        return false
     }

      var mydate = new Date();
      mydate.setFullYear(year, month-1, day);

      var currdate = new Date();
      currdate.setFullYear(currdate.getFullYear() - age);

      //  If Underage Redirect to Google Homepage
      if ((currdate - mydate) < 0){
        $.cookie('age_verify', 'underage', { expires: 1, path:'/'});
          $('#ageGateForm').html("
 Solo personas mayores de " + age + " años pueden entrar a este sitio
");
          window.location.href = "http://www.talkingalcohol.com/espanol/";
           return false
       }

       // If Age is Validated Hide form and show contents
      else {
      $.cookie('age_verify' , 'legal' , { expires: 1, path:'/'});
        $('.content_ingresar').hide();
        //if is legal show video
        $('.content_video').show();
        return false
   }

  return false;

});

//iOS emulator function

function iOS() {

  var iDevices = [

    'iPad Simulator',

    'iPhone Simulator',

    'iPod Simulator',

    'iPad',

    'iPhone',

    'iPod'

  ];

  while (iDevices.length) {

    if (navigator.platform === iDevices.pop()){ return true; }

  }
  return false;

}

  //Handle if video is finished
  document.getElementById('vid').addEventListener('ended',myHandler,false);
  function myHandler(e) {
      //Show actions on bottom
      $('body').addClass('steps');
  }

  document.getElementById('vid2').addEventListener('ended',myHandler,false);
  function myHandler(e) {
      //Show actions on bottom
      $('body').addClass('steps');
    }

//Domain validation

    //Function Facebook connect

    //If body have class refered by facebook
    if(body.hasClass('refered')){
      //Display just one video
      $('#vid').show();
      $('#vid2').remove();
      $('.content_facebook_connect').remove();
      //Launch facebook connect if widow is load
      $(window).load(function(){
        //Launch face connect
        faceConnect();
      });
    }else{
      //Display just one video
      $('#vid').remove();
      $('#vid2').show();
      //Click on facebook connect
      $('.content_facebook_connect .fb_boton').click(function(){
          //Launch face connect
          faceConnect();
          $(this).parent().remove();

        });
    }

});
<commit_msg>instancia de canvas con foto de perfil<commit_after>// custom functions
$(function(){

//Video events and functions
$('#vid,#vid2').click(function(){
  this.paused?this.play():this.pause();
  //class de parent
  $(this).parent().toggleClass('paused');
});

//Facebook global variables

var url_l = String((window.location != window.parent.location) ? document.referrer: document.location.href),
    body = $('body'),
    dominio = "datapola.com/",
    movil = false,
    ios =  iOS(),
    ref = document.referrer,
    fb_valid = false;

function faceConnect(){

  (function(d, s, id){

     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    window.fbAsyncInit = function() {
        FB.init({
          appId: '1660712804256395',
          status: true,
          xfbml: true,
          cookie: true,
          version    : 'v2.7',
          channelUrl: url_l+'/channelUrl.html'
        });

        FB.getLoginStatus(function(response) {

          // Check login status on load, and if the user is

          // already logged in, go directly to the welcome message.

          if (response.status == 'connected') {

            //Autoplay video if is connected
            var video = $("#vid, #vid2").get(0);
                video.play();

            //Draw Hidden Canvas
            function drawHidden(url) {

              var can = document.getElementById('can_hidden'),

                ctx = can.getContext('2d'),
                imgUrl = url;

                var img = new Image();
                img.src = url;

                var img2 = new Image();
                img2.src = 'https://'+dominio+'img/bg-canvas.jpg';

                ctx.drawImage(img2, 0, 0);
                ctx.drawImage(img, 30, 80);

                $('#can_hidden').hide();

            }

            //Draw image profile on video
            FB.api(
              '/me',
              'GET',
              {

                "fields":
                "context,first_name,last_name,name,id,picture.width(290).height(390).type(large)"},

              function(response) {

                  //Get profile photo if is refered
                  if(body.hasClass('refered')){
                    document.getElementById('profile-thumb').innerHTML = "";
                  }
              }

            );

            //Login for perimisions
            FB.login(function(response) {
              FB.api(
                '/me/friends',
                'GET',
                {

                  "fields":
                  "context,first_name,last_name,name,id,picture.width(290).height(390).type(large)"},

                function(response) {

                    var boxContainer = $('.box_amigos_facebook');

                    for(y=0; y<response.data.length; y++) {

                      $('.hidden').hide();

                      //Load images
                       boxContainer.append("
" + response.data[y].name + ""+ response.data[y].id +"
");

                      //Action for input
                      boxContainer.hide();

                      $('#search_friend').unbind('click').click(function(event) {
                          $(this).siblings('.box_amigos_facebook').toggle(400);
                      });

                      //Action box profile item
                      $('.box_perfil').click(function(event) {

                        var img = $(this).children('img').attr('src'),
                            nombre = $(this).children('.nombre').text(),
                            id_user = $(this).children('.id_man').text();

                            $('#search_friend').val(nombre);
                            $('#photo_friend').val(img);
                            $('#id_friend').val(id_user);
                            $(this).parent().hide(400);
                      });
                    }

                  //Click for publish BS
                  $('#push_public').click(function(e){
                    //Share action

                      FB.ui(

                      {

                          method: "feed",

                          to: $('#id_friend').val(),

                          link: 'https://datapola.tk/?id='+$('#id_friend').val(),

                          name: $('#search_friend').val() + ' debes '+ $('#beers_input').val() + ' Polas',

                          app_id: '1660712804256395',

                          description: 'Ingresa y reporta a los amigos que te deben las polas',

                          caption: 'Datapola',

                          //source: downloadURL,

                          type: 'photo',

                          picture: $('#photo_friend').val()

                      }, function(response){});

                      //Create canvas

                      function drawHidden(url) {

                        var canvas = document.getElementById('can_hidden');
                        var ctx = canvas.getContext("2d");

                        var img1 = new Image();
                            img1.src = url;

                        var img2 = new Image();
                            img2.src = 'https://'+dominio+'img/bg-canvas.jpg';

                            ctx.drawImage(img1, 0, 0);
                            ctx.drawImage(img2, 0, 0);

                        $('#can_hidden').hide();

                    }

                      //Launch canvas
                      drawHidden($('#photo_friend').val());

                      return false;

                  });

                }

              );

            }, {scope: 'publish_actions'});

          } else {

            // Otherwise, show Login dialog first.

            FB.login(function(response) {

            }, {scope: 'publish_actions'});

          }

        });
    }
}//End of face connect

  //Agegate validation

    function getUrlVars() {
      // Find the params in the URL, Used when linking from another site that has already screened for age
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }

    $(window).load(function() {
      // If There is no Age Cookie or Cookie is set to Failed Hide Contents of Page and display Age Gate PopUp
          if($.cookie('age_verify') == 'underage') {
           window.location.href = "http://www.talkingalcohol.com/espanol/";
          }
          var gateParam = getUrlVars()["agegate"];
          // If Cookie is found and True Show Contents of Page and Remove Age Gate modal
          if($.cookie('age_verify') == 'legal' ||  gateParam == 'valid' ) {
           $.cookie('age_verify' , 'legal' , { expires: 1, path:'/'});
            $('body').addClass('ageGateActive');
            $('.content_ingresar').hide();
            //if is legal show video
            $('.content_video').show();
          }
        else {
            //window.location.href = "http://www.talkingalcohol.com/espanol/";
        }
    });
    // Calculate your age based on inputs

      var day = $("#birthDay").val();
      var month = $("#birthMonth").val();
      var year = $("#birthYear").val();

      // Disallow Letters into the Age Gate Input Fields
      $('#ageGateForm input.date').on('input', function() {
       this.value = this.value.replace(/[\s\D]/g, '', function(){
       });
       if ($(this).val().length == $(this).attr('maxlength'))  {
        if($('#birthDay').val() > 31 || $('#birthMonth').val() > 12 || $('#birthYear').val() > 2014) {
          $(this).val('');
          }
        if($('html').hasClass('no-touch')) {
          $(this).parent().next().find('input.date').focus();}
        };
      });

  // FORM Submit
  $("#ageGateForm").submit(function(){

      var day = $("#birthDay").val();
      var month = $("#birthMonth").val();
      var year = $("#birthYear").val();
      var age  = $("#requiredAge").val();

      // If Input Fields are left empty or not Formatted Correctly Display Message
      if (day == "" || month == "" || year == "" || month.length < 2 || day.length < 2 || year.length < 4){
        $('li.errors').html("Por favor llene los campos con el formato Correcto").slideDown(300);

        return false
     }

      var mydate = new Date();
      mydate.setFullYear(year, month-1, day);

      var currdate = new Date();
      currdate.setFullYear(currdate.getFullYear() - age);

      //  If Underage Redirect to Google Homepage
      if ((currdate - mydate) < 0){
        $.cookie('age_verify', 'underage', { expires: 1, path:'/'});
          $('#ageGateForm').html("
 Solo personas mayores de " + age + " años pueden entrar a este sitio
");
          window.location.href = "http://www.talkingalcohol.com/espanol/";
           return false
       }

       // If Age is Validated Hide form and show contents
      else {
      $.cookie('age_verify' , 'legal' , { expires: 1, path:'/'});
        $('.content_ingresar').hide();
        //if is legal show video
        $('.content_video').show();
        return false
   }

  return false;

});

//iOS emulator function

function iOS() {

  var iDevices = [

    'iPad Simulator',

    'iPhone Simulator',

    'iPod Simulator',

    'iPad',

    'iPhone',

    'iPod'

  ];

  while (iDevices.length) {

    if (navigator.platform === iDevices.pop()){ return true; }

  }
  return false;

}

  //Handle if video is finished
  document.getElementById('vid').addEventListener('ended',myHandler,false);
  function myHandler(e) {
      //Show actions on bottom
      $('body').addClass('steps');
  }

  document.getElementById('vid2').addEventListener('ended',myHandler,false);
  function myHandler(e) {
      //Show actions on bottom
      $('body').addClass('steps');
    }

//Domain validation

    //Function Facebook connect

    //If body have class refered by facebook
    if(body.hasClass('refered')){
      //Display just one video
      $('#vid').show();
      $('#vid2').remove();
      $('.content_facebook_connect').remove();
      //Launch facebook connect if widow is load
      $(window).load(function(){
        //Launch face connect
        faceConnect();
      });
    }else{
      //Display just one video
      $('#vid').remove();
      $('#vid2').show();
      //Click on facebook connect
      $('.content_facebook_connect .fb_boton').click(function(){
          //Launch face connect
          faceConnect();
          $(this).parent().remove();

        });
    }

});
<|endoftext|>


<commit_before>/************************************************************

 * Problem:https://leetcode.com/problems/add-binary/
     Given two binary strings, return their sum (also a binary string).

 * Example 1:
    a = "11", b = "1"
	Return "100".

 * @param {string} a
 * @param {string} b
 * @return {string}

 * Analysis: Loop over each num and handle the carry num.

************************************************************/

export const addBinary = {};

addBinary.iterate = (a, b) => {
	// NOTE: here could hv a input check for int-string;
    let i = a.length - 1,
        j = b.length - 1,
        carry = 0,
        result = "";

    while (i >= 0 || j >= 0 || carry === 1) {
        carry += (i >= 0) ? parseInt(a[i--], 10) : 0;
        carry += (j >= 0) ? parseInt(b[j--], 10) : 0;

        result = (carry % 2) + result;
        carry = parseInt((carry / 2), 10);
    }

    return result;
};

/************************************************************

 * Lessons:
   1. Good practice of looping and handling of various cases of carry num.

************************************************************/
<commit_msg>minor<commit_after>/************************************************************

 * Problem:https://leetcode.com/problems/add-binary/
     Given two binary strings, return their sum (also a binary string).

 * Example 1:
    a = "11", b = "1"
	Return "100".

 * @param {string} a
 * @param {string} b
 * @return {string}

 * Analysis: Loop over each num and handle the carry num.

************************************************************/

export const addBinary = {};

addBinary.iterate = (a, b) => {
	// NOTE: here could hv a input check for int-string;
    let i = a.length - 1,
        j = b.length - 1,
        carry = 0,
        result = "";

    while (i >= 0 || j >= 0 || carry === 1) {
        carry += (i >= 0) ? parseInt(a[i--], 10) : 0;
        carry += (j >= 0) ? parseInt(b[j--], 10) : 0;

        result = (carry % 2) + result;
        carry = parseInt((carry / 2), 10);
    }

    return result;
};

/************************************************************

 * Lessons:
   1. Good practice of looping and handling of various cases of carry num.
   2. Mutiple condition while loop is powerful.

************************************************************/
<|endoftext|>


<commit_before>'use strict'

module.exports = {
  plugins: [ 'import' ],
  rules: {
    'import/default': 'off',
    'import/export': 'error',
    'import/extensions': 'off',
    'import/first': 'off',
    'import/max-dependencies': 'off',
    'import/named': 'error',
    'import/namespace': [ 'error', {
      allowComputed: true,
    } ],
    'import/newline-after-import': [ 'error', {
      count: 1,
    } ],
    'import/no-absolute-path': 'error',
    'import/no-amd': 'off',
    'import/no-anonymous-default-export': 'error',
    'import/no-commonjs': 'off',
    'import/no-deprecated': 'off',
    'import/no-duplicates': 'off',
    'import/no-dynamic-require': 'off',
    'import/no-extraneous-dependencies': [ 'error', {
      devDependencies: true,
      optionalDependencies: true,
      peerDependencies: false,
    } ],
    'import/no-internal-modules': 'off',
    'import/no-mutable-exports': 'error',
    'import/no-named-as-default-member': 'off',
    'import/no-named-as-default': 'error',
    'import/no-named-default': 'error',
    'import/no-namespace': 'off',
    'import/no-nodejs-modules': 'off',
    'import/no-restricted-paths': 'off',
    'import/no-unassigned-import': 'off',
    'import/no-unresolved': [ 'error', {
      commonjs: true,
      caseSensitive: true,
    } ],
    'import/no-webpack-loader-syntax': 'off',
    'import/order': 'error',
    'import/prefer-default-export': 'error',
    'import/unambiguous': 'off',
  },
}
<commit_msg>updated rules for eslint-plugin-import<commit_after>'use strict'

module.exports = {
  plugins: [ 'import' ],
  settings: {
    'import/resolver': {
      node: {
        extensions: [ '.js', '.json' ],
      },
    },
    'import/extensions': [ '.js', '.jsx' ],
    'import/core-modules': [],
    'import/ignore': [
      'node_modules',
      '\\.(coffee|scss|css|less|hbs|svg|json)$',
    ],
  },
  rules: {
    'import/default': 'off',
    'import/export': 'error',
    'import/extensions': 'off',
    'import/first': 'off',
    'import/max-dependencies': 'off',
    'import/named': 'error',
    'import/namespace': [ 'error', {
      allowComputed: true,
    } ],
    'import/newline-after-import': [ 'error', {
      count: 1,
    } ],
    'import/no-absolute-path': 'error',
    'import/no-amd': 'off',
    'import/no-anonymous-default-export': 'error',
    'import/no-commonjs': 'off',
    'import/no-deprecated': 'off',
    'import/no-duplicates': 'off',
    'import/no-dynamic-require': 'off',
    'import/no-extraneous-dependencies': [ 'error', {
      devDependencies: true,
      optionalDependencies: true,
      peerDependencies: false,
    } ],
    'import/no-internal-modules': 'off',
    'import/no-mutable-exports': 'error',
    'import/no-named-as-default-member': 'off',
    'import/no-named-as-default': 'error',
    'import/no-named-default': 'error',
    'import/no-namespace': 'off',
    'import/no-nodejs-modules': 'off',
    'import/no-restricted-paths': 'off',
    'import/no-unassigned-import': 'off',
    'import/no-unresolved': [ 'error', {
      commonjs: true,
      caseSensitive: true,
    } ],
    'import/no-webpack-loader-syntax': 'off',
    'import/order': 'error',
    'import/prefer-default-export': 'error',
    'import/unambiguous': 'off',
  },
}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  plugins: [
    'import',
  ],
  parserOptions: {
    ecmaVersion: 2018,
    sourceType: 'module',
  },
  settings: {
    'import/resolver': {
      node: {
        extensions: ['.js', '.jsx'],
      },
    },
    'import/extensions': ['.js', '.jsx'],
    'import/ignore': ['node_modules'],
  },
  rules: {
    // Static analysis
    'import/no-unresolved': ['error', {commonjs: true}],
    'import/named': 'error',
    'import/default': 'error',
    // TODO: Enable when issue has been fixed:
    // https://github.com/benmosher/eslint-plugin-import/issues/656
    // Original: 'import/namespace': ['error', {allowComputed: true}],
    'import/namespace': 'off',
    'import/no-restricted-paths': 'off',
    'import/no-absolute-path': 'error',
    'import/no-dynamic-require': 'error',
    'import/no-internal-modules': 'off',
    'import/no-webpack-loader-syntax': 'error',
    'import/no-self-import': 'error',

    // Helpful warnings
    'import/export': 'error',
    'import/no-named-as-default': 'error',
    'import/no-named-as-default-member': 'error',
    // TODO: Enable when the rule goes more stable
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-deprecated.md
    // Original: 'import/no-deprecated': 'error',
    'import/no-deprecated': 'off',
    'import/no-extraneous-dependencies': 'error',
    'import/no-mutable-exports': 'error',

    // Module systems
    // TODO: Disable rule due to Unambiguous JavaScript Grammar is rejected from tc39 and moved to inactive proposals
    // https://github.com/tc39/proposals/blob/eb23a429df79d13e0d8fff89dc38a53f5085fa1b/inactive-proposals.md
    // Original: 'import/unambiguous': 'error',
    'import/unambiguous': 'off',
    'import/no-commonjs': 'off',
    'import/no-amd': 'error',
    'import/no-nodejs-modules': 'off',

    // Style guide
    'import/first': 'error',
    'import/exports-last': 'off',
    'import/no-duplicates': 'error',
    'import/no-namespace': 'off',
    'import/extensions': ['error', {js: 'never', jsx: 'never'}],
    'import/order': ['error', {'newlines-between': 'never'}],
    'import/newline-after-import': 'error',
    'import/prefer-default-export': 'error',
    'import/max-dependencies': 'off',
    'import/no-unassigned-import': 'off',
    'import/no-useless-path-segments': 'error',
    'import/no-named-default': 'error',
    'import/no-default-export': 'off',
    'import/no-anonymous-default-export': [
      'error',
      {
        allowArray: true,
        allowArrowFunction: true,
        allowLiteral: true,
        allowObject: true,
      },
    ],
    'import/group-exports': 'off',
  },
};
<commit_msg>Add `import/no-cycle` rule<commit_after>'use strict';

module.exports = {
  plugins: [
    'import',
  ],
  parserOptions: {
    ecmaVersion: 2018,
    sourceType: 'module',
  },
  settings: {
    'import/resolver': {
      node: {
        extensions: ['.js', '.jsx'],
      },
    },
    'import/extensions': ['.js', '.jsx'],
    'import/ignore': ['node_modules'],
  },
  rules: {
    // Static analysis
    'import/no-unresolved': ['error', {commonjs: true}],
    'import/named': 'error',
    'import/default': 'error',
    // TODO: Enable when issue has been fixed:
    // https://github.com/benmosher/eslint-plugin-import/issues/656
    // Original: 'import/namespace': ['error', {allowComputed: true}],
    'import/namespace': 'off',
    'import/no-restricted-paths': 'off',
    'import/no-absolute-path': 'error',
    'import/no-dynamic-require': 'error',
    'import/no-internal-modules': 'off',
    'import/no-webpack-loader-syntax': 'error',
    'import/no-self-import': 'error',
    'import/no-cycle': 'error',

    // Helpful warnings
    'import/export': 'error',
    'import/no-named-as-default': 'error',
    'import/no-named-as-default-member': 'error',
    // TODO: Enable when the rule goes more stable
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-deprecated.md
    // Original: 'import/no-deprecated': 'error',
    'import/no-deprecated': 'off',
    'import/no-extraneous-dependencies': 'error',
    'import/no-mutable-exports': 'error',

    // Module systems
    // TODO: Disable rule due to Unambiguous JavaScript Grammar is rejected from tc39 and moved to inactive proposals
    // https://github.com/tc39/proposals/blob/eb23a429df79d13e0d8fff89dc38a53f5085fa1b/inactive-proposals.md
    // Original: 'import/unambiguous': 'error',
    'import/unambiguous': 'off',
    'import/no-commonjs': 'off',
    'import/no-amd': 'error',
    'import/no-nodejs-modules': 'off',

    // Style guide
    'import/first': 'error',
    'import/exports-last': 'off',
    'import/no-duplicates': 'error',
    'import/no-namespace': 'off',
    'import/extensions': ['error', {js: 'never', jsx: 'never'}],
    'import/order': ['error', {'newlines-between': 'never'}],
    'import/newline-after-import': 'error',
    'import/prefer-default-export': 'error',
    'import/max-dependencies': 'off',
    'import/no-unassigned-import': 'off',
    'import/no-useless-path-segments': 'error',
    'import/no-named-default': 'error',
    'import/no-default-export': 'off',
    'import/no-anonymous-default-export': [
      'error',
      {
        allowArray: true,
        allowArrowFunction: true,
        allowLiteral: true,
        allowObject: true,
      },
    ],
    'import/group-exports': 'off',
  },
};
<|endoftext|>


<commit_before>(function($) {

    /**
     * jQuery dialog with bootstrap styles
     *
     * @author Andriy Oblivantsev <eslider@gmail.com>
     * @copyright 05.11.2014 by WhereGroup GmbH & Co. KG
     */
    $.widget("mapbender.popupDialog", $.ui.dialog, {

        /**
         * Constructor, runs only if the object wasn't created before
         *
         * @return {*}
         * @private
         */
        _create: function() {
            var element = $(this.element);
            var widget = this;

            // overrides default options
            $.extend(this.options, {
                show: {
                    effect:   "fadeIn",
                    duration: 300
                },
                hide: {
                    effect:   "fadeOut",
                    duration: 300
                }
            });

            //resize dialog height fix
            element.bind('popupdialogresize', function(e, ui) {
                var win = $(e.target).closest('.ui-dialog');
                var height = 0;
                $.each($('> .modal-header, > .modal-body, > .modal-footer', win), function(idx, el) {
                    height += $(el).outerHeight();
                });
                win.height(Math.round(height));
                //$("> .modal-body",win).height(height-40);
            });

            // prevent key listening outside the dialog
            element.on('keydown', function(e) {
                e.stopPropagation();
            });

            var result = this._super();

            element.dialogExtend($.extend(true, {
                closable:    true,
                maximizable: true,
                //dblclick: true,
                //minimizable: true,
                //modal: true,
                collapsable: true
            }, this.options));

            var dialog = element.closest('.ui-dialog');
            if(this.options.modal){
                var modal = $('

');

                modal.insertBefore(dialog);
                modal.prepend(dialog);
                modal.find('> .background').on('click mousemove mouseout mouseover',function(e){
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                });
                element.bind('popupdialogclose',function(){
                    modal.fadeOut(function(){
                        modal.remove();
                    });
                });
            }

            // Fullscreen on double click
            $(dialog).dblclick(function() {
                if(element.dialogExtend('state') == 'normal'){
                    element.dialogExtend('maximize');
                }else{
                    element.dialogExtend('restore');
                }
            });

            return result;
        },

        /**
         * Overrides default open method, but adds some Bootstrap classes to the dialog
         * @return {}
         */
        open: function() {
            var content = $(this.element);
            var dialog = content.closest('.ui-dialog');
            var header = $('.ui-widget-header', dialog);
            var closeButton = $('.ui-dialog-titlebar-close', header);
            var dialogBody = $('.ui-dialog-content', dialog);
            var dialogBottomPane = $('.ui-dialog-buttonpane', dialog);
            var dialogBottomButtons = $('.ui-dialog-buttonset > .ui-button', dialogBottomPane);

            // Marriage of jQuery UI and Bootstrap
            dialog.addClass('modal-content');
            dialogBottomPane.addClass('modal-footer');
            dialogBottomButtons.addClass('btn').addClass('button');
            header.addClass('modal-header');
            closeButton.addClass('close');
            dialogBody.addClass('modal-body');

            // Set as mapbender element
            dialog.addClass('mb-element-popup-dialog');

            return this._super();
        }
    });

})(jQuery);<commit_msg>fix popupDialog click target<commit_after>(function($) {

    /**
     * jQuery dialog with bootstrap styles
     *
     * @author Andriy Oblivantsev <eslider@gmail.com>
     * @copyright 05.11.2014 by WhereGroup GmbH & Co. KG
     */
    $.widget("mapbender.popupDialog", $.ui.dialog, {

        /**
         * Constructor, runs only if the object wasn't created before
         *
         * @return {*}
         * @private
         */
        _create: function() {
            var element = $(this.element);
            var widget = this;

            // overrides default options
            $.extend(this.options, {
                show: {
                    effect:   "fadeIn",
                    duration: 300
                },
                hide: {
                    effect:   "fadeOut",
                    duration: 300
                }
            });

            //resize dialog height fix
            element.bind('popupdialogresize', function(e, ui) {
                var win = $(e.target).closest('.ui-dialog');
                var height = 0;
                $.each($('> .modal-header, > .modal-body, > .modal-footer', win), function(idx, el) {
                    height += $(el).outerHeight();
                });
                win.height(Math.round(height));
                //$("> .modal-body",win).height(height-40);
            });

            // prevent key listening outside the dialog
            element.on('keydown', function(e) {
                e.stopPropagation();
            });

            var result = this._super();

            element.dialogExtend($.extend(true, {
                closable:    true,
                maximizable: true,
                //dblclick: true,
                //minimizable: true,
                //modal: true,
                collapsable: true
            }, this.options));

            var dialog = element.closest('.ui-dialog');
            if(this.options.modal){
                var modal = $('

');

                modal.insertBefore(dialog);
                modal.prepend(dialog);
                modal.find('> .background').on('click mousemove mouseout mouseover',function(e){
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                });
                element.bind('popupdialogclose',function(){
                    modal.fadeOut(function(){
                        modal.remove();
                    });
                });
            }

            // Fullscreen on double click
            $(dialog).dblclick(function(event) {
                var target = $(event.target);
                if(!target.is('.ui-dialog-titlebar, .ui-dialog-title')){
                    return;
                }

                if(element.dialogExtend('state') == 'normal'){
                    element.dialogExtend('maximize');
                }else{
                    element.dialogExtend('restore');
                }
            });

            return result;
        },

        /**
         * Overrides default open method, but adds some Bootstrap classes to the dialog
         * @return {}
         */
        open: function() {
            var content = $(this.element);
            var dialog = content.closest('.ui-dialog');
            var header = $('.ui-widget-header', dialog);
            var closeButton = $('.ui-dialog-titlebar-close', header);
            var dialogBody = $('.ui-dialog-content', dialog);
            var dialogBottomPane = $('.ui-dialog-buttonpane', dialog);
            var dialogBottomButtons = $('.ui-dialog-buttonset > .ui-button', dialogBottomPane);

            // Marriage of jQuery UI and Bootstrap
            dialog.addClass('modal-content');
            dialogBottomPane.addClass('modal-footer');
            dialogBottomButtons.addClass('btn').addClass('button');
            header.addClass('modal-header');
            closeButton.addClass('close');
            dialogBody.addClass('modal-body');

            // Set as mapbender element
            dialog.addClass('mb-element-popup-dialog');

            return this._super();
        }
    });

})(jQuery);<|endoftext|>


<commit_before>// @license
// Copyright (c) 2017 Google Inc. All rights reserved.
// This code may only be used under the BSD style license found at
// http://polymer.github.io/LICENSE.txt
// Code distributed by Google as part of this project is also
// subject to an additional IP rights grant found at
// http://polymer.github.io/PATENTS.txt
'use strict';

import assert from '../platform/assert-web.js';

let nextVariableId = 0;

function addType(name, arg) {
  let lowerName = name[0].toLowerCase() + name.substring(1);
  Object.defineProperty(Type, `new${name}`, {
    value: function(arg) {
      return new Type(name, arg);
    }});
  let upperArg = arg ? arg[0].toUpperCase() + arg.substring(1) : '';
  Object.defineProperty(Type.prototype, `${lowerName}${upperArg}`, {
    get: function() {
      assert(this[`is${name}`], `{${this.tag}, ${this.data}} is not of type ${name}`);
      return this.data;
    }});
  Object.defineProperty(Type.prototype, `is${name}`, {
    get: function() {
      return this.tag == name;
    }});
}

class Type {
  constructor(tag, data) {
    assert(typeof tag == 'string');
    assert(data);
    if (tag == 'Entity') {
      assert(data instanceof Schema);
    }
    if (tag == 'SetView') {
      if (!(data instanceof Type) && data.tag && data.data) {
        data = new Type(data.tag, data.data);
      }
    }
    this.tag = tag;
    this.data = data;
  }

  static newHandle(type) {
    console.warn('Type.newView is deprecated. Please use Type.newSetView instead');
    return Type.newSetView(type);
  }

  get isView() {
    console.warn('Type.isView is deprecated. Please use Type.isSetView instead');
    return this.isSetView;
  }

  get viewType() {
    console.warn('Type.viewType is deprecated. Please use Type.setViewType isntead');
    return this.setViewType;
  }

  viewOf() {
    console.warn('Type.viewOf is deprecated. Please use Type.setViewOf instead');
    return this.setViewOf();
  }

  get manifestReferenceName() {
    console.warn('Type.manifestReferenceName is deprecated. Please use Type.manifestReference instead');
    return this.manifestReference;
  }

  get variableReferenceName() {
    console.warn('Type.variableReferenceName is deprecated. Please use Type.variableReference instead');
    return this.variableReference;
  }

  get variableVariable() {
    console.warn('Type.variableVariable is deprecated. Please use Type.variable instead');
    return this.variable;
  }

  // Replaces variableReference types with variable types .
  assignVariableIds(variableMap) {
    if (this.isVariableReference) {
      let name = this.data;
      let sharedVariable = variableMap.get(name);
      if (sharedVariable == undefined) {
        let id = nextVariableId++;
        sharedVariable = new TypeVariable(name, id);
        variableMap.set(name, sharedVariable);
      }
      return Type.newVariable(sharedVariable);
    }

    if (this.isSetView) {
      return this.primitiveType().assignVariableIds(variableMap).setViewOf();
    }

    if (this.isInterface) {
      let shape = this.interfaceShape.clone();
      shape._typeVars.map(({object, field}) => object[field] = object[field].assignVariableIds(variableMap));
      return Type.newInterface(shape);
    }

    return this;
  }

  static unwrapPair(type1, type2) {
    assert(type1 instanceof Type);
    assert(type2 instanceof Type);
    if (type1.isSetView && type2.isSetView)
      return [type1.primitiveType(), type2.primitiveType()]
    return [type1, type2];
  }

  equals(type) {
    if (this.tag !== type.tag)
      return false;
    if (this.tag == 'Entity') {
      return this.data.equals(type.data);
    }
    if (this.isSetView) {
      return this.data.equals(type.data);
    }
    if (this.isInterface) {
      return this.data.equals(type.data);
    }
    if (this.isVariable) {
      return this.data.equals(type.data);
    }
    // TODO: this doesn't always work with the way the parser keeps kind
    // information around
    return JSON.stringify(this.data) == JSON.stringify(type.data);
  }

  _applyExistenceTypeTest(test) {
    if (this.isSetView)
      return this.primitiveType()._applyExistenceTypeTest(test);
    if (this.isInterface)
      return this.data._applyExistenceTypeTest(test);
    return test(this);
  }

  get hasVariable() {
    return this._applyExistenceTypeTest(type => type.isVariable);
  }

  get hasUnresolvedVariable() {
    return this._applyExistenceTypeTest(type => type.isVariable && !type.variable.isResolved);
  }

  get hasVariableReference() {
    return this._applyExistenceTypeTest(type => type.isVariableReference);
  }

  primitiveType() {
    let type = this.setViewType;
    return new Type(type.tag, type.data);
  }

  resolvedType() {
    if (this.isSetView) {
      let resolvedPrimitiveType = this.primitiveType().resolvedType();
      return resolvedPrimitiveType ? resolvedPrimitiveType.setViewOf() : this;
    }
    if (this.isVariable && this.data.isResolved) {
      return this.data.resolution.resolvedType();
    }
    if (this.isTypeVariable && this.data.isResolved) {
      return this.data.resolution.resolvedType();
    }
    return this;
  }

  isResolved() {
    if (this.isSetView) {
      return this.primitiveType().isResolved();
    }
    if (this.isVariable) {
      return this.data.isResolved;
    }
    return true;
  }

  toLiteral() {
    if (this.data.toLiteral)
      return {tag: this.tag, data: this.data.toLiteral()};
    return this;
  }

  static _deliteralizer(tag) {
    switch (tag) {
      case 'Interface':
        return Shape.fromLiteral;
      case 'Entity':
        return Schema.fromLiteral;
      case 'SetView':
        return Type.fromLiteral;
      case 'Tuple':
        return TupleFields.fromLiteral;
      default:
        return a => a;
    }
  }

  static fromLiteral(literal) {
    return new Type(literal.tag, Type._deliteralizer(literal.tag)(literal.data));
  }

  setViewOf() {
    return Type.newSetView(this);
  }

  hasProperty(property) {
    if (property(this))
      return true;
    if (this.isSetView)
      return this.setViewType.hasProperty(property);
    return false;
  }

  toString() {
    if (this.isSetView)
      return `[${this.primitiveType().toString()}]`;
    if (this.isEntity)
      return this.entitySchema.name;
    if (this.isInterface)
      return 'Interface';
    if (this.isTuple)
      return this.tupleFields.toString();
    assert('Add support to serializing type:', this);
  }

  toPrettyString() {
    if (this.isRelation)
      return JSON.stringify(this.data);
    if (this.isSetView) {
      return `${this.primitiveType().toPrettyString()} List`;
    }
    if (this.isVariable)
      return this.data.isResolved ? this.data.resolution.toPrettyString() : `[~${this.name}]`;
    if (this.isVariableReference)
      return `[${this.variableReferenceName}]`;
    if (this.isEntity) {
      // Spit MyTypeFOO to My Type FOO
      if (this.entitySchema.name) {
        return this.entitySchema.name.replace(/([^A-Z])([A-Z])/g, '$1 $2').replace(/([A-Z][^A-Z])/g, ' $1').trim();
      }
      return JSON.stringify(this.entitySchema._model);
    }
    if (this.isTuple)
      return this.tupleFields.toString();
    if (this.isInterface)
      return this.interfaceShape.toPrettyString();
  }
}

addType('Entity', 'schema');
addType('VariableReference');
addType('Variable');
addType('SetView', 'type');
addType('Relation', 'entities');
addType('Interface', 'shape');
addType('Tuple', 'fields');

export default Type;

import Shape from './shape.js';
import Schema from './schema.js';
import TypeVariable from './type-variable.js';
import TupleFields from './tuple-fields.js';<commit_msg>Fix lint error<commit_after>// @license
// Copyright (c) 2017 Google Inc. All rights reserved.
// This code may only be used under the BSD style license found at
// http://polymer.github.io/LICENSE.txt
// Code distributed by Google as part of this project is also
// subject to an additional IP rights grant found at
// http://polymer.github.io/PATENTS.txt
'use strict';

import assert from '../platform/assert-web.js';

let nextVariableId = 0;

function addType(name, arg) {
  let lowerName = name[0].toLowerCase() + name.substring(1);
  Object.defineProperty(Type, `new${name}`, {
    value: function(arg) {
      return new Type(name, arg);
    }});
  let upperArg = arg ? arg[0].toUpperCase() + arg.substring(1) : '';
  Object.defineProperty(Type.prototype, `${lowerName}${upperArg}`, {
    get: function() {
      assert(this[`is${name}`], `{${this.tag}, ${this.data}} is not of type ${name}`);
      return this.data;
    }});
  Object.defineProperty(Type.prototype, `is${name}`, {
    get: function() {
      return this.tag == name;
    }});
}

class Type {
  constructor(tag, data) {
    assert(typeof tag == 'string');
    assert(data);
    if (tag == 'Entity') {
      assert(data instanceof Schema);
    }
    if (tag == 'SetView') {
      if (!(data instanceof Type) && data.tag && data.data) {
        data = new Type(data.tag, data.data);
      }
    }
    this.tag = tag;
    this.data = data;
  }

  static newHandle(type) {
    console.warn('Type.newView is deprecated. Please use Type.newSetView instead');
    return Type.newSetView(type);
  }

  get isView() {
    console.warn('Type.isView is deprecated. Please use Type.isSetView instead');
    return this.isSetView;
  }

  get viewType() {
    console.warn('Type.viewType is deprecated. Please use Type.setViewType isntead');
    return this.setViewType;
  }

  viewOf() {
    console.warn('Type.viewOf is deprecated. Please use Type.setViewOf instead');
    return this.setViewOf();
  }

  get manifestReferenceName() {
    console.warn('Type.manifestReferenceName is deprecated. Please use Type.manifestReference instead');
    return this.manifestReference;
  }

  get variableReferenceName() {
    console.warn('Type.variableReferenceName is deprecated. Please use Type.variableReference instead');
    return this.variableReference;
  }

  get variableVariable() {
    console.warn('Type.variableVariable is deprecated. Please use Type.variable instead');
    return this.variable;
  }

  // Replaces variableReference types with variable types .
  assignVariableIds(variableMap) {
    if (this.isVariableReference) {
      let name = this.data;
      let sharedVariable = variableMap.get(name);
      if (sharedVariable == undefined) {
        let id = nextVariableId++;
        sharedVariable = new TypeVariable(name, id);
        variableMap.set(name, sharedVariable);
      }
      return Type.newVariable(sharedVariable);
    }

    if (this.isSetView) {
      return this.primitiveType().assignVariableIds(variableMap).setViewOf();
    }

    if (this.isInterface) {
      let shape = this.interfaceShape.clone();
      shape._typeVars.map(({object, field}) => object[field] = object[field].assignVariableIds(variableMap));
      return Type.newInterface(shape);
    }

    return this;
  }

  static unwrapPair(type1, type2) {
    assert(type1 instanceof Type);
    assert(type2 instanceof Type);
    if (type1.isSetView && type2.isSetView)
      return [type1.primitiveType(), type2.primitiveType()];
    return [type1, type2];
  }

  equals(type) {
    if (this.tag !== type.tag)
      return false;
    if (this.tag == 'Entity') {
      return this.data.equals(type.data);
    }
    if (this.isSetView) {
      return this.data.equals(type.data);
    }
    if (this.isInterface) {
      return this.data.equals(type.data);
    }
    if (this.isVariable) {
      return this.data.equals(type.data);
    }
    // TODO: this doesn't always work with the way the parser keeps kind
    // information around
    return JSON.stringify(this.data) == JSON.stringify(type.data);
  }

  _applyExistenceTypeTest(test) {
    if (this.isSetView)
      return this.primitiveType()._applyExistenceTypeTest(test);
    if (this.isInterface)
      return this.data._applyExistenceTypeTest(test);
    return test(this);
  }

  get hasVariable() {
    return this._applyExistenceTypeTest(type => type.isVariable);
  }

  get hasUnresolvedVariable() {
    return this._applyExistenceTypeTest(type => type.isVariable && !type.variable.isResolved);
  }

  get hasVariableReference() {
    return this._applyExistenceTypeTest(type => type.isVariableReference);
  }

  primitiveType() {
    let type = this.setViewType;
    return new Type(type.tag, type.data);
  }

  resolvedType() {
    if (this.isSetView) {
      let resolvedPrimitiveType = this.primitiveType().resolvedType();
      return resolvedPrimitiveType ? resolvedPrimitiveType.setViewOf() : this;
    }
    if (this.isVariable && this.data.isResolved) {
      return this.data.resolution.resolvedType();
    }
    if (this.isTypeVariable && this.data.isResolved) {
      return this.data.resolution.resolvedType();
    }
    return this;
  }

  isResolved() {
    if (this.isSetView) {
      return this.primitiveType().isResolved();
    }
    if (this.isVariable) {
      return this.data.isResolved;
    }
    return true;
  }

  toLiteral() {
    if (this.data.toLiteral)
      return {tag: this.tag, data: this.data.toLiteral()};
    return this;
  }

  static _deliteralizer(tag) {
    switch (tag) {
      case 'Interface':
        return Shape.fromLiteral;
      case 'Entity':
        return Schema.fromLiteral;
      case 'SetView':
        return Type.fromLiteral;
      case 'Tuple':
        return TupleFields.fromLiteral;
      default:
        return a => a;
    }
  }

  static fromLiteral(literal) {
    return new Type(literal.tag, Type._deliteralizer(literal.tag)(literal.data));
  }

  setViewOf() {
    return Type.newSetView(this);
  }

  hasProperty(property) {
    if (property(this))
      return true;
    if (this.isSetView)
      return this.setViewType.hasProperty(property);
    return false;
  }

  toString() {
    if (this.isSetView)
      return `[${this.primitiveType().toString()}]`;
    if (this.isEntity)
      return this.entitySchema.name;
    if (this.isInterface)
      return 'Interface';
    if (this.isTuple)
      return this.tupleFields.toString();
    assert('Add support to serializing type:', this);
  }

  toPrettyString() {
    if (this.isRelation)
      return JSON.stringify(this.data);
    if (this.isSetView) {
      return `${this.primitiveType().toPrettyString()} List`;
    }
    if (this.isVariable)
      return this.data.isResolved ? this.data.resolution.toPrettyString() : `[~${this.name}]`;
    if (this.isVariableReference)
      return `[${this.variableReferenceName}]`;
    if (this.isEntity) {
      // Spit MyTypeFOO to My Type FOO
      if (this.entitySchema.name) {
        return this.entitySchema.name.replace(/([^A-Z])([A-Z])/g, '$1 $2').replace(/([A-Z][^A-Z])/g, ' $1').trim();
      }
      return JSON.stringify(this.entitySchema._model);
    }
    if (this.isTuple)
      return this.tupleFields.toString();
    if (this.isInterface)
      return this.interfaceShape.toPrettyString();
  }
}

addType('Entity', 'schema');
addType('VariableReference');
addType('Variable');
addType('SetView', 'type');
addType('Relation', 'entities');
addType('Interface', 'shape');
addType('Tuple', 'fields');

export default Type;

import Shape from './shape.js';
import Schema from './schema.js';
import TypeVariable from './type-variable.js';
import TupleFields from './tuple-fields.js';<|endoftext|>


<commit_before>'use strict';

var locationsInfo = [
['1st and Pike' , 23 , 65 ,6.3],
['SeaTac Airport', 3 ,24 , 1.2],
['Seattle Center', 11, 38 , 3.7],
['Capitol Hill', 20,38 , 2.3],
['Alki', 2 ,16 , 4.6],
];

function Store (name, minCustomer, maxCustomer, avgCookieSale) {
  this.name = name;
  this.minCustomer = minCustomer;
  this.maxCustomer = maxCustomer;
  this.avgCookieSale = avgCookieSale;
}

Store.prototype.customersPerHour = function() {
  return Math.random() * (this.maxCustomer - this.minCustomer) + this.minCustomer;
};

var stores = [];

for(var ea in locationsInfo){
  stores.push(
    new Store(
            locationsInfo[ea][0],
            locationsInfo[ea][1],
            locationsInfo[ea][2],
            locationsInfo[ea][3]
            )
  );
}

var hours = [ '6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'];

for (var i = 0; i < stores.length; i += 1){
  var locationsStats = [];
  var store = stores[i];
  var totalCookiesSold = 0;
  for (var j = 0; j < hours.length; j += 1){
    var flooredNumber = Math.floor(store.avgCookieSale * store.customersPerHour());
    // | Int Value of average sold | String description
    locationsStats.push(flooredNumber);
    totalCookiesSold += flooredNumber;
  }
  console.log(locationsStats);
  store.locationsStats = locationsStats;
  store.totalCookiesSold = totalCookiesSold;
}

Store.prototype.renderStats = function(parentElement){
  for(var statKey in this.locationsStats){
    var li = document.createElement('li');
    li.textContent = this.locationsStats[statKey];
    parentElement.appendChild(li);
  }
};

var parentMyElement = document.getElementById('mylistsOfStats');
console.log(document);
console.log(parentMyElement);

for (var each = 0; each < stores.length; each += 1){
  var eachStore = stores[each];
  var article = document.createElement('article');
  parentMyElement.appendChild(article);
  var title = document.createElement('h2');
  title.textContent = eachStore.name;
  article.appendChild(title);
  var ul = document.createElement('ul');
  article.appendChild(ul);
  eachStore.renderStats(ul);
  var liLast = document.createElement('li');
  liLast.textContent = 'Total: ' + eachStore.totalCookiesSold + ' cookies';
  ul.appendChild(liLast);

}
<commit_msg>added fucs to render elements<commit_after>'use strict';

var locationsInfo = [
['1st and Pike' , 23 , 65 ,6.3],
['SeaTac Airport', 3 ,24 , 1.2],
['Seattle Center', 11, 38 , 3.7],
['Capitol Hill', 20,38 , 2.3],
['Alki', 2 ,16 , 4.6],
];

function Store (name, minCustomer, maxCustomer, avgCookieSale) {
  this.name = name;
  this.minCustomer = minCustomer;
  this.maxCustomer = maxCustomer;
  this.avgCookieSale = avgCookieSale;
}

Store.prototype.customersPerHour = function() {
  return Math.random() * (this.maxCustomer - this.minCustomer) + this.minCustomer;
};

var stores = [];

for(var ea in locationsInfo){
  stores.push(
    new Store(
            locationsInfo[ea][0],
            locationsInfo[ea][1],
            locationsInfo[ea][2],
            locationsInfo[ea][3]
            )
  );
}

var hours = [ '6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'];

for (var i = 0; i < stores.length; i += 1){
  var locationsStats = [];
  var store = stores[i];
  var totalCookiesSold = 0;
  for (var j = 0; j < hours.length; j += 1){
    var flooredNumber = Math.floor(store.avgCookieSale * store.customersPerHour());
    // | Int Value of average sold | String description
    locationsStats.push(flooredNumber);
    totalCookiesSold += flooredNumber;
  }
  console.log(locationsStats);
  store.locationsStats = locationsStats;
  store.totalCookiesSold = totalCookiesSold;
}

function creatingElementNameWithContent(node, content){
  var li = document.createElement(node);
  li.textContent = content;
  return li;
}

Store.prototype.renderStats = function(parentElement){
  // appends Name
  parentElement.appendChild(creatingElementNameWithContent('li', this.name));
  // appends All Hours
  for(var statKey in this.locationsStats){
    parentElement.appendChild(creatingElementNameWithContent(
        'li', this.locationsStats[statKey]
      ));
  }
  // appends the total sold per store
  parentElement.appendChild(creatingElementNameWithContent('li', this.totalCookiesSold));
};

var parentMyElement = document.getElementById('mylistsOfStats');
console.log(document);
console.log(parentMyElement);

for (var each = 0; each < stores.length; each += 1){
  var eachStore = stores[each];
  var article = document.createElement('article');
  parentMyElement.appendChild(article);
  var title = document.createElement('h2');
  title.textContent = eachStore.name;
  article.appendChild(title);
  var ul = document.createElement('ul');
  article.appendChild(ul);
  eachStore.renderStats(ul);
  var liLast = document.createElement('li');
  liLast.textContent = 'Total: ' + eachStore.totalCookiesSold + ' cookies';
  ul.appendChild(liLast);

}
<|endoftext|>


<commit_before>/**
 * Created by Serhii Maksymchuk from Ubrainians for imCode
 * 01.09.17
 *
 * @namespace tinyMCE.activeEditor
 * @namespace tinyMCE.activeEditor.getContent
 */
Imcms.define("imcms-text-editor-initializer",
    [
        "tinyMCE", "imcms-uuid-generator", "jquery", "imcms", "imcms-texts-rest-api", "imcms-events",
        "imcms-text-history-window-builder", "imcms-texts-validation-rest-api", "imcms-text-validation-result-builder"
    ],
    function (tinyMCE, uuidGenerator, $, imcms, textsRestApi, events, textHistoryBuilder, textValidationAPI,
              textValidationBuilder) {
        var ACTIVE_EDIT_AREA_CLASS = "imcms-editor-area--active";

        function saveContent(editor) {
            var textDTO = $(editor.$()).data();
            textDTO.text = editor.getContent();

            textsRestApi.create(textDTO).success(function () { // todo: unfocus current editor, maybe
                events.trigger("imcms-version-modified");
            });
        }

        function addTextHistoryButton(editor) {

            editor.addButton('text_history', {
                icon: 'imcms-text-history-icon',
                tooltip: 'Show text history',
                onclick: function () {
                    var textDTO = $(this.$el).parents(".imcms-editor-area--text")
                        .find(".imcms-editor-content--text")
                        .data();

                    textHistoryBuilder.buildTextHistory(textDTO);
                }
            });
        }

        function addW3cValidationButton(editor) {

            editor.addButton('w3c_validation', {
                icon: 'imcms-w3c-text-validation-icon',
                tooltip: 'Validate Content over W3C',
                onclick: function () {
                    var content = tinyMCE.activeEditor.getContent();
                    var $icon = $(this.$el).find(".mce-ico")
                        .removeAttr("class")
                        .attr("class", "mce-ico mce-i-imcms-w3c-text-validation-processing-icon");

                    textValidationAPI.validate({content: content}).done(function (validationResult) {
                        var iconClass = validationResult.valid
                            ? "mce-i-imcms-w3c-text-validation-valid-icon"
                            : "mce-i-imcms-w3c-text-validation-invalid-icon";

                        $icon.removeAttr("class").attr("class", "mce-ico " + iconClass);

                        if (!validationResult.valid) {
                            textValidationBuilder.buildTextValidationFailWindow(validationResult);
                        }
                    });
                }
            });

        }

        function addImageEditorButton(editor) {

            editor.addButton('image_editor', {
                icon: 'imcms-image--in-text-editor-icon',
                tooltip: 'Add Image',
                onclick: function () {
                    // todo: implement here
                }
            });

        }

        var inlineEditorConfig = {
            skin_url: imcms.contextPath + '/js/libs/tinymce/skins/white',
            cache_suffix: '?v=0.0.1',
            branding: false,
            skin: 'white',
            inline: true,
            toolbar_items_size: 'small',
            content_css: imcms.contextPath + '/css_new/imcms-text_editor.css',
            plugins: ['autolink link lists hr code fullscreen save table contextmenu'],
            toolbar: 'code | bold italic underline | bullist numlist | hr |' +
            ' alignleft aligncenter alignright alignjustify | link image_editor | text_history w3c_validation |' +
            ' fullscreen | save',
            menubar: false,
            statusbar: false,
            init_instance_callback: prepareEditor,
            save_onsavecallback: saveContent,
            setup: function (editor) {
                addTextHistoryButton(editor);
                addW3cValidationButton(editor);
                addImageEditorButton(editor);
            }
        };

        function clearSaveBtnText(editor) {
            delete editor.buttons.save.text;
        }

        function setEditorFocusOnEditControlClick(editor) {
            editor.$()
                .parents('.imcms-editor-area--text')
                .find('.imcms-control--text')
                .on('click', function () {
                    editor.focus();
                });
        }

        function showEditButton($editor) {
            $editor.parent(".imcms-editor-area--text")
                .find(".imcms-control--edit.imcms-control--text")
                .css("display", "block");
        }

        function prepareEditor(editor) {
            clearSaveBtnText(editor);
            setEditorFocusOnEditControlClick(editor);
            showEditButton(editor.$());
        }

        function toggleFocusEditArea(e) {
            var $activeTextArea = $("." + ACTIVE_EDIT_AREA_CLASS);

            if ($activeTextArea.find(".mce-edit-focus").length) {
                return;
            }

            var $closestTextArea = $(e.target).closest(".imcms-editor-area--text");
            $activeTextArea.removeClass(ACTIVE_EDIT_AREA_CLASS);

            if ($closestTextArea.length && $closestTextArea.find(".mce-edit-focus").length) {
                $closestTextArea.addClass(ACTIVE_EDIT_AREA_CLASS);
            }
        }

        $(document).click(toggleFocusEditArea);

        function initTextEditor() {
            var toolbarId = uuidGenerator.generateUUID();
            var textAreaId = uuidGenerator.generateUUID();

            $(this).attr("id", textAreaId)
                .closest(".imcms-editor-area--text")
                .find(".imcms-editor-area__text-toolbar")
                .attr("id", toolbarId);

            var config = $.extend({
                selector: "#" + textAreaId,
                fixed_toolbar_container: "#" + toolbarId
            }, inlineEditorConfig);

            // 4.5.7 the last version compatible with IE 10
            if (Imcms.browserInfo.isIE10) {
                tinyMCE.baseURL = "https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.5.7";
                tinyMCE.suffix = ".min";
            }

            tinyMCE.init(config);
        }

        return {
            initEditor: function () {
                $(".imcms-editor-content--text").each(initTextEditor);
            }
        };
    }
);
<commit_msg>IMCMS-255 - Upgrade server side to work with new client: - Implemented inserting saved image into text editor.<commit_after>/**
 * Created by Serhii Maksymchuk from Ubrainians for imCode
 * 01.09.17
 *
 * @namespace tinyMCE.activeEditor
 * @namespace tinyMCE.activeEditor.getContent
 */
Imcms.define("imcms-text-editor-initializer",
    [
        "tinyMCE", "imcms-uuid-generator", "jquery", "imcms", "imcms-texts-rest-api", "imcms-events",
        "imcms-text-history-window-builder", "imcms-texts-validation-rest-api", "imcms-text-validation-result-builder",
        "imcms-image-editor-builder"
    ],
    function (tinyMCE, uuidGenerator, $, imcms, textsRestApi, events, textHistoryBuilder, textValidationAPI,
              textValidationBuilder, imageEditorBuilder) {

        var ACTIVE_EDIT_AREA_CLASS = "imcms-editor-area--active";

        function saveContent(editor) {
            var textDTO = $(editor.$()).data();
            textDTO.text = editor.getContent();

            textsRestApi.create(textDTO).success(function () { // todo: unfocus current editor, maybe
                events.trigger("imcms-version-modified");
            });
        }

        function addTextHistoryButton(editor) {

            editor.addButton('text_history', {
                icon: 'imcms-text-history-icon',
                tooltip: 'Show text history',
                onclick: function () {
                    var textDTO = $(this.$el).parents(".imcms-editor-area--text")
                        .find(".imcms-editor-content--text")
                        .data();

                    textHistoryBuilder.buildTextHistory(textDTO);
                }
            });
        }

        function addW3cValidationButton(editor) {

            editor.addButton('w3c_validation', {
                icon: 'imcms-w3c-text-validation-icon',
                tooltip: 'Validate Content over W3C',
                onclick: function () {
                    var content = tinyMCE.activeEditor.getContent();
                    var $icon = $(this.$el).find(".mce-ico")
                        .removeAttr("class")
                        .attr("class", "mce-ico mce-i-imcms-w3c-text-validation-processing-icon");

                    textValidationAPI.validate({content: content}).done(function (validationResult) {
                        var iconClass = validationResult.valid
                            ? "mce-i-imcms-w3c-text-validation-valid-icon"
                            : "mce-i-imcms-w3c-text-validation-invalid-icon";

                        $icon.removeAttr("class").attr("class", "mce-ico " + iconClass);

                        if (!validationResult.valid) {
                            textValidationBuilder.buildTextValidationFailWindow(validationResult);
                        }
                    });
                }
            });

        }

        function addImageEditorButton(editor) {

            editor.addButton('image_editor', {
                icon: 'imcms-image--in-text-editor-icon',
                tooltip: 'Add Image',
                onclick: function () {
                    var uniqueId = Date.now();
                    var tagHTML = '

';
                    var imageDTO = $(this.$el).parents(".imcms-editor-area--text")
                        .find(".imcms-editor-content--text")
                        .data();

                    imageDTO.index = null;
                    imageDTO.inText = true;

                    tinyMCE.activeEditor.execCommand('mceInsertContent', false, tagHTML);

                    var $tag = $(tinyMCE.activeEditor.getBody()).find("#" + uniqueId);

                    imageEditorBuilder.setTag($tag).build(imageDTO);
                }
            });

        }

        var inlineEditorConfig = {
            skin_url: imcms.contextPath + '/js/libs/tinymce/skins/white',
            cache_suffix: '?v=0.0.1',
            branding: false,
            skin: 'white',
            inline: true,
            toolbar_items_size: 'small',
            content_css: imcms.contextPath + '/css_new/imcms-text_editor.css',
            plugins: ['autolink link lists hr code fullscreen save table contextmenu'],
            toolbar: 'code | bold italic underline | bullist numlist | hr |' +
            ' alignleft aligncenter alignright alignjustify | link image_editor | text_history w3c_validation |' +
            ' fullscreen | save',
            menubar: false,
            statusbar: false,
            init_instance_callback: prepareEditor,
            save_onsavecallback: saveContent,
            setup: function (editor) {
                addTextHistoryButton(editor);
                addW3cValidationButton(editor);
                addImageEditorButton(editor);
            }
        };

        function clearSaveBtnText(editor) {
            delete editor.buttons.save.text;
        }

        function setEditorFocusOnEditControlClick(editor) {
            editor.$()
                .parents('.imcms-editor-area--text')
                .find('.imcms-control--text')
                .on('click', function () {
                    editor.focus();
                });
        }

        function showEditButton($editor) {
            $editor.parent(".imcms-editor-area--text")
                .find(".imcms-control--edit.imcms-control--text")
                .css("display", "block");
        }

        function prepareEditor(editor) {
            clearSaveBtnText(editor);
            setEditorFocusOnEditControlClick(editor);
            showEditButton(editor.$());
        }

        function toggleFocusEditArea(e) {
            var $activeTextArea = $("." + ACTIVE_EDIT_AREA_CLASS);

            if ($activeTextArea.find(".mce-edit-focus").length) {
                return;
            }

            var $closestTextArea = $(e.target).closest(".imcms-editor-area--text");
            $activeTextArea.removeClass(ACTIVE_EDIT_AREA_CLASS);

            if ($closestTextArea.length && $closestTextArea.find(".mce-edit-focus").length) {
                $closestTextArea.addClass(ACTIVE_EDIT_AREA_CLASS);
            }
        }

        $(document).click(toggleFocusEditArea);

        function initTextEditor() {
            var toolbarId = uuidGenerator.generateUUID();
            var textAreaId = uuidGenerator.generateUUID();

            $(this).attr("id", textAreaId)
                .closest(".imcms-editor-area--text")
                .find(".imcms-editor-area__text-toolbar")
                .attr("id", toolbarId);

            var config = $.extend({
                selector: "#" + textAreaId,
                fixed_toolbar_container: "#" + toolbarId
            }, inlineEditorConfig);

            // 4.5.7 the last version compatible with IE 10
            if (Imcms.browserInfo.isIE10) {
                tinyMCE.baseURL = "https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.5.7";
                tinyMCE.suffix = ".min";
            }

            tinyMCE.init(config);
        }

        return {
            initEditor: function () {
                $(".imcms-editor-content--text").each(initTextEditor);
            }
        };
    }
);
<|endoftext|>