<commit_before>/*

  list.js is released under the GNU Affero General Public License.
  See COPYRIGHT.txt and LICENSE.txt.

  Part of the OpenEnergyMonitor project:
  http://openenergymonitor.org

*/

var list = {

    'data':{},
    'fields':{},
    'element':"#table",
    'timezones':{},

    'init':function()
    {
        var table = $('
'),
            tr;
        for (field in list.fields) {
            tr = $("
").attr("field", field);
            tr.append('  '+list.fields[field].title+'	');
            tr.append('  '+(list.fieldtypes[list.fields[field].type].draw(list.data[field])||'N/A')+'	');
            tr.append('  	');
            table.append(tr);
        }
        $(list.element).html(table);

        $(list.element+" td[type=edit]").click(function() {
            var action = $(this).attr('action');
            var field = $(this).parent().attr('field');

            if (action=='edit')
            {
              $(list.element+" tr[field="+field+"] td[type=value]").html(list.fieldtypes[list.fields[field].type].edit(field,list.data[field]));
              $(this).html("Save").attr('action','save');
            }

            if (action=='save')
            {
              list.data[field] = list.fieldtypes[list.fields[field].type].save(field);
              $(list.element+" tr[field="+field+"] td[type=value]").html(list.fieldtypes[list.fields[field].type].draw(list.data[field]));
              $(this).html("").attr('action','edit');
              $(list.element).trigger("onSave",[]);
            }
        });

        // Show edit button only on hover
        $(list.element+" tr").hover(
          function() {
            $(this).find("td:last > i").show();
          },
          function() {
            $(this).find("td:last > i").hide();
          }
        );
    },

    'fieldtypes':
    {
        'text':
        {
          'draw':function(value) { return value; },
          'edit':function(field,value) { return "<input type='text' value='"+(value||'')+"' / >"; },
          'save':function(field) { return $(list.element+' tr[field='+field+'] td[type=value] input').val();}
        },

        'select':
        {
          'draw':function(value) { return value },
          'edit':function(field,value)
          {
            var options = '';
            for (i in list.fields[field].options)
            {
              var selected = ""; if (list.fields[field].options[i] == value) selected = 'selected';
              options += "<option value="+list.fields[field].options[i]+" "+selected+">"+list.fields[field].options[i]+"</option>";
            }
            return "<select>"+options+"</select>";
          },
          'save':function(field) { return $(list.element+' tr[field='+field+'] td[type=value] select').val();}
        },

        'language':
        {
          'draw':function(value) {
            for (i in list.fields['language'].options)
            {
              if (list.fields['language'].options[i] == value) return list.fields['language'].label[i];
            }
          },
          'edit':function(field,value)
          {
            var options = '';
            for (i in list.fields[field].options)
            {
              var selected = ""; if (list.fields[field].options[i] == value) selected = 'selected';
              options += "<option value="+list.fields[field].options[i]+" "+selected+">"+list.fields[field].label[i]+"</option>";
            }
            return "<select>"+options+"</select>";
          },
          'save':function(field) { return $(list.element+' tr[field='+field+'] td[type=value] select').val();}
        },

        'timezone':
        {
          'draw':function(value)
          {
            return value;
          },
          'edit':function(field,value)
          {
            var select = $('<select />'),
                selectedIndex = null;

            for (i in list.timezones) {
              var tz = list.timezones[i];
              var selected = "";
              if (value == tz.id) {
                selected = 'selected';
                selectedIndex = tz.id;
              }
              select.append("<option value="+tz.id+" "+selected+">"+tz.id+" ("+tz.gmt_offset_text+")</option>");
            }
            //If no selected index were set, then default to UTC
            if ( selectedIndex === null ) {
                select.find("option[value='UTC']").attr('selected', 'selected');
            }
            return select.wrap('
').parent().html();  //return HTML-string
          },
          'save':function(field) { return $(list.element+' tr[field='+field+'] td[type=value] select').val();}
        },

        'gravatar':
        {
          'draw':function(value) { return "" },
          'edit':function(field,value) { return "<input type='text' value='"+value+"' / >" },
          'save':function(field) { return $(list.element+' tr[field='+field+'] td[type=value] input').val();}
        }
    }
}
<commit_msg>sanitized user text input that would be displayed in the DOM<commit_after>/*

  list.js is released under the GNU Affero General Public License.
  See COPYRIGHT.txt and LICENSE.txt.

  Part of the OpenEnergyMonitor project:
  http://openenergymonitor.org

*/

var list = {

    'data':{},
    'fields':{},
    'element':"#table",
    'timezones':{},

    'init':function()
    {
        var table = $('
'),
            tr;
        for (field in list.fields) {
            tr = $("
").attr("field", field);
            tr.append('  '+list.fields[field].title+'	');
            tr.append('  '+(list.fieldtypes[list.fields[field].type].draw(list.data[field])||'N/A')+'	');
            tr.append('  	');
            table.append(tr);
        }
        $(list.element).html(table);

        $(list.element+" td[type=edit]").click(function() {
            var action = $(this).attr('action');
            var field = $(this).parent().attr('field');

            if (action=='edit')
            {
              $(list.element+" tr[field="+field+"] td[type=value]").html(list.fieldtypes[list.fields[field].type].edit(field,list.data[field]));
              $(this).html("Save").attr('action','save');
            }

            if (action=='save')
            {
              list.data[field] = list.fieldtypes[list.fields[field].type].save(field);
              $(list.element+" tr[field="+field+"] td[type=value]").html(list.fieldtypes[list.fields[field].type].draw(list.data[field]));
              $(this).html("").attr('action','edit');
              $(list.element).trigger("onSave",[]);
            }
        });

        // Show edit button only on hover
        $(list.element+" tr").hover(
          function() {
            $(this).find("td:last > i").show();
          },
          function() {
            $(this).find("td:last > i").hide();
          }
        );
    },

    'fieldtypes':
    {
        'text':
        {
          'draw':function(value) {
            //clean user input that is rendered in the DOM
            tmp = document.createElement('DIV');
            tmp.innerHTML = value;
            return tmp.textContent || tmp.innerText || "";
          },
          'edit':function(field,value) { return "<input type='text' value='"+(value||'')+"' / >"; },
          'save':function(field) { return $(list.element+' tr[field='+field+'] td[type=value] input').val();}
        },

        'select':
        {
          'draw':function(value) { return value },
          'edit':function(field,value)
          {
            var options = '';
            for (i in list.fields[field].options)
            {
              var selected = ""; if (list.fields[field].options[i] == value) selected = 'selected';
              options += "<option value="+list.fields[field].options[i]+" "+selected+">"+list.fields[field].options[i]+"</option>";
            }
            return "<select>"+options+"</select>";
          },
          'save':function(field) { return $(list.element+' tr[field='+field+'] td[type=value] select').val();}
        },

        'language':
        {
          'draw':function(value) {
            for (i in list.fields['language'].options)
            {
              if (list.fields['language'].options[i] == value) return list.fields['language'].label[i];
            }
          },
          'edit':function(field,value)
          {
            var options = '';
            for (i in list.fields[field].options)
            {
              var selected = ""; if (list.fields[field].options[i] == value) selected = 'selected';
              options += "<option value="+list.fields[field].options[i]+" "+selected+">"+list.fields[field].label[i]+"</option>";
            }
            return "<select>"+options+"</select>";
          },
          'save':function(field) { return $(list.element+' tr[field='+field+'] td[type=value] select').val();}
        },

        'timezone':
        {
          'draw':function(value)
          {
            return value;
          },
          'edit':function(field,value)
          {
            var select = $('<select />'),
                selectedIndex = null;

            for (i in list.timezones) {
              var tz = list.timezones[i];
              var selected = "";
              if (value == tz.id) {
                selected = 'selected';
                selectedIndex = tz.id;
              }
              select.append("<option value="+tz.id+" "+selected+">"+tz.id+" ("+tz.gmt_offset_text+")</option>");
            }
            //If no selected index were set, then default to UTC
            if ( selectedIndex === null ) {
                select.find("option[value='UTC']").attr('selected', 'selected');
            }
            return select.wrap('
').parent().html();  //return HTML-string
          },
          'save':function(field) { return $(list.element+' tr[field='+field+'] td[type=value] select').val();}
        },

        'gravatar':
        {
          'draw':function(value) { return "" },
          'edit':function(field,value) { return "<input type='text' value='"+value+"' / >" },
          'save':function(field) { return $(list.element+' tr[field='+field+'] td[type=value] input').val();}
        }
    }
}
<|endoftext|>


<commit_before>import React from 'react';
import { compose, toClass, withState } from 'recompose';
import { SlateWriter } from 'olymp-slate';
import { createComponent, Modal } from 'olymp-fela';
import { Button } from 'antd';
import FormItem from './form-item';

const Footer = createComponent(
  ({ theme }) => ({
    padding: theme.space2,
  }),
  ({ onClose, className }) => (
    <div className={className}>
      <Button type="primary" onClick={onClose}>
        Übernehmen
      </Button>
    </div>
  ),
  p => Object.keys(p),
);

const enhance = compose(withState('isOpen', 'setOpen', false), toClass);

export default {
  rule: ({ innerType }) => innerType.name === 'Blocks',
  form: enhance(
    ({
      isOpen,
      setOpen,
      'data-__field': dataField,
      'data-__meta': dataMeta,
      onChange,
      value,
      binding,
      label,
      children,
      ...p
    }) => (
      <FormItem label={label} {...p}>
        <Button.Group data-__field={dataField} data-__meta={dataMeta}>
          <Button
            type={isOpen === true ? 'primary' : 'default'}
            onClick={() => setOpen(!isOpen)}
          >
            Bearbeiten
          </Button>
          <Button onClick={() => setOpen('full')}>Vollbildmodus</Button>
        </Button.Group>

        {isOpen && (
          <SlateWriter
            onChange={onChange}
            value={value}
            binding={binding}
            placeholder={label || 'Hier Text eingeben!'}
            style={{ padding: 20 }}
            full={isOpen === 'full'}
            setFull={() => setOpen(false)}
          >
            {children}
          </SlateWriter>
        )}
      </FormItem>
    ),
  ),
};
<commit_msg>small cleanup<commit_after>import React from 'react';
import { compose, toClass, withState } from 'recompose';
import { SlateWriter } from 'olymp-slate';
import { createComponent } from 'olymp-fela';
import { Button } from 'antd';
import FormItem from './form-item';

const enhance = compose(withState('isOpen', 'setOpen', false), toClass);

export default {
  rule: ({ innerType }) => innerType.name === 'Blocks',
  form: enhance(
    ({
      isOpen,
      setOpen,
      'data-__field': dataField,
      'data-__meta': dataMeta,
      onChange,
      value,
      binding,
      label,
      children,
      ...p
    }) => (
      <FormItem label={label} {...p}>
        <Button.Group data-__field={dataField} data-__meta={dataMeta}>
          <Button
            type={isOpen === true ? 'primary' : 'default'}
            onClick={() => setOpen(!isOpen)}
          >
            Bearbeiten
          </Button>
          <Button onClick={() => setOpen('full')}>Vollbildmodus</Button>
        </Button.Group>

        {isOpen && (
          <SlateWriter
            onChange={onChange}
            value={value}
            binding={binding}
            placeholder={label || 'Hier Text eingeben!'}
            style={{ padding: 20 }}
            full={isOpen === 'full'}
            setFull={() => setOpen(false)}
          >
            {children}
          </SlateWriter>
        )}
      </FormItem>
    ),
  ),
};
<|endoftext|>


<commit_before>var amplitude = 10;
var frequency = .15;
var time = 0;
var diameter = 20;
var radius = diameter/2;

var cavansW = 600;
var canvasH = 400;
var margin = 20;
var centerX, centerY;

var data;
var activities, progress;

var gap;
var innerR, outerR;
var mask;

function preload(){
  // need to update this
  //data = {{activity_data |tojson }}
  data = loadJSON("../static/data/viz_activity_data.json");
  mask = loadImage("../static/img/mask.png");
}

function setup() {
  // get window height and width, min are 600 x 400
  if(window.innerWidth > 600){
    canvasW = window.innerWidth;}
  if(window.innerHeight > 400){
    canvasH = window.innerHeight;}
  createCanvas(canvasW, canvasH);
  centerX = canvasW / 2;
  centerY = canvasH / 2;
  //
  gap = 2.5*PI/180;
  innerR = canvasW/4;
  outerR = canvasH/1.3;
  //
  progress = data.progress;
  activities = [];
  var totalW = 0;
  for(var i = 0; i < data.activities.length; i++){
    var a = new Activity(data.activities[i].name,data.activities[i].weight,data.activities[i].start_time,data.activities[i].completed);
    activities.push(a);
    totalW = totalW + a.absoluteW;
  }
  for (var i = 0; i < activities.length; i++){
    activities[i].update(totalW);
  }
}

function draw() {
  background(255);
  //
  drawWave();
  image(mask, canvasW/2-canvasH/2, 0, canvasH, canvasH);
  fill(255);
  noStroke();
  rect(0,0,canvasW/2-canvasH/2,canvasH);
  rect(canvasW-canvasW/2+canvasH/2-5,0,canvasW/2-canvasH/2+10,canvasH);

  //
  var startA = -PI/2;
  for (var i = 0; i < activities.length; i++){
    activities[i].draw(startA);
    activities[i].drawText(startA);
    startA = startA + activities[i].length;
  }

}

function drawWave(){
  //var height = innerR * 2* progress;
  //var width = calculateW(height)/2;
  var height = canvasH*progress;
  push();
  translate(0, (canvasH-height));
  noStroke();

  for (var x = radius; x <= width-radius; x += diameter*1.5) {
    var phi = -x*.01;
    fill(35,183,211);
    ellipse(x, amplitude*sin(frequency * time + phi), 100, diameter);
  	ellipse(x, amplitude*sin(frequency * time + phi) + 17, 100, diameter);
  	rect(0, 0, width, height);
  }
  time += .5;
  noStroke();
  //line(0, 0, width, 0);
  pop();
}

function calculateW(h){
  var cos = (innerR - (innerR*2-h))/innerR;
  var alpha = 2 * Math.acos(cos);
  var s = 2 * innerR*Math.sin(alpha/2);
  return s;
}

class Activity {
  constructor(name,weight,startTime,completed){
    this.name = name;
    this.absoluteW = weight;
    this.relativeW = 0;
    this.startT = startTime;
    this.completed = completed;
    this.length = 0;
    if (this.completed == "true"){
      this.color = color(150,150,150); //edit color based on...
    }else {
      this.color = color(220,220,220);
    }
  }
  update(totalW){
    this.relativeW = this.absoluteW/totalW;
    this.length = PI*2*this.relativeW;
  }
  draw(startA){
    noFill();
    stroke(this.color);
    strokeWeight(10);
    for(var i = 0; i < 60; i=i+2){
      arc(centerX,centerY,outerR-2*i,outerR-2*i,startA,startA+this.length-3*gap);
    }
  }
  drawText(startA){
    var arc = innerR*2*PI*startA/(2*PI);
    for (var i=0; i < this.name.length; i++){
      var char = this.name.charAt(i);
      var w = textWidth(char);
      arc = arc + w;
      var theta = arc/(innerR);
      push();
      translate(centerX+(innerR)*Math.cos(theta), centerY+(innerR)*Math.sin(theta));
      rotate(theta+PI/2);
      fill(0,0,0,100);
      noStroke();
      textSize(20);
      text(char,0,0);
      pop();
      arc += w;
    }
  }
}
<commit_msg>update color<commit_after>var amplitude = 10;
var frequency = .15;
var time = 0;
var diameter = 20;
var radius = diameter/2;

var cavansW = 600;
var canvasH = 400;
var margin = 20;
var centerX, centerY;

var data;
var activities, progress;

var gap;
var innerR, outerR;
var mask;

function preload(){
  // need to update this
  //data = {{activity_data |tojson }}
  data = loadJSON("../static/data/viz_activity_data.json");
  mask = loadImage("../static/img/mask.png");
}

function setup() {
  // get window height and width, min are 600 x 400
  if(window.innerWidth > 600){
    canvasW = window.innerWidth;}
  if(window.innerHeight > 400){
    canvasH = window.innerHeight;}
  createCanvas(canvasW, canvasH);
  centerX = canvasW / 2;
  centerY = canvasH / 2;
  //
  gap = 2.5*PI/180;
  innerR = canvasW/4;
  outerR = canvasH/1.3;
  //
  progress = data.progress;
  activities = [];
  var totalW = 0;
  for(var i = 0; i < data.activities.length; i++){
    var a = new Activity(data.activities[i].name,data.activities[i].weight,data.activities[i].start_time,data.activities[i].completed);
    activities.push(a);
    totalW = totalW + a.absoluteW;
  }
  for (var i = 0; i < activities.length; i++){
    activities[i].update(totalW);
  }
}

function draw() {
  background(255);
  //
  drawWave();
  image(mask, canvasW/2-canvasH/2, 0, canvasH, canvasH);
  fill(255);
  noStroke();
  rect(0,0,canvasW/2-canvasH/2,canvasH);
  rect(canvasW-canvasW/2+canvasH/2-5,0,canvasW/2-canvasH/2+10,canvasH);

  //
  var startA = -PI/2;
  for (var i = 0; i < activities.length; i++){
    activities[i].draw(startA);
    activities[i].drawText(startA);
    startA = startA + activities[i].length;
  }

}

function drawWave(){
  var height = canvasH*progress;
  push();
  translate(0, (canvasH-height));
  noStroke();

  for (var x = radius; x <= width-radius; x += diameter*1.5) {
    var phi = -x*.01;
    fill('#B2E5FC');
    ellipse(x, amplitude*sin(frequency * time + phi), 100, diameter);
  	ellipse(x, amplitude*sin(frequency * time + phi) + 17, 100, diameter);
  	rect(0, 0, width, height);
  }
  time += .5;
  noStroke();
  pop();
}

function calculateW(h){
  var cos = (innerR - (innerR*2-h))/innerR;
  var alpha = 2 * Math.acos(cos);
  var s = 2 * innerR*Math.sin(alpha/2);
  return s;
}

class Activity {
  constructor(name,weight,startTime,completed){
    this.name = name;
    this.absoluteW = weight;
    this.relativeW = 0;
    this.startT = startTime;
    this.completed = completed;
    this.length = 0;
    if (this.completed == "true"){
      // set up color
      if (this.absoluteW == 1){
        this.color = color('#9856CA');
      } else if(this.absoluteW == 2){
        this.color = color('#2096F3');
      } else if (this.absoluteW == 3){
        this.color = color('#00BCD4');
      } else if (this.absoluteW == 4){
        this.color = color('#FFC105');
      } else {
        this.color = color('#FF5005');
      }
    }else {
      if (this.absoluteW == 1){
        this.color = color('#E5D5F2');
      } else if(this.absoluteW == 2){
        this.color = color('#C7E5FC');
      } else if (this.absoluteW == 3){
        this.color = color('#BFEEF4');
      } else if (this.absoluteW == 4){
        this.color = color('#FFEFC0');
      } else {
        this.color = color('#FFD3C0');
      }
    }
  }
  update(totalW){
    this.relativeW = this.absoluteW/totalW;
    this.length = PI*2*this.relativeW;
  }
  draw(startA){
    noFill();
    stroke(this.color);
    strokeWeight(10);
    for(var i = 0; i < 50; i=i+2){
      arc(centerX,centerY,outerR-2*i,outerR-2*i,startA,startA+this.length-3*gap);
    }
  }
  drawText(startA){
    var arc = innerR*2*PI*startA/(2*PI);
    for (var i=0; i < this.name.length; i++){
      var char = this.name.charAt(i);
      var w = textWidth(char);
      arc = arc + w;
      var theta = arc/(innerR);
      push();
      translate(centerX+(innerR)*Math.cos(theta), centerY+(innerR)*Math.sin(theta));
      rotate(theta+PI/2);
      fill(0,0,0,100);
      noStroke();
      textSize(20);
      text(char,0,0);
      pop();
      arc += w;
    }
  }
}
<|endoftext|>


<commit_before>import Emitter from 'component-emitter';

import { name as NAME, version as VERSION } from '../package.json';
import dataAttributesToObject from './data-attributes-to-object';
import interval from './interval';

const INIT = 'init';
const START = 'start';
const TYPE = 'type';
const LOOP = 'loop';
const STOP = 'stop';
const DESTROY = 'destroy';

const EVENTS = {
  INIT,
  START,
  TYPE,
  LOOP,
  STOP,
  DESTROY,
};

const DATA_ATTRIBUTES = [
  'text',
  'interval',
  'auto-start',
  'loop',
  'loop-interval',
  'empty-text',
];

const DEFAULTS = {
  text: 'This is the default text.',
  interval: [200, 300],
  autoStart: true,
  loop: false,
  // loopInterval: DEFAULTS.interval,
  emptyText: '\u00A0',
};

const autotyper = {
  init(...args) {
    let element;
    let options;

    if (process.env.NODE_ENV === 'test') {
      if (args[0] instanceof window.HTMLElement) {
        [element, options = {}] = args;
      } else {
        [options = {}] = args;
      }
    } else if (args[0] instanceof HTMLElement) {
      [element, options = {}] = args;
    } else {
      [options = {}] = args;
    }

    if (element) {
      const text = element.innerHTML.trim();
      const dataOptions = Object.assign(
        dataAttributesToObject(element, DATA_ATTRIBUTES, NAME),
        JSON.parse(element.getAttribute(`data-${NAME}-options`)),
      );

      this.element = element;
      this.settings = Object.assign(
        {},
        DEFAULTS,
        (text && { text }),
        dataOptions,
        options,
      );
      this.originalText = text;
    } else {
      this.settings = Object.assign({}, DEFAULTS, options);
      this.originalText = this.settings.text;
    }

    this.settings.loopInterval = this.settings.loopInterval || this.settings.interval;

    this.isRunning = false;

    this.emit(INIT);

    if (this.settings.autoStart === true) {
      this.start();
    } else {
      const delay = parseInt(this.settings.autoStart, 10);

      if (!isNaN(delay)) {
        setTimeout(() => this.start(), delay);
      }
    }

    return this;
  },
  start() {
    if (this.isRunning) {
      return this;
    }

    clearTimeout(this.timeout);

    this.isRunning = true;

    this.letterTotal = this.settings.text.length;
    this.letterCount = 0;

    if (this.settings.loop) {
      if (typeof this.settings.loop === 'number') {
        this.loopTotal = this.settings.loop;
      }

      this.loopCount = 0;
    }

    this.emit(START);

    this.type();

    return this;
  },
  setText(text) {
    this.text = text;

    if (this.element) {
      this.element.innerHTML = text;
    }

    return this;
  },
  type() {
    let text;

    this.tick(interval(this.settings.interval));

    if (this.letterCount > this.letterTotal) {
      if (this.settings.loop) {
        return this.loop();
      }

      return this.stop();
    }

    if (this.letterCount === 0) {
      text = this.settings.emptyText;
    } else {
      text = this.settings.text.substring(0, this.letterCount);
    }

    this.setText(text);

    this.emit(TYPE, text);

    this.letterCount += 1;

    return this;
  },
  stop() {
    if (!this.isRunning) {
      return this;
    }

    clearTimeout(this.timeout);

    this.isRunning = false;

    this.emit(STOP);

    return this;
  },
  resetText() {
    this.setText(this.originalText);

    return this;
  },
  destroy() {
    if (this.isRunning) {
      this.stop();
    }

    this.emit(DESTROY);

    this.off();

    this.element = null;
  },
  tick(duration) {
    clearTimeout(this.timeout);

    if (duration === 0) {
      return this.type();
    }

    this.timeout = setTimeout(() => this.type(), duration);

    return this;
  },
  loop() {
    this.tick(interval(this.settings.loopInterval));

    if (this.loopCount === this.loopTotal) {
      return this.stop();
    }

    this.loopCount += 1;

    this.letterTotal = this.settings.text.length;
    this.letterCount = 0;

    this.emit(LOOP, this.loopCount);

    return this;
  },
};

Emitter(autotyper);

export {
  autotyper as default,
  DATA_ATTRIBUTES,
  DEFAULTS,
  EVENTS,
  NAME,
  VERSION,
};
<commit_msg>feat(autotyper): extract `parseArguments` function<commit_after>import Emitter from 'component-emitter';

import { name as NAME, version as VERSION } from '../package.json';
import dataAttributesToObject from './data-attributes-to-object';
import interval from './interval';

const INIT = 'init';
const START = 'start';
const TYPE = 'type';
const LOOP = 'loop';
const STOP = 'stop';
const DESTROY = 'destroy';

const EVENTS = {
  INIT,
  START,
  TYPE,
  LOOP,
  STOP,
  DESTROY,
};

const DATA_ATTRIBUTES = [
  'text',
  'interval',
  'auto-start',
  'loop',
  'loop-interval',
  'empty-text',
];

const DEFAULTS = {
  text: 'This is the default text.',
  interval: [200, 300],
  autoStart: true,
  loop: false,
  // loopInterval: DEFAULTS.interval,
  emptyText: '\u00A0',
};

const autotyper = {
  init(...args) {
    const [
      element = null,
      options = {},
    ] = this.parseArguments(args);

    if (element) {
      const text = element.innerHTML.trim();
      const dataOptions = Object.assign(
        dataAttributesToObject(element, DATA_ATTRIBUTES, NAME),
        JSON.parse(element.getAttribute(`data-${NAME}-options`)),
      );

      this.element = element;
      this.settings = Object.assign(
        {},
        DEFAULTS,
        (text && { text }),
        dataOptions,
        options,
      );
      this.originalText = text;
    } else {
      this.settings = Object.assign({}, DEFAULTS, options);
      this.originalText = this.settings.text;
    }

    this.settings.loopInterval = this.settings.loopInterval || this.settings.interval;

    this.isRunning = false;

    this.emit(INIT);

    if (this.settings.autoStart === true) {
      this.start();
    } else {
      const delay = parseInt(this.settings.autoStart, 10);

      if (!isNaN(delay)) {
        setTimeout(() => this.start(), delay);
      }
    }

    return this;
  },
  parseArguments(args) {
    if (args.length === 0) {
      return args;
    }

    const [firstArg] = args;

    if (process.env.NODE_ENV === 'test') {
      if (firstArg instanceof window.HTMLElement) {
        return args;
      }

      return [null, firstArg];
    }

    if (firstArg instanceof HTMLElement) {
      return args;
    }

    return [null, firstArg];
  },
  start() {
    if (this.isRunning) {
      return this;
    }

    clearTimeout(this.timeout);

    this.isRunning = true;

    this.letterTotal = this.settings.text.length;
    this.letterCount = 0;

    if (this.settings.loop) {
      if (typeof this.settings.loop === 'number') {
        this.loopTotal = this.settings.loop;
      }

      this.loopCount = 0;
    }

    this.emit(START);

    this.type();

    return this;
  },
  setText(text) {
    this.text = text;

    if (this.element) {
      this.element.innerHTML = text;
    }

    return this;
  },
  type() {
    let text;

    this.tick(interval(this.settings.interval));

    if (this.letterCount > this.letterTotal) {
      if (this.settings.loop) {
        return this.loop();
      }

      return this.stop();
    }

    if (this.letterCount === 0) {
      text = this.settings.emptyText;
    } else {
      text = this.settings.text.substring(0, this.letterCount);
    }

    this.setText(text);

    this.emit(TYPE, text);

    this.letterCount += 1;

    return this;
  },
  stop() {
    if (!this.isRunning) {
      return this;
    }

    clearTimeout(this.timeout);

    this.isRunning = false;

    this.emit(STOP);

    return this;
  },
  resetText() {
    this.setText(this.originalText);

    return this;
  },
  destroy() {
    if (this.isRunning) {
      this.stop();
    }

    this.emit(DESTROY);

    this.off();

    this.element = null;
  },
  tick(duration) {
    clearTimeout(this.timeout);

    if (duration === 0) {
      return this.type();
    }

    this.timeout = setTimeout(() => this.type(), duration);

    return this;
  },
  loop() {
    this.tick(interval(this.settings.loopInterval));

    if (this.loopCount === this.loopTotal) {
      return this.stop();
    }

    this.loopCount += 1;

    this.letterTotal = this.settings.text.length;
    this.letterCount = 0;

    this.emit(LOOP, this.loopCount);

    return this;
  },
};

Emitter(autotyper);

export {
  autotyper as default,
  DATA_ATTRIBUTES,
  DEFAULTS,
  EVENTS,
  NAME,
  VERSION,
};
<|endoftext|>


<commit_before>import isFunction from "lodash/isFunction";
import fs from "fs";

//

export { default as File } from "../transformation/file";
export { default as options } from "../transformation/file/options/config";
export { default as buildExternalHelpers } from "../tools/build-external-helpers";
export { default as template } from "babel-template";
export { version } from "../../package";

//

import * as util from "../util";
export { util };

import * as messages from "babel-messages";
export { messages };

import * as t from "babel-types";
export { t as types };

import traverse from "babel-traverse";
export { traverse };

import OptionManager from "../transformation/file/options/option-manager";
export { OptionManager };

export function Plugin(alias) {
  throw new Error(`The (${alias}) Babel 5 plugin is being run with Babel 6.`);
}

// Sorry about all the MBs...
export const guy = "https://medium.com/friendship-dot-js/i-peeked-into-my-node-modules-directory-and-you-wont-believe-what-happened-next-b89f63d21558";

//

import Pipeline from "../transformation/pipeline";
export { Pipeline };

let pipeline = new Pipeline;
export let analyse = pipeline.analyse.bind(pipeline);
export let transform = pipeline.transform.bind(pipeline);
export let transformFromAst = pipeline.transformFromAst.bind(pipeline);

//

export function transformFile(filename: string, opts?: Object, callback: Function) {
  if (isFunction(opts)) {
    callback = opts;
    opts = {};
  }

  opts.filename = filename;

  fs.readFile(filename, function (err, code) {
    let result;

    if (!err) {
      try {
        result = transform(code, opts);
      } catch (_err) {
        err = _err;
      }
    }

    if (err) {
      callback(err);
    } else {
      callback(null, result);
    }
  });
}

export function transformFileSync(filename: string, opts?: Object = {}): string {
  opts.filename = filename;
  return transform(fs.readFileSync(filename, "utf8"), opts);
}
<commit_msg>Fix lint<commit_after>import isFunction from "lodash/isFunction";
import fs from "fs";

//

export { default as File } from "../transformation/file";
export { default as options } from "../transformation/file/options/config";
export { default as buildExternalHelpers } from "../tools/build-external-helpers";
export { default as template } from "babel-template";
export { version } from "../../package";

//

import * as util from "../util";
export { util };

import * as messages from "babel-messages";
export { messages };

import * as t from "babel-types";
export { t as types };

import traverse from "babel-traverse";
export { traverse };

import OptionManager from "../transformation/file/options/option-manager";
export { OptionManager };

export function Plugin(alias) {
  throw new Error(`The (${alias}) Babel 5 plugin is being run with Babel 6.`);
}

// Sorry about all the MBs...
export const guy = "https://medium.com/friendship-dot-js/i-peeked-into-my-node-modules-directory-and-you-wont-believe-what-happened-next-b89f63d21558"; // eslint-disable-line max-len

//

import Pipeline from "../transformation/pipeline";
export { Pipeline };

let pipeline = new Pipeline;
export let analyse = pipeline.analyse.bind(pipeline);
export let transform = pipeline.transform.bind(pipeline);
export let transformFromAst = pipeline.transformFromAst.bind(pipeline);

//

export function transformFile(filename: string, opts?: Object, callback: Function) {
  if (isFunction(opts)) {
    callback = opts;
    opts = {};
  }

  opts.filename = filename;

  fs.readFile(filename, function (err, code) {
    let result;

    if (!err) {
      try {
        result = transform(code, opts);
      } catch (_err) {
        err = _err;
      }
    }

    if (err) {
      callback(err);
    } else {
      callback(null, result);
    }
  });
}

export function transformFileSync(filename: string, opts?: Object = {}): string {
  opts.filename = filename;
  return transform(fs.readFileSync(filename, "utf8"), opts);
}
<|endoftext|>


<commit_before>import isFunction from "lodash/isFunction";
import fs from "fs";

//

export { default as File } from "../transformation/file";
export { default as options } from "../transformation/file/options/config";
export { default as buildExternalHelpers } from "../tools/build-external-helpers";
export { default as template } from "babel-template";
export { version } from "../../package";

//

import * as util from "../util";
export { util };

import * as messages from "babel-messages";
export { messages };

import * as t from "babel-types";
export { t as types };

import traverse from "babel-traverse";
export { traverse };

import OptionManager from "../transformation/file/options/option-manager";
export { OptionManager };

export function Plugin(alias) {
  throw new Error(`The (${alias}) Babel 5 plugin is being run with Babel 6.`);
}

//

import Pipeline from "../transformation/pipeline";
export { Pipeline };

let pipeline = new Pipeline;
export let analyse = pipeline.analyse.bind(pipeline);
export let transform = pipeline.transform.bind(pipeline);
export let transformFromAst = pipeline.transformFromAst.bind(pipeline);

//

export function transformFile(filename: string, opts?: Object, callback: Function) {
  if (isFunction(opts)) {
    callback = opts;
    opts = {};
  }

  opts.filename = filename;

  fs.readFile(filename, function (err, code) {
    let result;

    if (!err) {
      try {
        result = transform(code, opts);
      } catch (_err) {
        err = _err;
      }
    }

    if (err) {
      callback(err);
    } else {
      callback(null, result);
    }
  });
}

export function transformFileSync(filename: string, opts?: Object = {}): string {
  opts.filename = filename;
  return transform(fs.readFileSync(filename, "utf8"), opts);
}
<commit_msg>Fix exports of babel-core<commit_after>import isFunction from "lodash/isFunction";
import fs from "fs";

//

export { default as File } from "../transformation/file";
export { default as options } from "../transformation/file/options/config";
export { default as buildExternalHelpers } from "../tools/build-external-helpers";
export { default as template } from "babel-template";
export { version } from "../../package";

//

import * as util from "../util";
export { util };

import * as messages from "babel-messages";
export { messages };

import * as t from "babel-types";
export { t as types };

import traverse from "babel-traverse";
export { traverse };

import OptionManager from "../transformation/file/options/option-manager";
export { OptionManager };

export function Plugin(alias) {
  throw new Error(`The (${alias}) Babel 5 plugin is being run with Babel 6.`);
}

// Sorry about all the MBs...
export const guy = "https://medium.com/friendship-dot-js/i-peeked-into-my-node-modules-directory-and-you-wont-believe-what-happened-next-b89f63d21558";

//

import Pipeline from "../transformation/pipeline";
export { Pipeline };

let pipeline = new Pipeline;
export let analyse = pipeline.analyse.bind(pipeline);
export let transform = pipeline.transform.bind(pipeline);
export let transformFromAst = pipeline.transformFromAst.bind(pipeline);

//

export function transformFile(filename: string, opts?: Object, callback: Function) {
  if (isFunction(opts)) {
    callback = opts;
    opts = {};
  }

  opts.filename = filename;

  fs.readFile(filename, function (err, code) {
    let result;

    if (!err) {
      try {
        result = transform(code, opts);
      } catch (_err) {
        err = _err;
      }
    }

    if (err) {
      callback(err);
    } else {
      callback(null, result);
    }
  });
}

export function transformFileSync(filename: string, opts?: Object = {}): string {
  opts.filename = filename;
  return transform(fs.readFileSync(filename, "utf8"), opts);
}
<|endoftext|>


<commit_before>enyo.kind({
	name: "ProjectView",
	kind: "FittableColumns",
	classes: "enyo-unselectable",
	components: [
	    {kind: "ProjectList", onCreateProject: "createProjectAction", },
		{kind: "HermesFileTree", fit:true, name: "hermesFileTree"},
		{kind: "ProjectWizardPopup", canGenerate: false, name: "projectWizardPopup"}
    ],
	handlers: {
		onCancel: "cancelCreateProject",
		onConfirmCreateProject: "confirmCreateProject"
	},
	create: function() {
		this.inherited(arguments);
	},
    createProjectAction: function(inSender, inEvent) {
        this.$.projectWizardPopup.show();
        return true; //Stop event propagation
    },
    cancelCreateProject: function(inSender, inEvent) {
        this.$.projectWizardPopup.hide();
        return true; //Stop event propagation
    },
    confirmCreateProject: function(inSender, inEvent) {
    	this.$.projectWizardPopup.hide();
        // TODO - Auto-generated code
    	this.log("LET'S GO ...");
    	console.dir(inEvent);

    	var service = inEvent.selectedDir.service;

		// super hack
		var auth = service ? service.auth : null;
		var url = service ? service.url : null;
		var jsonp = service ? service.useJsonp : false;

		//this.log("service: auth: "+auth+" url: "+url+" jsonp: "+jsonp);
		var serviceObj = {
			auth: auth,
			url: url,
			jsonp: jsonp
		};
		this.log("LET'S GO ... with: " + JSON.stringify(serviceObj));
		this.$.hermesFileTree.setServiceInformation(serviceObj);
		this.$.hermesFileTree.reset();
		return true; //Stop event propagation
    }
});

enyo.kind({
	name: "ProjectList",
	classes: "enyo-unselectable",
	style: "width: 300px",
	events: {
		onCreateProject: ""
	},
	handlers: {
	},
	components: [
	{kind: "onyx.Toolbar", isContainer: true, name: "toolbar", components: [
			{kind: "onyx.Button", content: "Create Project", ontap: "doCreateProject"},
			{kind: "onyx.Button", content: "Open Project", ontap: "doOpenProject"}
		]},
	{kind: "List", content: "list", controlParentName: "client", name: "projectList", onSetupItem: "projectListSetupItem", ontap: "projectListTap"}
]
,
    projectListSetupItem: function(inSender, inEvent) {
        // TODO - Auto-generated code
    },
    projectListTap: function(inSender, inEvent) {
        // TODO - Auto-generated code
    }
});

enyo.kind({
	name: "ProjectWizard",
	classes: "enyo-unselectable",
	events: {
		onCancel: "",
		onConfirmCreateProject: ""
	},
	handlers: {
		onDirectorySelected: "directorySelected"
	},
	components: [
	    {kind: "FittableRows", fit: true, name: "fittableRows", components: [
			{kind: "FittableColumns", name: "fittableColumns", components: [
					{kind: "Control", content: "Project name: ", name: "control"},
					{kind: "onyx.InputDecorator", content: "Project name", name: "inputDecorator", components: [
							{kind: "Input", placeholder: "Enter project name", name: "projectName"}
						]}
				]},
			{kind: "FittableColumns", name: "fittableColumns4", components: [
					{kind: "Control", content: "Directory:", name: "control5"},
					{kind: "onyx.InputDecorator", name: "inputDecorator2", components: [
							{kind: "Input", placeholder: "Enter text here", name: "projectDirectory"}
						]},
					{kind: "onyx.Button", content: "Browse", name: "browse", ontap: "browseTap"}
				]},
			{kind: "Control", fit: true, name: "control2"},
			{kind: "FittableColumns", style: "margin-top: 10px", name: "fittableColumns5", components: [
					{kind: "Control", fit: true, name: "control7"},
					{kind: "onyx.Button", content: "Cancel", name: "cancel", ontap: "cancelTap"},
					{kind: "onyx.Button", content: "OK", name: "confirm", ontap: "confirmTap"}
				]}
		]},
		{kind: "SelectServicePopup", canGenerate: false, name: "selectServicePopup"}		// TODO to rename
    ],
    // TODO Reset the projectName, ...
    browseTap: function(inSender, inEvent) {
        this.$.selectServicePopup.show();
    },
    cancelTap: function(inSender, inEvent) {
        this.doCancel();
    },
    confirmTap: function(inSender, inEvent) {
        this.doConfirmCreateProject({name: this.$.projectName.getValue(), selectedDir: this.selectedDir});
    },
    directorySelected: function(inSender, inEvent) {
    	this.selectedDir =inEvent;
    	this.log("YES");
    	console.dir(this.selectedDir);
    	this.$.projectDirectory.setValue(this.selectedDir.id);
    	this.$.selectServicePopup.hide();
    }
});

enyo.kind({
	name: "ProjectWizardPopup",
	kind: "onyx.Popup",
	events: {
	},
	modal: true,
	centered: true,
	floating: true,
	autoDismiss: false,
	classes: "ares_pview_popup",
	components: [
        {kind: "ProjectWizard"}
	]
});

enyo.kind({
	name : "ServiceSelector",
	kind : "enyo.FittableRows",
	style: "height: 400px; width: 600px",
	components : [
	    {kind: "FittableColumns", content: "fittableColumns", fit: true, name: "fittableColumns", components: [
			{kind: "ProviderList", name: "providerList", onSelectProvider: "selectProvider"},
			{kind: "HermesFileTree", fit: true, name: "hermesFileTree", onFileClick: "selectFile", onFolderClick: "selectFolder"}
		]},
	    {kind: "FittableColumns", content: "fittableColumns2", isContainer: true, name: "fittableColumns2", components: [
			{name: "selectedDir", fit: true, content: "Selected: "},
			{kind: "onyx.Button", content: "Cancel", ontap: "doCancel"},
			{kind: "onyx.Button", content: "OK", isContainer: true, name: "confirm", ontap: "confirmTap"}
		]}
    ],
	events: {
		onDirectorySelected: ""
	},
	selectedDir: undefined,
	selectProvider: function(inSender, inInfo) {
		this.log("In " + this.kind + " service='"+JSON.stringify(inInfo.service)+"'");

		// super hack
		var auth = inInfo.service ? inInfo.service.auth : null;
		var url = inInfo.service ? inInfo.service.url : null;
		var jsonp = inInfo.service ? inInfo.service.useJsonp : false;

		//this.log("service: auth: "+auth+" url: "+url+" jsonp: "+jsonp);
		var serviceObj = {
			auth: auth,
			url: url,
			jsonp: jsonp
		};
		this.$.hermesFileTree.setServiceInformation(serviceObj);
		this.$.hermesFileTree.reset();
		return true; //Stop event propagation
	},
	selectFile: function(inSender, inEvent) {
		console.log("In " + this.kind + " Selected file: "+inEvent.file.id);
		this.selectedDir = undefined;
		this.$.selectedDir.setContent("Selected: ");
		this.$.confirm.setDisabled(true);
		return true; // Stop event propagation
	},
	selectFolder: function(inSender, inEvent) {
		this.selectedDir = inEvent.file;
		console.log("In " + this.kind + " Selected folder: " + this.selectedDir);
		this.$.selectedDir.setContent("Selected: " + this.selectedDir.id);
		this.$.confirm.setDisabled(false);
		return true; // Stop event propagation
	},
    confirmTap: function(inSender, inEvent) {
        this.log(this.kind + ":confirmTap");
        console.dir(this.selectedDir);
        this.doDirectorySelected(this.selectedDir);
        return true; // Stop event propagation
    }
,
    doCancel: function(inSender, inEvent) {
        // TODO - Auto-generated code
    }
});

enyo.kind({
	name: "SelectServicePopup",
	kind: "onyx.Popup",
	events: {
	},
	modal: true,
	centered: true,
	floating: true,
	autoDismiss: false,
//	classes: "ares_pview_popup",
	components: [
	{kind: "ServiceSelector", name: "serviceSelector"}
]
});<commit_msg>ENYO-889: Small adaptations needed after pulling changesfrom ENYO-1000<commit_after>enyo.kind({
	name: "ProjectView",
	kind: "FittableColumns",
	classes: "enyo-unselectable",
	components: [
	    {kind: "ProjectList", onCreateProject: "createProjectAction", },
		{kind: "HermesFileTree", fit:true, name: "hermesFileTree"},
		{kind: "ProjectWizardPopup", canGenerate: false, name: "projectWizardPopup"}
    ],
	handlers: {
		onCancel: "cancelCreateProject",
		onConfirmCreateProject: "confirmCreateProject"
	},
	create: function() {
		this.inherited(arguments);
	},
    createProjectAction: function(inSender, inEvent) {
        this.$.projectWizardPopup.show();
        return true; //Stop event propagation
    },
    cancelCreateProject: function(inSender, inEvent) {
        this.$.projectWizardPopup.hide();
        return true; //Stop event propagation
    },
    confirmCreateProject: function(inSender, inEvent) {
    	this.$.projectWizardPopup.hide();
        // TODO - Auto-generated code
    	this.log("LET'S GO ...");
    	console.dir(inEvent);

    	var service = inEvent.selectedDir.service;

		// super hack
		var auth = service ? service.auth : null;
		var url = service ? service.url : null;
		var jsonp = service ? service.useJsonp : false;

		//this.log("service: auth: "+auth+" url: "+url+" jsonp: "+jsonp);
		var serviceObj = {
			auth: auth,
			url: url,
			jsonp: jsonp
		};
		this.log("LET'S GO ... with: " + JSON.stringify(serviceObj));
		this.$.hermesFileTree.setServiceInformation(serviceObj);
		this.$.hermesFileTree.reset();
		return true; //Stop event propagation
    }
});

enyo.kind({
	name: "ProjectList",
	classes: "enyo-unselectable",
	style: "width: 300px",
	events: {
		onCreateProject: ""
	},
	handlers: {
	},
	components: [
	{kind: "onyx.Toolbar", isContainer: true, name: "toolbar", components: [
			{kind: "onyx.Button", content: "Create Project", ontap: "doCreateProject"},
			{kind: "onyx.Button", content: "Open Project", ontap: "doOpenProject"}
		]},
	{kind: "List", content: "list", controlParentName: "client", name: "projectList", onSetupItem: "projectListSetupItem", ontap: "projectListTap"}
]
,
    projectListSetupItem: function(inSender, inEvent) {
        // TODO - Auto-generated code
    },
    projectListTap: function(inSender, inEvent) {
        // TODO - Auto-generated code
    }
});

enyo.kind({
	name: "ProjectWizard",
	classes: "enyo-unselectable",
	events: {
		onCancel: "",
		onConfirmCreateProject: ""
	},
	handlers: {
		onDirectorySelected: "directorySelected"
	},
	components: [
	    {kind: "FittableRows", fit: true, name: "fittableRows", components: [
			{kind: "FittableColumns", name: "fittableColumns", components: [
					{kind: "Control", content: "Project name: ", name: "control"},
					{kind: "onyx.InputDecorator", content: "Project name", name: "inputDecorator", components: [
							{kind: "Input", placeholder: "Enter project name", name: "projectName"}
						]}
				]},
			{kind: "FittableColumns", name: "fittableColumns4", components: [
					{kind: "Control", content: "Directory:", name: "control5"},
					{kind: "onyx.InputDecorator", name: "inputDecorator2", components: [
							{kind: "Input", placeholder: "Enter text here", name: "projectDirectory"}
						]},
					{kind: "onyx.Button", content: "Browse", name: "browse", ontap: "browseTap"}
				]},
			{kind: "Control", fit: true, name: "control2"},
			{kind: "FittableColumns", style: "margin-top: 10px", name: "fittableColumns5", components: [
					{kind: "Control", fit: true, name: "control7"},
					{kind: "onyx.Button", content: "Cancel", name: "cancel", ontap: "cancelTap"},
					{kind: "onyx.Button", content: "OK", name: "confirm", ontap: "confirmTap"}
				]}
		]},
		{kind: "SelectServicePopup", canGenerate: false, name: "selectServicePopup"}		// TODO to rename
    ],
    // TODO Reset the projectName, ...
    browseTap: function(inSender, inEvent) {
        this.$.selectServicePopup.show();
    },
    cancelTap: function(inSender, inEvent) {
        this.doCancel();
    },
    confirmTap: function(inSender, inEvent) {
        this.doConfirmCreateProject({name: this.$.projectName.getValue(), selectedDir: this.selectedDir});
    },
    directorySelected: function(inSender, inEvent) {
    	this.selectedDir =inEvent;
    	this.log("YES");						// TODO TBR
    	console.dir(this.selectedDir);
    	this.$.projectDirectory.setValue(this.selectedDir.path);
    	this.$.selectServicePopup.hide();
    }
});

enyo.kind({
	name: "ProjectWizardPopup",
	kind: "onyx.Popup",
	events: {
	},
	modal: true,
	centered: true,
	floating: true,
	autoDismiss: false,
	classes: "ares_pview_popup",
	components: [
        {kind: "ProjectWizard"}
	]
});

enyo.kind({
	name : "ServiceSelector",
	kind : "enyo.FittableRows",
	style: "height: 400px; width: 600px",
	components : [
	    {kind: "FittableColumns", content: "fittableColumns", fit: true, name: "fittableColumns", components: [
			{kind: "ProviderList", name: "providerList", onSelectProvider: "selectProvider"},
			{kind: "HermesFileTree", fit: true, name: "hermesFileTree", onFileClick: "selectFile", onFolderClick: "selectFolder"}
		]},
	    {kind: "FittableColumns", content: "fittableColumns2", isContainer: true, name: "fittableColumns2", components: [
			{name: "selectedDir", fit: true, content: "Selected: "},
			{kind: "onyx.Button", content: "Cancel", ontap: "doCancel"},
			{kind: "onyx.Button", content: "OK", isContainer: true, name: "confirm", ontap: "confirmTap"}
		]}
    ],
	events: {
		onDirectorySelected: ""
	},
	selectedDir: undefined,
	selectProvider: function(inSender, inInfo) {
		this.log("In " + this.kind + " service='"+JSON.stringify(inInfo.service)+"'");

		// super hack
		var auth = inInfo.service ? inInfo.service.auth : null;
		var url = inInfo.service ? inInfo.service.url : null;
		var jsonp = inInfo.service ? inInfo.service.useJsonp : false;

		//this.log("service: auth: "+auth+" url: "+url+" jsonp: "+jsonp);
		var serviceObj = {
			auth: auth,
			url: url,
			jsonp: jsonp
		};
		this.$.hermesFileTree.setServiceInformation(serviceObj);
		this.$.hermesFileTree.reset();
		return true; //Stop event propagation
	},
	selectFile: function(inSender, inEvent) {
		console.log("In " + this.kind + " Selected file: "+inEvent.file.id);
		this.selectedDir = undefined;
		this.$.selectedDir.setContent("Selected: ");
		this.$.confirm.setDisabled(true);
		return true; // Stop event propagation
	},
	selectFolder: function(inSender, inEvent) {
		this.selectedDir = inEvent.file;
		this.log("Selected folder: " + this.selectedDir);
		console.dir(this.selectedDir);
		this.$.selectedDir.setContent("Selected: " + this.selectedDir.path);
		this.$.confirm.setDisabled(false);
		return true; // Stop event propagation
	},
    confirmTap: function(inSender, inEvent) {
        this.log(this.kind + ":confirmTap");
        console.dir(this.selectedDir);
        this.doDirectorySelected(this.selectedDir);
        return true; // Stop event propagation
    }
,
    doCancel: function(inSender, inEvent) {
        // TODO - Auto-generated code
    }
});

enyo.kind({
	name: "SelectServicePopup",
	kind: "onyx.Popup",
	events: {
	},
	modal: true,
	centered: true,
	floating: true,
	autoDismiss: false,
//	classes: "ares_pview_popup",
	components: [
	{kind: "ServiceSelector", name: "serviceSelector"}
]
});<|endoftext|>


<commit_before>import session from '../../session';
import helper from '../helper';
import { handleXhrError, backHistory } from '../../utils';
import { game as gameXhr, joinChallenge, cancelChallenge } from '../../xhr';
import storage from '../../storage';
import roundCtrl from '../round/roundCtrl';
import gameStatus from '../../lichess/status';
import gameApi from '../../lichess/game';
import socket from '../../socket';
import gamesMenu from '../gamesMenu';
import i18n from '../../i18n';
import m from 'mithril';

export default function controller() {
  const isAwaitingInvite = m.prop(false);
  const isAwaitingChallenge = m.prop(false);
  const isJoinable = m.prop(false);
  var gameData;
  var round;
  var challengeIntervalID;

  gameXhr(m.route.param('id'), m.route.param('color'), !!gamesMenu.lastJoined).then(function(data) {
    gameData = data;

    if (!data.player.spectator && !gameApi.isSupportedVariant(data)) {
      window.plugins.toast.show(i18n('unsupportedVariant', data.game.variant.name), 'short', 'center');
      m.route('/');
    }
    // joinable means it's a game opened from an url scheme (url invitation from
    // a friend)
    else if (data.game.joinable) {
      helper.analyticsTrackView('Join url invitation');
      isJoinable(true);
    }
    // status created means user has sent an url invitation or challenge, and is
    // waiting for friend to join
    else if (data.game.status.id === gameStatus.ids.created) {
      socket.createAwait(data.url.socket, data.player.version, {
        redirect: e => m.route('/game/' + e.id),
        declined: () => {
          window.plugins.toast.show('Challenge declined', 'short', 'center');
          backHistory();
        }
      });
      // userId param means it's a challenge, otherwise it's an invitation with url
      if (m.route.param('userId')) {
        helper.analyticsTrackView('Waiting for challenge acceptance');
        isAwaitingChallenge(true);
        // to keep challenge open
        challengeIntervalID = setInterval(() => {
          socket.send('challenge', m.route.param('userId'));
        }, 1500);
        window.plugins.insomnia.keepAwake();
      } else {
        helper.analyticsTrackView('Waiting for URL invitation acceptance');
        isAwaitingInvite(true);
      }
    }
    // if not joinable or created, it means the game is started, so let's play!
    else {
      if (session.isConnected()) session.refresh();
      round = new roundCtrl(data);
      if (data.player.user === undefined)
        storage.set('lastPlayedGameURLAsAnon', data.url.round);
    }
  }, function(error) {
    handleXhrError(error);
    m.route('/');
  });

  return {
    onunload: function() {
      if (round) {
        round.onunload();
        round = null;
      }
      if (challengeIntervalID) clearInterval(challengeIntervalID);
      socket.destroy();
      window.plugins.insomnia.allowSleepAgain();
    },
    getRound: function() {
      return round;
    },
    isJoinable,
    isAwaitingInvite,
    isAwaitingChallenge,
    joinChallenge: id => joinChallenge(id).then(data =>
      m.route('/game' + data.url.round)
    ),
    cancelChallenge: () => {
      cancelChallenge(gameData.url.round);
      if (challengeIntervalID) clearInterval(challengeIntervalID);
      backHistory();
    },
    getData: function() {
      return gameData;
    }
  };
}
<commit_msg>Play sound on game start<commit_after>import session from '../../session';
import helper from '../helper';
import { handleXhrError, backHistory } from '../../utils';
import { game as gameXhr, joinChallenge, cancelChallenge } from '../../xhr';
import storage from '../../storage';
import roundCtrl from '../round/roundCtrl';
import gameStatus from '../../lichess/status';
import gameApi from '../../lichess/game';
import socket from '../../socket';
import gamesMenu from '../gamesMenu';
import sound from '../../sound';
import i18n from '../../i18n';
import m from 'mithril';

export default function controller() {
  const isAwaitingInvite = m.prop(false);
  const isAwaitingChallenge = m.prop(false);
  const isJoinable = m.prop(false);
  var gameData;
  var round;
  var challengeIntervalID;

  gameXhr(m.route.param('id'), m.route.param('color'), !!gamesMenu.lastJoined).then(function(data) {
    gameData = data;

    if (!data.player.spectator && !gameApi.isSupportedVariant(data)) {
      window.plugins.toast.show(i18n('unsupportedVariant', data.game.variant.name), 'short', 'center');
      m.route('/');
    }
    // joinable means it's a game opened from an url scheme (url invitation from
    // a friend)
    else if (data.game.joinable) {
      helper.analyticsTrackView('Join url invitation');
      isJoinable(true);
    }
    // status created means user has sent an url invitation or challenge, and is
    // waiting for friend to join
    else if (data.game.status.id === gameStatus.ids.created) {
      socket.createAwait(data.url.socket, data.player.version, {
        redirect: e => m.route('/game/' + e.id),
        declined: () => {
          window.plugins.toast.show('Challenge declined', 'short', 'center');
          backHistory();
        }
      });
      // userId param means it's a challenge, otherwise it's an invitation with url
      if (m.route.param('userId')) {
        helper.analyticsTrackView('Waiting for challenge acceptance');
        isAwaitingChallenge(true);
        // to keep challenge open
        challengeIntervalID = setInterval(() => {
          socket.send('challenge', m.route.param('userId'));
        }, 1500);
        window.plugins.insomnia.keepAwake();
      } else {
        helper.analyticsTrackView('Waiting for URL invitation acceptance');
        isAwaitingInvite(true);
      }
    }
    // if not joinable or created, it means the game is started, so let's play!
    else {
      if (session.isConnected()) session.refresh();

      if (gameApi.playable(data) && data.game.turns - data.game.startedAtTurn <= 1)
        sound.dong();

      round = new roundCtrl(data);
      if (data.player.user === undefined)
        storage.set('lastPlayedGameURLAsAnon', data.url.round);
    }
  }, function(error) {
    handleXhrError(error);
    m.route('/');
  });

  return {
    onunload: function() {
      if (round) {
        round.onunload();
        round = null;
      }
      if (challengeIntervalID) clearInterval(challengeIntervalID);
      socket.destroy();
      window.plugins.insomnia.allowSleepAgain();
    },
    getRound: function() {
      return round;
    },
    isJoinable,
    isAwaitingInvite,
    isAwaitingChallenge,
    joinChallenge: id => joinChallenge(id).then(data =>
      m.route('/game' + data.url.round)
    ),
    cancelChallenge: () => {
      cancelChallenge(gameData.url.round);
      if (challengeIntervalID) clearInterval(challengeIntervalID);
      backHistory();
    },
    getData: function() {
      return gameData;
    }
  };
}
<|endoftext|>


<commit_before>var session = require('../../session');
var utils = require('../../utils');
var xhr = require('../../xhr');
var storage = require('../../storage');
var roundCtrl = require('../round/roundCtrl');

module.exports = function() {
  var id = m.route.param('id');
  var joinable = false;
  var gameData;
  var round;

  xhr.game(id, m.route.param('pov')).then(function(data) {
    if (data.game.joinable) {
      gameData = data;
      joinable = true;
    } else {
      if (session.isConnected()) session.refresh();
      round = new roundCtrl(data);
      if (data.player.user === undefined)
        storage.set('lastPlayedGameURLAsAnon', data.url.round);
    }
  }, function(error) {
    utils.handleXhrError(error);
    m.route('/');
  });

  return {
    onunload: function() {
      if (round) {
        round.onunload();
        round = null;
      }
    },
    round: function() {
      return round;
    },
    joinable: function() {
      return joinable;
    },
    joinUrlChallenge: function(id) {
      xhr.joinUrlChallenge(id).then(function(data) {
        m.route('/game' + data.url.round);
      });
    },
    data: function() {
      return gameData;
    }
  };
};
<commit_msg>Remove useless variable<commit_after>var session = require('../../session');
var utils = require('../../utils');
var xhr = require('../../xhr');
var storage = require('../../storage');
var roundCtrl = require('../round/roundCtrl');

module.exports = function() {
  var joinable = false;
  var gameData;
  var round;

  xhr.game(m.route.param('id'), m.route.param('pov')).then(function(data) {
    if (data.game.joinable) {
      gameData = data;
      joinable = true;
    } else {
      if (session.isConnected()) session.refresh();
      round = new roundCtrl(data);
      if (data.player.user === undefined)
        storage.set('lastPlayedGameURLAsAnon', data.url.round);
    }
  }, function(error) {
    utils.handleXhrError(error);
    m.route('/');
  });

  return {
    onunload: function() {
      if (round) {
        round.onunload();
        round = null;
      }
    },
    round: function() {
      return round;
    },
    joinable: function() {
      return joinable;
    },
    joinUrlChallenge: function(id) {
      xhr.joinUrlChallenge(id).then(function(data) {
        m.route('/game' + data.url.round);
      });
    },
    data: function() {
      return gameData;
    }
  };
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

const { program } = require("commander");
const chalk = require("chalk");
const prompts = require("prompts");
const path = require("path");
const { install, initGit } = require("./helpers/install");
const package = require("./package.json");
const copy = require("./helpers/copy");
const Listr = require("listr");

// Output path to create new portal app
let projectPath = "";

// Commander parameters to specify CLI behavior
program
  .name(package.name)
  .version(package.version)
  /**
   * TODO
   * Add Options
   * Add Example Options
   * Add templates
   */
  .arguments("[dir]")
  .usage(`${chalk.yellow("[dir]")}`)
  .description({
    dir: "Directory to be used on install Portal.js",
  })
  .action((name) => (projectPath = name))
  .allowUnknownOption()
  .parse(process.argv);

/**
 * Method to ask a custon name if was not passed as parameter
 * returns the value passed from terminal input
 */
async function promptPath() {
  return prompts({
    type: "text",
    name: "path",
    message: "Choose a name to your project",
    initial: "",
    validate: (name) => {
      //TODO Method to validate valid path name
      return true;
    },
  });
}

/**
 * Main method to start CLI and validate inputs
 */
async function run() {
  if (typeof projectPath === "string") {
    projectPath = projectPath.trim();
  }
  if (!projectPath) {
    const response = await promptPath();
    if (typeof response.path === "string") {
      projectPath = response.path.trim();
    }
  }
  if (!projectPath) {
    //TODO separate log methods
    console.log();
    console.log("Please choose a name to your project:");
    console.log();
    console.log("Example:");
    console.log(
      `${chalk.cyan(program.name())} ${chalk.yellow("ny-portal-app")}`
    );
    console.log();

    process.exit(1);
  }

  const root = path.join(__dirname + "/../portal");

  const parsedPath = path.resolve(projectPath);
  const project = path.basename(parsedPath);

  console.log();
  console.log(
    `Begin Instalation of new portal.js on ${chalk.cyan(projectPath)} folder`
  );
  console.log();
  //TODO Move this method to another one to keep more functional and split responsabilites
  const tasks = new Listr([
    {
      title: "Fetching Content",
      task: () => copy(root, project),
    },
    {
      title: "Updating Content",
      task: () => "",
    },
    {
      title: "Installing Dependencies",
      task: () => install(project, true),
    },
    {
      title: "Git Init",
      task: () => initGit(projectPath),
    },
  ]);

  tasks.run().then(() => {
    console.log();
    console.log(`${chalk.greenBright("Instalation Completed!")}`);
    console.log();
    console.log(
      `Run ${chalk.cyan("cd " + projectPath)} and ${chalk.green(
        "yarn dev"
      )} or ${chalk.yellow("npm run dev")}`
    );
    console.log();
    console.log("Enjoy =)");
  });
}

//Main CLI execution workflow
run()
  .then(`${chalk.greenBright("Project Installed Sucess")}`)
  .catch((error) => {
    if (error.command) {
      console.log(`${chalk.cyan("Error on Create App")}`);
    } else {
      console.log(
        `${chalk.red("Unexpected Erro. Please report it as a bug")}`
      );
      console.log(error);
    }
    console.log();
    process.exit(1);
  });
<commit_msg>[index][s] : add printing of Fancy portal.js letter in the terminal<commit_after>#!/usr/bin/env node

const { program } = require("commander");
const chalk = require("chalk");
const prompts = require("prompts");
const path = require("path");
const { install, initGit } = require("./helpers/install");
const package = require("./package.json");
const copy = require("./helpers/copy");
const Listr = require("listr");
const figlet = require('figlet');

// Output path to create new portal app
let projectPath = "";

// Commander parameters to specify CLI behavior
program
  .name(package.name)
  .version(package.version)
  /**
   * TODO
   * Add Options
   * Add Example Options
   * Add templates
   */
  .arguments("[dir]")
  .usage(`${chalk.yellow("[dir]")}`)
  .description({
    dir: "Directory to be used on install Portal.js",
  })
  .action((name) => (projectPath = name))
  .allowUnknownOption()
  .parse(process.argv);

// print a fancy Portal.js in the terminal
console.log(
  chalk.yellow(
    figlet.textSync('Portal.Js', {horizontalLayout: 'full'})
  )
);
/**
 * Method to ask a custon name if was not passed as parameter
 * returns the value passed from terminal input
 */
async function promptPath() {
  return prompts({
    type: "text",
    name: "path",
    message: "Choose a name to your project",
    initial: "",
    validate: (name) => {
      //TODO Method to validate valid path name
      return true;
    },
  });
}

/**
 * Main method to start CLI and validate inputs
 */
async function run() {
  if (typeof projectPath === "string") {
    projectPath = projectPath.trim();
  }
  if (!projectPath) {
    const response = await promptPath();
    if (typeof response.path === "string") {
      projectPath = response.path.trim();
    }
  }
  if (!projectPath) {
    //TODO separate log methods
    console.log();
    console.log("Please choose a name to your project:");
    console.log();
    console.log("Example:");
    console.log(
      `${chalk.cyan(program.name())} ${chalk.yellow("ny-portal-app")}`
    );
    console.log();

    process.exit(1);
  }

  const root = path.join(__dirname + "/../portal");

  const parsedPath = path.resolve(projectPath);
  const project = path.basename(parsedPath);

  console.log();
  console.log(
    `Begin Instalation of new portal.js on ${chalk.cyan(projectPath)} folder`
  );
  console.log();
  //TODO Move this method to another one to keep more functional and split responsabilites
  const tasks = new Listr([
    {
      title: "Fetching Content",
      task: () => copy(root, project),
    },
    {
      title: "Updating Content",
      task: () => "",
    },
    {
      title: "Installing Dependencies",
      task: () => install(project, true),
    },
    {
      title: "Git Init",
      task: () => initGit(projectPath),
    },
  ]);

  tasks.run().then(() => {
    console.log();
    console.log(`${chalk.greenBright("Instalation Completed!")}`);
    console.log();
    console.log(
      `Run ${chalk.cyan("cd " + projectPath)} and ${chalk.green(
        "yarn dev"
      )} or ${chalk.yellow("npm run dev")}`
    );
    console.log();
    console.log("Enjoy =)");
  });
}

//Main CLI execution workflow
run()
  .then(`${chalk.greenBright("Project Installed Sucess")}`)
  .catch((error) => {
    if (error.command) {
      console.log(`${chalk.cyan("Error on Create App")}`);
    } else {
      console.log(
        `${chalk.red("Unexpected Erro. Please report it as a bug")}`
      );
      console.log(error);
    }
    console.log();
    process.exit(1);
  });
<|endoftext|>


<commit_before>/*globals define registry requirejs */

define("resolver",
  ["exports"],
  function() {
    "use strict";
  /*
   * This module defines a subclass of Ember.DefaultResolver that adds two
   * important features:
   *
   *  1) The resolver makes the container aware of es6 modules via the AMD
   *     output. The loader's _seen is consulted so that classes can be
   *     resolved directly via the module loader, without needing a manual
   *     `import`.
   *  2) is able provide injections to classes that implement `extend`
   *     (as is typical with Ember).
   */

  function classFactory(klass) {
    return {
      create: function (injections) {
        if (typeof klass.extend === 'function') {
          return klass.extend(injections);
        } else {
          return klass;
        }
      }
    };
  }

  var underscore = Ember.String.underscore;
  var classify = Ember.String.classify;
  var get = Ember.get;

  function parseName(fullName) {
    /*jshint validthis:true */

    var nameParts = fullName.split(":"),
        type = nameParts[0], fullNameWithoutType = nameParts[1],
        name = fullNameWithoutType,
        namespace = get(this, 'namespace'),
        root = namespace;

    return {
      fullName: fullName,
      type: type,
      fullNameWithoutType: fullNameWithoutType,
      name: name,
      root: root,
      resolveMethodName: "resolve" + classify(type)
    };
  }

  function chooseModuleName(seen, moduleName) {
    var underscoredModuleName = Ember.String.underscore(moduleName);

    if (moduleName !== underscoredModuleName && seen[moduleName] && seen[underscoredModuleName]) {
      throw new TypeError("Ambigous module names: `" + moduleName + "` and `" + underscoredModuleName + "`");
    }

    if (seen[moduleName]) {
      return moduleName;
    } else if (seen[underscoredModuleName]) {
      return underscoredModuleName;
    } else {
      return moduleName;
    }
  }

  function resolveRouter(parsedName) {
    /*jshint validthis:true */

    var prefix = this.namespace.modulePrefix,
        routerModule;

    if (parsedName.fullName === 'router:main') {
      // for now, lets keep the router at app/router.js
      if (requirejs._eak_seen[prefix + '/router']) {
        routerModule = require(prefix + '/router');
        if (routerModule.default) { routerModule = routerModule.default; }

        return routerModule;
      }
    }
  }

  function resolveOther(parsedName) {
    /*jshint validthis:true */

    var prefix = this.namespace.modulePrefix;
    Ember.assert('module prefix must be defined', prefix);

    var pluralizedType = parsedName.type + 's';
    var name = parsedName.fullNameWithoutType;

    var moduleName = prefix + '/' +  pluralizedType + '/' + name;

    // allow treat all dashed and all underscored as the same thing
    // supports components with dashes and other stuff with underscores.
    var normalizedModuleName = chooseModuleName(requirejs._eak_seen, moduleName);

    if (requirejs._eak_seen[normalizedModuleName]) {
      var module = require(normalizedModuleName, null, null, true /* force sync */);

      if (module.default) { module = module.default; }

      if (module === undefined) {
        throw new Error(" Expected to find: '" + parsedName.fullName + "' within '" + normalizedModuleName + "' but got 'undefined'. Did you forget to `export default` within '" + normalizedModuleName + "'?");
      }

      if (this.shouldWrapInClassFactory(module, parsedName)) {
        module = classFactory(module);
      }

      if (Ember.ENV.LOG_MODULE_RESOLVER) {
        Ember.Logger.info('[*]', parsedName.fullName, Array(40 - parsedName.fullName.length).join('.'), moduleName);
      }

      return module;
    } else {
      if (Ember.ENV.LOG_MODULE_RESOLVER) {
        Ember.Logger.info('[ ]', parsedName.fullName, Array(40 - parsedName.fullName.length).join('.'), moduleName);
      }
      return this._super(parsedName);
    }
  }
  // Ember.DefaultResolver docs:
  //   https://github.com/emberjs/ember.js/blob/master/packages/ember-application/lib/system/resolver.js
  var Resolver = Ember.DefaultResolver.extend({
    resolveTemplate: resolveOther,
    resolveOther: resolveOther,
    resolveRouter: resolveRouter,
    parseName: parseName,
    shouldWrapInClassFactory: function(module, parsedName){
      return false;
    },
    normalize: function(fullName) {
      // replace `.` with `/` in order to make nested controllers work in the following cases
      // 1. `needs: ['posts/post']`
      // 2. `{{render "posts/post"}}`
      // 3. `this.render('posts/post')` from Route
      return Ember.String.dasherize(fullName.replace(/\./g, '/'));
    }
  });

  Resolver.default = Resolver;
  return Resolver;
});
<commit_msg>Added new keyword before using the array constructor to satisfy jshint.<commit_after>/*globals define registry requirejs */

define("resolver",
  ["exports"],
  function() {
    "use strict";
  /*
   * This module defines a subclass of Ember.DefaultResolver that adds two
   * important features:
   *
   *  1) The resolver makes the container aware of es6 modules via the AMD
   *     output. The loader's _seen is consulted so that classes can be
   *     resolved directly via the module loader, without needing a manual
   *     `import`.
   *  2) is able provide injections to classes that implement `extend`
   *     (as is typical with Ember).
   */

  function classFactory(klass) {
    return {
      create: function (injections) {
        if (typeof klass.extend === 'function') {
          return klass.extend(injections);
        } else {
          return klass;
        }
      }
    };
  }

  var underscore = Ember.String.underscore;
  var classify = Ember.String.classify;
  var get = Ember.get;

  function parseName(fullName) {
    /*jshint validthis:true */

    var nameParts = fullName.split(":"),
        type = nameParts[0], fullNameWithoutType = nameParts[1],
        name = fullNameWithoutType,
        namespace = get(this, 'namespace'),
        root = namespace;

    return {
      fullName: fullName,
      type: type,
      fullNameWithoutType: fullNameWithoutType,
      name: name,
      root: root,
      resolveMethodName: "resolve" + classify(type)
    };
  }

  function chooseModuleName(seen, moduleName) {
    var underscoredModuleName = Ember.String.underscore(moduleName);

    if (moduleName !== underscoredModuleName && seen[moduleName] && seen[underscoredModuleName]) {
      throw new TypeError("Ambigous module names: `" + moduleName + "` and `" + underscoredModuleName + "`");
    }

    if (seen[moduleName]) {
      return moduleName;
    } else if (seen[underscoredModuleName]) {
      return underscoredModuleName;
    } else {
      return moduleName;
    }
  }

  function resolveRouter(parsedName) {
    /*jshint validthis:true */

    var prefix = this.namespace.modulePrefix,
        routerModule;

    if (parsedName.fullName === 'router:main') {
      // for now, lets keep the router at app/router.js
      if (requirejs._eak_seen[prefix + '/router']) {
        routerModule = require(prefix + '/router');
        if (routerModule.default) { routerModule = routerModule.default; }

        return routerModule;
      }
    }
  }

  function resolveOther(parsedName) {
    /*jshint validthis:true */

    var prefix = this.namespace.modulePrefix;
    Ember.assert('module prefix must be defined', prefix);

    var pluralizedType = parsedName.type + 's';
    var name = parsedName.fullNameWithoutType;

    var moduleName = prefix + '/' +  pluralizedType + '/' + name;

    // allow treat all dashed and all underscored as the same thing
    // supports components with dashes and other stuff with underscores.
    var normalizedModuleName = chooseModuleName(requirejs._eak_seen, moduleName);

    if (requirejs._eak_seen[normalizedModuleName]) {
      var module = require(normalizedModuleName, null, null, true /* force sync */);

      if (module.default) { module = module.default; }

      if (module === undefined) {
        throw new Error(" Expected to find: '" + parsedName.fullName + "' within '" + normalizedModuleName + "' but got 'undefined'. Did you forget to `export default` within '" + normalizedModuleName + "'?");
      }

      if (this.shouldWrapInClassFactory(module, parsedName)) {
        module = classFactory(module);
      }

      if (Ember.ENV.LOG_MODULE_RESOLVER) {
        Ember.Logger.info('[*]', parsedName.fullName, new Array(40 - parsedName.fullName.length).join('.'), moduleName);
      }

      return module;
    } else {
      if (Ember.ENV.LOG_MODULE_RESOLVER) {
        Ember.Logger.info('[ ]', parsedName.fullName, new Array(40 - parsedName.fullName.length).join('.'), moduleName);
      }
      return this._super(parsedName);
    }
  }
  // Ember.DefaultResolver docs:
  //   https://github.com/emberjs/ember.js/blob/master/packages/ember-application/lib/system/resolver.js
  var Resolver = Ember.DefaultResolver.extend({
    resolveTemplate: resolveOther,
    resolveOther: resolveOther,
    resolveRouter: resolveRouter,
    parseName: parseName,
    shouldWrapInClassFactory: function(module, parsedName){
      return false;
    },
    normalize: function(fullName) {
      // replace `.` with `/` in order to make nested controllers work in the following cases
      // 1. `needs: ['posts/post']`
      // 2. `{{render "posts/post"}}`
      // 3. `this.render('posts/post')` from Route
      return Ember.String.dasherize(fullName.replace(/\./g, '/'));
    }
  });

  Resolver.default = Resolver;
  return Resolver;
});
<|endoftext|>


<commit_before>const exec = require('execa');

const createApp = require('frint').createApp;

const descriptionText = `
Usage:

  $ frint init
  $ frint init --example exampleName

Example:

  $ mkdir my-new-directory
  $ cd my-new-directory

  $ frint init --example kitchensink

You can find list of all available examples here:
https://github.com/Travix-International/frint/tree/master/examples
`.trim();

module.exports = createApp({
  name: 'init',
  providers: [
    {
      name: 'summary',
      useValue: 'Scaffolds a new Frint app in current working directory',
    },
    {
      name: 'description',
      useValue: descriptionText,
    },
    {
      name: 'execute',
      useFactory: function useFactory(deps) {
        return function execute() {
          const example = deps.params.example || 'counter';
          const dir = deps.pwd;

          const cmds = [
            `mkdir -p ${dir}`,
            `curl https://codeload.github.com/Travix-International/frint/tar.gz/master | tar -xz -C ${dir} --strip=3 frint-master/examples/ ${example}`,
          ];

          deps.console.log('Initializing...');
          const cmdPromises = cmds.map(cmd => exec.shell(cmd));

          Promise.all(cmdPromises)
            .then(() => deps.console.log('Done!'))
            .catch(e => deps.console.error(e));
        };
      },
      deps: [
        'console',
        'params',
        'pwd',
      ],
    }
  ],
});
<commit_msg>frint-cli: removed extra space from command. (#212)<commit_after>const exec = require('execa');

const createApp = require('frint').createApp;

const descriptionText = `
Usage:

  $ frint init
  $ frint init --example exampleName

Example:

  $ mkdir my-new-directory
  $ cd my-new-directory

  $ frint init --example kitchensink

You can find list of all available examples here:
https://github.com/Travix-International/frint/tree/master/examples
`.trim();

module.exports = createApp({
  name: 'init',
  providers: [
    {
      name: 'summary',
      useValue: 'Scaffolds a new Frint app in current working directory',
    },
    {
      name: 'description',
      useValue: descriptionText,
    },
    {
      name: 'execute',
      useFactory: function useFactory(deps) {
        return function execute() {
          const example = deps.params.example || 'counter';
          const dir = deps.pwd;

          const cmds = [
            `mkdir -p ${dir}`,
            `curl https://codeload.github.com/Travix-International/frint/tar.gz/master | tar -xz -C ${dir} --strip=3 frint-master/examples/${example}`,
          ];

          deps.console.log('Initializing...');
          const cmdPromises = cmds.map(cmd => exec.shell(cmd));

          Promise.all(cmdPromises)
            .then(() => deps.console.log('Done!'))
            .catch(e => deps.console.error(e));
        };
      },
      deps: [
        'console',
        'params',
        'pwd',
      ],
    }
  ],
});
<|endoftext|>


<commit_before>/* Milesian Compose and decompose routines.
// Character set is UTF-8
//
// The function of this package performs decompositions suitable to calendar computations.
// The Milesian calendar, given its regulars month, is able to use totally this principle.
// For other calendars, including Gregorian and Julian, this routines may be used to compute
// the rank of a day within a year, and then hours, minutes, seconds and milliseconds.
// Computations on months require more specific algorithms.
// The principles of these routines are explained in "L'heure milésienne",
// a book by Louis-Aimé de Fouquières.
*//////////////////////////////////////////////////////////////////////////////////////////////
/* Copyright Miletus 2016-2017 - Louis A. de Fouquières
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 1. The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
// 2. Changes with respect to any former version shall be documented.
//
// The software is provided "as is", without warranty of any kind,
// express of implied, including but not limited to the warranties of
// merchantability, fitness for a particular purpose and noninfringement.
// In no event shall the authors of copyright holders be liable for any
// claim, damages or other liability, whether in an action of contract,
// tort or otherwise, arising from, out of or in connection with the software
// or the use or other dealings in the software.
// Inquiries: www.calendriermilesien.org
*////////////////////////////////////////////////////////////////////////////////
/* Parameter object structure. Replace # with numbers or literals.
const decomposeParameterExample = {
	timeepoch : #, origin time in milliseconds (or in the suitable unit) to be used for the decomposition, with respect to 1/1/1970 00:00 UTC.
	coeff : [ // This array holds the coefficient used to decompose a time stamp into time cycles like eras, quadrisaeculae, centuries etc.
		{cyclelength : #, //length of the cycle, expressed in milliseconds.
		ceiling : #, // Infinity, or the maximum number of cycles of this size in the upper cycle; the last cycle may hold an intercalary unit.
		multiplier : #, // multiplies the number of cycle of this level to convert into target units.
		targer : #, // the unit (e.g. "year") of the decomposition element at this level.
		} ,
		{ // similar elements at the lower cycle level
		} // end of array element
	], // End of this array, but not end of object
	canvas : [ // this last array is the canvas of the decomposition , e.g. "year", "month", "date", with suitable properties at each level.
		{ name : #, // the name of the property at this level, which must match one target property of the coeff component,
		init : #, // value of this component at epoch, and lowest value (except for the first component), e.g. 0 for month, 1 for date, 0 for hours, minutes, seconds.
		} // End of array element (only two properties)
	] // End of second array
}	// End of object.
*/
var // A selection of composition objects
// Former Unix_Day_Time_Coeff
Day_milliseconds = { 	// To convert a time or a duration to and from days + milliseconds in day.
	timeepoch : 0,
	coeff : [ // to be used with a Unix timestamp in ms. Decompose into days and milliseconds in day.
	  {cyclelength : 86400000, ceiling : Infinity, multiplier : 1, target : "day_number"},
	  {cyclelength : 1, ceiling : Infinity, multiplier : 1, target : "milliseconds_in_day"}
	],
	canvas : [
		{name : "day_number", init : 0},
		{name : "milliseconds_in_day", init : 0},
	]
} ,
Milesian_time_params = { // To be used with a Unix timestamp in ms. Decompose into Milesian years, months, date, hours, minutes, seconds, ms
	timeepoch : -188395804800000, // Unix timestamp of 1 1m -4000 00h00 UTC in ms
	coeff : [
	  {cyclelength : 100982160000000, ceiling : Infinity, multiplier : 3200, target : "year"},
	  {cyclelength : 12622780800000, ceiling : Infinity, multiplier : 400, target : "year"},
	  {cyclelength : 3155673600000, ceiling :  3, multiplier : 100, target : "year"},
	  {cyclelength : 126230400000, ceiling : Infinity, multiplier : 4, target : "year"},
	  {cyclelength : 31536000000, ceiling : 3, multiplier : 1, target : "year"},
	  {cyclelength : 5270400000, ceiling : Infinity, multiplier : 2, target : "month"},
	  {cyclelength : 2592000000, ceiling : 1, multiplier : 1, target : "month"},
	  {cyclelength : 86400000, ceiling : Infinity, multiplier : 1, target : "date"},
	  {cyclelength : 3600000, ceiling : Infinity, multiplier : 1, target : "hours"},
	  {cyclelength : 60000, ceiling : Infinity, multiplier : 1, target : "minutes"},
	  {cyclelength : 1000, ceiling : Infinity, multiplier : 1, target : "seconds"},
	  {cyclelength : 1, ceiling : Infinity, multiplier : 1, target : "milliseconds"}
	],
	canvas : [
		{name : "year", init : -4000},
		{name : "month", init : 0},
		{name : "date", init : 1},
		{name : "hours", init : 0},
		{name : "minutes", init : 0},
		{name : "seconds", init : 0},
		{name : "milliseconds", init : 0},
	]
} ,
//
// Former Milesian_date_coeff and canvas
//
Milesian_date_JD_params = {  // To be used with a timestamp in integer days. Decomposes into year, month, date.
	timeepoch : 260081, // 1 1m -4000 in Julian Day
	coeff : [
		  {cyclelength : 1168775, ceiling : Infinity, multiplier : 3200, target : "year"},
		  {cyclelength : 146097, ceiling : Infinity, multiplier : 400, target : "year"},
		  {cyclelength : 36524, ceiling :  3, multiplier : 100, target : "year"},
		  {cyclelength : 1461, ceiling : Infinity, multiplier : 4, target : "year"},
		  {cyclelength : 365, ceiling : 3, multiplier : 1, target : "year"},
		  {cyclelength : 61, ceiling : Infinity, multiplier : 2, target : "month"},
		  {cyclelength : 30, ceiling : 1, multiplier : 1, target : "month"},
		  {cyclelength : 1, ceiling : Infinity, multiplier : 1, target : "date"}
	],
	canvas : [ // Timestamp is 0 on 1 1m -4000, month is in the JS way (0 to 11), date starts at 1.
		{name : "year", init : -4000},
		{name : "month", init : 0},
		{name : "date", init : 1}
	]
} ,
CE_Moon_params = { // to be used with a Unix timestamp in ms. Decompose into moon years, moon months and moon age.
	timeepoch : -62167873955000, // from the mean new moon of 3 1m 0 at 10:07:25 Terrestrial Time.
	coeff : [
		 {cyclelength : 30617314500, ceiling : Infinity, multiplier : 1, target : "year"}, // this cycle length is 12 mean lunar months
		 {cyclelength : 2551442875, ceiling : Infinity, multiplier : 1, target : "month"}, // this cycle length is one mean lunar month
		 {cyclelength : 86400000, ceiling : Infinity, multiplier : 1, target : "age"},
		 {cyclelength : 1, ceiling : Infinity, multiplier : 1.157407407E-8, target : "age"}
	],
	canvas : [
		{name : "year", init : 0},
		{name : "month", init : 0},
		{name : "age", init : 0}
	]
} ,
Lunar_Year_Month_Params = { // to be used in order to change lunar calendar epoch, without changing lunar age.
// Usage of this parameter set: change between Common Era and Hegirian moon calendar, 7688 lunar month offset.
	timeepoch : 0, // put the timeepoch in the parameter call.
	coeff : [
		{cyclelength : 12, ceiling : Infinity, multiplier : 1, target : "year"},
		{cyclelength : 1,  ceiling : Infinity, multiplier : 1, target : "month"}
	],
	canvas : [
		{name : "year", init :0},
		{name : "month", init : 0}
	]
}
/////////////////////////////////////////////
// milesianDecompose : from time serie figure to decomposition
/////////////////////////////////////////////
function milesianDecompose (quantity, params) { // from a chronological number, build an compound object holding the elements as required by cparams.
  quantity -= params.timeepoch; // set quantity to decompose into cycles to the right value.
  var result = new Object(); // Construct intitial result
  for (let i = 0; i < params.canvas.length; i++) {
    Object.defineProperty (result, params.canvas[i].name, {enumerable : true, writable : true, value : params.canvas[i].init});
  }
  for (let i = 0; i < params.coeff.length; ++i) {
    let r = 0; // r is computed quotient for this level of decomposition
    if (params.coeff[i].cyclelength == 1) r = quantity; // avoid performing a trivial divison by 1.
    else {
      while (quantity < 0) {
        --r;
        quantity += params.coeff[i].cyclelength;
      }
      while ((quantity >= params.coeff[i].cyclelength) && (r < params.coeff[i].ceiling)) {
        ++r;
        quantity -= params.coeff[i].cyclelength;
      }
    }
    result[params.coeff[i].target] += r*params.coeff[i].multiplier; // add result to suitable part of result array
  }
  return result;
}
////////////////////////////////////////////
// milesianCompose: from compound object to time serie figure.
////////////////////////////////////////////
function milesianCompose (cells, params) { // from an object structured as params.canvas, compute the chronological number
	var quantity = params.timeepoch ; // initialise quantity
	for (let i = 0; i < params.canvas.length; i++) { // cells value shifted as to have all 0 if at epoch
		cells[params.canvas[i].name] -= params.canvas[i].init
	}
	for (let i = params.coeff.length-1; i >= 0; --i) { // consolidate from small to large
		let factor = (params.coeff[i].multiplier == 1 ? params.coeff[i].cyclelength :
		params.coeff[i].cyclelength -
									(params.coeff[i+1].cyclelength * params.coeff[i].multiplier / params.coeff[i+1].multiplier )
									);
		quantity += Math.floor(cells[params.coeff[i].target] / params.coeff[i].multiplier) * factor;
	}
	return quantity ;
}<commit_msg>Delete MilesianCompose.js<commit_after><|endoftext|>


<commit_before>/*
    ___ usage ___ en_US ___
    usage: node sidecar.bin.js

        -p, --processor <string>        processor path
        -s, --supervisor <string>       pid of supervisor
        -t, --tmp <string>              path of temporary directory
        -c, --child <string>            monitored pid
        -m, --main <string>             source of child process
            --help                      display this message

    ___ . ___
*/
require('arguable')(module, {
    $trap: { SIGINT: 'swallow', SIGTERM: 'swallow' },
    process: process
}, async (arguable) => {
    arguable.required('processor', 'supervisor')

    const Destructible = require('destructible')
    const destructible = new Destructible('sidecar')

    // Node.js API.
    const assert = require('assert')

    const Consolidator = require('prolific.consolidator')

    const Logger = require('./logger')

    const tmp = arguable.ultimate.tmp

    const logger = new Logger(destructible.durable('logger'), Date, tmp, process.pid, 1000)
    logger.say('sidecar.start', { tmp })

    const _logger = require('prolific.logger').create('prolific')
    function memoryUsage () { _logger.notice('memory', process.memoryUsage()) }
    memoryUsage()
    const interval = setInterval(memoryUsage, 1000)
    destructible.destruct(() => clearInterval(interval))

    const Processor = require('./processor', arguable.ultimate.main)

    const processor = new Processor(arguable.ultimate.processor, arguable.ultimate.main, logger)

    const Queue = require('avenue')
    const queue = new Queue

    const processors = new Queue().shifter().paired

    async function update (socket) {
        for await (const processor of processors.shifter.iterator()) {
            logger.say('processor.send', { processor })
            socket.write(JSON.stringify(processor) + '\n')
        }
    }

    destructible.destruct(() => processors.shifter.destroy())

    processor.on('processor', (processor) => {
        logger.say('processor.load', { processor })
        processors.queue.push(processor)
    })

    // Listen to our asynchronous pipe.
    const consolidator = new Consolidator(queue)

    destructible.durable('process', queue.shifter().pump(chunk => {
        processor.process(chunk)
    }))
    destructible.ephemeral('configure', processor.configure())

    function message (message, socket) {
        switch (`${message.module}:${message.method}`) {
        case 'prolific:socket':
            logger.say('sidecar.socket', { message, socket: !! socket })
            if (socket != null) {
                socket.on('error', error => {
                    logger.say('socket.error', { stack: error.stack })
                })
                destructible.ephemeral('read', update(socket))
                destructible.ephemeral('asynchronous', consolidator.asynchronous(socket, socket))
            }
            break
        case 'prolific:synchronous':
            logger.say('processor.synchronous', { message })
            consolidator.synchronous(message.body)
            break
        }
    }
    arguable.options.process.on('message', message)
    destructible.destruct(() => arguable.options.process.removeListener('message', message))

    // Let the supervisor know that we're ready. It will send our asynchronous
    // pipe down to the monitored process.
    arguable.options.process.send({
        module: 'prolific',
        method: 'receiving',
        child: +arguable.ultimate.child
    })

    await destructible.promise

    return 0
})
<commit_msg>Sidecar logging messages now labeled `sidecar`.<commit_after>/*
    ___ usage ___ en_US ___
    usage: node sidecar.bin.js

        -p, --processor <string>        processor path
        -s, --supervisor <string>       pid of supervisor
        -t, --tmp <string>              path of temporary directory
        -c, --child <string>            monitored pid
        -m, --main <string>             source of child process
            --help                      display this message

    ___ . ___
*/
require('arguable')(module, {
    $trap: { SIGINT: 'swallow', SIGTERM: 'swallow' },
    process: process
}, async (arguable) => {
    arguable.required('processor', 'supervisor')

    const Destructible = require('destructible')
    const destructible = new Destructible('sidecar')

    // Node.js API.
    const assert = require('assert')

    const Consolidator = require('prolific.consolidator')

    const Logger = require('./logger')

    const tmp = arguable.ultimate.tmp

    const logger = new Logger(destructible.durable('logger'), Date, tmp, process.pid, 1000)
    logger.say('sidecar.start', { tmp })

    const _logger = require('prolific.logger').create('prolific')
    function memoryUsage () { _logger.notice('memory', process.memoryUsage()) }
    memoryUsage()
    const interval = setInterval(memoryUsage, 1000)
    destructible.destruct(() => clearInterval(interval))

    const Processor = require('./processor', arguable.ultimate.main)

    const processor = new Processor(arguable.ultimate.processor, arguable.ultimate.main, logger)

    const Queue = require('avenue')
    const queue = new Queue

    const processors = new Queue().shifter().paired

    async function update (socket) {
        for await (const processor of processors.shifter.iterator()) {
            logger.say('sidecar.triage', { processor })
            socket.write(JSON.stringify(processor) + '\n')
        }
    }

    destructible.destruct(() => processors.shifter.destroy())

    processor.on('processor', (processor) => {
        logger.say('sidecar.processor', { processor })
        processors.queue.push(processor)
    })

    // Listen to our asynchronous pipe.
    const consolidator = new Consolidator(queue)

    destructible.durable('process', queue.shifter().pump(chunk => {
        processor.process(chunk)
    }))
    destructible.ephemeral('configure', processor.configure())

    function message (message, socket) {
        switch (`${message.module}:${message.method}`) {
        case 'prolific:socket':
            logger.say('sidecar.socket', { message, socket: !! socket })
            if (socket != null) {
                socket.on('error', error => {
                    logger.say('socket.error', { stack: error.stack })
                })
                destructible.ephemeral('read', update(socket))
                destructible.ephemeral('asynchronous', consolidator.asynchronous(socket, socket))
            }
            break
        case 'prolific:synchronous':
            logger.say('sidecar.synchronous', { message })
            consolidator.synchronous(message.body)
            break
        }
    }
    arguable.options.process.on('message', message)
    destructible.destruct(() => arguable.options.process.removeListener('message', message))

    // Let the supervisor know that we're ready. It will send our asynchronous
    // pipe down to the monitored process.
    arguable.options.process.send({
        module: 'prolific',
        method: 'receiving',
        child: +arguable.ultimate.child
    })

    await destructible.promise

    return 0
})
<|endoftext|>


<commit_before>// @flow
import Display from "./display";
import RichestMime from "./richest-mime";
import Output from "./output";

module.exports = {
  Display,
  RichestMime,
  Output
};
<commit_msg>switch display area to es<commit_after>// @flow
import Display from "./display";
import RichestMime from "./richest-mime";
import Output from "./output";

export { Display, RichestMime, Output };
<|endoftext|>