<commit_before>var http = require('http');

var data={};
var pending={};

var fs=require('fs');

var writable={'chains.json':true};

var server=http.createServer(function (req, res) {

  console.log("Serving "+req.url);

  var parts = req.url.split('?');
  parts[0]=parts[0].substring(1); // strip trailing /
  var key=parts[0];

  if(req.method=='PUT')
  {
    // a new value is given, fetch body data and store it
    if(!data[key]) data[key]='';
    req.on('data',function(chunk){data[key]+=chunk;});
    req.on('end' ,function()
    {
      res.end();

      // if it denotes a file, store it.
      if(writable[key])
      {
        fs.writeFileSync(key,data[key]);
        delete data[key];
      }

      // answer pending requests for this key
      var waiter=pending[key];
      if(pending[key])
      {
        pending[key].end(data[key]);
        delete pending[key];
        delete data[key];
      }
    });
  }
  else if(fs.existsSync(key) && fs.statSync(key).isFile() && key.indexOf("..")==-1)
  {
    res.setHeader("Content-Type", "text/html");
    res.end(fs.readFileSync(parts[0]));
  }
  else
  {
    if(pending[key]) pending[key].end();
    pending[key]=res;
  }
});

var port=8082;
server.listen(port);
console.log("Listening at:%s", port);

<commit_msg>server.js: path anstelle von fs für exitst, für ältere node version<commit_after>var http = require('http');

var data={};
var pending={};

var fs=require('fs');
var path=require('path');

var writable={'chains.json':true};

var server=http.createServer(function (req, res) {

  console.log("Serving "+req.url);

  var parts = req.url.split('?');
  parts[0]=parts[0].substring(1); // strip trailing /
  var key=parts[0];

  if(req.method=='PUT')
  {
    // a new value is given, fetch body data and store it
    if(!data[key]) data[key]='';
    req.on('data',function(chunk){data[key]+=chunk;});
    req.on('end' ,function()
    {
      res.end();

      // if it denotes a file, store it.
      if(writable[key])
      {
        fs.writeFileSync(key,data[key]);
        delete data[key];
      }

      // answer pending requests for this key
      var waiter=pending[key];
      if(pending[key])
      {
        pending[key].end(data[key]);
        delete pending[key];
        delete data[key];
      }
    });
  }
  else if(path.existsSync(key) && fs.statSync(key).isFile() && key.indexOf("..")==-1)
  {
    res.setHeader("Content-Type", "text/html");
    res.end(fs.readFileSync(parts[0]));
  }
  else
  {
    if(pending[key]) pending[key].end();
    pending[key]=res;
  }
});

var port=8082;
server.listen(port);
console.log("Listening at:%s", port);

<|endoftext|>


<commit_before>function utils() {
	var a_table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
	this.b_table = a_table.split(' ').map(function(s){ return parseInt(s,16) });
}

utils.prototype.trace = function(msg) {
	//return;
	try {
		if (window.console) {
			window.console.log(msg);
		}
	} catch (e) {
	}
};

utils.prototype.crc32 = function(str) {
    var crc = crc ^ (-1);
    for(var i=0, iTop=str.length; i<iTop; i++) {
        crc = ( crc >>> 8 ) ^ this.b_table[( crc ^ str.charCodeAt( i ) ) & 0xFF];
    }
    return (crc ^ (-1)) >>> 0;
};

utils.prototype.getLinuxTime = function() {
	return Math.round((new Date()).getTime() / 1000);
}

module.exports = utils;

<commit_msg>Added nrand and report as methods<commit_after>function utils() {
	var a_table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
	this.b_table = a_table.split(' ').map(function(s){ return parseInt(s,16) });

}

utils.prototype.trace = function(msg) {
	//return;
	try {
		if (window.console) {
			window.console.log(msg);
		}
	} catch (e) {
	}
};

utils.prototype.crc32 = function(str) {
    var crc = crc ^ (-1);
    for(var i=0, iTop=str.length; i<iTop; i++) {
        crc = ( crc >>> 8 ) ^ this.b_table[( crc ^ str.charCodeAt( i ) ) & 0xFF];
    }
    return (crc ^ (-1)) >>> 0;
};

utils.prototype.getLinuxTime = function() {
	return Math.round((new Date()).getTime() / 1000);
}

utils.prototype.nrand = function(center, width) {
	var x1, x2, rad, y1;
	do {
		x1 = 2 * Math.random() - 1;
		x2 = 2 * Math.random() - 1;
		rad = x1 * x1 + x2 * x2;
	} while(rad >= 1 || rad == 0);
	var c = Math.sqrt(-2 * Math.log(rad) / rad);
	return ((x1 * c) * (width/2)) + center;
};

utils.prototype.report = function(msg) {
	if(typeof window !== 'undefined') {
		$("#txtMain").html(msg);
	} else {
		console.log(msg);
	}
}

module.exports = utils;

<|endoftext|>


<commit_before>biojsvispsicquic = require('./pGraph.js');
module.exports = biojsvispsicquic;<commit_msg>moved from js to root folder<commit_after><|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import ResourceLink from 'common/ResourceLink';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import Checklist from 'parser/shared/modules/features/Checklist';
import Rule from 'parser/shared/modules/features/Checklist/Rule';
import Requirement from 'parser/shared/modules/features/Checklist/Requirement';
import PreparationRule from 'parser/shared/modules/features/Checklist/PreparationRule';
import GenericCastEfficiencyRequirement from 'parser/shared/modules/features/Checklist/GenericCastEfficiencyRequirement';

class ProtectionWarriorChecklist extends React.PureComponent {
  static propTypes = {
    castEfficiency: PropTypes.object.isRequired,
    combatant: PropTypes.shape({
      hasTalent: PropTypes.func.isRequired,
      hasTrinket: PropTypes.func.isRequired,
    }).isRequired,
    thresholds: PropTypes.object.isRequired,
  };

  render() {
    const { combatant, castEfficiency, thresholds } = this.props;

    const AbilityRequirement = props => (
      <GenericCastEfficiencyRequirement
        castEfficiency={castEfficiency.getCastEfficiencyForSpellId(props.spell)}
        {...props}
      />
    );

    return (
      <Checklist>
        <Rule
          name="Rotational Spells"
          description={(
            <>
              As a protection warrior you want to maximize your rage generation which can be done by casting these spells as frequent as possible.
            </>
          )}
        >
          <AbilityRequirement spell={SPELLS.THUNDER_CLAP.id} />
          <AbilityRequirement spell={SPELLS.SHIELD_SLAM.id} />
          {combatant.hasTalent(SPELLS.BOOMING_VOICE_TALENT.id) && <AbilityRequirement spell={SPELLS.DEMORALIZING_SHOUT.id} />}
          {combatant.hasTalent(SPELLS.DRAGON_ROAR_TALENT.id) && <AbilityRequirement spell={SPELLS.DRAGON_ROAR_TALENT.id} />}
        </Rule>

        {this.rulesForShortCD()}

        <Rule
          name="Defensive Cooldowns"
          description={(
            <>
              As a protection warrior you have many options to mitigate damage and should be using all of them. Take <SpellLink id={SPELLS.SPELL_REFLECTION.id} /> with a grain a salt as some bosses it is not as helpful on as others.
            </>
          )}
        >
          <AbilityRequirement spell={SPELLS.SHIELD_WALL.id} />
          <AbilityRequirement spell={SPELLS.LAST_STAND.id} />
          <AbilityRequirement spell={SPELLS.SPELL_REFLECTION.id} />
          {!combatant.hasTalent(SPELLS.BOOMING_VOICE_TALENT.id) && <AbilityRequirement spell={SPELLS.DEMORALIZING_SHOUT.id} />}
        </Rule>

        <Rule
          name="Offensive Cooldowns"
          description={(
            <>
              As a protection warrior you have a few cooldowns you can use to maximize your damage which you should be using aggresively.
            </>
          )}
          >
            <AbilityRequirement spell={SPELLS.AVATAR_TALENT.id} />
            {combatant.hasTalent(SPELLS.BOOMING_VOICE_TALENT.id) && <AbilityRequirement spell={SPELLS.DEMORALIZING_SHOUT.id} />}
            {combatant.hasTalent(SPELLS.RAVAGER_TALENT_PROTECTION.id) && <AbilityRequirement spell={SPELLS.RAVAGER_TALENT_PROTECTION.id} />}
          </Rule>

        <Rule
          name="Don't get too angry"
          description={(
            <>
              Try to not waste <ResourceLink id={RESOURCE_TYPES.RAGE.id} /> by generating more when you are already at max.
            </>
          )}
        >
          <Requirement name="Lost Rage" thresholds={thresholds.rageDetails} />
        </Rule>

        <Rule
          name="Utility"
          description={(
            <>
              As a protection warrior you have many spells that provide utility to the raid. You should use these when you need to
            </>
          )}
        >
          <AbilityRequirement spell={SPELLS.RALLYING_CRY.id} />
          <AbilityRequirement spell={SPELLS.INTERCEPT.id} />
        </Rule>

        <PreparationRule thresholds={thresholds} />
      </Checklist>
    );
  }
}

export default ProtectionWarriorChecklist;
<commit_msg>Cleaning up a bit<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import ResourceLink from 'common/ResourceLink';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import Checklist from 'parser/shared/modules/features/Checklist';
import Rule from 'parser/shared/modules/features/Checklist/Rule';
import Requirement from 'parser/shared/modules/features/Checklist/Requirement';
import PreparationRule from 'parser/shared/modules/features/Checklist/PreparationRule';
import GenericCastEfficiencyRequirement from 'parser/shared/modules/features/Checklist/GenericCastEfficiencyRequirement';

class ProtectionWarriorChecklist extends React.PureComponent {
  static propTypes = {
    castEfficiency: PropTypes.object.isRequired,
    combatant: PropTypes.shape({
      hasTalent: PropTypes.func.isRequired,
      hasTrinket: PropTypes.func.isRequired,
    }).isRequired,
    thresholds: PropTypes.object.isRequired,
  };

  render() {
    const { combatant, castEfficiency, thresholds } = this.props;

    const AbilityRequirement = props => (
      <GenericCastEfficiencyRequirement
        castEfficiency={castEfficiency.getCastEfficiencyForSpellId(props.spell)}
        {...props}
      />
    );

    return (
      <Checklist>
        <Rule
          name="Rotational Spells"
          description={(
            <>
              As a protection warrior you want to maximize your rage generation which can be done by casting these spells as frequent as possible.
            </>
          )}
        >
          <AbilityRequirement spell={SPELLS.THUNDER_CLAP.id} />
          <AbilityRequirement spell={SPELLS.SHIELD_SLAM.id} />
          {combatant.hasTalent(SPELLS.STORM_BOLT_TALENT.id) && <AbilityRequirement spell={SPELLS.STORM_BOLT_TALENT.id} />}
          {combatant.hasTalent(SPELLS.BOOMING_VOICE_TALENT.id) && <AbilityRequirement spell={SPELLS.DEMORALIZING_SHOUT.id} />}
          {combatant.hasTalent(SPELLS.DRAGON_ROAR_TALENT.id) && <AbilityRequirement spell={SPELLS.DRAGON_ROAR_TALENT.id} />}

        </Rule>

        <Rule
          name="Defensive Cooldowns"
          description={(
            <>
              As a protection warrior you have many options to mitigate damage and should be using all of them. Take <SpellLink id={SPELLS.SPELL_REFLECTION.id}/> with a grain a salt as some bosses it is not as helpful on as others
            </>
          )}
        >
          <AbilityRequirement spell={SPELLS.SHIELD_WALL.id} />
          <AbilityRequirement spell={SPELLS.LAST_STAND.id} />
          <AbilityRequirement spell={SPELLS.SPELL_REFLECTION.id} />
          {!combatant.hasTalent(SPELLS.BOOMING_VOICE_TALENT.id) && <AbilityRequirement spell={SPELLS.DEMORALIZING_SHOUT.id} />}
        </Rule>

        <Rule
          name="Offensive Cooldowns"
          description={(
            <>
              As a protection warrior you have a few cooldowns you can use to maximize your damage which you should be using aggresively.
            </>
          )}
          >
            <AbilityRequirement spell={SPELLS.AVATAR_TALENT.id} />
            {combatant.hasTalent(SPELLS.BOOMING_VOICE_TALENT.id) && <AbilityRequirement spell={SPELLS.DEMORALIZING_SHOUT.id} />}
            {combatant.hasTalent(SPELLS.RAVAGER_TALENT_PROTECTION.id) && <AbilityRequirement spell={SPELLS.RAVAGER_TALENT_PROTECTION.id} />}

          </Rule>

        <Rule
          name="Don't get too angry"
          description={(
            <>
              Try to not waste <ResourceLink id={RESOURCE_TYPES.RAGE.id} /> by generating more when you are already at max.
            </>
          )}
        >
          <Requirement name="Lost Rage" thresholds={thresholds.rageDetails}/>
        </Rule>

        <Rule
          name="Utility"
          description={(
            <>
              As a protection warrior you have many spells that provide utility to the raid. You should use these when you need to
            </>
          )}
        >
          <AbilityRequirement spell={SPELLS.RALLYING_CRY.id} />
          <AbilityRequirement spell={SPELLS.INTERCEPT.id} />
        </Rule>

        <PreparationRule thresholds={thresholds} />
      </Checklist>
    );
  }
}

export default ProtectionWarriorChecklist;
<|endoftext|>


<commit_before>import React from 'react';
import { browserHistory } from 'react-router';
import { identity } from 'lodash';

import Progress from '../../helpers/progress.js';

export default ({ student, selectStudent, updateStudent }) => {
  const message = `mailto:student@email.com?subject=Coaching By Hack Reactor&body=Hello
  -Student Name Here -,%0D%0A%0D%0A Welcome to your Personal Coaching .%0D%0A%0D%0A
  Here will body of the email where we can put whatever we like`;
  console.log("selectStudent", selectStudent)
  console.log("updateStudent", updateStudent)
  const onDetailsClick = () => {
    selectStudent(student);
    browserHistory.push('/student');
  };

  const onCheckBoxClick = () => {
    if (student.contacted === '') {
      student.contacted = 'checked';
    }
    student.contacted = '';
    updateStudent(student);
  };

  return (

      {/* {console.log(student)} */}

            {student.name}
               Actions

{student.email}

 Inverview:{student.interview}

 Decision:{student.decision}

 Contacted:
              <input type="checkbox" id="contacted" checked={student.contacted} onChange={identity} />

            Current progress: {student.lesson} of 8
            <Progress className="students-progress-bar" />

Details

            Actions

 Complete Level: Done

 Introduction Email: Send

 Reminder Email:Send

 On-Hold Email:Send

  );
};
<commit_msg>before pull<commit_after>import React from 'react';
import { browserHistory } from 'react-router';
import { identity } from 'lodash';

import Progress from '../../helpers/progress.js';

export default ({ student, selectStudent, updateStudent }) => {
  const message = `mailto:student@email.com?subject=Coaching By Hack Reactor&body=Hello
  -Student Name Here -,%0D%0A%0D%0A Welcome to your Personal Coaching .%0D%0A%0D%0A
  Here will body of the email where we can put whatever we like`;
  console.log("selectStudent", selectStudent);
  console.log("updateStudent", updateStudent);
  const onDetailsClick = () => {
    selectStudent(student);
    browserHistory.push('/student');
  };

  const onCheckBoxClick = () => {
    if (student.contacted === '') {
      student.contacted = 'checked';
    }
    student.contacted = '';
    updateStudent(student);
  };

  return (

      {/* {console.log(student)} */}

            {student.name}
               Actions

{student.email}

 Inverview:{student.interview}

 Decision:{student.decision}

 Contacted:
              <input type="checkbox" id="contacted" checked={student.contacted} onChange={identity} />

            Current progress: {student.lesson} of 8
            <Progress className="students-progress-bar" />

Details

            Actions

 Complete Level: Done

 Introduction Email: Send

 Reminder Email:Send

 On-Hold Email:Send

  );
};
<|endoftext|>


<commit_before>var screen = $(window).width();
var inviteList = $('#invite-list button');
var saveButton = $('#save');

if (screen > 420) {
    $('.blackout').css('display', 'block')
}

saveButton.click(function () {
    $('.confirm').css('display', 'none');
    $('.question').text('¿Querés saber quienes vienen?');
    inviteList.css('display', 'block');
})

// LISTA DE CONFIRMADOS!
var invitedPep = {
	"invitados": [
		{ "name":"Ernesto", "subsecretary":"Ciudad Inteligente", "direction":"DGGEDI"  },
		{ "name":"Ponja", "subsecretary":"Ciudad Inteligente", "direction":"DGGEDI"  }
	]
}

var listInvited = ( function () {

	var name;
	var subse;
	var direction;
	var listElement = $('.invited-list');

	for (var i = 0; i < invitedPep.invitados.length; i++) {
		name = invitedPep.invitados[i].name;
		subse = invitedPep.invitados[i].subsecretary;
		direction = invitedPep.invitados[i].direction;

		listElement.append('
 ' + name + ' ' + '' + subse + ', ' + direction + '
');
	}
})()

<commit_msg>update users<commit_after>var screen = $(window).width();
var inviteList = $('#invite-list button');
var saveButton = $('#save');

if (screen > 420) {
    $('.blackout').css('display', 'block')
}

saveButton.click(function () {
    $('.confirm').css('display', 'none');
    $('.question').text('¿Querés saber quienes vienen?');
    inviteList.css('display', 'block');
})

// LISTA DE CONFIRMADOS!
var invitedPep = {
	"invitados": [
		{ "name":"Florchi", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Ernesto", "subsecretary":"Ciudad Inteligente", "direction":"GEDI"  },
		{ "name":"Ponja", "subsecretary":"Ciudad Inteligente", "direction":"GEDI"  }
	]
}

var listInvited = ( function () {

	var name;
	var subse;
	var direction;
	var listElement = $('.invited-list');

	for (var i = 0; i < invitedPep.invitados.length; i++) {
		name = invitedPep.invitados[i].name;
		subse = invitedPep.invitados[i].subsecretary;
		direction = invitedPep.invitados[i].direction;

		listElement.append('
 ' + name + ' ' + '' + subse + ', ' + direction + '
');
	}
})()

<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    stylish = require('jshint-stylish'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    plumber = require('gulp-plumber'),
    sass = require('gulp-ruby-sass'),
    rename = require('gulp-rename'),
    livereload = require('gulp-livereload');

var paths = {
  sassFiles: 'static/styles/sass/**/*.scss',
  sassFolder: 'static/styles/sass',
  htmlFiles: [
    '**/*.html'
  ],
  scriptFiles: [
    'static/scripts/**/*.js'
  ]
};

gulp.task('jshint', function() {
  return gulp.src(paths.scriptFiles)
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

/* Sass Task */
gulp.task('sass', function() {
  sass(paths.sassFiles, {
    sourcemap: true,
    noCache: true,
    style: 'compressed'
  })
  .on('error', sass.logError)
  .pipe(plumber())
  .pipe(gulp.dest('build/styles'))
  .pipe(livereload());
});

/* Autoreload html */
gulp.task('html', function() {
  gulp.src(paths.htmlFiles)
    .pipe(plumber())
    .pipe(livereload());
});

/* Autoreload scripts */
gulp.task('script', function() {
  gulp.src(paths.scriptFiles)
    .pipe(plumber())
    .pipe(livereload());
});

gulp.task('watch', function() {
  livereload.listen();

  gulp.watch(paths.sassFiles, ['sass']);

  gulp.watch('static/scripts', ['script']);

  gulp.watch('**/*.html', ['html']);

});

gulp.task('default', ['sass', 'jshint', 'watch']);<commit_msg>Updated gulp task for watching changes to scripts<commit_after>'use strict';

var gulp = require('gulp'),
    stylish = require('jshint-stylish'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    plumber = require('gulp-plumber'),
    sass = require('gulp-ruby-sass'),
    rename = require('gulp-rename'),
    livereload = require('gulp-livereload');

var paths = {
  sassFiles: 'static/styles/sass/**/*.scss',
  sassFolder: 'static/styles/sass',
  htmlFiles: [
    '**/*.html'
  ],
  scriptFiles: [
    'static/scripts/**/*.js'
  ]
};

gulp.task('jshint', function() {
  return gulp.src(paths.scriptFiles)
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

/* Sass Task */
gulp.task('sass', function() {
  sass(paths.sassFiles, {
    sourcemap: true,
    noCache: true,
    style: 'compressed'
  })
  .on('error', sass.logError)
  .pipe(plumber())
  .pipe(gulp.dest('build/styles'))
  .pipe(livereload());
});

/* Autoreload html */
gulp.task('html', function() {
  gulp.src(paths.htmlFiles)
    .pipe(plumber())
    .pipe(livereload());
});

/* Autoreload scripts */
gulp.task('script', function() {
  gulp.src(paths.scriptFiles)
    .pipe(plumber())
    .pipe(livereload());
});

gulp.task('watch', function() {
  livereload.listen();

  gulp.watch(paths.sassFiles, ['sass']);

  gulp.watch('static/scripts/**/*.js', ['script']);

  gulp.watch('**/*.html', ['html']);

});

gulp.task('default', ['sass', 'jshint', 'watch']);<|endoftext|>


<commit_before>import colors from '../../components/styles/colors'
import dims from '../../components/styles/dims'

export default {
  TopBar: {
    height: dims.topBar,
    backgroundColor: colors.black,
    color: colors.white
  },
  title: {
    color: colors.white,
    fontSize: 20,
    position: 'fixed',
    left: '50%',
    transform: 'translate(-50%, 0)',
    height: dims.topBar,
    display: 'flex',
    alignItems: 'center'
  }
}
<commit_msg>change style of top bar<commit_after>import colors from '../../components/styles/colors'
import dims from '../../components/styles/dims'

export default {
  TopBar: {
    height: dims.topBar,
    backgroundColor: colors.white,
    borderBottom: `1px solid ${colors.black}`
  },
  title: {
    color: colors.black,
    fontSize: 20,
    position: 'fixed',
    left: '50%',
    transform: 'translate(-50%, 0)',
    height: dims.topBar,
    display: 'flex',
    alignItems: 'center'
  }
}
<|endoftext|>


<commit_before>defaultConf = {
    height: 100,
    width: 300,
    fingerprintLength: 4
};

describe("The constructor is supposed a proper Captcha object", function() {
    it('Constructor Captcha exists', function(){
        expect(Captcha).toBeDefined();
    });
    var captcha = new Captcha();
    it("Captcha object is not null", function(){
       expect(captcha).not.toBeNull();
    });
    it('captcha object should be an instance of Captcha class', function(){
        expect(captcha instanceof Captcha).toBeTruthy();
    });
    it('the height of the svg should be set to the configured height', function(){
        expect(Number(captcha.height)).toEqual(defaultConf.height);
    });
    it('the width of the svg should be set to the configured width', function(){
        expect(Number(captcha.width)).toEqual(defaultConf.width);
    });
    it('the length of the fingerprint should be set to the configured fingerprintLength', function(){
        expect(Number(captcha.fingerprintLength)).toEqual(defaultConf.fingerprintLength);
    });
});
<commit_msg>Add base test for getSVG function. It fails<commit_after>defaultConf = {
    height: 100,
    width: 300,
    fingerprintLength: 4
};

describe("The constructor is supposed a proper Captcha object", function() {
    it('Constructor Captcha exists', function(){
        expect(Captcha).toBeDefined();
    });
    var captcha = new Captcha();
    it("Captcha object is not null", function(){
       expect(captcha).not.toBeNull();
    });
    it('captcha object should be an instance of Captcha class', function(){
        expect(captcha instanceof Captcha).toBeTruthy();
    });
    it('the height of the svg should be set to the configured height', function(){
        expect(Number(captcha.height)).toEqual(defaultConf.height);
    });
    it('the width of the svg should be set to the configured width', function(){
        expect(Number(captcha.width)).toEqual(defaultConf.width);
    });
    it('the length of the fingerprint should be set to the configured fingerprintLength', function(){
        expect(Number(captcha.fingerprintLength)).toEqual(defaultConf.fingerprintLength);
    });
});

describe('The setData method of Captcha objects is supposed to generate the captcha as SVG', function(){
    var captcha = new Captcha();
    it('getSVG method is supposed to be a function', function(){
        expect(typeof captcha.getSVG()).toEqual('function');
    });
});
<|endoftext|>


<commit_before>const MAIN_BLOCK = 'dual-listbox';

const CONTAINER_ELEMENT = 'dual-listbox__container';
const AVAILABLE_ELEMENT = 'dual-listbox__available';
const SELECTED_ELEMENT = 'dual-listbox__selected';
const TITLE_ELEMENT = 'dual-listbox__title';
const ITEM_ELEMENT = 'dual-listbox__item';
const BUTTONS_ELEMENT = 'dual-listbox__buttons';
const BUTTON_ELEMENT = 'dual-listbox__button';
const SEARCH_ELEMENT = 'dual-listbox__search';

const SELECTED_MODIFIER = 'dual-listbox__item--selected';

/**
 * Dual select interface allowing the user to select items from a list of provided options.
 * @class
 */
class DualListbox {
    constructor(selector, options = {}) {
        this.setDefaults();
        this.selected = [];
        this.available = [];

        if (DualListbox.isDomElement(selector)) {
            this.select = selector;
        } else {
            this.select = document.querySelector(selector);
        }

        this._initOptions(options);
        this._initReusableElements();
        this._splitOptions(this.select.options);
        if (options.options !== undefined) {
            this._splitOptions(options.options);
        }
        this._buildDualListbox(this.select.parentNode);
        this._addActions();

        this.redraw();

        return this.dualListbox;
    }

    /**
     * Sets the default values that can be overwritten.
     */
    setDefaults() {
        this.addEvent = null; // TODO: Remove in favor of eventListener
        this.removeEvent = null; // TODO: Remove in favor of eventListener
        this.availableTitle = 'Available options';
        this.selectedTitle = 'Selected options';
        this.addButtonText = 'add';
        this.removeButtonText = 'remove';
        this.addAllButtonText = 'add all';
        this.removeAllButtonText = 'remove all';
        this.searchPlaceholder = 'Search';
    }

    /**
     * Add the listItem to the selected list.
     *
     * @param {NodeElement} listItem
     */
    addSelected(listItem) {
        let index = this.available.indexOf(listItem);
        if (index > -1) {
            this.available.splice(index, 1);
            this.selected.push(listItem);
            this._selectOption(listItem.dataset.id);
            this.redraw();

            let event = document.createEvent("HTMLEvents");
            event.initEvent("added", false, true);
            event.addedElement = listItem;
            this.dualListbox.dispatchEvent(event);
        }
    }

    /**
     * Redraws the Dual listbox content
     */
    redraw() {
        this.updateAvailableListbox();
        this.updateSelectedListbox();
    }

    /**
     * Removes the listItem from the selected list.
     *
     * @param {NodeElement} listItem
     */
    removeSelected(listItem) {
        let index = this.selected.indexOf(listItem);
        if (index > -1) {
            this.selected.splice(index, 1);
            this.available.push(listItem);
            this._deselectOption(listItem.dataset.id);
            this.redraw();

            let event = document.createEvent("HTMLEvents");
            event.initEvent("removed", false, true);
            event.removedElement = listItem;
            this.dualListbox.dispatchEvent(event);
        }
    }

    /**
     * Filters the listboxes with the given searchString.
     *
     * @param {Object} searchString
     * @param dualListbox
     */
    searchLists(searchString, dualListbox) {
        let items = dualListbox.querySelectorAll(`.${ITEM_ELEMENT}`);
        let lowerCaseSearchString = searchString.toLowerCase();

        for (let i = 0; i < items.length; i++) {
            let item = items[i];
            if (item.textContent.toLowerCase().indexOf(lowerCaseSearchString) === -1) {
                item.style.display = 'none';
            } else {
                item.style.display = 'list-item';
            }
        }
    }

    /**
     * Update the elements in the available listbox;
     */
    updateAvailableListbox() {
        this._updateListbox(this.availableList, this.available);
    }

    /**
     * Update the elements in the selected listbox;
     */
    updateSelectedListbox() {
        this._updateListbox(this.selectedList, this.selected);
    }

    //
    //
    // PRIVATE FUNCTIONS
    //
    //

    /**
     * Action to set all listItems to selected.
     */
    _actionAllSelected(event) {
        event.preventDefault();

        while (this.available.length > 0) {
            this.addSelected(this.available[0]);
        }
    }

    /**
     * Update the elements in the listbox;
     */
    _updateListbox(list, elements) {
        list.innerHTML = '';
        for (let i = 0; i < elements.length; i++) {
            let listItem = elements[i];
            list.appendChild(listItem);
        }
    }

    /**
     * Action to set one listItem to selected.
     */
    _actionItemSelected(event) {
        event.preventDefault();

        let selected = this.dualListbox.querySelector(`.${SELECTED_MODIFIER}`);
        if (selected) {
            this.addSelected(selected);
        }
    }

    /**
     * Action to set all listItems to available.
     */
    _actionAllDeselected(event) {
        event.preventDefault();

        while (this.selected.length > 0) {
            this.removeSelected(this.selected[0]);
        }
    }

    /**
     * Action to set one listItem to available.
     */
    _actionItemDeselected(event) {
        event.preventDefault();

        let selected = this.dualListbox.querySelector(`.${SELECTED_MODIFIER}`);
        if (selected) {
            this.removeSelected(selected);
        }
    }

    /**
     * Action when double clicked on a listItem.
     */
    _actionItemDoubleClick(listItem, event = null) {
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }

        if (this.selected.indexOf(listItem) > -1) {
            this.removeSelected(listItem);
        } else {
            this.addSelected(listItem);
        }
    }

    /**
     * Action when single clicked on a listItem.
     */
    _actionItemClick(listItem, dualListbox, event = null) {
        if (event) {
            event.preventDefault();
        }

        let items = dualListbox.querySelectorAll(`.${ITEM_ELEMENT}`);

        for (let i = 0; i < items.length; i++) {
            let value = items[i];
            if (value !== listItem) {
                value.classList.remove(SELECTED_MODIFIER);
            }
        }

        if (listItem.classList.contains(SELECTED_MODIFIER)) {
            listItem.classList.remove(SELECTED_MODIFIER);
        } else {
            listItem.classList.add(SELECTED_MODIFIER);
        }
    }

    /**
     * @Private
     * Adds the needed actions to the elements.
     */
    _addActions() {
        this._addButtonActions();
        this._addSearchActions();
    }

    /**
     * Adds the actions to the buttons that are created.
     */
    _addButtonActions() {
        this.add_all_button.addEventListener('click', (event) => this._actionAllSelected(event));
        this.add_button.addEventListener('click', (event) => this._actionItemSelected(event));
        this.remove_button.addEventListener('click', (event) => this._actionItemDeselected(event));
        this.remove_all_button.addEventListener('click', (event) => this._actionAllDeselected(event));
    }

    /**
     * Adds the click items to the listItem.
     *
     * @param {Object} listItem
     */
    _addClickActions(listItem) {
        listItem.addEventListener('dblclick', (event) => this._actionItemDoubleClick(listItem, event));
        listItem.addEventListener('click', (event) => this._actionItemClick(listItem, this.dualListbox, event));
        return listItem;
    }

    /**
     * @Private
     * Adds the actions to the search input.
     */
    _addSearchActions() {
        this.search.addEventListener('change', (event) => this.searchLists(event.target.value, this.dualListbox));
        this.search.addEventListener('keyup', (event) => this.searchLists(event.target.value, this.dualListbox));
    }

    /**
     * @Private
     * Builds the Dual listbox and makes it visible to the user.
     */
    _buildDualListbox(container) {
        this.select.style.display = 'none';

        this.dualListBoxContainer.appendChild(this._createList(this.availableListTitle, this.availableList));
        this.dualListBoxContainer.appendChild(this.buttons);
        this.dualListBoxContainer.appendChild(this._createList(this.selectedListTitle, this.selectedList));

        this.dualListbox.appendChild(this.search);
        this.dualListbox.appendChild(this.dualListBoxContainer);

        container.insertBefore(this.dualListbox, this.select);
    }

    /**
     * Creates list with the header.
     */
    _createList(header, list) {
        let result = document.createElement('div');
        result.appendChild(header);
        result.appendChild(list);
        return result;
    }

    /**
     * Creates the buttons to add/remove the selected item.
     */
    _createButtons() {
        this.buttons = document.createElement('div');
        this.buttons.classList.add(BUTTONS_ELEMENT);

        this.add_all_button = document.createElement('button');
        this.add_all_button.classList.add(BUTTON_ELEMENT);
        this.add_all_button.innerHTML = this.addAllButtonText;

        this.add_button = document.createElement('button');
        this.add_button.classList.add(BUTTON_ELEMENT);
        this.add_button.innerHTML = this.addButtonText;

        this.remove_button = document.createElement('button');
        this.remove_button.classList.add(BUTTON_ELEMENT);
        this.remove_button.innerHTML = this.removeButtonText;

        this.remove_all_button = document.createElement('button');
        this.remove_all_button.classList.add(BUTTON_ELEMENT);
        this.remove_all_button.innerHTML = this.removeAllButtonText;

        this.buttons.appendChild(this.add_all_button);
        this.buttons.appendChild(this.add_button);
        this.buttons.appendChild(this.remove_button);
        this.buttons.appendChild(this.remove_all_button);
    }

    /**
     * @Private
     * Creates the listItem out of the option.
     */
    _createListItem(option) {
        let listItem = document.createElement('li');

        listItem.classList.add(ITEM_ELEMENT);
        listItem.innerHTML = option.text;
        listItem.dataset.id = option.value;

        this._addClickActions(listItem);

        return listItem;
    }

    /**
     * @Private
     * Creates the search input.
     */
    _createSearch() {
        this.search = document.createElement('input');
        this.search.classList.add(SEARCH_ELEMENT);
        this.search.placeholder = this.searchPlaceholder;
    }

    /**
     * @Private
     * Deselects the option with the matching value
     *
     * @param {Object} value
     */
    _deselectOption(value) {
        let options = this.select.options;

        for (let i = 0; i < options.length; i++) {
            let option = options[i];
            if (option.value === value) {
                option.selected = false;
            }
        }

        if (this.removeEvent) {
            this.removeEvent(value);
        }
    }

    /**
     * @Private
     * Set the option variables to this.
     */
    _initOptions(options) {
        for (let key in options) {
            if (options.hasOwnProperty(key)) {
                this[key] = options[key];
            }
        }
    }

    /**
     * @Private
     * Creates all the static elements for the Dual listbox.
     */
    _initReusableElements() {
        this.dualListbox = document.createElement('div');
        this.dualListbox.classList.add(MAIN_BLOCK);
        if (this.select.id) {
            this.dualListbox.classList.add(this.select.id);
        }

        this.dualListBoxContainer = document.createElement('div');
        this.dualListBoxContainer.classList.add(CONTAINER_ELEMENT);

        this.availableList = document.createElement('ul');
        this.availableList.classList.add(AVAILABLE_ELEMENT);

        this.selectedList = document.createElement('ul');
        this.selectedList.classList.add(SELECTED_ELEMENT);

        this.availableListTitle = document.createElement('div');
        this.availableListTitle.classList.add(TITLE_ELEMENT);
        this.availableListTitle.innerText = this.availableTitle;

        this.selectedListTitle = document.createElement('div');
        this.selectedListTitle.classList.add(TITLE_ELEMENT);
        this.selectedListTitle.innerText = this.selectedTitle;

        this._createButtons();
        this._createSearch();
    }

    /**
     * @Private
     * Selects the option with the matching value
     *
     * @param {Object} value
     */
    _selectOption(value) {
        let options = this.select.options;

        for (let i = 0; i < options.length; i++) {
            let option = options[i];
            if (option.value === value) {
                option.selected = true;
            }
        }

        if (this.addEvent) {
            this.addEvent(value);
        }
    }

    /**
     * @Private
     * Splits the options and places them in the correct list.
     */
    _splitOptions(options) {
        for (let i = 0; i < options.length; i++) {
            let option = options[i];
            if (DualListbox.isDomElement(option)) {
                this._addOption({
                    text: option.innerHTML,
                    value: option.value,
                    selected: option.attributes.selected
                });
            } else {
                this._addOption(option);
            }
        }
    }

    /**
     * @Private
     * Adds option to the selected of available list (depending on the data).
     */
    _addOption(option) {
        let listItem = this._createListItem(option);

        if (option.selected) {
            this.selected.push(listItem);
        } else {
            this.available.push(listItem);
        }
    }

    /**
     * @Private
     * Returns true if argument is a DOM element
     */
    static isDomElement(o) {
        return (
            typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
                o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string"
        );
    }
}

export default DualListbox;
export {DualListbox};
<commit_msg>return from constructor removed, because it introduced errors<commit_after>const MAIN_BLOCK = 'dual-listbox';

const CONTAINER_ELEMENT = 'dual-listbox__container';
const AVAILABLE_ELEMENT = 'dual-listbox__available';
const SELECTED_ELEMENT = 'dual-listbox__selected';
const TITLE_ELEMENT = 'dual-listbox__title';
const ITEM_ELEMENT = 'dual-listbox__item';
const BUTTONS_ELEMENT = 'dual-listbox__buttons';
const BUTTON_ELEMENT = 'dual-listbox__button';
const SEARCH_ELEMENT = 'dual-listbox__search';

const SELECTED_MODIFIER = 'dual-listbox__item--selected';

/**
 * Dual select interface allowing the user to select items from a list of provided options.
 * @class
 */
class DualListbox {
    constructor(selector, options = {}) {
        this.setDefaults();
        this.selected = [];
        this.available = [];

        if (DualListbox.isDomElement(selector)) {
            this.select = selector;
        } else {
            this.select = document.querySelector(selector);
        }

        this._initOptions(options);
        this._initReusableElements();
        this._splitOptions(this.select.options);
        if (options.options !== undefined) {
            this._splitOptions(options.options);
        }
        this._buildDualListbox(this.select.parentNode);
        this._addActions();

        this.redraw();
    }

    /**
     * Sets the default values that can be overwritten.
     */
    setDefaults() {
        this.addEvent = null; // TODO: Remove in favor of eventListener
        this.removeEvent = null; // TODO: Remove in favor of eventListener
        this.availableTitle = 'Available options';
        this.selectedTitle = 'Selected options';
        this.addButtonText = 'add';
        this.removeButtonText = 'remove';
        this.addAllButtonText = 'add all';
        this.removeAllButtonText = 'remove all';
        this.searchPlaceholder = 'Search';
    }

    /**
     * Add the listItem to the selected list.
     *
     * @param {NodeElement} listItem
     */
    addSelected(listItem) {
        let index = this.available.indexOf(listItem);
        if (index > -1) {
            this.available.splice(index, 1);
            this.selected.push(listItem);
            this._selectOption(listItem.dataset.id);
            this.redraw();

            let event = document.createEvent("HTMLEvents");
            event.initEvent("added", false, true);
            event.addedElement = listItem;
            this.dualListbox.dispatchEvent(event);
        }
    }

    /**
     * Redraws the Dual listbox content
     */
    redraw() {
        this.updateAvailableListbox();
        this.updateSelectedListbox();
    }

    /**
     * Removes the listItem from the selected list.
     *
     * @param {NodeElement} listItem
     */
    removeSelected(listItem) {
        let index = this.selected.indexOf(listItem);
        if (index > -1) {
            this.selected.splice(index, 1);
            this.available.push(listItem);
            this._deselectOption(listItem.dataset.id);
            this.redraw();

            let event = document.createEvent("HTMLEvents");
            event.initEvent("removed", false, true);
            event.removedElement = listItem;
            this.dualListbox.dispatchEvent(event);
        }
    }

    /**
     * Filters the listboxes with the given searchString.
     *
     * @param {Object} searchString
     * @param dualListbox
     */
    searchLists(searchString, dualListbox) {
        let items = dualListbox.querySelectorAll(`.${ITEM_ELEMENT}`);
        let lowerCaseSearchString = searchString.toLowerCase();

        for (let i = 0; i < items.length; i++) {
            let item = items[i];
            if (item.textContent.toLowerCase().indexOf(lowerCaseSearchString) === -1) {
                item.style.display = 'none';
            } else {
                item.style.display = 'list-item';
            }
        }
    }

    /**
     * Update the elements in the available listbox;
     */
    updateAvailableListbox() {
        this._updateListbox(this.availableList, this.available);
    }

    /**
     * Update the elements in the selected listbox;
     */
    updateSelectedListbox() {
        this._updateListbox(this.selectedList, this.selected);
    }

    //
    //
    // PRIVATE FUNCTIONS
    //
    //

    /**
     * Action to set all listItems to selected.
     */
    _actionAllSelected(event) {
        event.preventDefault();

        while (this.available.length > 0) {
            this.addSelected(this.available[0]);
        }
    }

    /**
     * Update the elements in the listbox;
     */
    _updateListbox(list, elements) {
        list.innerHTML = '';
        for (let i = 0; i < elements.length; i++) {
            let listItem = elements[i];
            list.appendChild(listItem);
        }
    }

    /**
     * Action to set one listItem to selected.
     */
    _actionItemSelected(event) {
        event.preventDefault();

        let selected = this.dualListbox.querySelector(`.${SELECTED_MODIFIER}`);
        if (selected) {
            this.addSelected(selected);
        }
    }

    /**
     * Action to set all listItems to available.
     */
    _actionAllDeselected(event) {
        event.preventDefault();

        while (this.selected.length > 0) {
            this.removeSelected(this.selected[0]);
        }
    }

    /**
     * Action to set one listItem to available.
     */
    _actionItemDeselected(event) {
        event.preventDefault();

        let selected = this.dualListbox.querySelector(`.${SELECTED_MODIFIER}`);
        if (selected) {
            this.removeSelected(selected);
        }
    }

    /**
     * Action when double clicked on a listItem.
     */
    _actionItemDoubleClick(listItem, event = null) {
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }

        if (this.selected.indexOf(listItem) > -1) {
            this.removeSelected(listItem);
        } else {
            this.addSelected(listItem);
        }
    }

    /**
     * Action when single clicked on a listItem.
     */
    _actionItemClick(listItem, dualListbox, event = null) {
        if (event) {
            event.preventDefault();
        }

        let items = dualListbox.querySelectorAll(`.${ITEM_ELEMENT}`);

        for (let i = 0; i < items.length; i++) {
            let value = items[i];
            if (value !== listItem) {
                value.classList.remove(SELECTED_MODIFIER);
            }
        }

        if (listItem.classList.contains(SELECTED_MODIFIER)) {
            listItem.classList.remove(SELECTED_MODIFIER);
        } else {
            listItem.classList.add(SELECTED_MODIFIER);
        }
    }

    /**
     * @Private
     * Adds the needed actions to the elements.
     */
    _addActions() {
        this._addButtonActions();
        this._addSearchActions();
    }

    /**
     * Adds the actions to the buttons that are created.
     */
    _addButtonActions() {
        this.add_all_button.addEventListener('click', (event) => this._actionAllSelected(event));
        this.add_button.addEventListener('click', (event) => this._actionItemSelected(event));
        this.remove_button.addEventListener('click', (event) => this._actionItemDeselected(event));
        this.remove_all_button.addEventListener('click', (event) => this._actionAllDeselected(event));
    }

    /**
     * Adds the click items to the listItem.
     *
     * @param {Object} listItem
     */
    _addClickActions(listItem) {
        listItem.addEventListener('dblclick', (event) => this._actionItemDoubleClick(listItem, event));
        listItem.addEventListener('click', (event) => this._actionItemClick(listItem, this.dualListbox, event));
        return listItem;
    }

    /**
     * @Private
     * Adds the actions to the search input.
     */
    _addSearchActions() {
        this.search.addEventListener('change', (event) => this.searchLists(event.target.value, this.dualListbox));
        this.search.addEventListener('keyup', (event) => this.searchLists(event.target.value, this.dualListbox));
    }

    /**
     * @Private
     * Builds the Dual listbox and makes it visible to the user.
     */
    _buildDualListbox(container) {
        this.select.style.display = 'none';

        this.dualListBoxContainer.appendChild(this._createList(this.availableListTitle, this.availableList));
        this.dualListBoxContainer.appendChild(this.buttons);
        this.dualListBoxContainer.appendChild(this._createList(this.selectedListTitle, this.selectedList));

        this.dualListbox.appendChild(this.search);
        this.dualListbox.appendChild(this.dualListBoxContainer);

        container.insertBefore(this.dualListbox, this.select);
    }

    /**
     * Creates list with the header.
     */
    _createList(header, list) {
        let result = document.createElement('div');
        result.appendChild(header);
        result.appendChild(list);
        return result;
    }

    /**
     * Creates the buttons to add/remove the selected item.
     */
    _createButtons() {
        this.buttons = document.createElement('div');
        this.buttons.classList.add(BUTTONS_ELEMENT);

        this.add_all_button = document.createElement('button');
        this.add_all_button.classList.add(BUTTON_ELEMENT);
        this.add_all_button.innerHTML = this.addAllButtonText;

        this.add_button = document.createElement('button');
        this.add_button.classList.add(BUTTON_ELEMENT);
        this.add_button.innerHTML = this.addButtonText;

        this.remove_button = document.createElement('button');
        this.remove_button.classList.add(BUTTON_ELEMENT);
        this.remove_button.innerHTML = this.removeButtonText;

        this.remove_all_button = document.createElement('button');
        this.remove_all_button.classList.add(BUTTON_ELEMENT);
        this.remove_all_button.innerHTML = this.removeAllButtonText;

        this.buttons.appendChild(this.add_all_button);
        this.buttons.appendChild(this.add_button);
        this.buttons.appendChild(this.remove_button);
        this.buttons.appendChild(this.remove_all_button);
    }

    /**
     * @Private
     * Creates the listItem out of the option.
     */
    _createListItem(option) {
        let listItem = document.createElement('li');

        listItem.classList.add(ITEM_ELEMENT);
        listItem.innerHTML = option.text;
        listItem.dataset.id = option.value;

        this._addClickActions(listItem);

        return listItem;
    }

    /**
     * @Private
     * Creates the search input.
     */
    _createSearch() {
        this.search = document.createElement('input');
        this.search.classList.add(SEARCH_ELEMENT);
        this.search.placeholder = this.searchPlaceholder;
    }

    /**
     * @Private
     * Deselects the option with the matching value
     *
     * @param {Object} value
     */
    _deselectOption(value) {
        let options = this.select.options;

        for (let i = 0; i < options.length; i++) {
            let option = options[i];
            if (option.value === value) {
                option.selected = false;
            }
        }

        if (this.removeEvent) {
            this.removeEvent(value);
        }
    }

    /**
     * @Private
     * Set the option variables to this.
     */
    _initOptions(options) {
        for (let key in options) {
            if (options.hasOwnProperty(key)) {
                this[key] = options[key];
            }
        }
    }

    /**
     * @Private
     * Creates all the static elements for the Dual listbox.
     */
    _initReusableElements() {
        this.dualListbox = document.createElement('div');
        this.dualListbox.classList.add(MAIN_BLOCK);
        if (this.select.id) {
            this.dualListbox.classList.add(this.select.id);
        }

        this.dualListBoxContainer = document.createElement('div');
        this.dualListBoxContainer.classList.add(CONTAINER_ELEMENT);

        this.availableList = document.createElement('ul');
        this.availableList.classList.add(AVAILABLE_ELEMENT);

        this.selectedList = document.createElement('ul');
        this.selectedList.classList.add(SELECTED_ELEMENT);

        this.availableListTitle = document.createElement('div');
        this.availableListTitle.classList.add(TITLE_ELEMENT);
        this.availableListTitle.innerText = this.availableTitle;

        this.selectedListTitle = document.createElement('div');
        this.selectedListTitle.classList.add(TITLE_ELEMENT);
        this.selectedListTitle.innerText = this.selectedTitle;

        this._createButtons();
        this._createSearch();
    }

    /**
     * @Private
     * Selects the option with the matching value
     *
     * @param {Object} value
     */
    _selectOption(value) {
        let options = this.select.options;

        for (let i = 0; i < options.length; i++) {
            let option = options[i];
            if (option.value === value) {
                option.selected = true;
            }
        }

        if (this.addEvent) {
            this.addEvent(value);
        }
    }

    /**
     * @Private
     * Splits the options and places them in the correct list.
     */
    _splitOptions(options) {
        for (let i = 0; i < options.length; i++) {
            let option = options[i];
            if (DualListbox.isDomElement(option)) {
                this._addOption({
                    text: option.innerHTML,
                    value: option.value,
                    selected: option.attributes.selected
                });
            } else {
                this._addOption(option);
            }
        }
    }

    /**
     * @Private
     * Adds option to the selected of available list (depending on the data).
     */
    _addOption(option) {
        let listItem = this._createListItem(option);

        if (option.selected) {
            this.selected.push(listItem);
        } else {
            this.available.push(listItem);
        }
    }

    /**
     * @Private
     * Returns true if argument is a DOM element
     */
    static isDomElement(o) {
        return (
            typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
                o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string"
        );
    }
}

export default DualListbox;
export {DualListbox};
<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular
    .module('dowser')
    .directive('chart', chart);

  /** @ngInject */
  function chart() {
    var directive = {
      restrict: 'E',
      templateUrl: 'app/components/chart/chart.html',
      scope: {},
      controller: ChartController,
      controllerAs: 'vm',
      bindToController: true
    };

    return directive;

    /** @ngInject */
    function ChartController($timeout, $element) {
      var self = this;

      self.render = function() {
        var chart = c3.generate({
          bindto: $element.find('div')[0],
          data: {
            columns: [
              ['data1', 30, 200, 100, 400, 150, 250],
              ['data2', 50, 20, 10, 40, 15, 25]
            ]
          }
        });
      }

      self.render();
    }
  }

})();
<commit_msg>Remove unecessary injection<commit_after>(function() {
  'use strict';

  angular
    .module('dowser')
    .directive('chart', chart);

  /** @ngInject */
  function chart() {
    var directive = {
      restrict: 'E',
      templateUrl: 'app/components/chart/chart.html',
      scope: {},
      controller: ChartController,
      controllerAs: 'vm',
      bindToController: true
    };

    return directive;

    /** @ngInject */
    function ChartController($element) {
      var self = this;

      self.render = function() {
        var chart = c3.generate({
          bindto: $element.find('div')[0],
          data: {
            columns: [
              ['data1', 30, 200, 100, 400, 150, 250],
              ['data2', 50, 20, 10, 40, 15, 25]
            ]
          }
        });
      }

      self.render();
    }
  }

})();
<|endoftext|>


<commit_before>
var parse = require("./parse");
var solve = require("./algebra");
var compileObserver = require("./compile-observer");
var compileBinder = require("./compile-binder");
var Observers = require("./observers");

module.exports = bind;
function bind(target, targetPath, descriptor) {

    descriptor.target = target;
    descriptor.targetPath = targetPath;
    var source = descriptor.source = descriptor.source || target;

    var sourcePath = descriptor["<-"] || descriptor["<->"] || "";
    var twoWay = descriptor.twoWay = "<->" in descriptor;
    descriptor.sourcePath = sourcePath;
    var value = descriptor.value;
    var parameters = descriptor.parameters = descriptor.parameters || source;
    var trace = descriptor.trace;

    // promote convert and revert from a converter object up to the descriptor
    if (descriptor.converter) {
        var converter = descriptor.converter;
        if (converter.convert) {
            descriptor.convert = converter.convert.bind(converter);
        }
        if (converter.revert) {
            descriptor.revert = converter.revert.bind(converter);
        }
    }

    var convert = descriptor.convert;
    var revert = descriptor.revert;

    var sourceSyntax = descriptor.sourceSyntax = parse(sourcePath);
    var targetSyntax = descriptor.targetSyntax = parse(targetPath);

    // <- source to target
    trace && console.log("DEFINE BINDING", targetPath, "<-", sourcePath, target);
    var cancelSourceToTarget = bindOneWay(
        target,
        targetSyntax,
        source,
        sourceSyntax,
        parameters,
        convert,
        descriptor,
        trace ? {
            sourcePath: sourcePath,
            targetPath: targetPath
        } : undefined
    );

    // -> target to source
    var cancelTargetToSource = noop;
    if (twoWay) {
        trace && console.log("DEFINE BINDING", targetPath, "->", sourcePath, source);
        cancelTargetToSource = bindOneWay(
            source,
            sourceSyntax,
            target,
            targetSyntax,
            parameters,
            revert,
            descriptor,
            trace ? {
                sourcePath: targetPath,
                targetPath: sourcePath
            } : undefined
        );
    }

    return function cancel() {
        cancelSourceToTarget();
        cancelTargetToSource();
    };

}

function bindOneWay(
    target,
    targetSyntax,
    source,
    sourceSyntax,
    parameters,
    convert,
    descriptor,
    trace
) {

    // rotate operators from the target side of the binding to the
    // by inversion onto the source
    var solution = solve(targetSyntax, sourceSyntax);
    targetSyntax = solution[0];
    sourceSyntax = solution[1];

    var observeSource = compileObserver(sourceSyntax);
    if (convert) {
        observeSource = Observers.makeConverterObserver(
            observeSource,
            convert,
            source
        );
    }

    var bindTarget = compileBinder(targetSyntax);
    return bindTarget(
        observeSource,
        source,
        target,
        parameters,
        descriptor,
        trace
    );

}

function noop() {}

<commit_msg>Rewrite trace paths after algebra<commit_after>
var parse = require("./parse");
var solve = require("./algebra");
var stringify = require("./stringify");
var compileObserver = require("./compile-observer");
var compileBinder = require("./compile-binder");
var Observers = require("./observers");

module.exports = bind;
function bind(target, targetPath, descriptor) {

    descriptor.target = target;
    descriptor.targetPath = targetPath;
    var source = descriptor.source = descriptor.source || target;

    var sourcePath = descriptor["<-"] || descriptor["<->"] || "";
    var twoWay = descriptor.twoWay = "<->" in descriptor;
    descriptor.sourcePath = sourcePath;
    var value = descriptor.value;
    var parameters = descriptor.parameters = descriptor.parameters || source;
    var trace = descriptor.trace;

    // promote convert and revert from a converter object up to the descriptor
    if (descriptor.converter) {
        var converter = descriptor.converter;
        if (converter.convert) {
            descriptor.convert = converter.convert.bind(converter);
        }
        if (converter.revert) {
            descriptor.revert = converter.revert.bind(converter);
        }
    }

    var convert = descriptor.convert;
    var revert = descriptor.revert;

    var sourceSyntax = descriptor.sourceSyntax = parse(sourcePath);
    var targetSyntax = descriptor.targetSyntax = parse(targetPath);

    // <- source to target
    trace && console.log("DEFINE BINDING", targetPath, "<-", sourcePath, target);
    var cancelSourceToTarget = bindOneWay(
        target,
        targetSyntax,
        source,
        sourceSyntax,
        parameters,
        convert,
        descriptor,
        trace
    );

    // -> target to source
    var cancelTargetToSource = noop;
    if (twoWay) {
        trace && console.log("DEFINE BINDING", targetPath, "->", sourcePath, source);
        cancelTargetToSource = bindOneWay(
            source,
            sourceSyntax,
            target,
            targetSyntax,
            parameters,
            revert,
            descriptor,
            trace
        );
    }

    return function cancel() {
        cancelSourceToTarget();
        cancelTargetToSource();
    };

}

function bindOneWay(
    target,
    targetSyntax,
    source,
    sourceSyntax,
    parameters,
    convert,
    descriptor,
    trace
) {

    // rotate operators from the target side of the binding to the
    // by inversion onto the source
    var solution = solve(targetSyntax, sourceSyntax);
    targetSyntax = solution[0];
    sourceSyntax = solution[1];

    var observeSource = compileObserver(sourceSyntax);
    if (convert) {
        observeSource = Observers.makeConverterObserver(
            observeSource,
            convert,
            source
        );
    }

    var bindTarget = compileBinder(targetSyntax);
    return bindTarget(
        observeSource,
        source,
        target,
        parameters,
        descriptor,
        trace ? {
            sourcePath: stringify(sourceSyntax),
            targetPath: stringify(targetSyntax)
        } : null
    );

}

function noop() {}

<|endoftext|>


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

const statusCodes = require('http-status-codes');
const app = require('../../app');
const logs = require('../../utils/log');
const Request = require('../../utils/request');
const querystring = require('../../utils/query-string');

describe('Error Tracker Server', () => {
  const makeQuery = (function() {
    const mappings = {
      version: 'v',
      message: 'm',
      stack: 's',
      runtime: 'rt',
      assert: 'a',
      canary: 'ca',
      expected: 'ex',
      debug: 'debug',
      thirdParty: '3p',
      binaryType: 'bt',
    };
    const booleans = ['assert', 'canary', 'expected', 'debug', 'thirdParty'];

    return function makeQuery(options) {
      const query = {};
      for (const prop in options) {
        let value;
        if (booleans.includes(prop)) {
          value = options[prop] ? '1' : '0';
        } else {
          value = options[prop];
        }
        query[mappings[prop]] = value;
      }

      return query;
    };
  })();

  function makeGetRequest(referrer, query) {
    return chai.request(server)
        .get('/r')
        .set('Referer', referrer)
        .set('User-Agent', userAgent)
        .query(querystring.stringify(makeQuery(query)));
  }
  function makePostRequest(type) {
    return function(referrer, query) {
      const q = makeQuery(query);
      return chai.request(server)
          .post('/r')
          .type(type)
          .set('Referer', referrer)
          .set('User-Agent', userAgent)
          .send(type === 'json' ? q : JSON.stringify(q));
    };
  }

  const referrer = 'https://cdn.ampproject.org/';
  const userAgent = 'Google Chrome blah blah version';
  const knownGoodQuery = Object.freeze({
    version: '011530043289240',
    // chai.request will encode this for us.
    message: 'The object does not support the operation or argument.',
    assert: false,
    runtime: '1p',
    // chai.request will encode this for us.
    stack: 'Error: stuff\n at file.js:2:2\n at n (file2.js:4:4)',
  });
  const rawSourceMap = {
    version: 3,
    file: 'min.js',
    names: ['bar', 'baz', 'n'],
    sources: ['one.js', 'two.js'],
    sourcesContent: [
      ' ONE.foo = function (bar) {\n   return baz(bar);\n };',
      ' TWO.inc = function (n) {\n   return n + 1;\n };',
    ],
    sourceRoot: 'https://cdn.ampproject.org',
    mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;' +
        'CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA',
  };
  let sandbox;
  let clock;
  let server;

  before(() => {
    server = app.listen(0);
  });
  after(() => {
    server.close();
  });

  beforeEach(() => {
    sandbox = sinon.createSandbox({
      useFakeTimers: true,
    });
    clock = sandbox.clock;
    for (const key in logs) {
      sandbox.stub(logs[key], 'write').callsFake((entry, callback) => {
        Promise.resolve(null).then(callback);
      });
    }
    sandbox.stub(Request, 'request').callsFake((url, callback) => {
      Promise.reject(new Error('network disabled')).catch(callback);
    });
  });

  afterEach(() => {
    clock.tick(1e10);
    sandbox.restore();
  });

  testSuite('GET', makeGetRequest);
  testSuite('POST JSON', makePostRequest('json'));
  testSuite('POST Text', makePostRequest('text/plain'));

  function testSuite(description, makeRequest) {
    describe(description, () => {
      describe('rejects bad requests', () => {
        it('without referrer', () => {
          return makeRequest('', knownGoodQuery).then((res) => {
            expect(res.text).to.equal('Bad Request');
          });
        });

        it('without version', () => {
          const query = Object.assign({}, knownGoodQuery, {version: ''});
          return makeRequest(referrer, query).then((res) => {
            expect(res.text).to.equal('Bad Request');
          });
        });

        it('without error message', () => {
          const query = Object.assign({}, knownGoodQuery, {message: ''});
          return makeRequest(referrer, query).then((res) => {
            expect(res.text).to.equal('Bad Request');
          });
        });

        it('with blacklisted error', () => {
          sandbox.stub(Math, 'random').returns(0);
          const query = Object.assign({}, knownGoodQuery, {
            message: 'stop_youtube',
          });

          return makeRequest(referrer, query).then((res) => {
            expect(res.text).to.equal('Bad Request');
          });
        });
      });

      it('ignores development errors', () => {
        const query = Object.assign({}, knownGoodQuery, {
          version: '$internalRuntimeVersion$',
        });

        return makeRequest(referrer, query).then((res) => {
          expect(res.status).to.equal(statusCodes.OK);
        });
      });

      describe('throttling', () => {
        it('does not throttle canary dev errors', () => {
          sandbox.stub(Math, 'random').returns(1);
          const query = Object.assign({}, knownGoodQuery, {canary: true});

          return makeRequest(referrer, query).then((res) => {
            expect(res.status).to.equal(statusCodes.ACCEPTED);
          });
        });

        it('does not throttle "control" binary type errors', () => {
          sandbox.stub(Math, 'random').returns(1);
          const query = Object.assign({}, knownGoodQuery, {binaryType: 'control'});

          return makeRequest(referrer, query).then((res) => {
            expect(res.status).to.equal(statusCodes.ACCEPTED);
          });
        });

        it('throttles 90% of canary user errors', () => {
          sandbox.stub(Math, 'random').returns(0.1);
          const query = Object.assign({}, knownGoodQuery, {
            canary: true,
            assert: true,
          });

          return makeRequest(referrer, query).then((res) => {
            expect(res.status).to.equal(statusCodes.ACCEPTED);
            Math.random.returns(0.11);
            return makeRequest(referrer, query);
          }).then((res) => {
            expect(res.status).to.equal(statusCodes.OK);
          });
        });

        it('throttles 90% of dev errors', () => {
          sandbox.stub(Math, 'random').returns(0.1);

          return makeRequest(referrer, knownGoodQuery).then((res) => {
            expect(res.status).to.equal(statusCodes.ACCEPTED);
            Math.random.returns(0.11);
            return makeRequest(referrer, knownGoodQuery);
          }).then((res) => {
            expect(res.status).to.equal(statusCodes.OK);
          });
        });

        it('throttles 99% of user errors', () => {
          sandbox.stub(Math, 'random').returns(0.01);
          const query = Object.assign({}, knownGoodQuery, {
            assert: true,
          });

          return makeRequest(referrer, query).then((res) => {
            expect(res.status).to.equal(statusCodes.ACCEPTED);
            Math.random.returns(0.02);
            return makeRequest(referrer, query);
          }).then((res) => {
            expect(res.status).to.equal(statusCodes.OK);
          });
        });

        describe('handles binary type and canary flags', () => {
          beforeEach(() => {
            sandbox.stub(Math, 'random').returns(0);
          });

          it('should use canary', () => {
            const query = Object.assign({}, knownGoodQuery, {
              stack: '',
              canary: true,
              debug: true,
            });

            return makeRequest(referrer, query).then(res => {
              expect(res.body.event.serviceContext.service)
                .to.be.equal('default-cdn-1p-canary');
            });
          });

          it('should use binary type and take priority over canary flag', () => {
            const query = Object.assign({}, knownGoodQuery, {
              stack: '',
              // "canary" state should be ignored since `bt` should take precedence.
              canary: true,
              debug: true,
              binaryType: 'production',
            });
            return makeRequest(referrer, query).then(res => {
              expect(res.body.event.serviceContext.service)
                .to.be.equal('default-cdn-1p');
            });
          });

          it('should allow any binary type', () => {
            const query = Object.assign({}, knownGoodQuery, {
              stack: '',
              debug: true,
              binaryType: 'hello-world',
            });
            return makeRequest(referrer, query).then(res => {
              expect(res.body.event.serviceContext.service)
                .to.be.equal('default-cdn-1p-hello-world');
            });
          });
        });
      });

      describe('logging errors', () => {
        beforeEach(() => {
          sandbox.stub(Math, 'random').returns(0);
        });

        describe('empty stack traces', () => {
          const query = Object.assign({}, knownGoodQuery, {
            stack: '',
            debug: true,
          });

          it('logs http request', () => {
            return makeRequest(referrer, query).then((res) => {
              const {httpRequest} = res.body.event.context;
              expect(httpRequest.url).to.be.equal(
                '/r?v=011530043289240&m=The%20object%20does%20' +
                'not%20support%20the%20operation%20or%20argument.&a=0&rt=1p' +
                '&s=&debug=1'
              );
              expect(httpRequest.userAgent).to.be.equal(userAgent);
              expect(httpRequest.referrer).to.be.equal(referrer);
            });
          });

          it('logs missing stack trace', () => {
            return makeRequest(referrer, query).then((res) => {
              expect(res.body.event.message).to.be.equal(
                `Error: ${query.message}\n    at ` +
                'the-object-does-not-support-the-operation-or-argument.js:1:1');
            });
          });
        });

        describe('safari stack traces', () => {
          const query = Object.assign({}, knownGoodQuery, {
            stack: 't@https://cdn.ampproject.org/v0.js:2:18\n' +
            'https://cdn.ampproject.org/v0.js:3:18',
            debug: true,
          });

          it('logs http request', () => {
            return makeRequest(referrer, query).then((res) => {
              const {httpRequest} = res.body.event.context;
              expect(httpRequest.url).to.be.equal(
                '/r?v=011530043289240&m=The%20object%20does%20' +
                'not%20support%20the%20operation%20or%20argument.&a=0&rt=1p' +
                '&s=t%40https%3A%2F%2Fcdn.ampproject.org%2Fv0.js%3A2%3A18%0A' +
                'https%3A%2F%2Fcdn.ampproject.org%2Fv0.js%3A3%3A18&debug=1'
              );
              expect(httpRequest.userAgent).to.be.equal(userAgent);
              expect(httpRequest.referrer).to.be.equal(referrer);
            });
          });

          describe('when unminification fails', () => {
            it('logs full error', () => {
              return makeRequest(referrer, query).then((res) => {
                expect(res.body.event.message).to.be.equal(
                  'Error: The object does not support the operation or argument.\n' +
                  '    at t (https://cdn.ampproject.org/v0.js:2:18)\n' +
                  '    at https://cdn.ampproject.org/v0.js:3:18');
              });
            });
          });

          describe('when unminification succeeds', () => {
            beforeEach(() => {
              Request.request.callsFake((url, callback) => {
                Promise.resolve().then(() => {
                  callback(null, null, JSON.stringify(rawSourceMap));
                });
              });
            });

            it('logs full error', () => {
              return makeRequest(referrer, query).then((res) => {
                expect(res.body.event.message).to.be.equal(
                  'Error: The object does not support the operation or argument.\n' +
                  '    at bar (https://cdn.ampproject.org/one.js:1:21)\n' +
                  '    at n (https://cdn.ampproject.org/two.js:1:21)');
              });
            });
          });
        });

        describe('chrome stack traces', () => {
          const query = Object.assign({}, knownGoodQuery, {
            stack: `${knownGoodQuery.message}\n` +
            '    at t (https://cdn.ampproject.org/v0.js:2:18)\n' +
            '    at https://cdn.ampproject.org/v0.js:3:18',
            debug: true,
          });

          it('logs http request', () => {
            return makeRequest(referrer, query).then((res) => {
              const {httpRequest} = res.body.event.context;
              expect(httpRequest.url).to.be.equal(
                '/r?v=011530043289240&m=The%20object%20does%20' +
                'not%20support%20the%20operation%20or%20argument.&a=0&rt=1p' +
                '&s=The%20object%20does%20not%20support%20the%20operation%20or' +
                '%20argument.%0A%20%20%20%20at%20t%20(https%3A%2F%2Fcdn.ampproject.org' +
                '%2Fv0.js%3A2%3A18)%0A%20%20%20%20at%20https%3A%2F%2Fcdn.ampproject.' +
                'org%2Fv0.js%3A3%3A18&debug=1'
              );
              expect(httpRequest.userAgent).to.be.equal(userAgent);
              expect(httpRequest.referrer).to.be.equal(referrer);
            });
          });

          describe('when unminification fails', () => {
            it('logs full error', () => {
              return makeRequest(referrer, query).then((res) => {
                expect(res.body.event.message).to.be.equal(
                  'Error: The object does not support the operation or argument.\n' +
                  '    at t (https://cdn.ampproject.org/v0.js:2:18)\n' +
                  '    at https://cdn.ampproject.org/v0.js:3:18');
              });
            });
          });

          describe('when unminification succeeds', () => {
            beforeEach(() => {
              Request.request.callsFake((url, callback) => {
                Promise.resolve().then(() => {
                  callback(null, null, JSON.stringify(rawSourceMap));
                });
              });
            });

            it('logs full error', () => {
              return makeRequest(referrer, query).then((res) => {
                expect(res.body.event.message).to.be.equal(
                  'Error: The object does not support the operation or argument.\n' +
                  '    at bar (https://cdn.ampproject.org/one.js:1:21)\n' +
                  '    at n (https://cdn.ampproject.org/two.js:1:21)');
              });
            });
          });
        });
      });
    });
  }
});
<commit_msg>Update filter<commit_after>/**
 * Copyright 2017 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions andc
 * limitations under the License.
 */

const statusCodes = require('http-status-codes');
const app = require('../../app');
const logs = require('../../utils/log');
const Request = require('../../utils/request');
const querystring = require('../../utils/query-string');

describe('Error Tracker Server', () => {
  const makeQuery = (function() {
    const mappings = {
      version: 'v',
      message: 'm',
      stack: 's',
      runtime: 'rt',
      assert: 'a',
      canary: 'ca',
      expected: 'ex',
      debug: 'debug',
      thirdParty: '3p',
      binaryType: 'bt',
    };
    const booleans = ['assert', 'canary', 'expected', 'debug', 'thirdParty'];

    return function makeQuery(options) {
      const query = {};
      for (const prop in options) {
        let value;
        if (booleans.includes(prop)) {
          value = options[prop] ? '1' : '0';
        } else {
          value = options[prop];
        }
        query[mappings[prop]] = value;
      }

      return query;
    };
  })();

  function makeGetRequest(referrer, query) {
    return chai.request(server)
        .get('/r')
        .set('Referer', referrer)
        .set('User-Agent', userAgent)
        .query(querystring.stringify(makeQuery(query)));
  }
  function makePostRequest(type) {
    return function(referrer, query) {
      const q = makeQuery(query);
      return chai.request(server)
          .post('/r')
          .type(type)
          .set('Referer', referrer)
          .set('User-Agent', userAgent)
          .send(type === 'json' ? q : JSON.stringify(q));
    };
  }

  const referrer = 'https://cdn.ampproject.org/';
  const userAgent = 'Google Chrome blah blah version';
  const knownGoodQuery = Object.freeze({
    version: '011830043289240',
    // chai.request will encode this for us.
    message: 'The object does not support the operation or argument.',
    assert: false,
    runtime: '1p',
    // chai.request will encode this for us.
    stack: 'Error: stuff\n at file.js:2:2\n at n (file2.js:4:4)',
  });
  const rawSourceMap = {
    version: 3,
    file: 'min.js',
    names: ['bar', 'baz', 'n'],
    sources: ['one.js', 'two.js'],
    sourcesContent: [
      ' ONE.foo = function (bar) {\n   return baz(bar);\n };',
      ' TWO.inc = function (n) {\n   return n + 1;\n };',
    ],
    sourceRoot: 'https://cdn.ampproject.org',
    mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;' +
        'CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA',
  };
  let sandbox;
  let clock;
  let server;

  before(() => {
    server = app.listen(0);
  });
  after(() => {
    server.close();
  });

  beforeEach(() => {
    sandbox = sinon.createSandbox({
      useFakeTimers: true,
    });
    clock = sandbox.clock;
    for (const key in logs) {
      sandbox.stub(logs[key], 'write').callsFake((entry, callback) => {
        Promise.resolve(null).then(callback);
      });
    }
    sandbox.stub(Request, 'request').callsFake((url, callback) => {
      Promise.reject(new Error('network disabled')).catch(callback);
    });
  });

  afterEach(() => {
    clock.tick(1e10);
    sandbox.restore();
  });

  testSuite('GET', makeGetRequest);
  testSuite('POST JSON', makePostRequest('json'));
  testSuite('POST Text', makePostRequest('text/plain'));

  function testSuite(description, makeRequest) {
    describe(description, () => {
      describe('rejects bad requests', () => {
        it('without referrer', () => {
          return makeRequest('', knownGoodQuery).then((res) => {
            expect(res.text).to.equal('Bad Request');
          });
        });

        it('without version', () => {
          const query = Object.assign({}, knownGoodQuery, {version: ''});
          return makeRequest(referrer, query).then((res) => {
            expect(res.text).to.equal('Bad Request');
          });
        });

        it('without error message', () => {
          const query = Object.assign({}, knownGoodQuery, {message: ''});
          return makeRequest(referrer, query).then((res) => {
            expect(res.text).to.equal('Bad Request');
          });
        });

        it('with blacklisted error', () => {
          sandbox.stub(Math, 'random').returns(0);
          const query = Object.assign({}, knownGoodQuery, {
            message: 'stop_youtube',
          });

          return makeRequest(referrer, query).then((res) => {
            expect(res.text).to.equal('Bad Request');
          });
        });
      });

      it('ignores development errors', () => {
        const query = Object.assign({}, knownGoodQuery, {
          version: '$internalRuntimeVersion$',
        });

        return makeRequest(referrer, query).then((res) => {
          expect(res.status).to.equal(statusCodes.OK);
        });
      });

      describe('throttling', () => {
        it('does not throttle canary dev errors', () => {
          sandbox.stub(Math, 'random').returns(1);
          const query = Object.assign({}, knownGoodQuery, {canary: true});

          return makeRequest(referrer, query).then((res) => {
            expect(res.status).to.equal(statusCodes.ACCEPTED);
          });
        });

        it('does not throttle "control" binary type errors', () => {
          sandbox.stub(Math, 'random').returns(1);
          const query = Object.assign({}, knownGoodQuery, {binaryType: 'control'});

          return makeRequest(referrer, query).then((res) => {
            expect(res.status).to.equal(statusCodes.ACCEPTED);
          });
        });

        it('throttles 90% of canary user errors', () => {
          sandbox.stub(Math, 'random').returns(0.1);
          const query = Object.assign({}, knownGoodQuery, {
            canary: true,
            assert: true,
          });

          return makeRequest(referrer, query).then((res) => {
            expect(res.status).to.equal(statusCodes.ACCEPTED);
            Math.random.returns(0.11);
            return makeRequest(referrer, query);
          }).then((res) => {
            expect(res.status).to.equal(statusCodes.OK);
          });
        });

        it('throttles 90% of dev errors', () => {
          sandbox.stub(Math, 'random').returns(0.1);

          return makeRequest(referrer, knownGoodQuery).then((res) => {
            expect(res.status).to.equal(statusCodes.ACCEPTED);
            Math.random.returns(0.11);
            return makeRequest(referrer, knownGoodQuery);
          }).then((res) => {
            expect(res.status).to.equal(statusCodes.OK);
          });
        });

        it('throttles 99% of user errors', () => {
          sandbox.stub(Math, 'random').returns(0.01);
          const query = Object.assign({}, knownGoodQuery, {
            assert: true,
          });

          return makeRequest(referrer, query).then((res) => {
            expect(res.status).to.equal(statusCodes.ACCEPTED);
            Math.random.returns(0.02);
            return makeRequest(referrer, query);
          }).then((res) => {
            expect(res.status).to.equal(statusCodes.OK);
          });
        });

        describe('handles binary type and canary flags', () => {
          beforeEach(() => {
            sandbox.stub(Math, 'random').returns(0);
          });

          it('should use canary', () => {
            const query = Object.assign({}, knownGoodQuery, {
              stack: '',
              canary: true,
              debug: true,
            });

            return makeRequest(referrer, query).then(res => {
              expect(res.body.event.serviceContext.service)
                .to.be.equal('default-cdn-1p-canary');
            });
          });

          it('should use binary type and take priority over canary flag', () => {
            const query = Object.assign({}, knownGoodQuery, {
              stack: '',
              // "canary" state should be ignored since `bt` should take precedence.
              canary: true,
              debug: true,
              binaryType: 'production',
            });
            return makeRequest(referrer, query).then(res => {
              expect(res.body.event.serviceContext.service)
                .to.be.equal('default-cdn-1p');
            });
          });

          it('should allow any binary type', () => {
            const query = Object.assign({}, knownGoodQuery, {
              stack: '',
              debug: true,
              binaryType: 'hello-world',
            });
            return makeRequest(referrer, query).then(res => {
              expect(res.body.event.serviceContext.service)
                .to.be.equal('default-cdn-1p-hello-world');
            });
          });
        });
      });

      describe('logging errors', () => {
        beforeEach(() => {
          sandbox.stub(Math, 'random').returns(0);
        });

        describe('empty stack traces', () => {
          const query = Object.assign({}, knownGoodQuery, {
            stack: '',
            debug: true,
          });

          it('logs http request', () => {
            return makeRequest(referrer, query).then((res) => {
              const {httpRequest} = res.body.event.context;
              expect(httpRequest.url).to.be.equal(
                '/r?v=011830043289240&m=The%20object%20does%20' +
                'not%20support%20the%20operation%20or%20argument.&a=0&rt=1p' +
                '&s=&debug=1'
              );
              expect(httpRequest.userAgent).to.be.equal(userAgent);
              expect(httpRequest.referrer).to.be.equal(referrer);
            });
          });

          it('logs missing stack trace', () => {
            return makeRequest(referrer, query).then((res) => {
              expect(res.body.event.message).to.be.equal(
                `Error: ${query.message}\n    at ` +
                'the-object-does-not-support-the-operation-or-argument.js:1:1');
            });
          });
        });

        describe('safari stack traces', () => {
          const query = Object.assign({}, knownGoodQuery, {
            stack: 't@https://cdn.ampproject.org/v0.js:2:18\n' +
            'https://cdn.ampproject.org/v0.js:3:18',
            debug: true,
          });

          it('logs http request', () => {
            return makeRequest(referrer, query).then((res) => {
              const {httpRequest} = res.body.event.context;
              expect(httpRequest.url).to.be.equal(
                '/r?v=011830043289240&m=The%20object%20does%20' +
                'not%20support%20the%20operation%20or%20argument.&a=0&rt=1p' +
                '&s=t%40https%3A%2F%2Fcdn.ampproject.org%2Fv0.js%3A2%3A18%0A' +
                'https%3A%2F%2Fcdn.ampproject.org%2Fv0.js%3A3%3A18&debug=1'
              );
              expect(httpRequest.userAgent).to.be.equal(userAgent);
              expect(httpRequest.referrer).to.be.equal(referrer);
            });
          });

          describe('when unminification fails', () => {
            it('logs full error', () => {
              return makeRequest(referrer, query).then((res) => {
                expect(res.body.event.message).to.be.equal(
                  'Error: The object does not support the operation or argument.\n' +
                  '    at t (https://cdn.ampproject.org/v0.js:2:18)\n' +
                  '    at https://cdn.ampproject.org/v0.js:3:18');
              });
            });
          });

          describe('when unminification succeeds', () => {
            beforeEach(() => {
              Request.request.callsFake((url, callback) => {
                Promise.resolve().then(() => {
                  callback(null, null, JSON.stringify(rawSourceMap));
                });
              });
            });

            it('logs full error', () => {
              return makeRequest(referrer, query).then((res) => {
                expect(res.body.event.message).to.be.equal(
                  'Error: The object does not support the operation or argument.\n' +
                  '    at bar (https://cdn.ampproject.org/one.js:1:21)\n' +
                  '    at n (https://cdn.ampproject.org/two.js:1:21)');
              });
            });
          });
        });

        describe('chrome stack traces', () => {
          const query = Object.assign({}, knownGoodQuery, {
            stack: `${knownGoodQuery.message}\n` +
            '    at t (https://cdn.ampproject.org/v0.js:2:18)\n' +
            '    at https://cdn.ampproject.org/v0.js:3:18',
            debug: true,
          });

          it('logs http request', () => {
            return makeRequest(referrer, query).then((res) => {
              const {httpRequest} = res.body.event.context;
              expect(httpRequest.url).to.be.equal(
                '/r?v=011830043289240&m=The%20object%20does%20' +
                'not%20support%20the%20operation%20or%20argument.&a=0&rt=1p' +
                '&s=The%20object%20does%20not%20support%20the%20operation%20or' +
                '%20argument.%0A%20%20%20%20at%20t%20(https%3A%2F%2Fcdn.ampproject.org' +
                '%2Fv0.js%3A2%3A18)%0A%20%20%20%20at%20https%3A%2F%2Fcdn.ampproject.' +
                'org%2Fv0.js%3A3%3A18&debug=1'
              );
              expect(httpRequest.userAgent).to.be.equal(userAgent);
              expect(httpRequest.referrer).to.be.equal(referrer);
            });
          });

          describe('when unminification fails', () => {
            it('logs full error', () => {
              return makeRequest(referrer, query).then((res) => {
                expect(res.body.event.message).to.be.equal(
                  'Error: The object does not support the operation or argument.\n' +
                  '    at t (https://cdn.ampproject.org/v0.js:2:18)\n' +
                  '    at https://cdn.ampproject.org/v0.js:3:18');
              });
            });
          });

          describe('when unminification succeeds', () => {
            beforeEach(() => {
              Request.request.callsFake((url, callback) => {
                Promise.resolve().then(() => {
                  callback(null, null, JSON.stringify(rawSourceMap));
                });
              });
            });

            it('logs full error', () => {
              return makeRequest(referrer, query).then((res) => {
                expect(res.body.event.message).to.be.equal(
                  'Error: The object does not support the operation or argument.\n' +
                  '    at bar (https://cdn.ampproject.org/one.js:1:21)\n' +
                  '    at n (https://cdn.ampproject.org/two.js:1:21)');
              });
            });
          });
        });
      });
    });
  }
});
<|endoftext|>