<commit_before>import {Button} from 'widget/button'
import {compose} from 'compose'
import {isMobile} from 'widget/userAgent'
import Keybinding from 'widget/keybinding'
import Label from 'widget/label'
import PropTypes from 'prop-types'
import React from 'react'
import TextareaAutosize from 'react-textarea-autosize'
import styles from './formComponents.module.css'
import withForwardedRef from 'ref'

export class FormComponent extends React.Component {
    render() {
        const {layout, spacing, errorMessage, className, onClick, children} = this.props
        return (
            <React.Fragment>

 onClick && onClick(e)}>
                    {this.renderLabel()}

 styles[className]).join(' '),
                        styles[spacing],
                        errorMessage ? styles.error : null
                    ].join(' ')}>
                        {children}

                    {this.renderErrorMessage()}

                {this.renderErrorMessageSpacer()}
            </React.Fragment>
        )
    }

    renderLabel() {
        const {label, tooltip, tooltipPlacement, alignment, disabled} = this.props
        return label
            ? (

            )
            : null
    }

    renderErrorMessage() {
        const {errorMessage} = this.props
        return errorMessage
            ? (

                        {errorMessage}

            )
            : null
    }

    renderErrorMessageSpacer() {
        const {errorMessage} = this.props
        return errorMessage === undefined || errorMessage === false
            ? null
            :

    }
}

FormComponent.propTypes = {
    children: PropTypes.any.isRequired,
    alignment: PropTypes.oneOf(['left', 'center', 'right']),
    className: PropTypes.string,
    disabled: PropTypes.any,
    errorMessage: PropTypes.any,
    label: PropTypes.string,
    layout: PropTypes.oneOf(['vertical', 'horizontal', 'horizontal-nowrap']),
    spacing: PropTypes.oneOf(['normal', 'compact', 'none']),
    tooltip: PropTypes.string,
    tooltipPlacement: PropTypes.string,
    onClick: PropTypes.func
}

FormComponent.defaultProps = {
    alignment: 'left',
    layout: 'vertical',
    spacing: 'none',
    tooltipPlacement: 'top'
}

class _Input extends React.Component {
    constructor(props) {
        super(props)
        this.ref = props.forwardedRef || React.createRef()
    }

    state = {
        value: null
    }

    static getDerivedStateFromProps(props) {
        const {value} = props
        return {
            value
        }
    }

    render() {
        const {className, disabled, label, tooltip, tooltipPlacement, errorMessage, border, onClick} = this.props
        return (
            <FormComponent
                className={[
                    styles.input,
                    border ? styles.border : null,
                    className
                ].join(' ')}
                disabled={disabled}
                label={label}
                tooltip={tooltip}
                tooltipPlacement={tooltipPlacement}
                errorMessage={errorMessage}
                onClick={e => onClick && onClick(e)}
            >
                {this.renderContent()}
            </FormComponent>
        )
    }

    renderContent() {
        const {leftComponent, rightComponent} = this.props
        return leftComponent || rightComponent
            ? (
                <FormComponent
                    layout='horizontal-nowrap'
                    spacing='none'>
                    {this.renderLeftComponent()}
                    {this.renderInput()}
                    {this.renderRightComponent()}
                </FormComponent>
            )
            : this.renderInput()
    }

    renderInput() {
        const {
            type, name, value, defaultValue, placeholder, maxLength, tabIndex,
            autoFocus, autoComplete, autoCorrect, autoCapitalize, spellCheck, disabled, readOnly,
            onBlur, onChange, onFocus
        } = this.props
        return (
            <input
                ref={this.ref}
                className={readOnly ? styles.readOnly : null}
                type={this.isSearchInput() ? 'text' : type}
                name={name}
                value={value}
                defaultValue={defaultValue}
                placeholder={placeholder}
                maxLength={maxLength}
                tabIndex={tabIndex}
                autoFocus={autoFocus && !isMobile()}
                autoComplete={autoComplete ? 'on' : 'off'}
                autoCorrect={autoCorrect ? 'on' : 'off'}
                autoCapitalize={autoCapitalize ? 'on' : 'off'}
                spellCheck={spellCheck ? 'true' : 'false'}
                disabled={disabled}
                readOnly={readOnly ? 'readonly' : ''}
                onBlur={e => onBlur && onBlur(e)}
                onChange={e => onChange && onChange(e)}
                onFocus={e => onFocus && onFocus(e)}
            />
        )
    }

    renderLeftComponent() {
        const {leftComponent} = this.props
        return leftComponent
            ? (

                    {leftComponent}

            )
            : null
    }

    renderRightComponent() {
        const {value, rightComponent} = this.props
        return value && this.isSearchInput()
            ? this.renderClearButton()
            : rightComponent
                ? (

                        {rightComponent}

                )
                : null
    }

    renderClearButton() {
        return (

                <Button
                    chromeless
                    shape='none'
                    icon='times'
                    onClick={() => this.props.onChange({target: {value: ''}})}
                    // [TODO] change signature from event to value
                />

        )
    }

    isSearchInput() {
        const {type} = this.props
        return type === 'search'
    }
}

export const Input = compose(
    _Input,
    withForwardedRef()
)

Input.propTypes = {
    autoCapitalize: PropTypes.any,
    autoComplete: PropTypes.any,
    autoCorrect: PropTypes.any,
    autoFocus: PropTypes.any,
    border: PropTypes.any,
    className: PropTypes.string,
    defaultValue: PropTypes.any,
    disabled: PropTypes.any,
    errorMessage: PropTypes.string,
    fadeOverflow: PropTypes.any,
    label: PropTypes.string,
    leftComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
    maxLength: PropTypes.number,
    name: PropTypes.string,
    placeholder: PropTypes.any,
    readOnly: PropTypes.any,
    rightComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
    spellCheck: PropTypes.any,
    tabIndex: PropTypes.number,
    tooltip: PropTypes.string,
    tooltipPlacement: PropTypes.string,
    type: PropTypes.string,
    value: PropTypes.any,
    onBlur: PropTypes.func,
    onChange: PropTypes.func,
    onClick: PropTypes.func,
    onFocus: PropTypes.func
}

Input.defaultProps = {
    autoFocus: false,
    autoComplete: false,
    autoCorrect: false,
    autoCapitalize: false,
    border: true,
    spellCheck: false,
    type: 'text',
    tooltipPlacement: 'top'
}

export class _Textarea extends React.Component {
    state = {
        textareaFocused: false
    }

    constructor(props) {
        super(props)
        this.ref = props.forwardedRef || React.createRef()
    }

    render() {
        const {disabled, label, tooltip, tooltipPlacement, errorMessage} = this.props
        return (
            <FormComponent
                disabled={disabled}
                label={label}
                tooltip={tooltip}
                tooltipPlacement={tooltipPlacement}
                errorMessage={errorMessage}>
                {this.renderTextArea()}
            </FormComponent>
        )
    }

    renderTextArea() {
        const {className, name, value, autoFocus, tabIndex, minRows, maxRows, onChange, onBlur} = this.props
        const {textareaFocused} = this.state
        return (
            <Keybinding keymap={{Enter: null}} disabled={!textareaFocused} priority>

                    <TextareaAutosize
                        ref={this.element}
                        className={className}
                        name={name}
                        value={value || ''}
                        tabIndex={tabIndex}
                        autoFocus={autoFocus && !isMobile()}
                        minRows={minRows}
                        maxRows={maxRows}
                        onChange={e => onChange && onChange(e)}
                        onFocus={() => this.setState({textareaFocused: true})}
                        onBlur={e => {
                            this.setState({textareaFocused: false})
                            onBlur && onBlur(e)
                        }}
                    />

            </Keybinding>
        )
    }
}

export const Textarea = compose(
    _Textarea,
    withForwardedRef()
)

Textarea.propTypes = {
    autoFocus: PropTypes.any,
    className: PropTypes.string,
    disabled: PropTypes.any,
    errorMessage: PropTypes.string,
    label: PropTypes.string,
    maxRows: PropTypes.number,
    minRows: PropTypes.number,
    name: PropTypes.string,
    placeholder: PropTypes.string,
    tabIndex: PropTypes.number,
    tooltip: PropTypes.string,
    tooltipPlacement: PropTypes.string,
    value: PropTypes.any,
    onBlur: PropTypes.func,
    onChange: PropTypes.func
}

Textarea.defaultProp = {
    tooltipPlacement: 'top'
}

export default {
    FormComponent,
    Input,
    Textarea
}
<commit_msg>Added missing Textarea border.<commit_after>import {Button} from 'widget/button'
import {compose} from 'compose'
import {isMobile} from 'widget/userAgent'
import Keybinding from 'widget/keybinding'
import Label from 'widget/label'
import PropTypes from 'prop-types'
import React from 'react'
import TextareaAutosize from 'react-textarea-autosize'
import styles from './formComponents.module.css'
import withForwardedRef from 'ref'

export class FormComponent extends React.Component {
    render() {
        const {layout, spacing, errorMessage, className, onClick, children} = this.props
        return (
            <React.Fragment>

 onClick && onClick(e)}>
                    {this.renderLabel()}

 styles[className]).join(' '),
                        styles[spacing],
                        errorMessage ? styles.error : null
                    ].join(' ')}>
                        {children}

                    {this.renderErrorMessage()}

                {this.renderErrorMessageSpacer()}
            </React.Fragment>
        )
    }

    renderLabel() {
        const {label, tooltip, tooltipPlacement, alignment, disabled} = this.props
        return label
            ? (

            )
            : null
    }

    renderErrorMessage() {
        const {errorMessage} = this.props
        return errorMessage
            ? (

                        {errorMessage}

            )
            : null
    }

    renderErrorMessageSpacer() {
        const {errorMessage} = this.props
        return errorMessage === undefined || errorMessage === false
            ? null
            :

    }
}

FormComponent.propTypes = {
    children: PropTypes.any.isRequired,
    alignment: PropTypes.oneOf(['left', 'center', 'right']),
    className: PropTypes.string,
    disabled: PropTypes.any,
    errorMessage: PropTypes.any,
    label: PropTypes.string,
    layout: PropTypes.oneOf(['vertical', 'horizontal', 'horizontal-nowrap']),
    spacing: PropTypes.oneOf(['normal', 'compact', 'none']),
    tooltip: PropTypes.string,
    tooltipPlacement: PropTypes.string,
    onClick: PropTypes.func
}

FormComponent.defaultProps = {
    alignment: 'left',
    layout: 'vertical',
    spacing: 'none',
    tooltipPlacement: 'top'
}

class _Input extends React.Component {
    constructor(props) {
        super(props)
        this.ref = props.forwardedRef || React.createRef()
    }

    state = {
        value: null
    }

    static getDerivedStateFromProps(props) {
        const {value} = props
        return {
            value
        }
    }

    render() {
        const {className, disabled, label, tooltip, tooltipPlacement, errorMessage, border, onClick} = this.props
        return (
            <FormComponent
                className={[
                    styles.input,
                    border ? styles.border : null,
                    className
                ].join(' ')}
                disabled={disabled}
                label={label}
                tooltip={tooltip}
                tooltipPlacement={tooltipPlacement}
                errorMessage={errorMessage}
                onClick={e => onClick && onClick(e)}
            >
                {this.renderContent()}
            </FormComponent>
        )
    }

    renderContent() {
        const {leftComponent, rightComponent} = this.props
        return leftComponent || rightComponent
            ? (
                <FormComponent
                    layout='horizontal-nowrap'
                    spacing='none'>
                    {this.renderLeftComponent()}
                    {this.renderInput()}
                    {this.renderRightComponent()}
                </FormComponent>
            )
            : this.renderInput()
    }

    renderInput() {
        const {
            type, name, value, defaultValue, placeholder, maxLength, tabIndex,
            autoFocus, autoComplete, autoCorrect, autoCapitalize, spellCheck, disabled, readOnly,
            onBlur, onChange, onFocus
        } = this.props
        return (
            <input
                ref={this.ref}
                className={readOnly ? styles.readOnly : null}
                type={this.isSearchInput() ? 'text' : type}
                name={name}
                value={value}
                defaultValue={defaultValue}
                placeholder={placeholder}
                maxLength={maxLength}
                tabIndex={tabIndex}
                autoFocus={autoFocus && !isMobile()}
                autoComplete={autoComplete ? 'on' : 'off'}
                autoCorrect={autoCorrect ? 'on' : 'off'}
                autoCapitalize={autoCapitalize ? 'on' : 'off'}
                spellCheck={spellCheck ? 'true' : 'false'}
                disabled={disabled}
                readOnly={readOnly ? 'readonly' : ''}
                onBlur={e => onBlur && onBlur(e)}
                onChange={e => onChange && onChange(e)}
                onFocus={e => onFocus && onFocus(e)}
            />
        )
    }

    renderLeftComponent() {
        const {leftComponent} = this.props
        return leftComponent
            ? (

                    {leftComponent}

            )
            : null
    }

    renderRightComponent() {
        const {value, rightComponent} = this.props
        return value && this.isSearchInput()
            ? this.renderClearButton()
            : rightComponent
                ? (

                        {rightComponent}

                )
                : null
    }

    renderClearButton() {
        return (

                <Button
                    chromeless
                    shape='none'
                    icon='times'
                    onClick={() => this.props.onChange({target: {value: ''}})}
                    // [TODO] change signature from event to value
                />

        )
    }

    isSearchInput() {
        const {type} = this.props
        return type === 'search'
    }
}

export const Input = compose(
    _Input,
    withForwardedRef()
)

Input.propTypes = {
    autoCapitalize: PropTypes.any,
    autoComplete: PropTypes.any,
    autoCorrect: PropTypes.any,
    autoFocus: PropTypes.any,
    border: PropTypes.any,
    className: PropTypes.string,
    defaultValue: PropTypes.any,
    disabled: PropTypes.any,
    errorMessage: PropTypes.string,
    fadeOverflow: PropTypes.any,
    label: PropTypes.string,
    leftComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
    maxLength: PropTypes.number,
    name: PropTypes.string,
    placeholder: PropTypes.any,
    readOnly: PropTypes.any,
    rightComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
    spellCheck: PropTypes.any,
    tabIndex: PropTypes.number,
    tooltip: PropTypes.string,
    tooltipPlacement: PropTypes.string,
    type: PropTypes.string,
    value: PropTypes.any,
    onBlur: PropTypes.func,
    onChange: PropTypes.func,
    onClick: PropTypes.func,
    onFocus: PropTypes.func
}

Input.defaultProps = {
    autoFocus: false,
    autoComplete: false,
    autoCorrect: false,
    autoCapitalize: false,
    border: true,
    spellCheck: false,
    type: 'text',
    tooltipPlacement: 'top'
}

export class _Textarea extends React.Component {
    state = {
        textareaFocused: false
    }

    constructor(props) {
        super(props)
        this.ref = props.forwardedRef || React.createRef()
    }

    render() {
        const {disabled, label, tooltip, tooltipPlacement, errorMessage} = this.props
        return (
            <FormComponent
                disabled={disabled}
                label={label}
                tooltip={tooltip}
                tooltipPlacement={tooltipPlacement}
                errorMessage={errorMessage}>
                {this.renderTextArea()}
            </FormComponent>
        )
    }

    renderTextArea() {
        const {className, name, value, autoFocus, tabIndex, minRows, maxRows, onChange, onBlur} = this.props
        const {textareaFocused} = this.state
        return (
            <Keybinding keymap={{Enter: null}} disabled={!textareaFocused} priority>

                    <TextareaAutosize
                        ref={this.element}
                        className={className}
                        name={name}
                        value={value || ''}
                        tabIndex={tabIndex}
                        autoFocus={autoFocus && !isMobile()}
                        minRows={minRows}
                        maxRows={maxRows}
                        onChange={e => onChange && onChange(e)}
                        onFocus={() => this.setState({textareaFocused: true})}
                        onBlur={e => {
                            this.setState({textareaFocused: false})
                            onBlur && onBlur(e)
                        }}
                    />

            </Keybinding>
        )
    }
}

export const Textarea = compose(
    _Textarea,
    withForwardedRef()
)

Textarea.propTypes = {
    autoFocus: PropTypes.any,
    className: PropTypes.string,
    disabled: PropTypes.any,
    errorMessage: PropTypes.string,
    label: PropTypes.string,
    maxRows: PropTypes.number,
    minRows: PropTypes.number,
    name: PropTypes.string,
    placeholder: PropTypes.string,
    tabIndex: PropTypes.number,
    tooltip: PropTypes.string,
    tooltipPlacement: PropTypes.string,
    value: PropTypes.any,
    onBlur: PropTypes.func,
    onChange: PropTypes.func
}

Textarea.defaultProp = {
    tooltipPlacement: 'top'
}

export default {
    FormComponent,
    Input,
    Textarea
}
<|endoftext|>


<commit_before>function afterDraw(expect) {
  waits(32)

  runs(function() {
    expect()
  });
}

var view = {
  controller: function(p) {
    this.p = [1, 2]
    this.h2 = {
      _text: 'tester',
      _config: function(n, is, c, i) {
        c.count = c.count + 1 || 1
        c.onunload = function(context, node, cache, path) {
          expect(context.count).toEqual(1)
          expect(path).toEqual('id("test")/H2[1]')
        }
      }
    }
  },
  view: function(s, p, e) {
    s.b = {
      _onclick: function() {
        s.p = [2]
        s.h2 = null
      }
    }
  }
}

// specs code
describe("MagJS - module", function() {

  beforeEach(function() {
    affix("div#test h2+p>b")
  })

  it("is defined", function() {
    expect(mag.module).toBeDefined();
  });
  it("accepts one argument", function() {

    spyOn(mag, 'module')
    mag.module('test')
    expect(mag.module).toHaveBeenCalledWith('test')
  });

  it("props are not modifiable", function() {

    mag.module('test', {
      controller: function(p) {
        expect(p.alwaysstay).toEqual(true)
        p.alwaysstay = false
      },
      view: function(s, p) {
        expect(p.alwaysstay).toEqual(true)
      }
    }, {
      alwaysstay: true
    })
  })

  it("lists change when state changes", function() {
    spyOn(mag, 'module').andCallThrough()
    mag.module('test', view)

    expect(mag.module).toHaveBeenCalledWith('test', view)

    afterDraw(function() {
      expect($('#test h2').text()).toEqual('tester')
      expect($('#test p').length).toEqual(2)
      $('#test b').click()
      afterDraw(function() {
        expect($('#test p').length).toEqual(1)
      });
    });
  });

  it("will call onunload after node is removed", function() {
    mag.module('test', view)
    afterDraw(function() {
      $('#test b').click()
      afterDraw(function() {
        expect($('#test h2').text()).toEqual('')
      });
    })
  })

});
<commit_msg>Update module-spec.js<commit_after>function afterDraw(expect) {
  waits(32)

  runs(function() {
    expect()
  });
}

var view = {
  controller: function(p) {
    this.p = [1, 2]
    this.h2 = {
      _text: 'tester',
      _config: function(n, is, c, i) {
        c.count = c.count + 1 || 1
        c.onunload = function(context, node, path) {
          expect(context.count).toEqual(1)
          expect(path).toEqual('id("test")/H2[1]')
        }
      }
    }
  },
  view: function(s, p, e) {
    s.b = {
      _onclick: function() {
        s.p = [2]
        s.h2 = null
      }
    }
  }
}

// specs code
describe("MagJS - module", function() {

  beforeEach(function() {
    affix("div#test h2+p>b")
  })

  it("is defined", function() {
    expect(mag.module).toBeDefined();
  });
  it("accepts one argument", function() {

    spyOn(mag, 'module')
    mag.module('test')
    expect(mag.module).toHaveBeenCalledWith('test')
  });

  it("props are not modifiable", function() {

    mag.module('test', {
      controller: function(p) {
        expect(p.alwaysstay).toEqual(true)
        p.alwaysstay = false
      },
      view: function(s, p) {
        expect(p.alwaysstay).toEqual(true)
      }
    }, {
      alwaysstay: true
    })
  })

  it("lists change when state changes", function() {
    spyOn(mag, 'module').andCallThrough()
    mag.module('test', view)

    expect(mag.module).toHaveBeenCalledWith('test', view)

    afterDraw(function() {
      expect($('#test h2').text()).toEqual('tester')
      expect($('#test p').length).toEqual(2)
      $('#test b').click()
      afterDraw(function() {
        expect($('#test p').length).toEqual(1)
      });
    });
  });

  it("will call onunload after node is removed", function() {
    mag.module('test', view)
    afterDraw(function() {
      $('#test b').click()
      afterDraw(function() {
        expect($('#test h2').text()).toEqual('')
      });
    })
  })

});
<|endoftext|>


<commit_before>
/**
 * Helper functions shared across all the tasks
 */

var spawn = require('child_process').spawn,
  fs = require('fs'),
  utils = {
    /**
     * Convert an options object into a valid arguments array for the child_process.spawn method
     * from:
     *   var options = {
     *     foo: 'hello',
     *     baz: 'world'
     *   }
     * to:
     *   ['--foo=', 'hello', '--baz=','world']
     *
     * @param   { Object }  obj - object we need to convert
     * @param   { Array }   optionsPrefix - use a prefix for the new array created
     * @param   { Boolean } hasEquals - set the options commands using the equal
     * @returns { Array } - options array
     */
    optionsToArray(obj, optionsPrefix, hasEquals) {
      optionsPrefix = optionsPrefix || '--'
      var ret = []
      Object.keys(obj).forEach((key) => {
        ret.push(optionsPrefix + key + (hasEquals ? '=' : ''))
        if (obj[key]) {
          ret.push(obj[key])
        }
      })
      return ret
    },
    /**
     * Simple object extend function
     * @param   { Object } obj1 - destination
     * @param   { Object } obj2 - source
     * @returns { Object } - destination object
     */
    extend(obj1, obj2) {
      for (var i in obj2) {
        if (obj2.hasOwnProperty(i)) {
          obj1[i] = obj2[i]
        }
      }
      return obj1
    },
    /**
     * Run any system command
     * @param  { String } command - command to execute
     * @param  { Array } args - command arguments
     * @param  { Object } envVariables - command environment variables
     * @returns { Promise } chainable promise object
     */
    exec(command, args, envVariables) {

      var path = require('path')

      return new Promise(function(resolve, reject) {

        // extend the env variables with some other custom options
        utils.extend(process.env, envVariables)
        utils.print(`Executing: ${command}  ${args.join(' ')} \n`, 'confirm')

        var cmd = spawn(path.normalize(command), args, {
          stdio: 'inherit',
          cwd: process.cwd()
        })

        cmd.on('exit', function(code) {
          if (code === 1)
            reject()
          else
            resolve()

        })

      })

    },
    /**
     * Read all the files crawling starting from a certain folder path
     * @param  { String } path directory path
     * @param  { bool } mustDelete delete the files found
     * @returns { Array } files path list
     */
    listFiles(path, mustDelete) {
      utils.print(`Listing all the files in the folder: ${path}`, 'confirm')
      var files = []
      if (fs.existsSync(path)) {
        var tmpFiles = fs.readdirSync(path)
        tmpFiles.forEach((file) => {
          var curPath = path + '/' + file
          files.push(curPath)
          if (fs.lstatSync(curPath).isDirectory()) { // recurse
            utils.listFiles(curPath, mustDelete)
          } else if (mustDelete) { // delete file
            fs.unlinkSync(curPath)
          }
        })
        if (mustDelete) {
          fs.rmdirSync(path)
        }
      }

      return files
    },
    /**
     * Delete synchronously any folder or file
     * @param  { String } path - path to clean
     */
    clean(path) {
      var files = utils.listFiles(path, true)
      utils.print(`Deleting the following files: \n ${files.join('\n')}`, 'cool')
    },
    /**
     * Log messages in the terminal using custom colors
     * @param  { String } msg - message to output
     * @param  { String } type - message type to handle the right color
     */
    print(msg, type) {
      var color
      switch (type) {
      case 'error':
        color = '\x1B[31m'
        break
      case 'warning':
        color = '\x1B[33m'
        break
      case 'confirm':
        color = '\x1B[32m'
        break
      case 'cool':
        color = '\x1B[36m'
        break
      default:
        color = ''
      }
      console.log(`${color} ${msg} \x1B[39m`)
    }
  }

module.exports = utils
<commit_msg>extended exec to support windows platform<commit_after>
/**
 * Helper functions shared across all the tasks
 */

var spawn = require('child_process').spawn,
  fs = require('fs'),
  utils = {
    /**
     * Convert an options object into a valid arguments array for the child_process.spawn method
     * from:
     *   var options = {
     *     foo: 'hello',
     *     baz: 'world'
     *   }
     * to:
     *   ['--foo=', 'hello', '--baz=','world']
     *
     * @param   { Object }  obj - object we need to convert
     * @param   { Array }   optionsPrefix - use a prefix for the new array created
     * @param   { Boolean } hasEquals - set the options commands using the equal
     * @returns { Array } - options array
     */
    optionsToArray(obj, optionsPrefix, hasEquals) {
      optionsPrefix = optionsPrefix || '--'
      var ret = []
      Object.keys(obj).forEach((key) => {
        ret.push(optionsPrefix + key + (hasEquals ? '=' : ''))
        if (obj[key]) {
          ret.push(obj[key])
        }
      })
      return ret
    },
    /**
     * Simple object extend function
     * @param   { Object } obj1 - destination
     * @param   { Object } obj2 - source
     * @returns { Object } - destination object
     */
    extend(obj1, obj2) {
      for (var i in obj2) {
        if (obj2.hasOwnProperty(i)) {
          obj1[i] = obj2[i]
        }
      }
      return obj1
    },
    /**
     * Run any system command
     * @param  { String } command - command to execute
     * @param  { Array } args - command arguments
     * @param  { Object } envVariables - command environment variables
     * @returns { Promise } chainable promise object
     */
    exec(command, args, envVariables) {

      var path = require('path')
      var os = require('os')

      return new Promise(function(resolve, reject) {

        if (os.platform() == 'win32' || os.platform() == 'win64') {
          command = command + '.cmd'
        }

        // extend the env variables with some other custom options
        utils.extend(process.env, envVariables)
        utils.print(`Executing: ${command}  ${args.join(' ')} \n`, 'confirm')

        var cmd = spawn(path.normalize(command), args, {
          stdio: 'inherit',
          cwd: process.cwd()
        })

        cmd.on('exit', function(code) {
          if (code === 1)
            reject()
          else
            resolve()

        })

      })

    },
    /**
     * Read all the files crawling starting from a certain folder path
     * @param  { String } path directory path
     * @param  { bool } mustDelete delete the files found
     * @returns { Array } files path list
     */
    listFiles(path, mustDelete) {
      utils.print(`Listing all the files in the folder: ${path}`, 'confirm')
      var files = []
      if (fs.existsSync(path)) {
        var tmpFiles = fs.readdirSync(path)
        tmpFiles.forEach((file) => {
          var curPath = path + '/' + file
          files.push(curPath)
          if (fs.lstatSync(curPath).isDirectory()) { // recurse
            utils.listFiles(curPath, mustDelete)
          } else if (mustDelete) { // delete file
            fs.unlinkSync(curPath)
          }
        })
        if (mustDelete) {
          fs.rmdirSync(path)
        }
      }

      return files
    },
    /**
     * Delete synchronously any folder or file
     * @param  { String } path - path to clean
     */
    clean(path) {
      var files = utils.listFiles(path, true)
      utils.print(`Deleting the following files: \n ${files.join('\n')}`, 'cool')
    },
    /**
     * Log messages in the terminal using custom colors
     * @param  { String } msg - message to output
     * @param  { String } type - message type to handle the right color
     */
    print(msg, type) {
      var color
      switch (type) {
      case 'error':
        color = '\x1B[31m'
        break
      case 'warning':
        color = '\x1B[33m'
        break
      case 'confirm':
        color = '\x1B[32m'
        break
      case 'cool':
        color = '\x1B[36m'
        break
      default:
        color = ''
      }
      console.log(`${color} ${msg} \x1B[39m`)
    }
  }

module.exports = utils
<|endoftext|>


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

var fs = require('fs');
var util = require('util');
var http = require('http');
var url = require('url');
var path = require('path');
var zlib = require('zlib');
var tar = require('tar');

var OS = process.platform; // e.g. linux
var ARCH = process.arch; // e.g. ia32
var ENDIANNESS = process.config.variables.node_byteorder; // e.g. 'little'
var INSTALL_DIR = process.cwd();
var BASE_DOWNLOAD_URL = 'http://public.dhe.ibm.com/ibmdl/export/pub/software/websphere/runtimes/tools/healthcenter/agents';
var AGENTCORE_PLATFORMS = ['aix-ppc',
                           'aix-ppc64',
                           'darwin-ia32',
                           'darwin-x64',
                           'linux-ia32',
                           'linux-ppc',
                           'linux-ppc64',
                           'linux-ppc64le',
                           'linux-s390',
                           'linux-s390x',
                           'linux-x64',
                           'win32-ia32',
                           'win32-x64'];
var AGENTCORE_VERSION = '3.0.5';

var LOG_FILE = path.join(INSTALL_DIR, 'install.log');
var logFileStream = fs.createWriteStream(LOG_FILE, {flags : 'a'});

console.log = function(info) { //
	logFileStream.write(util.format(info) + '\n');
	process.stdout.write(util.format(info) + '\n');
};

var showLegalWarning = function() {
	/* Legal warning */
	console.log(new Date().toUTCString());
	console.log('********************************************************************************');
	console.log('You are installing the Node Application Metrics monitoring and profiling module.');
	console.log('This package includes the IBM Monitoring and Diagnostic Tools - Health Center ');
	console.log('monitoring agent for Node.js, which is automatically downloaded as the module is');
	console.log('installed on your system/device. This is released under a proprietary IBM');
	console.log('licence. The license agreement for IBM Monitoring and Diagnostic Tools - Health');
	console.log('Center is available in the following location:');
	console.log('node_modules/appmetrics/licenses');
	console.log('Your use of the components of the package and dependencies constitutes your ');
	console.log('acceptance of this license agreement. If you do not accept the terms of the ');
	console.log('license agreement(s), delete the relevant component(s) immediately from your ');
	console.log('device.');
	console.log('********************************************************************************');
};

var getPlatform = function() {
	var platform;
	if (ARCH === 'ppc64' && ENDIANNESS === 'little') {
		platform = 'linux-ppc64le';
	} else {
		platform = OS + '-' + ARCH;
	}
	return platform;
};

var ensureSupportedPlatformOrExit = function() {
	/*
	 * Check up front for the platform-architectures for which there are
	 * available Health Center core agent downloads.
	 */
	var platform = getPlatform();
	if (AGENTCORE_PLATFORMS.indexOf(platform) === -1) {
		console.log(platform + ' is not a currently supported platform. Exiting');
		process.exit(1);
	}
};

var getAgentCorePlatformVersionDownloadURL = function() {
	return [BASE_DOWNLOAD_URL, 'core/tgz'].join('/') +
	       ['/agentcore', AGENTCORE_VERSION, getPlatform()].join('-') + '.tgz';
};

var downloadAndExtractTGZ = function(downloadURL, destDir) {
	/* Downloading the binaries */
	var req = http.get(downloadURL, function(response) {
		console.log('Downloading and extracting tgz from ' + downloadURL + ' to ' + destDir);

		if (response.statusCode != 200) {
			console.log('ERROR: Unable to download ' + downloadURL);
			process.exit(1);
		}

		response.pipe(zlib.createGunzip())         .on('error', function(e) { console.log("Failed to gunzip: " + e.message); })
		        .pipe(tar.Extract({path: destDir})).on('error', function(e) { console.log("Failed to untar: " + e.message); })
		        .on('close', function() {
		        	console.log('Download and extract of ' + downloadURL + ' finished.');
		        });
	}).on('error', function(e) {
		console.log('Got an error: ' + e.message);
		process.exit(1);
	});
};

/*
 * Start the download
 */
showLegalWarning();
ensureSupportedPlatformOrExit();
downloadAndExtractTGZ(getAgentCorePlatformVersionDownloadURL(), '.');
<commit_msg>Bump appmetrics/agentcore versions in download scripts<commit_after>/*******************************************************************************
 * Copyright 2015 IBM Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/

var fs = require('fs');
var util = require('util');
var http = require('http');
var url = require('url');
var path = require('path');
var zlib = require('zlib');
var tar = require('tar');

var OS = process.platform; // e.g. linux
var ARCH = process.arch; // e.g. ia32
var ENDIANNESS = process.config.variables.node_byteorder; // e.g. 'little'
var INSTALL_DIR = process.cwd();
var BASE_DOWNLOAD_URL = 'http://public.dhe.ibm.com/ibmdl/export/pub/software/websphere/runtimes/tools/healthcenter/agents';
var AGENTCORE_PLATFORMS = ['aix-ppc',
                           'aix-ppc64',
                           'darwin-ia32',
                           'darwin-x64',
                           'linux-ia32',
                           'linux-ppc',
                           'linux-ppc64',
                           'linux-ppc64le',
                           'linux-s390',
                           'linux-s390x',
                           'linux-x64',
                           'win32-ia32',
                           'win32-x64'];
var AGENTCORE_VERSION = '3.0.6';

var LOG_FILE = path.join(INSTALL_DIR, 'install.log');
var logFileStream = fs.createWriteStream(LOG_FILE, {flags : 'a'});

console.log = function(info) { //
	logFileStream.write(util.format(info) + '\n');
	process.stdout.write(util.format(info) + '\n');
};

var showLegalWarning = function() {
	/* Legal warning */
	console.log(new Date().toUTCString());
	console.log('********************************************************************************');
	console.log('You are installing the Node Application Metrics monitoring and profiling module.');
	console.log('This package includes the IBM Monitoring and Diagnostic Tools - Health Center ');
	console.log('monitoring agent for Node.js, which is automatically downloaded as the module is');
	console.log('installed on your system/device. This is released under a proprietary IBM');
	console.log('licence. The license agreement for IBM Monitoring and Diagnostic Tools - Health');
	console.log('Center is available in the following location:');
	console.log('node_modules/appmetrics/licenses');
	console.log('Your use of the components of the package and dependencies constitutes your ');
	console.log('acceptance of this license agreement. If you do not accept the terms of the ');
	console.log('license agreement(s), delete the relevant component(s) immediately from your ');
	console.log('device.');
	console.log('********************************************************************************');
};

var getPlatform = function() {
	var platform;
	if (ARCH === 'ppc64' && ENDIANNESS === 'little') {
		platform = 'linux-ppc64le';
	} else {
		platform = OS + '-' + ARCH;
	}
	return platform;
};

var ensureSupportedPlatformOrExit = function() {
	/*
	 * Check up front for the platform-architectures for which there are
	 * available Health Center core agent downloads.
	 */
	var platform = getPlatform();
	if (AGENTCORE_PLATFORMS.indexOf(platform) === -1) {
		console.log(platform + ' is not a currently supported platform. Exiting');
		process.exit(1);
	}
};

var getAgentCorePlatformVersionDownloadURL = function() {
	return [BASE_DOWNLOAD_URL, 'core/tgz'].join('/') +
	       ['/agentcore', AGENTCORE_VERSION, getPlatform()].join('-') + '.tgz';
};

var downloadAndExtractTGZ = function(downloadURL, destDir) {
	/* Downloading the binaries */
	var req = http.get(downloadURL, function(response) {
		console.log('Downloading and extracting tgz from ' + downloadURL + ' to ' + destDir);

		if (response.statusCode != 200) {
			console.log('ERROR: Unable to download ' + downloadURL);
			process.exit(1);
		}

		response.pipe(zlib.createGunzip())         .on('error', function(e) { console.log("Failed to gunzip: " + e.message); })
		        .pipe(tar.Extract({path: destDir})).on('error', function(e) { console.log("Failed to untar: " + e.message); })
		        .on('close', function() {
		        	console.log('Download and extract of ' + downloadURL + ' finished.');
		        });
	}).on('error', function(e) {
		console.log('Got an error: ' + e.message);
		process.exit(1);
	});
};

/*
 * Start the download
 */
showLegalWarning();
ensureSupportedPlatformOrExit();
downloadAndExtractTGZ(getAgentCorePlatformVersionDownloadURL(), '.');
<|endoftext|>


<commit_before>CKEDITOR.editorConfig = function( config ) {
    var fixThings = false;
    // https://dev.ckeditor.com/ticket/10907
    needsBrFiller= fixThings;
    needsNbspFiller= fixThings;

    removeButtons= 'Source,Maximize';
    // magicline plugin inserts html crap into the document which is not part of the
    // document itself and causes problems when it's sent across the wire and reflected back
    removePlugins= 'resize';
    extraPlugins= 'autolink,colorbutton,colordialog,font';
    toolbarGroups= [{"name":"clipboard","groups":["clipboard","undo"]},{"name":"editing","groups":["find","selection"]},{"name":"links"},{"name":"insert"},{"name":"forms"},{"name":"tools"},{"name":"document","groups":["mode","document","doctools"]},{"name":"others"},{"name":"basicstyles","groups":["basicstyles","cleanup"]},{"name":"paragraph","groups":["list","indent","blocks","align","bidi"]},{"name":"styles"},{"name":"colors"}];

    //skin: 'moono-cryptpad,/pad/themes/moono-cryptpad/'
    //skin: 'flat,/pad/themes/flat/'
    //skin: 'moono-lisa,/pad/themes/moono-lisa/'
    //skin: 'moono-dark,/pad/themes/moono-dark/'
    //skin: 'office2013,/pad/themes/office2013/'
;
<commit_msg>unbreak ckeditor<commit_after>CKEDITOR.editorConfig = function( config ) {
    var fixThings = false;
    // https://dev.ckeditor.com/ticket/10907
    config.needsBrFiller= fixThings;
    config.needsNbspFiller= fixThings;

    config.removeButtons= 'Source,Maximize';
    // magicline plugin inserts html crap into the document which is not part of the
    // document itself and causes problems when it's sent across the wire and reflected back
    config.removePlugins= 'resize';
    config.extraPlugins= 'autolink,colorbutton,colordialog,font';
    config.toolbarGroups= [{"name":"clipboard","groups":["clipboard","undo"]},{"name":"editing","groups":["find","selection"]},{"name":"links"},{"name":"insert"},{"name":"forms"},{"name":"tools"},{"name":"document","groups":["mode","document","doctools"]},{"name":"others"},{"name":"basicstyles","groups":["basicstyles","cleanup"]},{"name":"paragraph","groups":["list","indent","blocks","align","bidi"]},{"name":"styles"},{"name":"colors"}];

    //skin: 'moono-cryptpad,/pad/themes/moono-cryptpad/'
    //skin: 'flat,/pad/themes/flat/'
    //skin: 'moono-lisa,/pad/themes/moono-lisa/'
    //skin: 'moono-dark,/pad/themes/moono-dark/'
    //skin: 'office2013,/pad/themes/office2013/'
};
<|endoftext|>


<commit_before>/*
* ProtectedInfowindow
* v0.21
*/

function ProtectedInfowindow(map, opts) {

  this.latlng_ = null;
  this.offsetHorizontal_ = 0;
  this.offsetVertical_   = -10;
  this.width_ = 295;
  this.div_ = null;
  this.map_ = map;
  this.setMap(map);

  if (opts) {
    this.className         = opts.className;
    this.offsetHorizontal_ = ("offsetHorizontal" in opts) ? opts.offsetHorizontal : 0;
    this.offsetVertical_   = ("offsetVertical" in opts) ? opts.offsetVertical : 0;
    this.width_            = opts.width;
    this.template          = opts.template;
  }
}

ProtectedInfowindow.prototype = new google.maps.OverlayView();

ProtectedInfowindow.prototype.draw = function() {
  var me = this;

  var div = this.div_;
  if (!div) {
    div = this.div_ = document.createElement('DIV');

    div.className = this.className || "cartodb_infowindow with_image";

    div.innerHTML = ''+
      '
'+
      '
' +
      '

'+
      '
' +
      '
'+
      '

' +
      '
'+
      '
'+
      '

'+
      '

';

    var a = this.getElementsByClassName("close", div)[0];

    google.maps.event.addDomListener(a, 'click', function (ev) {
      //ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
      //me._hide();
    });

    google.maps.event.addDomListener(div, 'click', function (ev) {
      //ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
      //ev.stopPropagation ? ev.stopPropagation() : window.event.cancelBubble = true;
    });

    google.maps.event.addDomListener(a, 'touchend', function (ev) {
      ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
      //me._hide();
    });

    google.maps.event.addDomListener(div, 'touchstart', function (ev) {
      ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
    });

    google.maps.event.addDomListener(div, 'touchend', function (ev) {
      ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
    });

    google.maps.event.addDomListener(div, 'dblclick', function (ev) {
      ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
    });
    google.maps.event.addDomListener(div, 'mousedown', function (ev) {
      ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
      ev.stopPropagation ? ev.stopPropagation() : window.event.cancelBubble = true;
    });
    google.maps.event.addDomListener(div, 'mouseup', function (ev) {
      ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
    });
    google.maps.event.addDomListener(div, 'mousewheel', function (ev) {
      ev.stopPropagation ? ev.stopPropagation() : window.event.cancelBubble = true;
    });
    google.maps.event.addDomListener(div, 'DOMMouseScroll', function (ev) {
      ev.stopPropagation ? ev.stopPropagation() : window.event.cancelBubble = true;
    });

    var panes = this.getPanes();
    panes.floatPane.appendChild(div);

    div.style.opacity = 0;
  }

  this.setPosition();

};

ProtectedInfowindow.prototype.setTemplate = function(template){
  this.template_ = template;
};

ProtectedInfowindow.prototype.setOffset = function(offsetVertical, offsetHorizontal){
  this.offsetHorizontal_ = offsetHorizontal;
  this.offsetVertical_   = offsetVertical;
};

ProtectedInfowindow.prototype.setContent = function(content){

  if (this.div_) {

    var div = this.div_
    , top = this.getElementsByClassName("infowindow_content", div)[0];

    if (!content) { return; }

      top.innerHTML = '';
      var html = '';

      for(var column in content) {

        if (column != "title" && column != "image" && column != "image" && column != "slug" && content[column] != null && content[column] != ''){
          html += '' + column + '';
          html += '
'+(content[column] || 'empty')+'
';
        }

      }

      top.innerHTML = html;
      $(div).find("h1").html(content.name);
      $(div).find("img").attr("src", content.image.replace("square", "medium"));
      $(div).find("img").css("width", "295px");

      var pane = $(".cartodb_infowindow.with_image .infowindow_content").jScrollPane( { showArrows: true });
      var api = pane.data('jsp');
      api.scrollToY(0); // scroll to top

  }

};

ProtectedInfowindow.prototype.setPosition = function(latlng) {
  if (latlng) {
    this.latlng_ = latlng;
    // Adjust pan
    //this._adjustPan();
  }

  if (this.div_) {
    var div = this.div_
    , pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
    if (pixPosition) {
      div.style.width = this.width_ + 'px';
      div.style.left = (pixPosition.x - this.width_ / 2 + this.offsetHorizontal_) + 'px';
      var actual_height = - div.clientHeight;
      div.style.top = (pixPosition.y + actual_height + this.offsetVertical_) + 'px';
    }
  }
};

ProtectedInfowindow.prototype.open = function(){
  this._show();
};

ProtectedInfowindow.prototype.close2 = function(){
  this._hide();
};
ProtectedInfowindow.prototype.close = function(){
  this._hide();
};

ProtectedInfowindow.prototype.destroy = function() {
  // Check if the overlay was on the map and needs to be removed.
  if (this.div_) {
    this.div_.parentNode.removeChild(this.div_);
    this.div_ = null;
  }
  this.setMap(null);
};

ProtectedInfowindow.prototype._hide = function() {

  if (this.div_) {

    var div = this.div_;

    $(div).find(".header img").attr("src", "/assets/backgrounds/cover.png");

    emile(div,{
      opacity: 0,
      duration: 1,
      after: function(){
        div.style.visibility = "hidden";
      }
    });
  }
};

ProtectedInfowindow.prototype._show = function() {
  if (this.div_) {

    var div = this.div_;
    div.style.opacity = 0;
    div.style.top = (parseInt(div.style.top, 10) - 10) + 'px';

    div.style.visibility = "visible";
     $(".imgLiquidFill").imgLiquid();

    emile(div,{
      opacity: 1,
      duration: 250
    });
  }
};

ProtectedInfowindow.prototype._adjustPan = function() {
  var left = 0
  , top = 0
  , pixPosition = this.getProjection().fromLatLngToContainerPixel(this.latlng_)
  , container = this.map_.getDiv()
  , div_height = this.div_.clientHeight;

  if ((pixPosition.x - 65) < 0) {
    left = (pixPosition.x - 65);
  }

  if ((pixPosition.x + 180) >= container.clientWidth) {
    left = (pixPosition.x + 180 - container.clientWidth);
  }

  if ((pixPosition.y - div_height) < 0) {
    top = (pixPosition.y - div_height - 20);
  }

  this.map_.panBy(left,top);
};

ProtectedInfowindow.prototype.getElementsByClassName = function(classname, node)  {
  if(!node) node = document.getElementsByTagName("body")[0];
  var a = [];
  var re = new RegExp('\\b' + classname + '\\b');
  var els = node.getElementsByTagName("*");
  for(var i=0,j=els.length; i<j; i++)
    if(re.test(els[i].className))a.push(els[i]);
  return a;
}

/*!
* emile.js (c) 2009 - 2011 Thomas Fuchs
* Licensed under the terms of the MIT license.
*/
!function(a){function A(a,b){a=typeof a=="string"?document.getElementById(a):a,b=z(b);var c={duration:b.duration,easing:b.easing,after:b.after};delete b.duration,delete b.easing,delete b.after;if(e&&typeof c.easing!="function")return y(a,b,c);var d=q(b,function(a,b){a=r(a);return p(a)in h&&g.test(b)?[a,b+"px"]:[a,b]});x(a,d,c)}function z(a){var b={};for(var c in a)b[c]=a[c],c=="after"&&delete a[c];return b}function y(a,b,c){var d=[],f=[],i=c.duration||1e3,j=c.easing||"ease-out",k="";i=i+"ms",a.addEventListener(l,function m(){a.setAttribute("style",k),c.after&&c.after(),a.removeEventListener(l,m,!0)},!0),setTimeout(function(){var c;for(c in b)b.hasOwnProperty(c)&&d.push(r(c)+" "+i+" "+j);for(c in b){var f=p(c)in h&&g.test(b[c])?b[c]+"px":b[c];b.hasOwnProperty(c)&&(a.style[p(c)]=f)}k=a.getAttribute("style"),d=d.join(","),a.style[e+"Transition"]=d},10)}function x(a,b,c,d){c=c||{};var e=w(b),f=a.currentStyle?a.currentStyle:getComputedStyle(a,null),g={},h=+(new Date),i,j=c.duration||200,k=h+j,l,m=c.easing||function(a){return-Math.cos(a*Math.PI)/2+.5};for(i in e)g[i]=v(f[i]);l=setInterval(function(){var b=+(new Date),f,i=b>k?1:(b-h)/j;for(f in e)a.style[f]=e[f].f(g[f].v,e[f].v,m(i))+e[f].u;b>k&&(clearInterval(l),c.after&&c.after(),d&&setTimeout(d,1))},10)}function w(a){var c,d={},e=k.length,f;b.innerHTML='

',c=b.childNodes[0].style;while(e--)(f=c[k[e]])&&(d[k[e]]=v(f));return d}function v(a){var b=parseFloat(a),c=a?a.replace(/^[\-\d\.]+/,""):a;return isNaN(b)?{v:c,f:u,u:""}:{v:b,f:s,u:c}}function u(a,b,c){var d=2,e,f,g,h=[],i=[];while((e=3)&&(f=arguments[d-1])&&d--)if(t(f,0)=="r"){f=f.match(/\d+/g);while(e--)h.push(~~f[e])}else{f.length==4&&(f="#"+t(f,1)+t(f,1)+t(f,2)+t(f,2)+t(f,3)+t(f,3));while(e--)h.push(parseInt(t(f,1+e*2,2),16))}while(e--)g=~~(h[e+3]+(h[e]-h[e+3])*c),i.push(g<0?0:g>255?255:g);return"rgb("+i.join(",")+")"}function t(a,b,c){return a.substr(b,c||1)}function s(a,b,c){return(a+(b-a)*c).toFixed(3)}function r(a){if(a.toUpperCase()===a)return a;return a.replace(/([a-zA-Z0-9])([A-Z])/g,function(a,b,c){return b+"-"+c}).toLowerCase()}function q(a,b){return o(a,function(a,c){var d=b?b(c,a):[c,a];return d[0]+":"+d[1]+";"}).join("")}function p(a){return a.replace(/-(.)/g,function(a,b){return b.toUpperCase()})}function o(a,b,c){var d=[],e;for(e in a)d.push(b.call(c,a[e],e,a));return d}var b=document.createElement("div"),c=["webkit","Moz","O"],d=3,e,f,g=/\d+$/,h={},i="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color fontWeight lineHeight opacity outlineColor zIndex",j="top bottom left right borderWidth borderBottomWidth borderLeftWidth borderRightWidth borderTopWidth borderSpacing borderRadius marginBottom marginLeft marginRight marginTop width height maxHeight maxWidth minHeight minWidth paddingBottom paddingLeft paddingRight paddingTop fontSize wordSpacing textIndent letterSpacing outlineWidth outlineOffset",k=(i+" "+j).split(" ");while(d--)f=c[d],b.style.cssText="-"+f.toLowerCase()+"-transition-property:opacity;",typeof b.style[f+"TransitionProperty"]!="undefined"&&(e=f);var l=/^w/.test(e)?"webkitTransitionEnd":"transitionend";for(var m=j.split(" "),n=m.length;n--;)h[m[n]]=1;var B=a.emile;A.noConflict=function(){a.emile=B;return this},a.emile=A}(this)
<commit_msg>Adds infowindow panning<commit_after>/*
* ProtectedInfowindow
* v0.21
*/

function ProtectedInfowindow(map, opts) {

  this.latlng_ = null;
  this.offsetHorizontal_ = 0;
  this.offsetVertical_   = -10;
  this.width_ = 295;
  this.div_ = null;
  this.map_ = map;
  this.setMap(map);

  if (opts) {
    this.className         = opts.className;
    this.offsetHorizontal_ = ("offsetHorizontal" in opts) ? opts.offsetHorizontal : 0;
    this.offsetVertical_   = ("offsetVertical" in opts) ? opts.offsetVertical : 0;
    this.width_            = opts.width;
    this.template          = opts.template;
  }
}

ProtectedInfowindow.prototype = new google.maps.OverlayView();

ProtectedInfowindow.prototype.draw = function() {
  var me = this;

  var div = this.div_;
  if (!div) {
    div = this.div_ = document.createElement('DIV');

    div.className = this.className || "cartodb_infowindow with_image";

    div.innerHTML = ''+
      '
'+
      '
' +
      '

'+
      '
' +
      '
'+
      '

' +
      '
'+
      '
'+
      '

'+
      '

';

    var a = this.getElementsByClassName("close", div)[0];

    google.maps.event.addDomListener(a, 'click', function (ev) {
      //ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
      //me._hide();
    });

    google.maps.event.addDomListener(div, 'click', function (ev) {
      //ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
      //ev.stopPropagation ? ev.stopPropagation() : window.event.cancelBubble = true;
    });

    google.maps.event.addDomListener(a, 'touchend', function (ev) {
      ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
      //me._hide();
    });

    google.maps.event.addDomListener(div, 'touchstart', function (ev) {
      ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
    });

    google.maps.event.addDomListener(div, 'touchend', function (ev) {
      ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
    });

    google.maps.event.addDomListener(div, 'dblclick', function (ev) {
      ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
    });
    google.maps.event.addDomListener(div, 'mousedown', function (ev) {
      ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
      ev.stopPropagation ? ev.stopPropagation() : window.event.cancelBubble = true;
    });
    google.maps.event.addDomListener(div, 'mouseup', function (ev) {
      ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
    });
    google.maps.event.addDomListener(div, 'mousewheel', function (ev) {
      ev.stopPropagation ? ev.stopPropagation() : window.event.cancelBubble = true;
    });
    google.maps.event.addDomListener(div, 'DOMMouseScroll', function (ev) {
      ev.stopPropagation ? ev.stopPropagation() : window.event.cancelBubble = true;
    });

    var panes = this.getPanes();
    panes.floatPane.appendChild(div);

    div.style.opacity = 0;
  }

  this.setPosition();

};

ProtectedInfowindow.prototype.setTemplate = function(template){
  this.template_ = template;
};

ProtectedInfowindow.prototype.setOffset = function(offsetVertical, offsetHorizontal){
  this.offsetHorizontal_ = offsetHorizontal;
  this.offsetVertical_   = offsetVertical;
};

ProtectedInfowindow.prototype.setContent = function(content){

  if (this.div_) {

    var div = this.div_
    , top = this.getElementsByClassName("infowindow_content", div)[0];

    if (!content) { return; }

      top.innerHTML = '';
      var html = '';

      for(var column in content) {

        if (column != "title" && column != "image" && column != "image" && column != "slug" && content[column] != null && content[column] != ''){
          html += '' + column + '';
          html += '
'+(content[column] || 'empty')+'
';
        }

      }

      top.innerHTML = html;
      $(div).find("h1").html(content.name);
      $(div).find("img").attr("src", content.image.replace("square", "medium"));
      $(div).find("img").css("width", "295px");

      var pane = $(".cartodb_infowindow.with_image .infowindow_content").jScrollPane( { showArrows: true });
      var api = pane.data('jsp');
      api.scrollToY(0); // scroll to top

  }

};

ProtectedInfowindow.prototype.setPosition = function(latlng) {
  if (latlng) {
    this.latlng_ = latlng;
    // Adjust pan
    this._adjustPan();
  }

  if (this.div_) {
    var div = this.div_
    , pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
    if (pixPosition) {
      div.style.width = this.width_ + 'px';
      div.style.left = (pixPosition.x - this.width_ / 2 + this.offsetHorizontal_) + 'px';
      var actual_height = - div.clientHeight;
      div.style.top = (pixPosition.y + actual_height + this.offsetVertical_) + 'px';
    }
  }
};

ProtectedInfowindow.prototype.open = function(){
  this._show();
};

ProtectedInfowindow.prototype.close2 = function(){
  this._hide();
};
ProtectedInfowindow.prototype.close = function(){
  this._hide();
};

ProtectedInfowindow.prototype.destroy = function() {
  // Check if the overlay was on the map and needs to be removed.
  if (this.div_) {
    this.div_.parentNode.removeChild(this.div_);
    this.div_ = null;
  }
  this.setMap(null);
};

ProtectedInfowindow.prototype._hide = function() {

  if (this.div_) {

    var div = this.div_;

    $(div).find(".header img").attr("src", "/assets/backgrounds/cover.png");

    emile(div,{
      opacity: 0,
      duration: 1,
      after: function(){
        div.style.visibility = "hidden";
      }
    });
  }
};

ProtectedInfowindow.prototype._show = function() {
  if (this.div_) {

    var div = this.div_;
    div.style.opacity = 0;
    div.style.top = (parseInt(div.style.top, 10) - 10) + 'px';

    div.style.visibility = "visible";
     $(".imgLiquidFill").imgLiquid();

    emile(div,{
      opacity: 1,
      duration: 250
    });
  }
};

ProtectedInfowindow.prototype._adjustPan = function() {
  var left = 0
  , top = 0
  , pixPosition = this.getProjection().fromLatLngToContainerPixel(this.latlng_)
  , container = this.map_.getDiv()
  , div_height = this.div_.clientHeight;

  if ((pixPosition.x - 165) < 0) {
    left = (pixPosition.x - 165);
  }

  if ((pixPosition.x + 180) >= container.clientWidth) {
    left = (pixPosition.x + 180 - container.clientWidth);
  }

  if ((pixPosition.y - div_height) < 0) {
    top = (pixPosition.y - div_height - 20);
  }

  this.map_.panBy(left,top);
};

ProtectedInfowindow.prototype.getElementsByClassName = function(classname, node)  {
  if(!node) node = document.getElementsByTagName("body")[0];
  var a = [];
  var re = new RegExp('\\b' + classname + '\\b');
  var els = node.getElementsByTagName("*");
  for(var i=0,j=els.length; i<j; i++)
    if(re.test(els[i].className))a.push(els[i]);
  return a;
}

/*!
* emile.js (c) 2009 - 2011 Thomas Fuchs
* Licensed under the terms of the MIT license.
*/
!function(a){function A(a,b){a=typeof a=="string"?document.getElementById(a):a,b=z(b);var c={duration:b.duration,easing:b.easing,after:b.after};delete b.duration,delete b.easing,delete b.after;if(e&&typeof c.easing!="function")return y(a,b,c);var d=q(b,function(a,b){a=r(a);return p(a)in h&&g.test(b)?[a,b+"px"]:[a,b]});x(a,d,c)}function z(a){var b={};for(var c in a)b[c]=a[c],c=="after"&&delete a[c];return b}function y(a,b,c){var d=[],f=[],i=c.duration||1e3,j=c.easing||"ease-out",k="";i=i+"ms",a.addEventListener(l,function m(){a.setAttribute("style",k),c.after&&c.after(),a.removeEventListener(l,m,!0)},!0),setTimeout(function(){var c;for(c in b)b.hasOwnProperty(c)&&d.push(r(c)+" "+i+" "+j);for(c in b){var f=p(c)in h&&g.test(b[c])?b[c]+"px":b[c];b.hasOwnProperty(c)&&(a.style[p(c)]=f)}k=a.getAttribute("style"),d=d.join(","),a.style[e+"Transition"]=d},10)}function x(a,b,c,d){c=c||{};var e=w(b),f=a.currentStyle?a.currentStyle:getComputedStyle(a,null),g={},h=+(new Date),i,j=c.duration||200,k=h+j,l,m=c.easing||function(a){return-Math.cos(a*Math.PI)/2+.5};for(i in e)g[i]=v(f[i]);l=setInterval(function(){var b=+(new Date),f,i=b>k?1:(b-h)/j;for(f in e)a.style[f]=e[f].f(g[f].v,e[f].v,m(i))+e[f].u;b>k&&(clearInterval(l),c.after&&c.after(),d&&setTimeout(d,1))},10)}function w(a){var c,d={},e=k.length,f;b.innerHTML='

',c=b.childNodes[0].style;while(e--)(f=c[k[e]])&&(d[k[e]]=v(f));return d}function v(a){var b=parseFloat(a),c=a?a.replace(/^[\-\d\.]+/,""):a;return isNaN(b)?{v:c,f:u,u:""}:{v:b,f:s,u:c}}function u(a,b,c){var d=2,e,f,g,h=[],i=[];while((e=3)&&(f=arguments[d-1])&&d--)if(t(f,0)=="r"){f=f.match(/\d+/g);while(e--)h.push(~~f[e])}else{f.length==4&&(f="#"+t(f,1)+t(f,1)+t(f,2)+t(f,2)+t(f,3)+t(f,3));while(e--)h.push(parseInt(t(f,1+e*2,2),16))}while(e--)g=~~(h[e+3]+(h[e]-h[e+3])*c),i.push(g<0?0:g>255?255:g);return"rgb("+i.join(",")+")"}function t(a,b,c){return a.substr(b,c||1)}function s(a,b,c){return(a+(b-a)*c).toFixed(3)}function r(a){if(a.toUpperCase()===a)return a;return a.replace(/([a-zA-Z0-9])([A-Z])/g,function(a,b,c){return b+"-"+c}).toLowerCase()}function q(a,b){return o(a,function(a,c){var d=b?b(c,a):[c,a];return d[0]+":"+d[1]+";"}).join("")}function p(a){return a.replace(/-(.)/g,function(a,b){return b.toUpperCase()})}function o(a,b,c){var d=[],e;for(e in a)d.push(b.call(c,a[e],e,a));return d}var b=document.createElement("div"),c=["webkit","Moz","O"],d=3,e,f,g=/\d+$/,h={},i="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color fontWeight lineHeight opacity outlineColor zIndex",j="top bottom left right borderWidth borderBottomWidth borderLeftWidth borderRightWidth borderTopWidth borderSpacing borderRadius marginBottom marginLeft marginRight marginTop width height maxHeight maxWidth minHeight minWidth paddingBottom paddingLeft paddingRight paddingTop fontSize wordSpacing textIndent letterSpacing outlineWidth outlineOffset",k=(i+" "+j).split(" ");while(d--)f=c[d],b.style.cssText="-"+f.toLowerCase()+"-transition-property:opacity;",typeof b.style[f+"TransitionProperty"]!="undefined"&&(e=f);var l=/^w/.test(e)?"webkitTransitionEnd":"transitionend";for(var m=j.split(" "),n=m.length;n--;)h[m[n]]=1;var B=a.emile;A.noConflict=function(){a.emile=B;return this},a.emile=A}(this)
<|endoftext|>


<commit_before>var ws = require('websocket.io')
  , server = ws.listen(3381)
var net = require('net');
var sock;
var tcpcon;
var client;
var connected = false;
var buffer;
server.on('connection', function (socket) {
	sock = socket;
	console.log('connections');
	client = 	net.createConnection('3381','ec2-46-137-225-15.ap-southeast-1.compute.amazonaws.com',
	function() { //'connect' listener
		console.log('client connected');
		connected = true;
		client.on('data', function(data) {
	//		console.log('data received:'+data);
		//	sock.send(new Buffer(data,'binary').toString('base64'));
			sock.send(data);
		});
		client.on('end', function() {
		sock.close();
		console.log('client disconnected');
		});

	});

	socket.on('message', function (message) {
//	console.log(message);
//	buffer= new Buffer(message,'base64');
	if(connected == true)
	{
		//client.write(new Buffer(message,'base64'));
		client.write(message);
	}
	else
	{
		setTimeout('sendLater()',500);
	}
	});
	socket.on('close', function () {
	if(connected)
	{
		client.end();
	}
	});
});

function sendLater()
{

if(connected)
{
	client.write(buffer);
}
else
{
	setTimeout('sendLater()',500);
}
}
<commit_msg>wrong repo for this file<commit_after><|endoftext|>


<commit_before>var _            = require("underscore"),
    Promise      = require("bluebird"),
    thicket      = require("thicket"),
    Logger       = thicket.c("logger"),
    CLA          = thicket.c("appenders/console-log"),
    App          = thicket.c("app"),
    Bootstrapper = thicket.c("bootstrapper");

var MySampleApp = function() {
  this.initialize.apply(this, arguments);
};

_.extend(MySampleApp.prototype, App.prototype, {
  initialize: function() {
    App.prototype.initialize.apply(this, arguments);
    this._log = Logger.create("MySampleApp");
  },
  up: Promise.method(function() {
    this._log.debug("Look at me, doing some meaningful setup work...");
  }),
  down: Promise.method(function() {
    this._log.debug("Look at me, doing some meaningful teardown work...");
  })
});

Log = Logger.create("Main");
Logger.root().setLogLevel(Logger.Level.Debug);
Logger.root().addAppender(new CLA());

var bootstrapper = new Bootstrapper({applicationConstructor: MySampleApp});
bootstrapper
  .bootstrap()
  .then(function(appContainer) {
    return appContainer.start();
  });
<commit_msg>Remove superfluous logger.<commit_after>var _            = require("underscore"),
    Promise      = require("bluebird"),
    thicket      = require("thicket"),
    Logger       = thicket.c("logger"),
    CLA          = thicket.c("appenders/console-log"),
    App          = thicket.c("app"),
    Bootstrapper = thicket.c("bootstrapper");

var Log = Logger.create("MySampleApp");

var MySampleApp = function() {
  this.initialize.apply(this, arguments);
};

_.extend(MySampleApp.prototype, App.prototype, {
  initialize: function() {
    App.prototype.initialize.apply(this, arguments);
  },
  up: Promise.method(function() {
    Log.debug("Look at me, doing some meaningful setup work...");
  }),
  down: Promise.method(function() {
    Log.debug("Look at me, doing some meaningful teardown work...");
  })
});

Logger.root().setLogLevel(Logger.Level.Debug);
Logger.root().addAppender(new CLA());

var bootstrapper = new Bootstrapper({applicationConstructor: MySampleApp});
bootstrapper
  .bootstrap()
  .then(function(appContainer) {
    return appContainer.start();
  });
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

var shell = require('shelljs');
var argv = require('minimist')(process.argv.slice(2));
var fs = require('fs');
var path = require('path');
var tmpl = require('blueimp-tmpl').tmpl;
var projectName = require('project-name');

var BASE_DIR = path.resolve(__dirname, '..');
var DIST_DIR = path.join(BASE_DIR, 'dist');
var SCAFFOLD_DIR = path.join(BASE_DIR, 'scaffolds');
var TEMPLATES_DIR = path.join(BASE_DIR, 'src', 'templates');
var VALID_PACKAGES = ['react-web'];
var DIST_ESLINT_DIR = path.join('node_modules', projectName(BASE_DIR), 'dist');
var BASE_ESLINT_PATH = './' + path.join(DIST_ESLINT_DIR, 'json', 'base-eslintrc.json');
var DEV_ESLINT_PATH = './' + path.join(DIST_ESLINT_DIR, 'json', 'dev-eslintrc.json');
var TEST_ESLINT_PATH = './' + path.join(DIST_ESLINT_DIR, 'json', 'test-eslintrc.json');

var packages = [];
var packageInstall = argv.install || argv.i || '';
var webpackGroup = argv.webpack || packageInstall || '';
var forceInstall = argv.force || argv.f;

function npmInstall(pkgs) {
  var total = pkgs.length;

  pkgs.forEach(function(pkg, index) {
    shell.echo('');
    shell.echo('----> Install Package: ' + pkg + ' (' + (index + 1) + '/' + total + ')');
    shell.exec('npm install --save ' + pkg);
  });
}

function devNpmInstall(pkgs) {
  var total = pkgs.length;

  pkgs.forEach(function(pkg, index) {
    shell.echo('');
    shell.echo('----> Install Dev Package: ' + pkg + ' (' + (index + 1) + '/' + total + ')');
    shell.exec('npm install --save-dev ' + pkg);
  });
}

function copyDistConfig(source, destination) {
  var sourcePath = path.join(DIST_DIR, source);
  shell.cp('-f', sourcePath, destination);
}

function copyScaffold(source, destination) {
  var sourcePath = path.join(SCAFFOLD_DIR, source);
  shell.cp('-f', sourcePath, destination);
}

function buildTemplateFromFile(templatePath, data) {
  var template = fs.readFileSync(path.join(TEMPLATES_DIR, templatePath), 'utf8');
  return tmpl(template, data);
}

function generateTemplate(templatePath, data, destination) {
  var template = buildTemplateFromFile(templatePath, data);
  template.to(destination);
}

if (argv.help) {
  shell.echo('Usage:');
  shell.echo('  js-config-gen <args>');
  shell.echo('');
  shell.echo('Args:');
  shell.echo('');
  shell.echo('  --install, -i: install predefined package list, options: [' + VALID_PACKAGES.join(',') + ']');
  shell.echo('  --force, -f: overwrite existing configs, does not override --skip-install or --skip-commands');
  shell.echo('  --eslintrc: create eslintrc');
  shell.echo('  --babelrc: create babelrc');
  shell.echo('  --webpack: create webpack configs');
  shell.echo('  --webpack-dev-server: create webpack dev server config');
  shell.echo('  --karma: create karma configs');
  shell.echo('  --index-html: creates dev & prod index.html');
  shell.echo('  --redux: creates scaffold for redux');
  shell.echo('  --assets: creates assets folder with dirs for images, fonts, and stylesheets');
  shell.echo('  --skip-install: override to skip installing of packages');
  shell.echo('  --skip-tests: override to skip setup for tests');
  shell.echo('  --skip-commands: override to skip adding of commands');
  shell.exit(0);
}

if (!argv['skip-commands'] && packageInstall) {
  shell.echo('----> Adding commands to your project package.json');
  switch (packageInstall.toLowerCase()) {
    case 'react-web':
      require('../src/commands/react-web').injectCommands(path.join(process.cwd(), 'package.json'));
      break;
    default:
      shell.echo('Requires packages list name (--install or -i), valid options: ' + VALID_PACKAGES.join(','));
      shell.exit(1);
  }
}

if (!argv['skip-install'] && packageInstall) {
  switch (packageInstall.toLowerCase()) {
    case 'react-web':
      packages = require('../src/packages/react-web');
      break;
    default:
      shell.echo('Requires packages list name (--install or -i), valid options: ' + VALID_PACKAGES.join(','));
      shell.exit(1);
  }

  shell.echo('----> Installing packages...');
  npmInstall(packages.depends);

  shell.echo('----> Installing dev packages...');
  devNpmInstall(packages.dev);
}

if (packageInstall || argv.assets) {
  if (forceInstall || !shell.test('-d', 'src/assets')) {
    shell.echo('----> Generating assets folders...');
    shell.mkdir('-p', 'src/assets/images');
    shell.mkdir('-p', 'src/assets/fonts');
    shell.mkdir('-p', 'src/assets/stylesheets');
  }
}

if (
  ((packageInstall || argv.babelrc) && forceInstall) ||
  ((packageInstall || argv.babelrc) && !shell.test('-f', '.babelrc'))
) {
  shell.echo('----> Generating .babelrc...');
  copyDistConfig('/json/babelrc.json', '.babelrc');
}

if (packageInstall || argv.eslintrc) {
  if (argv.force || !shell.test('-f', '.eslintrc')) {
    shell.echo('----> Generating project .eslintrc...');
    generateTemplate('project-eslintrc.json.tmpl', BASE_ESLINT_PATH, '.eslintrc');
  }

  if (forceInstall || !shell.test('-f', '.eslintrc.dev')) {
    shell.echo('----> Generating development project .eslintrc.dev');
    generateTemplate('project-eslintrc.json.tmpl', DEV_ESLINT_PATH, '.eslintrc.dev');
  }
}

if ((packageInstall && !argv['skip-tests']) || !argv['skip-tests']) {
  if (forceInstall && !shell.test('-d', 'tests')) {
    shell.echo('----> Setting up test dir...');
    shell.mkdir('-p', 'tests');
  }

  if (forceInstall || !shell.test('-f', './tests/.eslintrc')) {
    shell.echo('----> Generating test project .eslintrc...');
    generateTemplate('project-eslintrc.json.tmpl', TEST_ESLINT_PATH, './tests/.eslintrc');
    copyDistConfig('/json/test-eslintrc.json', 'tests/.eslintrc');
  }
}

if (packageInstall || webpackGroup) {
  if (forceInstall || !shell.test('-f', './webpack.config.dev.js')) {
    shell.echo('----> Generating webpack.config.dev.js...');
    require('../src/configs/webpack/' + webpackGroup).project.development.template.to('webpack.config.dev.js');
  }

  if (forceInstall || !shell.test('-f', './webpack.config.test.js')) {
    shell.echo('----> Generating webpack.config.test.js...');
    require('../src/configs/webpack/' + webpackGroup).project.test.template.to('webpack.config.test.js');
  }

  if (forceInstall || !shell.test('-f', './webpack.config.prod.js')) {
    shell.echo('----> Generating webpack.config.production.js...');
    require('../src/configs/webpack/' + webpackGroup).project.production.template.to('webpack.config.prod.js');
  }
}

if (packageInstall || argv['webpack-dev-server']) {
  if (forceInstall || !shell.test('-f', './webpack-dev.server.js')) {
    shell.echo('----> Generating webpack-dev.server.js...');
    copyDistConfig('webpack-dev.server.js', 'webpack-dev.server.js');
  }
}

if (packageInstall || argv.karma) {
  if (forceInstall || !shell.test('-f', './karma.conf.js')) {
    shell.echo('----> Generating project karma.conf.js');
    require('../src/configs/karma/project-config')().template.to('karma.conf.js');
  }

  if (forceInstall || !shell.test('-f', './tests/karma_tests.js')) {
    shell.echo('----> Generating project tests/karma_tests.js');
    copyDistConfig('karma-test-index.js', 'tests/karma_tests.js');
  }
}

if (packageInstall || argv.html) {
  shell.mkdir('-p', 'static');

  if (forceInstall || !shell.test('-f', './static/dev.index.html')) {
    shell.echo('----> Generating static/dev.index.html...');
    copyDistConfig('static/dev.index.html', 'static/dev.index.html');
  }

  if (forceInstall || !shell.test('-f', './static/prod.index.html')) {
    shell.echo('----> Generating static/prod.index.html...');
    copyDistConfig('static/prod.index.html', 'static/prod.index.html');
  }
}

if (packageInstall || argv.redux) {
  if (forceInstall) {
    shell.echo('----> Generating redux scaffolds...');
  }

  if (forceInstall || !shell.test('-f', './src/index.js')) {
    copyScaffold('redux/index.js', 'src/index.js');
  }

  if (forceInstall || !shell.test('-d', './src/containers/Root')) {
    shell.mkdir('-p', 'src/containers/Root');
    copyScaffold('redux/containers/Root/index.js', 'src/containers/Root/index.js');
    copyScaffold('redux/containers/Root/_dev.jsx', 'src/containers/Root/_dev.jsx');
    copyScaffold('redux/containers/Root/_prod.jsx', 'src/containers/Root/_prod.jsx');
  }

  if (forceInstall || !shell.test('-f', './src/containers/App.jsx')) {
    copyScaffold('redux/containers/App.jsx', 'src/containers/App.jsx');
  }

  if (forceInstall || !shell.test('-f', './src/containers/DevTools.jsx')) {
    copyScaffold('redux/containers/DevTools.jsx', 'src/containers/DevTools.jsx');
  }

  if (forceInstall || !shell.test('-f', './src/reducers/index.js')) {
    shell.mkdir('-p', 'src/reducers');
    copyScaffold('redux/reducers/index.js', './src/reducers/index.js');
  }

  if (forceInstall || !shell.test('-d', './src/stores/configureStore')) {
    shell.mkdir('-p', 'src/stores/configureStore');
    copyScaffold('redux/stores/configureStore/index.js', 'src/stores/configureStore/index.js');
    copyScaffold('redux/stores/configureStore/_dev.js', 'src/stores/configureStore/_dev.js');
    copyScaffold('redux/stores/configureStore/_prod.js', 'src/stores/configureStore/_prod.js');
  }
}

shell.echo('----> Done!');
shell.exit(0);
<commit_msg>Remove --skip-tests arg<commit_after>#!/usr/bin/env node
'use strict';

var shell = require('shelljs');
var argv = require('minimist')(process.argv.slice(2));
var fs = require('fs');
var path = require('path');
var tmpl = require('blueimp-tmpl').tmpl;
var projectName = require('project-name');

var BASE_DIR = path.resolve(__dirname, '..');
var DIST_DIR = path.join(BASE_DIR, 'dist');
var SCAFFOLD_DIR = path.join(BASE_DIR, 'scaffolds');
var TEMPLATES_DIR = path.join(BASE_DIR, 'src', 'templates');
var VALID_PACKAGES = ['react-web'];
var DIST_ESLINT_DIR = path.join('node_modules', projectName(BASE_DIR), 'dist');
var BASE_ESLINT_PATH = './' + path.join(DIST_ESLINT_DIR, 'json', 'base-eslintrc.json');
var DEV_ESLINT_PATH = './' + path.join(DIST_ESLINT_DIR, 'json', 'dev-eslintrc.json');
var TEST_ESLINT_PATH = './' + path.join(DIST_ESLINT_DIR, 'json', 'test-eslintrc.json');

var packages = [];
var packageInstall = argv.install || argv.i || '';
var webpackGroup = argv.webpack || packageInstall || '';
var forceInstall = argv.force || argv.f;

function npmInstall(pkgs) {
  var total = pkgs.length;

  pkgs.forEach(function(pkg, index) {
    shell.echo('');
    shell.echo('----> Install Package: ' + pkg + ' (' + (index + 1) + '/' + total + ')');
    shell.exec('npm install --save ' + pkg);
  });
}

function devNpmInstall(pkgs) {
  var total = pkgs.length;

  pkgs.forEach(function(pkg, index) {
    shell.echo('');
    shell.echo('----> Install Dev Package: ' + pkg + ' (' + (index + 1) + '/' + total + ')');
    shell.exec('npm install --save-dev ' + pkg);
  });
}

function copyDistConfig(source, destination) {
  var sourcePath = path.join(DIST_DIR, source);
  shell.cp('-f', sourcePath, destination);
}

function copyScaffold(source, destination) {
  var sourcePath = path.join(SCAFFOLD_DIR, source);
  shell.cp('-f', sourcePath, destination);
}

function buildTemplateFromFile(templatePath, data) {
  var template = fs.readFileSync(path.join(TEMPLATES_DIR, templatePath), 'utf8');
  return tmpl(template, data);
}

function generateTemplate(templatePath, data, destination) {
  var template = buildTemplateFromFile(templatePath, data);
  template.to(destination);
}

if (argv.help) {
  shell.echo('Usage:');
  shell.echo('  js-config-gen <args>');
  shell.echo('');
  shell.echo('Args:');
  shell.echo('');
  shell.echo('  --install, -i: install predefined package list, options: [' + VALID_PACKAGES.join(',') + ']');
  shell.echo('  --force, -f: overwrite existing configs, does not override --skip-install or --skip-commands');
  shell.echo('  --eslintrc: create eslintrc');
  shell.echo('  --babelrc: create babelrc');
  shell.echo('  --webpack: create webpack configs');
  shell.echo('  --webpack-dev-server: create webpack dev server config');
  shell.echo('  --karma: create karma configs');
  shell.echo('  --index-html: creates dev & prod index.html');
  shell.echo('  --redux: creates scaffold for redux');
  shell.echo('  --assets: creates assets folder with dirs for images, fonts, and stylesheets');
  shell.echo('  --skip-install: override to skip installing of packages');
  shell.echo('  --skip-commands: override to skip adding of commands');
  shell.exit(0);
}

if (!argv['skip-commands'] && packageInstall) {
  shell.echo('----> Adding commands to your project package.json');
  switch (packageInstall.toLowerCase()) {
    case 'react-web':
      require('../src/commands/react-web').injectCommands(path.join(process.cwd(), 'package.json'));
      break;
    default:
      shell.echo('Requires packages list name (--install or -i), valid options: ' + VALID_PACKAGES.join(','));
      shell.exit(1);
  }
}

if (!argv['skip-install'] && packageInstall) {
  switch (packageInstall.toLowerCase()) {
    case 'react-web':
      packages = require('../src/packages/react-web');
      break;
    default:
      shell.echo('Requires packages list name (--install or -i), valid options: ' + VALID_PACKAGES.join(','));
      shell.exit(1);
  }

  shell.echo('----> Installing packages...');
  npmInstall(packages.depends);

  shell.echo('----> Installing dev packages...');
  devNpmInstall(packages.dev);
}

if (packageInstall || argv.assets) {
  if (forceInstall || !shell.test('-d', 'src/assets')) {
    shell.echo('----> Generating assets folders...');
    shell.mkdir('-p', 'src/assets/images');
    shell.mkdir('-p', 'src/assets/fonts');
    shell.mkdir('-p', 'src/assets/stylesheets');
  }
}

if (
  ((packageInstall || argv.babelrc) && forceInstall) ||
  ((packageInstall || argv.babelrc) && !shell.test('-f', '.babelrc'))
) {
  shell.echo('----> Generating .babelrc...');
  copyDistConfig('/json/babelrc.json', '.babelrc');
}

if (packageInstall || argv.eslintrc) {
  if (argv.force || !shell.test('-f', '.eslintrc')) {
    shell.echo('----> Generating project .eslintrc...');
    generateTemplate('project-eslintrc.json.tmpl', BASE_ESLINT_PATH, '.eslintrc');
  }

  if (forceInstall || !shell.test('-f', '.eslintrc.dev')) {
    shell.echo('----> Generating development project .eslintrc.dev');
    generateTemplate('project-eslintrc.json.tmpl', DEV_ESLINT_PATH, '.eslintrc.dev');
  }
}

if (packageInstall || webpackGroup) {
  if (forceInstall || !shell.test('-f', './webpack.config.dev.js')) {
    shell.echo('----> Generating webpack.config.dev.js...');
    require('../src/configs/webpack/' + webpackGroup).project.development.template.to('webpack.config.dev.js');
  }

  if (forceInstall || !shell.test('-f', './webpack.config.test.js')) {
    shell.echo('----> Generating webpack.config.test.js...');
    require('../src/configs/webpack/' + webpackGroup).project.test.template.to('webpack.config.test.js');
  }

  if (forceInstall || !shell.test('-f', './webpack.config.prod.js')) {
    shell.echo('----> Generating webpack.config.production.js...');
    require('../src/configs/webpack/' + webpackGroup).project.production.template.to('webpack.config.prod.js');
  }
}

if (packageInstall || argv['webpack-dev-server']) {
  if (forceInstall || !shell.test('-f', './webpack-dev.server.js')) {
    shell.echo('----> Generating webpack-dev.server.js...');
    copyDistConfig('webpack-dev.server.js', 'webpack-dev.server.js');
  }
}

if (packageInstall || argv.karma) {
  shell.echo('----> Generating test project .eslintrc...');
  shell.mkdir('-p', 'tests');

  if (forceInstall || !shell.test('-f', './tests/.eslintrc')) {
    generateTemplate('project-eslintrc.json.tmpl', TEST_ESLINT_PATH, './tests/.eslintrc');
    copyDistConfig('/json/test-eslintrc.json', 'tests/.eslintrc');
  }

  if (forceInstall || !shell.test('-f', './karma.conf.js')) {
    shell.echo('----> Generating project karma.conf.js');
    require('../src/configs/karma/project-config')().template.to('karma.conf.js');
  }

  if (forceInstall || !shell.test('-f', './tests/karma_tests.js')) {
    shell.echo('----> Generating project tests/karma_tests.js');
    copyDistConfig('karma-test-index.js', 'tests/karma_tests.js');
  }
}

if (packageInstall || argv.html) {
  shell.mkdir('-p', 'static');

  if (forceInstall || !shell.test('-f', './static/dev.index.html')) {
    shell.echo('----> Generating static/dev.index.html...');
    copyDistConfig('static/dev.index.html', 'static/dev.index.html');
  }

  if (forceInstall || !shell.test('-f', './static/prod.index.html')) {
    shell.echo('----> Generating static/prod.index.html...');
    copyDistConfig('static/prod.index.html', 'static/prod.index.html');
  }
}

if (packageInstall || argv.redux) {
  if (forceInstall) {
    shell.echo('----> Generating redux scaffolds...');
  }

  if (forceInstall || !shell.test('-f', './src/index.js')) {
    copyScaffold('redux/index.js', 'src/index.js');
  }

  if (forceInstall || !shell.test('-d', './src/containers/Root')) {
    shell.mkdir('-p', 'src/containers/Root');
    copyScaffold('redux/containers/Root/index.js', 'src/containers/Root/index.js');
    copyScaffold('redux/containers/Root/_dev.jsx', 'src/containers/Root/_dev.jsx');
    copyScaffold('redux/containers/Root/_prod.jsx', 'src/containers/Root/_prod.jsx');
  }

  if (forceInstall || !shell.test('-f', './src/containers/App.jsx')) {
    copyScaffold('redux/containers/App.jsx', 'src/containers/App.jsx');
  }

  if (forceInstall || !shell.test('-f', './src/containers/DevTools.jsx')) {
    copyScaffold('redux/containers/DevTools.jsx', 'src/containers/DevTools.jsx');
  }

  if (forceInstall || !shell.test('-f', './src/reducers/index.js')) {
    shell.mkdir('-p', 'src/reducers');
    copyScaffold('redux/reducers/index.js', './src/reducers/index.js');
  }

  if (forceInstall || !shell.test('-d', './src/stores/configureStore')) {
    shell.mkdir('-p', 'src/stores/configureStore');
    copyScaffold('redux/stores/configureStore/index.js', 'src/stores/configureStore/index.js');
    copyScaffold('redux/stores/configureStore/_dev.js', 'src/stores/configureStore/_dev.js');
    copyScaffold('redux/stores/configureStore/_prod.js', 'src/stores/configureStore/_prod.js');
  }
}

shell.echo('----> Done!');
shell.exit(0);
<|endoftext|>