<commit_before>//     Zepto.js
//     (c) 2010-2012 Thomas Fuchs
//     Zepto.js may be freely distributed under the MIT license.

;(function($){
  var jsonpID = 0,
      document = window.document,
      key,
      name,
      rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
      scriptTypeRE = /^(?:text|application)\/javascript/i,
      xmlTypeRE = /^(?:text|application)\/xml/i,
      jsonType = 'application/json',
      htmlType = 'text/html',
      blankRE = /^\s*$/

  // trigger a custom event and return false if it was cancelled
  function triggerAndReturn(context, eventName, data) {
    var event = $.Event(eventName)
    $(context).trigger(event, data)
    return !event.defaultPrevented
  }

  // trigger an Ajax "global" event
  function triggerGlobal(settings, context, eventName, data) {
    if (settings.global) return triggerAndReturn(context || document, eventName, data)
  }

  // Number of active Ajax requests
  $.active = 0

  function ajaxStart(settings) {
    if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart')
  }
  function ajaxStop(settings) {
    if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop')
  }

  // triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable
  function ajaxBeforeSend(xhr, settings) {
    var context = settings.context
    if (settings.beforeSend.call(context, xhr, settings) === false ||
        triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false)
      return false

    triggerGlobal(settings, context, 'ajaxSend', [xhr, settings])
  }
  function ajaxSuccess(data, xhr, settings) {
    var context = settings.context, status = 'success'
    settings.success.call(context, data, status, xhr)
    triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data])
    ajaxComplete(status, xhr, settings)
  }
  // type: "timeout", "error", "abort", "parsererror"
  function ajaxError(error, type, xhr, settings) {
    var context = settings.context
    settings.error.call(context, xhr, type, error)
    triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error])
    ajaxComplete(type, xhr, settings)
  }
  // status: "success", "notmodified", "error", "timeout", "abort", "parsererror"
  function ajaxComplete(status, xhr, settings) {
    var context = settings.context
    settings.complete.call(context, xhr, status)
    triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings])
    ajaxStop(settings)
  }

  // Empty function, used as default callback
  function empty() {}

  $.ajaxJSONP = function(options){
    if (!('type' in options)) return $.ajax(options)

    var callbackName = 'jsonp' + (++jsonpID),
      script = document.createElement('script'),
      cleanup = function() {
        clearTimeout(abortTimeout)
        $(script).remove()
        delete window[callbackName]
      },
      abort = function(type){
        cleanup()
        // In case of manual abort or timeout, keep an empty function as callback
        // so that the SCRIPT tag that eventually loads won't result in an error.
        if (!type || type == 'timeout') window[callbackName] = empty
        ajaxError(null, type || 'abort', xhr, options)
      },
      xhr = { abort: abort }, abortTimeout

    if (ajaxBeforeSend(xhr, options) === false) {
      abort('abort')
      return false
    }

    window[callbackName] = function(data){
      cleanup()
      ajaxSuccess(data, xhr, options)
    }

    script.onerror = function() { abort('error') }

    script.src = options.url.replace(/=\?/, '=' + callbackName)
    $('head').append(script)

    if (options.timeout > 0) abortTimeout = setTimeout(function(){
      abort('timeout')
    }, options.timeout)

    return xhr
  }

  $.ajaxSettings = {
    // Default type of request
    type: 'GET',
    // Callback that is executed before request
    beforeSend: empty,
    // Callback that is executed if the request succeeds
    success: empty,
    // Callback that is executed the the server drops error
    error: empty,
    // Callback that is executed on request complete (both: error and success)
    complete: empty,
    // The context for the callbacks
    context: null,
    // Whether to trigger "global" Ajax events
    global: true,
    // Transport
    xhr: function () {
      return new window.XMLHttpRequest()
    },
    // MIME types mapping
    accepts: {
      script: 'text/javascript, application/javascript',
      json:   jsonType,
      xml:    'application/xml, text/xml',
      html:   htmlType,
      text:   'text/plain'
    },
    // Whether the request is to another domain
    crossDomain: false,
    // Default timeout
    timeout: 0,
    // Whether data should be serialized to string
    processData: true,
    // Whether the browser should be allowed to cache GET responses
    cache: true
  }

  function mimeToDataType(mime) {
    if (mime) mime = mime.split(';', 2)[0]
    return mime && ( mime == htmlType ? 'html' :
      mime == jsonType ? 'json' :
      scriptTypeRE.test(mime) ? 'script' :
      xmlTypeRE.test(mime) && 'xml' ) || 'text'
  }

  function appendQuery(url, query) {
    return (url + '&' + query).replace(/[&?]{1,2}/, '?')
  }

  // serialize payload and append it to the URL for GET requests
  function serializeData(options) {
    if (options.processData && options.data && $.type(options.data) != "string")
      options.data = $.param(options.data, options.traditional)
    if (options.data && (!options.type || options.type.toUpperCase() == 'GET'))
      options.url = appendQuery(options.url, options.data)
  }

  $.ajax = function(options){
    var settings = $.extend({}, options || {})
    for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key]

    ajaxStart(settings)

    if (!settings.crossDomain) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) &&
      RegExp.$2 != window.location.host

    if (!settings.url) settings.url = window.location.toString()
    serializeData(settings)
    if (settings.cache === false) settings.url = appendQuery(settings.url, '_=' + Date.now())

    var dataType = settings.dataType, hasPlaceholder = /=\?/.test(settings.url)
    if (dataType == 'jsonp' || hasPlaceholder) {
      if (!hasPlaceholder) settings.url = appendQuery(settings.url, 'callback=?')
      return $.ajaxJSONP(settings)
    }

    var mime = settings.accepts[dataType],
        baseHeaders = { },
        protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol,
        xhr = settings.xhr(), abortTimeout

    if (!settings.crossDomain) baseHeaders['X-Requested-With'] = 'XMLHttpRequest'
    if (mime) {
      baseHeaders['Accept'] = mime
      if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0]
      xhr.overrideMimeType && xhr.overrideMimeType(mime)
    }
    if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET'))
      baseHeaders['Content-Type'] = (settings.contentType || 'application/x-www-form-urlencoded')
    settings.headers = $.extend(baseHeaders, settings.headers || {})

    xhr.onreadystatechange = function(){
      if (xhr.readyState == 4) {
        xhr.onreadystatechange = empty;
        clearTimeout(abortTimeout)
        var result, error = false
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) {
          dataType = dataType || mimeToDataType(xhr.getResponseHeader('content-type'))
          result = xhr.responseText

          try {
            // http://perfectionkills.com/global-eval-what-are-the-options/
            if (dataType == 'script')    (1,eval)(result)
            else if (dataType == 'xml')  result = xhr.responseXML
            else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result)
          } catch (e) { error = e }

          if (error) ajaxError(error, 'parsererror', xhr, settings)
          else ajaxSuccess(result, xhr, settings)
        } else {
          ajaxError(null, xhr.status ? 'error' : 'abort', xhr, settings)
        }
      }
    }

    var async = 'async' in settings ? settings.async : true
    xhr.open(settings.type, settings.url, async)

    for (name in settings.headers) xhr.setRequestHeader(name, settings.headers[name])

    if (ajaxBeforeSend(xhr, settings) === false) {
      xhr.abort()
      return false
    }

    if (settings.timeout > 0) abortTimeout = setTimeout(function(){
        xhr.onreadystatechange = empty
        xhr.abort()
        ajaxError(null, 'timeout', xhr, settings)
      }, settings.timeout)

    // avoid sending empty string (#319)
    xhr.send(settings.data ? settings.data : null)
    return xhr
  }

  // handle optional data/success arguments
  function parseArguments(url, data, success, dataType) {
    var hasData = !$.isFunction(data)
    return {
      url:      url,
      data:     hasData  ? data : undefined,
      success:  !hasData ? data : $.isFunction(success) ? success : undefined,
      dataType: hasData  ? dataType || success : success
    }
  }

  $.get = function(url, data, success, dataType){
    return $.ajax(parseArguments.apply(null, arguments))
  }

  $.post = function(url, data, success, dataType){
    var options = parseArguments.apply(null, arguments)
    options.type = 'POST'
    return $.ajax(options)
  }

  $.getJSON = function(url, data, success){
    var options = parseArguments.apply(null, arguments)
    options.dataType = 'json'
    return $.ajax(options)
  }

  $.fn.load = function(url, data, success){
    if (!this.length) return this
    var self = this, parts = url.split(/\s/), selector,
        options = parseArguments(url, data, success),
        callback = options.success
    if (parts.length > 1) options.url = parts[0], selector = parts[1]
    options.success = function(response){
      self.html(selector ?
        $('<div>').html(response.replace(rscript, "")).find(selector)
        : response)
      callback && callback.apply(self, arguments)
    }
    $.ajax(options)
    return this
  }

  var escape = encodeURIComponent

  function serialize(params, obj, traditional, scope){
    var type, array = $.isArray(obj)
    $.each(obj, function(key, value) {
      type = $.type(value)
      if (scope) key = traditional ? scope : scope + '[' + (array ? '' : key) + ']'
      // handle data in serializeArray() format
      if (!scope && array) params.add(value.name, value.value)
      // recurse into nested objects
      else if (type == "array" || (!traditional && type == "object"))
        serialize(params, value, traditional, key)
      else params.add(key, value)
    })
  }

  $.param = function(obj, traditional){
    var params = []
    params.add = function(k, v){ this.push(escape(k) + '=' + escape(v)) }
    serialize(params, obj, traditional)
    return params.join('&').replace(/%20/g, '+')
  }
})(Zepto)
<commit_msg>Update ajax.js<commit_after>//     Zepto.js
//     (c) 2010-2012 Thomas Fuchs
//     Zepto.js may be freely distributed under the MIT license.

;(function($){
  var jsonpID = 0,
      document = window.document,
      key,
      name,
      rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
      scriptTypeRE = /^(?:text|application)\/javascript/i,
      xmlTypeRE = /^(?:text|application)\/xml/i,
      jsonType = 'application/json',
      htmlType = 'text/html',
      blankRE = /^\s*$/

  // trigger a custom event and return false if it was cancelled
  function triggerAndReturn(context, eventName, data) {
    var event = $.Event(eventName)
    $(context).trigger(event, data)
    return !event.defaultPrevented
  }

  // trigger an Ajax "global" event
  function triggerGlobal(settings, context, eventName, data) {
    if (settings.global) return triggerAndReturn(context || document, eventName, data)
  }

  // Number of active Ajax requests
  $.active = 0

  function ajaxStart(settings) {
    if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart')
  }
  function ajaxStop(settings) {
    if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop')
  }

  // triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable
  function ajaxBeforeSend(xhr, settings) {
    var context = settings.context
    if (settings.beforeSend.call(context, xhr, settings) === false ||
        triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false)
      return false

    triggerGlobal(settings, context, 'ajaxSend', [xhr, settings])
  }
  function ajaxSuccess(data, xhr, settings) {
    var context = settings.context, status = 'success'
    settings.success.call(context, data, status, xhr)
    triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data])
    ajaxComplete(status, xhr, settings)
  }
  // type: "timeout", "error", "abort", "parsererror"
  function ajaxError(error, type, xhr, settings) {
    var context = settings.context
    settings.error.call(context, xhr, type, error)
    triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error])
    ajaxComplete(type, xhr, settings)
  }
  // status: "success", "notmodified", "error", "timeout", "abort", "parsererror"
  function ajaxComplete(status, xhr, settings) {
    var context = settings.context
    settings.complete.call(context, xhr, status)
    triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings])
    ajaxStop(settings)
  }

  // Empty function, used as default callback
  function empty() {}

  $.ajaxJSONP = function(options){
    if (!('type' in options)) return $.ajax(options)

    var callbackName = options.jsonpCallback || ('jsonp' + (++jsonpID)),
      script = document.createElement('script'),
      cleanup = function() {
        clearTimeout(abortTimeout)
        $(script).remove()
        delete window[callbackName]
      },
      abort = function(type){
        cleanup()
        // In case of manual abort or timeout, keep an empty function as callback
        // so that the SCRIPT tag that eventually loads won't result in an error.
        if (!type || type == 'timeout') window[callbackName] = empty
        ajaxError(null, type || 'abort', xhr, options)
      },
      xhr = { abort: abort }, abortTimeout

    if (ajaxBeforeSend(xhr, options) === false) {
      abort('abort')
      return false
    }

    window[callbackName] = function(data){
      cleanup()
      ajaxSuccess(data, xhr, options)
    }

    script.onerror = function() { abort('error') }

    script.src = options.url.replace(/=\?/, '=' + callbackName)
    $('head').append(script)

    if (options.timeout > 0) abortTimeout = setTimeout(function(){
      abort('timeout')
    }, options.timeout)

    return xhr
  }

  $.ajaxSettings = {
    // Default type of request
    type: 'GET',
    // Callback that is executed before request
    beforeSend: empty,
    // Callback that is executed if the request succeeds
    success: empty,
    // Callback that is executed the the server drops error
    error: empty,
    // Callback that is executed on request complete (both: error and success)
    complete: empty,
    // The context for the callbacks
    context: null,
    // Whether to trigger "global" Ajax events
    global: true,
    // Transport
    xhr: function () {
      return new window.XMLHttpRequest()
    },
    // MIME types mapping
    accepts: {
      script: 'text/javascript, application/javascript',
      json:   jsonType,
      xml:    'application/xml, text/xml',
      html:   htmlType,
      text:   'text/plain'
    },
    // Whether the request is to another domain
    crossDomain: false,
    // Default timeout
    timeout: 0,
    // Whether data should be serialized to string
    processData: true,
    // Whether the browser should be allowed to cache GET responses
    cache: true
  }

  function mimeToDataType(mime) {
    if (mime) mime = mime.split(';', 2)[0]
    return mime && ( mime == htmlType ? 'html' :
      mime == jsonType ? 'json' :
      scriptTypeRE.test(mime) ? 'script' :
      xmlTypeRE.test(mime) && 'xml' ) || 'text'
  }

  function appendQuery(url, query) {
    return (url + '&' + query).replace(/[&?]{1,2}/, '?')
  }

  // serialize payload and append it to the URL for GET requests
  function serializeData(options) {
    if (options.processData && options.data && $.type(options.data) != "string")
      options.data = $.param(options.data, options.traditional)
    if (options.data && (!options.type || options.type.toUpperCase() == 'GET'))
      options.url = appendQuery(options.url, options.data)
  }

  $.ajax = function(options){
    var settings = $.extend({}, options || {})
    for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key]

    ajaxStart(settings)

    if (!settings.crossDomain) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) &&
      RegExp.$2 != window.location.host

    if (!settings.url) settings.url = window.location.toString()
    serializeData(settings)
    if (settings.cache === false) settings.url = appendQuery(settings.url, '_=' + Date.now())

    var dataType = settings.dataType, hasPlaceholder = /=\?/.test(settings.url)
    if (dataType == 'jsonp' || hasPlaceholder) {
      if (!hasPlaceholder) settings.url = appendQuery(settings.url, settings.jsonp ? (settings.jsonp + '=?') : 'callback=?')
      return $.ajaxJSONP(settings)
    }

    var mime = settings.accepts[dataType],
        baseHeaders = { },
        protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol,
        xhr = settings.xhr(), abortTimeout

    if (!settings.crossDomain) baseHeaders['X-Requested-With'] = 'XMLHttpRequest'
    if (mime) {
      baseHeaders['Accept'] = mime
      if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0]
      xhr.overrideMimeType && xhr.overrideMimeType(mime)
    }
    if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET'))
      baseHeaders['Content-Type'] = (settings.contentType || 'application/x-www-form-urlencoded')
    settings.headers = $.extend(baseHeaders, settings.headers || {})

    xhr.onreadystatechange = function(){
      if (xhr.readyState == 4) {
        xhr.onreadystatechange = empty;
        clearTimeout(abortTimeout)
        var result, error = false
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) {
          dataType = dataType || mimeToDataType(xhr.getResponseHeader('content-type'))
          result = xhr.responseText

          try {
            // http://perfectionkills.com/global-eval-what-are-the-options/
            if (dataType == 'script')    (1,eval)(result)
            else if (dataType == 'xml')  result = xhr.responseXML
            else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result)
          } catch (e) { error = e }

          if (error) ajaxError(error, 'parsererror', xhr, settings)
          else ajaxSuccess(result, xhr, settings)
        } else {
          ajaxError(null, xhr.status ? 'error' : 'abort', xhr, settings)
        }
      }
    }

    var async = 'async' in settings ? settings.async : true
    xhr.open(settings.type, settings.url, async)

    for (name in settings.headers) xhr.setRequestHeader(name, settings.headers[name])

    if (ajaxBeforeSend(xhr, settings) === false) {
      xhr.abort()
      return false
    }

    if (settings.timeout > 0) abortTimeout = setTimeout(function(){
        xhr.onreadystatechange = empty
        xhr.abort()
        ajaxError(null, 'timeout', xhr, settings)
      }, settings.timeout)

    // avoid sending empty string (#319)
    xhr.send(settings.data ? settings.data : null)
    return xhr
  }

  // handle optional data/success arguments
  function parseArguments(url, data, success, dataType) {
    var hasData = !$.isFunction(data)
    return {
      url:      url,
      data:     hasData  ? data : undefined,
      success:  !hasData ? data : $.isFunction(success) ? success : undefined,
      dataType: hasData  ? dataType || success : success
    }
  }

  $.get = function(url, data, success, dataType){
    return $.ajax(parseArguments.apply(null, arguments))
  }

  $.post = function(url, data, success, dataType){
    var options = parseArguments.apply(null, arguments)
    options.type = 'POST'
    return $.ajax(options)
  }

  $.getJSON = function(url, data, success){
    var options = parseArguments.apply(null, arguments)
    options.dataType = 'json'
    return $.ajax(options)
  }

  $.fn.load = function(url, data, success){
    if (!this.length) return this
    var self = this, parts = url.split(/\s/), selector,
        options = parseArguments(url, data, success),
        callback = options.success
    if (parts.length > 1) options.url = parts[0], selector = parts[1]
    options.success = function(response){
      self.html(selector ?
        $('<div>').html(response.replace(rscript, "")).find(selector)
        : response)
      callback && callback.apply(self, arguments)
    }
    $.ajax(options)
    return this
  }

  var escape = encodeURIComponent

  function serialize(params, obj, traditional, scope){
    var type, array = $.isArray(obj)
    $.each(obj, function(key, value) {
      type = $.type(value)
      if (scope) key = traditional ? scope : scope + '[' + (array ? '' : key) + ']'
      // handle data in serializeArray() format
      if (!scope && array) params.add(value.name, value.value)
      // recurse into nested objects
      else if (type == "array" || (!traditional && type == "object"))
        serialize(params, value, traditional, key)
      else params.add(key, value)
    })
  }

  $.param = function(obj, traditional){
    var params = []
    params.add = function(k, v){ this.push(escape(k) + '=' + escape(v)) }
    serialize(params, obj, traditional)
    return params.join('&').replace(/%20/g, '+')
  }
})(Zepto)
<|endoftext|>


<commit_before>var fs = require('fs');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var cache = require('gulp-cache');
var path = require('path');
var stream = require("event-stream")
var replace = require('gulp-replace-task');
var neon = require('neon-js/src/neon.js');

var configRaw = fs.readFileSync('./app/config/config.local.neon', 'utf8');
var config = neon.decode(configRaw);

var buildDir = './www/build';
var libDir = './www/libs';
var bsDir = './www/libs/bootstrap/less/';
var jsDir = './www/js';
var jsFiles = [
	path.join(jsDir, 'app/*.js'),
	path.join(jsDir, 'services/*.js'),
	path.join(jsDir, 'snippets/*.js'),
	path.join(jsDir, 'components/*.js'),
	path.join(jsDir, 'components/controls/*.js'),
	path.join(jsDir, 'components/forms/*.js'),
	path.join(jsDir, 'components/exercises/*.js')
];
var jsLibFiles = [
	path.join(libDir, 'bootstrap/js/alert.js'),
	path.join(libDir, 'bootstrap/js/tab.js'),
	path.join(libDir, 'bootstrap/js/modal.js'),
	path.join(libDir, 'jquery-timeago/jquery.timeago.js'),
	path.join(libDir, 'jquery-timeago/locales/jquery.timeago.cs.js'),
	path.join(libDir, 'nette-forms/src/assets/netteForms.js'),
	path.join(libDir, 'typeahead.js/dist/typeahead.jquery.min.js'),
	path.join(libDir, 'smooth-scroll/dist/js/smooth-scroll.js'),
	path.join(libDir, 'isInViewport/lib/isInViewport.min.js')
];
var jsAdminFiles = [
	path.join(jsDir, 'admin/*.js')
];
var jsAdminLibFiles = [
	path.join(libDir, 'jquery-ui/jquery-ui.min.js'),
	path.join(libDir, 'chosen/chosen.jquery.min.js'),
	path.join(libDir, 'zeroclipboard/dist/ZeroClipboard.min.js'),
	path.join(libDir, 'handsontable/dist/handsontable.full.min.js')
];
var lessDir = './www/less';
var lessBootstrapFiles = [
	path.join(bsDir, 'variables.less'),
	path.join(lessDir, 'variables.less'),

	path.join(bsDir, 'mixins.less'),
	path.join(bsDir, 'normalize.less'),
	//path.join(bsDir, 'print.less'),
	//path.join(bsDir, 'glyphicons.less'),
	path.join(bsDir, 'scaffolding.less'),
	path.join(bsDir, 'type.less'),
	//path.join(bsDir, 'code.less'),
	path.join(bsDir, 'grid.less'),
	//path.join(bsDir, 'tables.less'),
	path.join(bsDir, 'forms.less'),
	path.join(bsDir, 'buttons.less'),
	path.join(bsDir, 'component-animations.less'),
	path.join(bsDir, 'dropdowns.less'),
	//path.join(bsDir, 'button-groups.less'),
	//path.join(bsDir, 'input-groups.less'),
	path.join(bsDir, 'navs.less'),
	//path.join(bsDir, 'navbar.less'),
	//path.join(bsDir, 'breadcrumbs.less'),
	//path.join(bsDir, 'pagination.less'),
	//path.join(bsDir, 'pager.less'),
	//path.join(bsDir, 'labels.less'),
	//path.join(bsDir, 'badges.less'),
	//path.join(bsDir, 'jumbotron.less'),
	//path.join(bsDir, 'thumbnails.less'),
	path.join(bsDir, 'alerts.less'),
	//path.join(bsDir, 'progress-bars.less'),
	//path.join(bsDir, 'media.less'),
	//path.join(bsDir, 'list-group.less'),
	//path.join(bsDir, 'panels.less'),
	//path.join(bsDir, 'responsive-embed.less'),
	//path.join(bsDir, 'wells.less'),
	path.join(bsDir, 'close.less'),
	path.join(bsDir, 'modals.less'),
	//path.join(bsDir, 'tooltip.less'),
	//path.join(bsDir, 'popovers.less'),
	//path.join(bsDir, 'carousel.less'),
	path.join(bsDir, 'utilities.less'),
	path.join(bsDir, 'responsive-utilities.less')
];
var lessFiles = [
	path.join(bsDir, 'variables.less'),
	path.join(bsDir, 'mixins.less'),

	path.join(lessDir, 'variables.less'),
	path.join(lessDir, 'mixins.less'),
	path.join(lessDir, 'main/fonts/*.less'),
	path.join(lessDir, 'main/base.less'),
	path.join(lessDir, 'main/components/*.less'),
	path.join(lessDir, 'main/pages/*.less')
];
var lessAdminLibFiles = [
	path.join(libDir, 'chosen/chosen.min.css'),
	path.join(libDir, 'handsontable/dist/handsontable.full.min.css')
];
var lessAdminFiles = [
	path.join(lessDir, 'variables.less'),
	path.join(lessDir, 'mixins.less'),
	path.join(lessDir, 'admin/*.less'),
	path.join(lessDir, 'admin/pages/*.less')
];
var lessExperimentFiles = [
	path.join(lessDir, 'experiments/*.less')
];

gulp.task('less-dev-main', function() {
	return stream.concat(
		gulp.src(lessBootstrapFiles)
			.pipe($.concat('bootstrap.less'))
			.pipe(cache($.less())),
		gulp.src(lessFiles)
			.pipe($.sourcemaps.init())
			.pipe($.concat('main.less'))
			.pipe($.less())
			.pipe($.autoprefixer())
	)
		.pipe($.concat('main.css'))
		.pipe($.rename({suffix: '.min'}))
		.pipe($.sourcemaps.write('.', {
			sourceRoot: '../less'
		}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('less-dev-admin', function() {
	return stream.concat(
		gulp.src(lessAdminLibFiles),
		gulp.src(lessAdminFiles)
			.pipe($.sourcemaps.init())
			.pipe($.concat('main.admin.less'))
			.pipe($.less())
			.pipe($.autoprefixer())
	)
		.pipe($.concat('main.admin.css'))
		.pipe($.rename({suffix: '.min'}))
		.pipe($.sourcemaps.write('.', {
			sourceRoot: '../less'
		}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('less-experiment', function() {
	return gulp.src(lessExperimentFiles)
		.pipe($.concat('experiment.search.always.visible.less'))
		.pipe($.less())
		.pipe($.autoprefixer())
		.pipe($.cssmin())
		.pipe($.rename({suffix: '.min'}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('less-production-main', function() {
	return gulp.src(lessFiles)
		.pipe($.concat('main.less'))
		.pipe($.less())
		.pipe($.autoprefixer())
		.pipe($.cssmin())
		.pipe($.rename({suffix: '.min'}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('less-production-admin', function() {
	return stream.concat(
		gulp.src(lessAdminLibFiles),
		gulp.src(lessAdminFiles)
			.pipe($.concat('main.admin.less'))
			.pipe($.less())
			.pipe($.autoprefixer())
			.pipe($.cssmin())
	)
		.pipe($.concat('main.admin.css'))
		.pipe($.rename({suffix: '.min'}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('js-dev-main', function() {
	return stream.concat(
		gulp.src(jsLibFiles),
		gulp.src(jsFiles)
			.pipe($.sourcemaps.init())
			.pipe($.concat('app.min.js'))
			.pipe($.uglify())
			.pipe(replace({
				patterns: [{
					json: {
						elastic: {
							url: 'http://' + config.get('parameters').get('elastic').get('hosts').get(0) + ':9200',
							index: config.get('parameters').get('elastic').get('index')
						}
					}
				}]
			}))
	)
		.pipe($.concat('app.min.js'))
		.pipe($.sourcemaps.write('.', {
			sourceRoot: '../js'
		}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('js-dev-admin', function() {
	return stream.concat(
		gulp.src(jsAdminLibFiles),
		gulp.src(jsAdminFiles)
			.pipe($.sourcemaps.init())
			.pipe($.concat('app.admin.min.js'))
			.pipe($.uglify())
	)
		.pipe($.concat('app.admin.min.js'))
		.pipe($.sourcemaps.write('.', {
			sourceRoot: '../js'
		}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('js-production-main', function() {
	return stream.concat(
		gulp.src(jsLibFiles),
		gulp.src(jsFiles)
			.pipe($.concat('app.min.js'))
			.pipe($.uglify())
			.pipe(replace({
				patterns: [{
					json: {
						elastic: {
							url: 'https://elastic.khanovaskola.cz',
							index: config.get('parameters').get('elastic').get('index')
						}
					}
				}]
			}))
	)
		.pipe($.concat('app.min.js'))
		.pipe(gulp.dest(buildDir));
});

gulp.task('js-production-admin', function() {
	return stream.concat(
		gulp.src(jsAdminLibFiles),
		gulp.src(jsAdminFiles)
			.pipe($.concat('app.admin.min.js'))
			.pipe($.uglify())
	)
		.pipe($.concat('app.admin.min.js'))
		.pipe(gulp.dest(buildDir));
});

gulp.task('less-dev', ['less-dev-main', 'less-dev-admin']);
gulp.task('less', ['less-dev-main', 'less-dev-admin']);
gulp.task('less-production', ['less-production-main', 'less-production-admin']);

gulp.task('js-dev', ['js-dev-main', 'js-dev-admin']);
gulp.task('js', ['js-dev-main', 'js-dev-admin']);
gulp.task('js-production', ['js-production-main', 'js-production-admin']);

gulp.task('dev', ['less-dev', 'js-dev']);

gulp.task('production', ['less-production', 'js-production']);

gulp.task('default', ['dev']);
<commit_msg>fix less-production-main<commit_after>var fs = require('fs');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var cache = require('gulp-cache');
var path = require('path');
var stream = require("event-stream")
var replace = require('gulp-replace-task');
var neon = require('neon-js/src/neon.js');

var configRaw = fs.readFileSync('./app/config/config.local.neon', 'utf8');
var config = neon.decode(configRaw);

var buildDir = './www/build';
var libDir = './www/libs';
var bsDir = './www/libs/bootstrap/less/';
var jsDir = './www/js';
var jsFiles = [
	path.join(jsDir, 'app/*.js'),
	path.join(jsDir, 'services/*.js'),
	path.join(jsDir, 'snippets/*.js'),
	path.join(jsDir, 'components/*.js'),
	path.join(jsDir, 'components/controls/*.js'),
	path.join(jsDir, 'components/forms/*.js'),
	path.join(jsDir, 'components/exercises/*.js')
];
var jsLibFiles = [
	path.join(libDir, 'bootstrap/js/alert.js'),
	path.join(libDir, 'bootstrap/js/tab.js'),
	path.join(libDir, 'bootstrap/js/modal.js'),
	path.join(libDir, 'jquery-timeago/jquery.timeago.js'),
	path.join(libDir, 'jquery-timeago/locales/jquery.timeago.cs.js'),
	path.join(libDir, 'nette-forms/src/assets/netteForms.js'),
	path.join(libDir, 'typeahead.js/dist/typeahead.jquery.min.js'),
	path.join(libDir, 'smooth-scroll/dist/js/smooth-scroll.js'),
	path.join(libDir, 'isInViewport/lib/isInViewport.min.js')
];
var jsAdminFiles = [
	path.join(jsDir, 'admin/*.js')
];
var jsAdminLibFiles = [
	path.join(libDir, 'jquery-ui/jquery-ui.min.js'),
	path.join(libDir, 'chosen/chosen.jquery.min.js'),
	path.join(libDir, 'zeroclipboard/dist/ZeroClipboard.min.js'),
	path.join(libDir, 'handsontable/dist/handsontable.full.min.js')
];
var lessDir = './www/less';
var lessBootstrapFiles = [
	path.join(bsDir, 'variables.less'),
	path.join(lessDir, 'variables.less'),

	path.join(bsDir, 'mixins.less'),
	path.join(bsDir, 'normalize.less'),
	//path.join(bsDir, 'print.less'),
	//path.join(bsDir, 'glyphicons.less'),
	path.join(bsDir, 'scaffolding.less'),
	path.join(bsDir, 'type.less'),
	//path.join(bsDir, 'code.less'),
	path.join(bsDir, 'grid.less'),
	//path.join(bsDir, 'tables.less'),
	path.join(bsDir, 'forms.less'),
	path.join(bsDir, 'buttons.less'),
	path.join(bsDir, 'component-animations.less'),
	path.join(bsDir, 'dropdowns.less'),
	//path.join(bsDir, 'button-groups.less'),
	//path.join(bsDir, 'input-groups.less'),
	path.join(bsDir, 'navs.less'),
	//path.join(bsDir, 'navbar.less'),
	//path.join(bsDir, 'breadcrumbs.less'),
	//path.join(bsDir, 'pagination.less'),
	//path.join(bsDir, 'pager.less'),
	//path.join(bsDir, 'labels.less'),
	//path.join(bsDir, 'badges.less'),
	//path.join(bsDir, 'jumbotron.less'),
	//path.join(bsDir, 'thumbnails.less'),
	path.join(bsDir, 'alerts.less'),
	//path.join(bsDir, 'progress-bars.less'),
	//path.join(bsDir, 'media.less'),
	//path.join(bsDir, 'list-group.less'),
	//path.join(bsDir, 'panels.less'),
	//path.join(bsDir, 'responsive-embed.less'),
	//path.join(bsDir, 'wells.less'),
	path.join(bsDir, 'close.less'),
	path.join(bsDir, 'modals.less'),
	//path.join(bsDir, 'tooltip.less'),
	//path.join(bsDir, 'popovers.less'),
	//path.join(bsDir, 'carousel.less'),
	path.join(bsDir, 'utilities.less'),
	path.join(bsDir, 'responsive-utilities.less')
];
var lessFiles = [
	path.join(bsDir, 'variables.less'),
	path.join(bsDir, 'mixins.less'),

	path.join(lessDir, 'variables.less'),
	path.join(lessDir, 'mixins.less'),
	path.join(lessDir, 'main/fonts/*.less'),
	path.join(lessDir, 'main/base.less'),
	path.join(lessDir, 'main/components/*.less'),
	path.join(lessDir, 'main/pages/*.less')
];
var lessAdminLibFiles = [
	path.join(libDir, 'chosen/chosen.min.css'),
	path.join(libDir, 'handsontable/dist/handsontable.full.min.css')
];
var lessAdminFiles = [
	path.join(lessDir, 'variables.less'),
	path.join(lessDir, 'mixins.less'),
	path.join(lessDir, 'admin/*.less'),
	path.join(lessDir, 'admin/pages/*.less')
];
var lessExperimentFiles = [
	path.join(lessDir, 'experiments/*.less')
];

gulp.task('less-dev-main', function() {
	return stream.concat(
		gulp.src(lessBootstrapFiles)
			.pipe($.concat('bootstrap.less'))
			.pipe(cache($.less())),
		gulp.src(lessFiles)
			.pipe($.sourcemaps.init())
			.pipe($.concat('main.less'))
			.pipe($.less())
			.pipe($.autoprefixer())
	)
		.pipe($.concat('main.css'))
		.pipe($.rename({suffix: '.min'}))
		.pipe($.sourcemaps.write('.', {
			sourceRoot: '../less'
		}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('less-dev-admin', function() {
	return stream.concat(
		gulp.src(lessAdminLibFiles),
		gulp.src(lessAdminFiles)
			.pipe($.sourcemaps.init())
			.pipe($.concat('main.admin.less'))
			.pipe($.less())
			.pipe($.autoprefixer())
	)
		.pipe($.concat('main.admin.css'))
		.pipe($.rename({suffix: '.min'}))
		.pipe($.sourcemaps.write('.', {
			sourceRoot: '../less'
		}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('less-experiment', function() {
	return gulp.src(lessExperimentFiles)
		.pipe($.concat('experiment.search.always.visible.less'))
		.pipe($.less())
		.pipe($.autoprefixer())
		.pipe($.cssmin())
		.pipe($.rename({suffix: '.min'}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('less-production-main', function() {
	return stream.concat(
		gulp.src(lessBootstrapFiles)
			.pipe($.concat('bootstrap.less'))
			.pipe($.less()),
		gulp.src(lessFiles)
			.pipe($.concat('main.less'))
			.pipe($.less())
			.pipe($.autoprefixer())
	)
		.pipe($.concat('main.css'))
		.pipe($.cssmin())
		.pipe($.rename({suffix: '.min'}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('less-production-admin', function() {
	return stream.concat(
		gulp.src(lessAdminLibFiles),
		gulp.src(lessAdminFiles)
			.pipe($.concat('main.admin.less'))
			.pipe($.less())
			.pipe($.autoprefixer())
			.pipe($.cssmin())
	)
		.pipe($.concat('main.admin.css'))
		.pipe($.rename({suffix: '.min'}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('js-dev-main', function() {
	return stream.concat(
		gulp.src(jsLibFiles),
		gulp.src(jsFiles)
			.pipe($.sourcemaps.init())
			.pipe($.concat('app.min.js'))
			.pipe($.uglify())
			.pipe(replace({
				patterns: [{
					json: {
						elastic: {
							url: 'http://' + config.get('parameters').get('elastic').get('hosts').get(0) + ':9200',
							index: config.get('parameters').get('elastic').get('index')
						}
					}
				}]
			}))
	)
		.pipe($.concat('app.min.js'))
		.pipe($.sourcemaps.write('.', {
			sourceRoot: '../js'
		}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('js-dev-admin', function() {
	return stream.concat(
		gulp.src(jsAdminLibFiles),
		gulp.src(jsAdminFiles)
			.pipe($.sourcemaps.init())
			.pipe($.concat('app.admin.min.js'))
			.pipe($.uglify())
	)
		.pipe($.concat('app.admin.min.js'))
		.pipe($.sourcemaps.write('.', {
			sourceRoot: '../js'
		}))
		.pipe(gulp.dest(buildDir));
});

gulp.task('js-production-main', function() {
	return stream.concat(
		gulp.src(jsLibFiles),
		gulp.src(jsFiles)
			.pipe($.concat('app.min.js'))
			.pipe($.uglify())
			.pipe(replace({
				patterns: [{
					json: {
						elastic: {
							url: 'https://elastic.khanovaskola.cz',
							index: config.get('parameters').get('elastic').get('index')
						}
					}
				}]
			}))
	)
		.pipe($.concat('app.min.js'))
		.pipe(gulp.dest(buildDir));
});

gulp.task('js-production-admin', function() {
	return stream.concat(
		gulp.src(jsAdminLibFiles),
		gulp.src(jsAdminFiles)
			.pipe($.concat('app.admin.min.js'))
			.pipe($.uglify())
	)
		.pipe($.concat('app.admin.min.js'))
		.pipe(gulp.dest(buildDir));
});

gulp.task('less-dev', ['less-dev-main', 'less-dev-admin']);
gulp.task('less', ['less-dev-main', 'less-dev-admin']);
gulp.task('less-production', ['less-production-main', 'less-production-admin']);

gulp.task('js-dev', ['js-dev-main', 'js-dev-admin']);
gulp.task('js', ['js-dev-main', 'js-dev-admin']);
gulp.task('js-production', ['js-production-main', 'js-production-admin']);

gulp.task('dev', ['less-dev', 'js-dev']);

gulp.task('production', ['less-production', 'js-production']);

gulp.task('default', ['dev']);
<|endoftext|>


<commit_before>angular.module('app').controller('dataViewerCtrl', [
  '$scope',
  '$rootScope',
  '$log',
  '$state',
  '$timeout',
  'alertService',
  function($scope, $rootScope, $log, $state, $timeout, alertService) {
    $scope.setTitle('Mongotron Data Viewer');

    $scope.currentCollections = []; //collections stored while user is querying

    if (!$scope.currentConnections || !$scope.currentConnections.length) {
      $state.go('connect');
      return;
    } else {
      //collapse any accordions levels on view load
      _.each($scope.currentConnections, function(connection) {
        _collapseConnection(connection);
      });
    }

    // sidebar accordion functionality
    function _collapseConnection(connection) {
      connection.isOpen = false;

      _.each(connection.databases, function(database) {
        _collapseDatabase(database);
      });
    }

    function _collapseDatabase(database) {
      database.isOpen = false;
    }

    $scope.openConnection = function(connection) {
      if (!connection) return;

      if (!connection.isOpen) {
        connection.connect(function(err) {
          $timeout(function() {
            if (err) {
              alertService.error(err);
              connection.isOpen = false;
            } else {
              connection.isOpen = true;
            }
          });
        });
      } else {
        _collapseConnection(connection);
      }
    };

    $scope.openDatabase = function openDatabase(database) {
      if (!database) return;

      if (!database.isOpen) {
        database.opening = true;
        database.open(function(err) {
          $timeout(function() {
            database.opening = false;

            if (err) {
              return alertService.error(err);
            }

            database.isOpen = true;
          }, 500);
        });
      } else {
        _collapseDatabase(database);
      }

      database.showFolders = !database.showFolders;
    };

    $scope.listDatabaseCollections = function listDatabaseCollections(database) {
      if (!database) return;

      if (!database.collections || !database.collections.length) {
        database.loadingCollections = true;
        database.listCollections(function(err, collections) {
          $timeout(function() {
            database.loadingCollections = false;

            if (err) {
              return alertService.error(err);
            }

            database.collections = collections.map(function(collection) {
              collection.host = database.host;
              collection.port = database.port;
              return collection;
            });
          }, 500);
        });
      }

      database.showCollections = !database.showCollections;

      $scope.activateItem(database);
    };

    // content view tabs functionality
    $scope.loadCollection = function loadCollection(collection) {
      $scope.collections.push(collection);
    };

    $scope.activateItem = function activateItem(item, type) {
      if ($scope.currentActiveItem) {
        $scope.currentActiveItem.active = false;
      }
      $scope.currentActiveItem = item;
      $scope.currentActiveItem.active = true;

      switch (type) {
        case 'collection':
          $scope.currentCollections.push(item);
          $state.go('data-viewer.collections');
          break;
      }
    };
  }
]);
<commit_msg>don’t add duplicate collections<commit_after>angular.module('app').controller('dataViewerCtrl', [
  '$scope',
  '$rootScope',
  '$log',
  '$state',
  '$timeout',
  'alertService',
  function($scope, $rootScope, $log, $state, $timeout, alertService) {
    $scope.setTitle('Mongotron Data Viewer');

    $scope.currentCollections = []; //collections stored while user is querying

    if (!$scope.currentConnections || !$scope.currentConnections.length) {
      $state.go('connect');
      return;
    } else {
      //collapse any accordions levels on view load
      _.each($scope.currentConnections, function(connection) {
        _collapseConnection(connection);
      });
    }

    // sidebar accordion functionality
    function _collapseConnection(connection) {
      connection.isOpen = false;

      _.each(connection.databases, function(database) {
        _collapseDatabase(database);
      });
    }

    function _collapseDatabase(database) {
      database.isOpen = false;
    }

    $scope.openConnection = function(connection) {
      if (!connection) return;

      if (!connection.isOpen) {
        connection.connect(function(err) {
          $timeout(function() {
            if (err) {
              alertService.error(err);
              connection.isOpen = false;
            } else {
              connection.isOpen = true;
            }
          });
        });
      } else {
        _collapseConnection(connection);
      }
    };

    $scope.openDatabase = function openDatabase(database) {
      if (!database) return;

      if (!database.isOpen) {
        database.opening = true;
        database.open(function(err) {
          $timeout(function() {
            database.opening = false;

            if (err) {
              return alertService.error(err);
            }

            database.isOpen = true;
          }, 500);
        });
      } else {
        _collapseDatabase(database);
      }

      database.showFolders = !database.showFolders;
    };

    $scope.listDatabaseCollections = function listDatabaseCollections(database) {
      if (!database) return;

      if (!database.collections || !database.collections.length) {
        database.loadingCollections = true;
        database.listCollections(function(err, collections) {
          $timeout(function() {
            database.loadingCollections = false;

            if (err) {
              return alertService.error(err);
            }

            database.collections = collections.map(function(collection) {
              collection.databaseName = database.name;
              collection.databaseHost = database.host;
              collection.databasePort = database.port;
              return collection;
            });
          }, 500);
        });
      }

      database.showCollections = !database.showCollections;

      $scope.activateItem(database);
    };

    // content view tabs functionality
    $scope.loadCollection = function loadCollection(collection) {
      $scope.collections.push(collection);
    };

    $scope.activateItem = function activateItem(item, type) {
      if ($scope.currentActiveItem) {
        $scope.currentActiveItem.active = false;
      }
      $scope.currentActiveItem = item;
      $scope.currentActiveItem.active = true;

      switch (type) {
        case 'collection':
          _addCollection(item);
          break;
      }
    };

    function _addCollection(collection) {
      if (!collection) return;

      var existingCollection = _.findWhere($scope.currentCollections, {
        databaseName: collection.databaseName,
        collectionName: collection.collectionName
      });

      if (!existingCollection) $scope.currentCollections.push(collection);

      $state.go('data-viewer.collections');
    }
  }
]);
<|endoftext|>


<commit_before>define(
	[
		openhmis.url.backboneBase + 'js/lib/jquery',
		openhmis.url.backboneBase + 'js/lib/backbone',
		openhmis.url.backboneBase + 'js/lib/underscore',
		openhmis.url.backboneBase + 'js/lib/backbone-forms',
		openhmis.url.backboneBase + 'js/lib/labelOver',
	],
	function($, Backbone, _, openhmis) {
		var editors = Backbone.Form.editors;

		editors.BasicNumber = editors.Number.extend({
			initialize: function(options) {
				this.defaultValue = null;
				editors.Text.prototype.initialize.call(this, options);
			},

			/**
			* Check value is numeric
			*/
			onKeyPress: function(event) {
				var self = this,
					delayedDetermineChange = function() {
					  setTimeout(function() {
						self.determineChange();
					  }, 0);
					}

				//Allow backspace && enter
				if (event.which == 8 || event.which == 13) {
				  delayedDetermineChange();
				  return;
				}

				//Get the whole new value so that we can prevent things like double decimals points etc.
				var newVal = this.$el.val() + String.fromCharCode(event.which);

				var numeric = /^[0-9]*\.?[0-9]*?$/.test(newVal);

				if (numeric) {
				  delayedDetermineChange();
				}
				else {
				  event.preventDefault();
				}
		   },

		   setValue: function(value) {
				if (value !== undefined && value !== null && this.schema.format)
					this.$el.val(this.schema.format(value));
				else
					this.$el.val(value);
		   }
		});

		editors.CustomNumber = editors.Number.extend({
			initialize: function(options) {
				this.events = _.extend(this.events, {
					'click': 'determineChange'
				});
				editors.Number.prototype.initialize.call(this, options);
				if (options && options.schema) this.minimum = options.schema.minimum;
			},

			onKeyPress: function(event) {
			  var self = this,
				  delayedDetermineChange = function() {
					setTimeout(function() {
					  self.determineChange();
					}, 0);
				  }

			  //Allow backspace and minus character
			  if (event.which == 8 || event.which == 45) {
				delayedDetermineChange();
				return;
			  }

			  //Get the whole new value so that we can prevent things like double decimals points etc.
			  var newVal = this.$el.val() + String.fromCharCode(event.which);

			  var numeric = /^[0-9]*\.?[0-9]*?$/.test(newVal);

			  if (numeric) {
				delayedDetermineChange();
			  }
			  else {
				event.preventDefault();
			  }
			},

			setValue: function(value) {
				this.el.defaultValue = value;
				editors.Number.prototype.setValue.call(this, value);
			},

			determineChange: function(event) {
				if (this.minimum && parseInt(this.$el.val()) < this.minimum) {
					this.$el.val(this.minimum);
					return;
				}
				editors.Number.prototype.determineChange.call(this, event);
			}
			//valueChanged: function(event) {
			//		this.$el.val(this.el.defaultValue);
			//		return;
			//	}
			//	event.target.defaultValue = event.target.value;
			//}
		});

		editors.GenericModelSelect = editors.Select.extend({
		    getValue: function() {
				$selected = this.$('option:selected');
				var model = new this.modelType({ uuid: $selected.val() })
				model.set(this.displayAttr, $selected.text());
				return model;
			},

			setValue: function(value) {
				var flt = parseFloat(value);
				if (value === null)
					return;
				else if (_.isString(value))
					this.$el.val(value);
				else if (value.attributes)
					this.$el.val(value.id); // Backbone model
				// This should be after Backbone model because it can evaluate
				// to a number :S
				else if (!isNaN(parseFloat(value)))
					this.$el.val(value);
				else
					this.$el.val(value.uuid); // bare object
			},

			render: function() {
				if (this.options.options !== undefined)
					this.setOptions(this.options.options);
				else
					this.setOptions(this.schema.options);
				return this;
			}
		});

		return editors;
	}
)
<commit_msg>Added option to select contents of number fields upon focus; factored out regular expression to check if a string is numeric, and added support for negative numbers.<commit_after>define(
	[
		openhmis.url.backboneBase + 'js/lib/jquery',
		openhmis.url.backboneBase + 'js/lib/backbone',
		openhmis.url.backboneBase + 'js/lib/underscore',
		openhmis.url.backboneBase + 'js/lib/backbone-forms',
		openhmis.url.backboneBase + 'js/lib/labelOver',
	],
	function($, Backbone, _, openhmis) {
		var editors = Backbone.Form.editors;

		editors.isNumeric = function(strVal) {
			return /^-?[0-9]*\.?[0-9]*?$/.test(strVal);
		}

		editors.BasicNumber = editors.Number.extend({
			initialize: function(options) {
				this.defaultValue = null;
				editors.Text.prototype.initialize.call(this, options);
			},

			/**
			* Check value is numeric
			*/
			onKeyPress: function(event) {
				var self = this,
					delayedDetermineChange = function() {
					  setTimeout(function() {
						self.determineChange();
					  }, 0);
					}

				//Allow backspace && enter
				if (event.which == 8 || event.which == 13) {
				  delayedDetermineChange();
				  return;
				}

				//Get the whole new value so that we can prevent things like double decimals points etc.
				var newVal = this.$el.val() + String.fromCharCode(event.which);

				if (editors.isNumeric(newVal)) {
				  delayedDetermineChange();
				}
				else {
				  event.preventDefault();
				}
		   },

		   setValue: function(value) {
				if (value !== undefined && value !== null && this.schema.format)
					this.$el.val(this.schema.format(value));
				else
					this.$el.val(value);
		   },

		   focus: function(select) {
				editors.Number.prototype.focus.call(this);
				if (select === true) this.$el.select();
		   }
		});

		editors.CustomNumber = editors.Number.extend({
			initialize: function(options) {
				this.events = _.extend(this.events, {
					'click': 'determineChange'
				});
				editors.Number.prototype.initialize.call(this, options);
				if (options && options.schema) this.minimum = options.schema.minimum;
			},

			onKeyPress: function(event) {
			  var self = this,
				  delayedDetermineChange = function() {
					setTimeout(function() {
					  self.determineChange();
					}, 0);
				  }

			  //Allow backspace and minus character
			  if (event.which == 8 || event.which == 45) {
				delayedDetermineChange();
				return;
			  }

			  //Get the whole new value so that we can prevent things like double decimals points etc.
			  var newVal = this.$el.val() + String.fromCharCode(event.which);

			  if (editors.isNumeric(newVal)) {
				delayedDetermineChange();
			  }
			  else {
				event.preventDefault();
			  }
			},

			setValue: function(value) {
				this.el.defaultValue = value;
				editors.Number.prototype.setValue.call(this, value);
			},

			determineChange: function(event) {
				if (this.minimum && parseInt(this.$el.val()) < this.minimum) {
					this.$el.val(this.minimum);
					return;
				}
				editors.Number.prototype.determineChange.call(this, event);
			},

		   focus: function(select) {
				editors.Number.prototype.focus.call(this);
				if (select === true) this.$el.select();
		   }
		});

		editors.GenericModelSelect = editors.Select.extend({
		    getValue: function() {
				$selected = this.$('option:selected');
				var model = new this.modelType({ uuid: $selected.val() })
				model.set(this.displayAttr, $selected.text());
				return model;
			},

			setValue: function(value) {
				var flt = parseFloat(value);
				if (value === null)
					return;
				else if (_.isString(value))
					this.$el.val(value);
				else if (value.attributes)
					this.$el.val(value.id); // Backbone model
				// This should be after Backbone model because it can evaluate
				// to a number :S
				else if (!isNaN(parseFloat(value)))
					this.$el.val(value);
				else
					this.$el.val(value.uuid); // bare object
			},

			render: function() {
				if (this.options.options !== undefined)
					this.setOptions(this.options.options);
				else
					this.setOptions(this.schema.options);
				return this;
			}
		});

		return editors;
	}
)
<|endoftext|>


<commit_before>/*
 *  SettingScene.js
 *  2014/06/25
 *  @auther minimo
 *  This Program is MIT license.
 *
 */

tm.define("shotgun.SettingScene", {
    superClass: tm.app.Scene,

    bgm: null,
    se: null,

    //ラベル用フォントパラメータ
    headerParam: {fontFamily:"CasinoRegular", align: "center", baseline:"middle", outlineWidth:2 },
    labelParam: {fontFamily:"azuki", align: "center", baseline:"middle", outlineWidth:2 },

    init: function() {
        this.superInit();
        this.background = "rgba(0, 0, 0, 0.0)";
        var that = this;

        //バックグラウンド
        tm.display.Shape(SC_W, SC_H)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.5)
            .renderRectangle({fillStyle: appMain.bgColor, strokeStyle: appMain.bgColor});

        tm.display.OutlineLabel("OPTION", 60)
            .addChildTo(this)
            .setParam(this.headerParam)
            .setPosition(SC_W*0.5, SC_H*0.1);

        tm.display.OutlineLabel("SOUND SETTING", 50)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.5, SC_H*0.2);

        //ＢＧＭ音量
        var volBGM = appMain.sounds.volumeBGM;
        tm.display.OutlineLabel("BGM", 60)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.1, SC_H*0.3);
        this.bgm = [];
        for (var i = 0; i < 10; i++) {
            this.bgm[i] = tm.display.Sprite("card", CARD_W, CARD_H)
                .addChildTo(this)
                .setScale(0.3)
                .setPosition(SC_W*0.25+i*44, SC_H*0.3)
        }
        this.setVolumeBGM(appMain.sounds.volumeBGM);

        //ＳＥ音量
        var volSE = appMain.sounds.volumeSE;
        tm.display.OutlineLabel("SE", 60)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.1, SC_H*0.4);
        this.se = [];
        for (var i = 0; i < 10; i++) {
            this.se[i] = tm.display.Sprite("card", CARD_W, CARD_H)
                .addChildTo(this)
                .setScale(0.3)
                .setPosition(SC_W*0.25+i*44, SC_H*0.4)
        }
        this.setVolumeSE(appMain.sounds.volumeSE);

        tm.display.OutlineLabel("GAME SETTING", 50)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.5, SC_H*0.5);

        //ジョーカー戻り設定ボタン
        var that = this;
        tm.display.OutlineLabel("RETURN JOKER", 50)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.3, SC_H*0.7);
        var width = 150, height = 70;
        this.retJoker = shotgun.ToggleButton(width, height, "ON", "OFF")
            .addChildTo(this)
            .setPosition(SC_W*0.8, SC_H*0.7)
            .addEventListener("pushed", function() {
                appMain.returnJoker = that.retJoker.toggleON;
            });
        this.retJoker.toggleON = appMain.returnJoker;

        //戻るボタン
        var width = 300, height = 70;
        shotgun.Button(width, height, "RETURN")
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.85)
            .addEventListener("pushed", function() {
                that.mask.tweener.clear().fadeOut(200);
                appMain.saveConfig();
                appMain.popScene();
            });

        //目隠し
        this.mask = tm.display.Shape(SC_W, SC_H)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.5)
            .renderRectangle({fillStyle: "rgba(0, 0, 0, 1.0)", strokeStyle: "rgba(0, 0, 0, 1.0)"});
        this.mask.tweener.clear().fadeOut(200);

        //サウンドテスト
//        this.addSountTestButton();

        this.time = 0;
    },

    setVolumeBGM: function(vol) {
        if (vol != appMain.sounds.volumeBGM) {
            appMain.sounds.pauseBGM();
            appMain.sounds.setVolumeBGM(vol);
            appMain.sounds.resumeBGM();
        }
        for (var i = 0; i < 10; i++) {
            this.bgm[i].setFrameIndex(52).setScale(0.3);
            if (i == vol-1) {
                this.bgm[i].remove().addChildTo(this);
                this.bgm[i].setFrameIndex(i).setScale(0.5);
            } else {
                this.bgm[i].setFrameIndex(52).setScale(0.3);
            }
        }
    },

    setVolumeSE: function(vol) {
        if (vol != appMain.sounds.volumeSE) {
            appMain.sounds.setVolumeSE(vol);
            appMain.playSE("hand");
        }
        for (var i = 0; i < 10; i++) {
            this.se[i].setFrameIndex(53).setScale(0.3);
            if (i == vol-1) {
                this.se[i].remove().addChildTo(this);
                this.se[i].setFrameIndex(i+13*3).setScale(0.5);
            } else {
                this.se[i].setFrameIndex(53).setScale(0.3);
            }
        }
    },

    //サウンドテストボタン追加
    addSoundTestButton: function() {
        var width = 150, height = 70;
        shotgun.Button(width, height, "BGM1")
            .addChildTo(this)
            .setPosition(SC_W*0.2, SC_H*0.7)
            .addEventListener("pushed", function() {
                tm.asset.AssetManager.get("titleBGM").clone().play();
            });
        shotgun.Button(width, height, "BGM2")
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.7)
            .addEventListener("pushed", function() {
                tm.asset.AssetManager.get("mainBGM").clone().play();
            });
        shotgun.Button(width, height, "BGM3")
            .addChildTo(this)
            .setPosition(SC_W*0.8, SC_H*0.7)
            .addEventListener("pushed", function() {
                tm.asset.AssetManager.get("tutorialBGM").clone().play();
            });

        var width = 100, height = 70;
        shotgun.Button(width, height, "SE1")
            .addChildTo(this)
            .setPosition(SC_W*0.1, SC_H*0.8)
            .addEventListener("pushed", function() {
                tm.asset.AssetManager.get("countdown").clone().play();
            });
        shotgun.Button(width, height, "SE2")
            .addChildTo(this)
            .setPosition(SC_W*0.3, SC_H*0.8)
            .addEventListener("pushed", function() {
                tm.asset.AssetManager.get("deal").clone().play();
            });
        shotgun.Button(width, height, "SE3")
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.8)
            .addEventListener("pushed", function() {
                tm.asset.AssetManager.get("dist").clone().play();
            });
        shotgun.Button(width, height, "SE4")
            .addChildTo(this)
            .setPosition(SC_W*0.7, SC_H*0.8)
            .addEventListener("pushed", function() {
                tm.asset.AssetManager.get("hand").clone().play();
            });
        shotgun.Button(width, height, "SE5")
            .addChildTo(this)
            .setPosition(SC_W*0.9, SC_H*0.8)
            .addEventListener("pushed", function() {
                tm.asset.AssetManager.get("nopair").clone().play();
            });
    },

    update: function() {
        this.time++;
    },

    //タッチorクリック開始処理
    ontouchstart: function(e) {
    },

    //タッチorクリック移動処理
    ontouchmove: function(e) {
        var sx = e.pointing.x;
        var sy = e.pointing.y;

        sx += 22;
        if (SC_W*0.10 < sx && sx < SC_W*0.25+440) {
            sx -= SC_W*0.25;
            var x = ~~(sx/44)+1;
            //ＢＧＭボリューム
            if ( SC_H*0.25 < sy && sy < SC_H*0.35) {
                if (sx < 0) {
                    this.setVolumeBGM(0);
                } else {
                    this.setVolumeBGM(x);
                }
            }

            //ＳＥボリューム
            if ( SC_H*0.35 < sy && sy < SC_H*0.45) {
                if (sx < 0) {
                    this.setVolumeSE(0);
                } else {
                    this.setVolumeSE(x);
                }
            }
        }
    },

    //タッチorクリック終了処理
    ontouchend: function(e) {
    },
});

<commit_msg>不要コード削除<commit_after>/*
 *  SettingScene.js
 *  2014/06/25
 *  @auther minimo
 *  This Program is MIT license.
 *
 */

tm.define("shotgun.SettingScene", {
    superClass: tm.app.Scene,

    bgm: null,
    se: null,

    //ラベル用フォントパラメータ
    headerParam: {fontFamily:"CasinoRegular", align: "center", baseline:"middle", outlineWidth:2 },
    labelParam: {fontFamily:"azuki", align: "center", baseline:"middle", outlineWidth:2 },

    init: function() {
        this.superInit();
        this.background = "rgba(0, 0, 0, 0.0)";
        var that = this;

        //バックグラウンド
        tm.display.Shape(SC_W, SC_H)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.5)
            .renderRectangle({fillStyle: appMain.bgColor, strokeStyle: appMain.bgColor});

        tm.display.OutlineLabel("OPTION", 60)
            .addChildTo(this)
            .setParam(this.headerParam)
            .setPosition(SC_W*0.5, SC_H*0.1);

        tm.display.OutlineLabel("SOUND SETTING", 50)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.5, SC_H*0.2);

        //ＢＧＭ音量
        var volBGM = appMain.sounds.volumeBGM;
        tm.display.OutlineLabel("BGM", 60)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.1, SC_H*0.3);
        this.bgm = [];
        for (var i = 0; i < 10; i++) {
            this.bgm[i] = tm.display.Sprite("card", CARD_W, CARD_H)
                .addChildTo(this)
                .setScale(0.3)
                .setPosition(SC_W*0.25+i*44, SC_H*0.3)
        }
        this.setVolumeBGM(appMain.sounds.volumeBGM);

        //ＳＥ音量
        var volSE = appMain.sounds.volumeSE;
        tm.display.OutlineLabel("SE", 60)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.1, SC_H*0.4);
        this.se = [];
        for (var i = 0; i < 10; i++) {
            this.se[i] = tm.display.Sprite("card", CARD_W, CARD_H)
                .addChildTo(this)
                .setScale(0.3)
                .setPosition(SC_W*0.25+i*44, SC_H*0.4)
        }
        this.setVolumeSE(appMain.sounds.volumeSE);

        tm.display.OutlineLabel("GAME SETTING", 50)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.5, SC_H*0.5);

        //ジョーカー戻り設定ボタン
        var that = this;
        tm.display.OutlineLabel("RETURN JOKER", 50)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.3, SC_H*0.7);
        var width = 150, height = 70;
        this.retJoker = shotgun.ToggleButton(width, height, "ON", "OFF")
            .addChildTo(this)
            .setPosition(SC_W*0.8, SC_H*0.7)
            .addEventListener("pushed", function() {
                appMain.returnJoker = that.retJoker.toggleON;
            });
        this.retJoker.toggleON = appMain.returnJoker;

        //戻るボタン
        var width = 300, height = 70;
        shotgun.Button(width, height, "RETURN")
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.85)
            .addEventListener("pushed", function() {
                that.mask.tweener.clear().fadeOut(200);
                appMain.saveConfig();
                appMain.popScene();
            });

        //目隠し
        this.mask = tm.display.Shape(SC_W, SC_H)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.5)
            .renderRectangle({fillStyle: "rgba(0, 0, 0, 1.0)", strokeStyle: "rgba(0, 0, 0, 1.0)"});
        this.mask.tweener.clear().fadeOut(200);

        this.time = 0;
    },

    setVolumeBGM: function(vol) {
        if (vol != appMain.sounds.volumeBGM) {
            appMain.sounds.pauseBGM();
            appMain.sounds.setVolumeBGM(vol);
            appMain.sounds.resumeBGM();
        }
        for (var i = 0; i < 10; i++) {
            this.bgm[i].setFrameIndex(52).setScale(0.3);
            if (i == vol-1) {
                this.bgm[i].remove().addChildTo(this);
                this.bgm[i].setFrameIndex(i).setScale(0.5);
            } else {
                this.bgm[i].setFrameIndex(52).setScale(0.3);
            }
        }
    },

    setVolumeSE: function(vol) {
        if (vol != appMain.sounds.volumeSE) {
            appMain.sounds.setVolumeSE(vol);
            appMain.playSE("hand");
        }
        for (var i = 0; i < 10; i++) {
            this.se[i].setFrameIndex(53).setScale(0.3);
            if (i == vol-1) {
                this.se[i].remove().addChildTo(this);
                this.se[i].setFrameIndex(i+13*3).setScale(0.5);
            } else {
                this.se[i].setFrameIndex(53).setScale(0.3);
            }
        }
    },

    update: function() {
        this.time++;
    },

    //タッチorクリック開始処理
    ontouchstart: function(e) {
    },

    //タッチorクリック移動処理
    ontouchmove: function(e) {
        var sx = e.pointing.x;
        var sy = e.pointing.y;

        sx += 22;
        if (SC_W*0.10 < sx && sx < SC_W*0.25+440) {
            sx -= SC_W*0.25;
            var x = ~~(sx/44)+1;
            //ＢＧＭボリューム
            if ( SC_H*0.25 < sy && sy < SC_H*0.35) {
                if (sx < 0) {
                    this.setVolumeBGM(0);
                } else {
                    this.setVolumeBGM(x);
                }
            }

            //ＳＥボリューム
            if ( SC_H*0.35 < sy && sy < SC_H*0.45) {
                if (sx < 0) {
                    this.setVolumeSE(0);
                } else {
                    this.setVolumeSE(x);
                }
            }
        }
    },

    //タッチorクリック終了処理
    ontouchend: function(e) {
    },
});

<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    var PlayerMove = move || 'getInput()';
    return PlayerMove;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    var ComputerMove = move || 'randomPlay()';
    return ComputerMove;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    if (playerMove == computerMove) {
        winner = 'tie';
    } else if (playerMove == 'rock') {
        if (computerMove == 'paper') {
            winner = 'computer';
        } else {
            winner = 'player';
        }
    } else if (playerMove == 'paper') {
        if (computerMove == 'rock') {
            winner = 'player';
        } else {
            winner = 'computer';
        }
    } else if (playerMove == 'scissors') {
        if (computerMove == 'rock') {
            winner = 'computer';
        } else {
            winner = 'player';
        }
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>added playToFive<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    var playerMove = move || getInput();
    return playerMove;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    var computerMove = move || randomPlay();
    return computerMove;
}

function getWinner(playerMove, computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    if (playerMove == computerMove) {
        winner = 'tie';
    } else if (playerMove == 'rock') {
        if (computerMove == 'paper') {
            winner = 'computer';
        } else {
            winner = 'player';
        }
    } else if (playerMove == 'paper') {
        if (computerMove == 'rock') {
            winner = 'player';
        } else {
            winner = 'computer';
        }
    } else if (playerMove == 'scissors') {
        if (computerMove == 'rock') {
            winner = 'computer';
        } else {
            winner = 'player';
        }
    }
    return winner;
}
function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    while (playerWins < 5 && computerWins < 5) {
        var playerMove = getPlayerMove();
      var computerMove = getComputerMove();
      var winner = getWinner(playerMove, computerMove);
      if (winner == 'tie') {
        console.log("Player chose " + playerMove + " and Computer chose " + computerMove);
        console.log("It's a tie!");
        console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
      } else if (winner == 'player') {
        playerWins +=1;
        console.log("Player chose " + playerMove + " and Computer chose" + computerMove);
        console.log("Player wins!");
        console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
      } else {
        computerWins +=1;
        console.log("Player chose " + playerMove + " and Computer chose " + computerMove);
        console.log("Computer wins!");
        console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
      }
    }
    // This function should continue to play Rock Paper Scissors until either the
  // player or the computer has won five times.
  // After each 'round', display some text in the console indicating who played
  // what, who won, and what the current scoreboard looks like.
  // For example,
  //  console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
  //  console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
  /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

playToFive();<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const { has, toNumber, isUndefined, isPlainObject } = require('lodash/fp');

/**
 * Default limit values from config
 * @return {{maxLimit: number, defaultLimit: number}}
 */
const getLimitConfigDefaults = () => ({
  defaultLimit: toNumber(strapi.config.get('api.rest.defaultLimit', 25)),
  maxLimit: toNumber(strapi.config.get('api.rest.maxLimit')) || null,
});

/**
 * if there is max limit set and limit exceeds this number, return configured max limit
 * @param {number} limit - limit you want to cap
 * @param {number?} maxLimit - maxlimit used has capping
 * @returns {number}
 */
const applyMaxLimit = (limit, maxLimit) => {
  if (maxLimit && (limit === -1 || limit > maxLimit)) {
    return maxLimit;
  }

  return limit;
};

const shouldCount = params => {
  if (_.has(params, 'pagination.withCount')) {
    return params.pagination.withCount === 'false' ? false : true;
  }

  return Boolean(strapi.config.get('api.rest.withCount', true));
};

const isOffsetPagination = pagination => has('start', pagination) || has('limit', pagination);
const isPagedPagination = pagination => has('page', pagination) || has('page', pagination);

const getPaginationInfo = params => {
  const { defaultLimit, maxLimit } = getLimitConfigDefaults();

  if (isUndefined(params.pagination) || !isPlainObject(params.pagination)) {
    return {
      page: 1,
      pageSize: defaultLimit,
    };
  }

  const { pagination } = params;

  if (isOffsetPagination(pagination) && isPagedPagination(pagination)) {
    throw new Error('Invalid pagination parameters. Expected either start/limit or page/pageSize');
  }

  if (isPagedPagination(pagination)) {
    const pageSize = isUndefined(pagination.pageSize)
      ? defaultLimit
      : Math.max(1, toNumber(pagination.pageSize));

    return {
      page: Math.max(1, toNumber(pagination.page || 1)),
      pageSize: applyMaxLimit(pageSize, maxLimit),
    };
  }

  const limit = isUndefined(pagination.limit)
    ? defaultLimit
    : Math.max(1, toNumber(pagination.limit));

  return {
    start: Math.max(0, toNumber(pagination.start || 0)),
    limit: applyMaxLimit(limit, maxLimit),
  };
};

const convertPagedToStartLimit = pagination => {
  if (_.has(pagination, 'page')) {
    const { page, pageSize } = pagination;
    return {
      start: (page - 1) * pageSize,
      limit: pageSize,
    };
  }

  return pagination;
};

const transformPaginationResponse = (paginationInfo, count) => {
  if (paginationInfo.page) {
    return {
      ...paginationInfo,
      pageCount: Math.ceil(count / paginationInfo.pageSize),
      total: count,
    };
  }

  return {
    ...paginationInfo,
    total: count,
  };
};

module.exports = {
  getPaginationInfo,
  convertPagedToStartLimit,
  transformPaginationResponse,
  shouldCount,
};
<commit_msg>Fix wrong parameter name check<commit_after>'use strict';

const _ = require('lodash');
const { has, toNumber, isUndefined, isPlainObject } = require('lodash/fp');

/**
 * Default limit values from config
 * @return {{maxLimit: number, defaultLimit: number}}
 */
const getLimitConfigDefaults = () => ({
  defaultLimit: toNumber(strapi.config.get('api.rest.defaultLimit', 25)),
  maxLimit: toNumber(strapi.config.get('api.rest.maxLimit')) || null,
});

/**
 * if there is max limit set and limit exceeds this number, return configured max limit
 * @param {number} limit - limit you want to cap
 * @param {number?} maxLimit - maxlimit used has capping
 * @returns {number}
 */
const applyMaxLimit = (limit, maxLimit) => {
  if (maxLimit && (limit === -1 || limit > maxLimit)) {
    return maxLimit;
  }

  return limit;
};

const shouldCount = params => {
  if (_.has(params, 'pagination.withCount')) {
    return params.pagination.withCount === 'false' ? false : true;
  }

  return Boolean(strapi.config.get('api.rest.withCount', true));
};

const isOffsetPagination = pagination => has('start', pagination) || has('limit', pagination);
const isPagedPagination = pagination => has('page', pagination) || has('pageSize', pagination);

const getPaginationInfo = params => {
  const { defaultLimit, maxLimit } = getLimitConfigDefaults();

  if (isUndefined(params.pagination) || !isPlainObject(params.pagination)) {
    return {
      page: 1,
      pageSize: defaultLimit,
    };
  }

  const { pagination } = params;

  if (isOffsetPagination(pagination) && isPagedPagination(pagination)) {
    throw new Error('Invalid pagination parameters. Expected either start/limit or page/pageSize');
  }

  if (isPagedPagination(pagination)) {
    const pageSize = isUndefined(pagination.pageSize)
      ? defaultLimit
      : Math.max(1, toNumber(pagination.pageSize));

    return {
      page: Math.max(1, toNumber(pagination.page || 1)),
      pageSize: applyMaxLimit(pageSize, maxLimit),
    };
  }

  const limit = isUndefined(pagination.limit)
    ? defaultLimit
    : Math.max(1, toNumber(pagination.limit));

  return {
    start: Math.max(0, toNumber(pagination.start || 0)),
    limit: applyMaxLimit(limit, maxLimit),
  };
};

const convertPagedToStartLimit = pagination => {
  if (_.has(pagination, 'page')) {
    const { page, pageSize } = pagination;
    return {
      start: (page - 1) * pageSize,
      limit: pageSize,
    };
  }

  return pagination;
};

const transformPaginationResponse = (paginationInfo, count) => {
  if (paginationInfo.page) {
    return {
      ...paginationInfo,
      pageCount: Math.ceil(count / paginationInfo.pageSize),
      total: count,
    };
  }

  return {
    ...paginationInfo,
    total: count,
  };
};

module.exports = {
  getPaginationInfo,
  convertPagedToStartLimit,
  transformPaginationResponse,
  shouldCount,
};
<|endoftext|>


<commit_before>/**
 * @module src/UploadSource
 *
 * Component that display SourceDocument
 * Accepts the following properties:
 *  - language: Ethnologue code of the language
 *  - content: Content of all the source documents stored
 *  - Access ID & Key: Returned as a response after authentication
*/

import React, { Component } from 'react';
import './App.css';
import Header from './Header';
import Footer from './Footer';
import { FormControl } from 'react-bootstrap';
import SourceLanguages from './SourceLanguages';
import $ from 'jquery';

class UploadSource extends Component {
  constructor(props) {
    super(props);

    this.state = {
      language:'',
      version: '',
      base64_arr: [],
      uploaded:'Uploading'
    }

      // Upload file specific callback handlers
      this.uploadFile = this.uploadFile.bind(this);
      this.onSelect = this.onSelect.bind(this);
      this.file_base64 = this.file_base64.bind(this);
  }

  onSelect(e) {
    this.setState({
      [e.target.name]: e.target.value });
  }

  file_base64(e){
    var files = document.getElementById('file-input').files;
    var file = files[0]
    global.base64_arr = [];
    if(files.length > 0){
      for (var i = 0; i < files.length; i++) {
        var reader = new FileReader();
        reader.readAsDataURL(files[0]);
        reader.onload = (function (file) {
          return function (e) {
            var data = this.result;
            var unwantedData = "data:;base64,";
            data = data.replace(unwantedData, "");
            global.base64_arr.push(data);
          }
        })(file);
        reader.onerror = function (error) {
         console.log('Error: ', error);
        };
      }
    }

  }

  uploadFile(e){

    e.preventDefault();
    var ext = $('#file-input').val().split('.').pop().toLowerCase();
    if($.inArray(ext, ['usfm']) === -1) {
      // alert("File is not valid");
      this.setState({uploaded: 'success'})
    } else {
      // alert("File is valid");
      this.setState({uploaded: 'failure'})
    }

    var _this = this
    var data = {
            "language": this.state.language, "version": this.state.version, "content": global.base64_arr
          }

    let accessToken = JSON.parse(window.localStorage.getItem('access_token'))

    $.ajax({
      url: "http://127.0.0.1:8000/v1/sources",
      contentType: "application/json; charset=utf-8",
      data : JSON.stringify(data),
      method : "POST",
      headers: {
                "Authorization": "bearer " + JSON.stringify(accessToken['access_token']).slice(1,-1)},
      success: function (result) {
        _this.setState({uploaded: 'success'})
        console.log({uploaded: 'success'})
      },
      error: function (error) {
        console.log("Sources Uploaded failure !!!")
        _this.setState({uploaded: 'failure'})
      }
    });

  }

  render() {
    return(

          <form className="col-md-8 uploader" encType="multipart/form-data">

Upload Sources

                Sources Uploaded Successfully !!!

                Failed to Upload Sources !!!

                <lable className="control-label">  Language Name  </lable>
                    <FormControl value={this.state.language} onChange={this.onSelect} name="language" componentClass="select" placeholder="select">
                      {SourceLanguages.map((language, i) => <option  key={i} value={language.code}>{language.value}</option>)}
                    </FormControl>

                <lable className="control-lable">  Ethnologue Code  </lable>
                      <input value={this.state.language} onChange={this.onSelect} type="text" name="EthnologueCode" placeholder="tam" className="form-control"/>

                <lable className="control-lable">  Version  </lable>
                    <input value={this.state.version} onChange={this.onSelect} name="version" type="text"  placeholder="version" className="form-control" />

                  <input id="file-input" type="file" className="fileInput" onChange={this.file_base64} multiple />

                  <button id="button" type="button" className="btn btn-success sourcefooter" onClick={this.uploadFile}>Upload Source</button>

          </form>

      );
    }
}

export default UploadSource;
<commit_msg>Added new code in upload source<commit_after>/**
 * @module src/UploadSource
 *
 * Component that display SourceDocument
 * Accepts the following properties:
 *  - language: Ethnologue code of the language
 *  - content: Content of all the source documents stored
 *  - Access ID & Key: Returned as a response after authentication
*/

import React, { Component } from 'react';
import './App.css';
import Header from './Header';
import Footer from './Footer';
import { FormControl } from 'react-bootstrap';
import SourceLanguages from './SourceLanguages';
import $ from 'jquery';

class UploadSource extends Component {
  constructor(props) {
    super(props);

    this.state = {
      language:'',
      version: '',
      base64_arr: [],
      uploaded:'Uploading',
      message: ''
    }

      // Upload file specific callback handlers
      this.uploadFile = this.uploadFile.bind(this);
      this.onSelect = this.onSelect.bind(this);
      this.file_base64 = this.file_base64.bind(this);
  }

  onSelect(e) {
    this.setState({
      [e.target.name]: e.target.value });
  }

  file_base64(e){
    var files = document.getElementById('file-input').files;
    var file = files[0]
    global.base64_arr = [];
    if(files.length > 0){
      for (var i = 0; i < files.length; i++) {
        var reader = new FileReader();
        reader.readAsDataURL(files[0]);
        reader.onload = (function (file) {
          return function (e) {
            var data = this.result;
            var unwantedData = "data:;base64,";
            data = data.replace(unwantedData, "");
            global.base64_arr.push(data);
          }
        })(file);
        reader.onerror = function (error) {
         console.log('Error: ', error);
        };
      }
    }

  }

  uploadFile(e){

    e.preventDefault();
    var ext = $('#file-input').val().split('.').pop().toLowerCase();
    if($.inArray(ext, ['usfm']) === -1) {
      // alert("File is not valid");
      this.setState({uploaded: 'success'})
    } else {
      // alert("File is valid");
      this.setState({uploaded: 'failure'})
    }

    var _this = this
    console.log(this.state.version)
    var data = {
            "language": this.state.language, "version": this.state.version, "content": global.base64_arr
          }

    let accessToken = JSON.parse(window.localStorage.getItem('access_token'))

    $.ajax({
      url: "http://127.0.0.1:8000/v1/sources",
      contentType: "application/json; charset=utf-8",
      data : JSON.stringify(data),
      method : "POST",
      headers: {
                "Authorization": "bearer " + JSON.stringify(accessToken['access_token']).slice(1,-1)},
      success: function (result) {
        result = JSON.parse(result)
        _this.setState({uploaded: result.success ? 'success' : ''})
        _this.setState({message: result.message})

      },
      error: function (error) {
         console.log(error);
        _this.setState({uploaded: 'failure'})
      }
    });

  }

  render() {
    return(

          <form className="col-md-8 uploader" encType="multipart/form-data">

Upload Sources

                {this.state.message}

                Failed to Upload Sources !!!

                <lable className="control-label">  Language Name  </lable>
                    <FormControl value={this.state.language} onChange={this.onSelect} name="language" componentClass="select" placeholder="select">
                      {SourceLanguages.map((language, i) => <option  key={i} value={language.code}>{language.value}</option>)}
                    </FormControl>

                <lable className="control-lable">  Ethnologue Code  </lable>
                      <input value={this.state.language} onChange={this.onSelect} type="text" name="EthnologueCode" placeholder="tam" className="form-control"/>

                <lable className="control-lable">  Version  </lable>
                    <input value={this.state.version} onChange={this.onSelect} name="version" type="text"  placeholder="version" className="form-control" />

                  <input id="file-input" type="file" className="fileInput" onChange={this.file_base64} multiple />

                  <button id="button" type="button" className="btn btn-success sourcefooter" onClick={this.uploadFile}>Upload Source</button>

          </form>

      );
    }
}

export default UploadSource;
<|endoftext|>