<commit_before>import React from "react";
import simple, {css} from "react-simple";

import {View} from "./core";
import {addLatestGust} from "./LatestWindReadings";

const swing = css.keyframes({
    "0%": {transform: "rotate(30deg)"},
    "50%": {transform: "rotate(-30deg)"},
    "100%": {transform: "rotate(30deg)"},
});

const rotate = css.keyframes({
    "0%": {transform: "rotate(0deg)"},
    "100%": {transform: "rotate(360deg)"},
});

export const ParachutePlain = simple(
    View,
    {
        background: "url(/parachute.svg)",
        backgroundSize: "contain",
        backgroundRepeat: "no-repeat !important",
        backgroundPosition: "center",
        flex: 1,
        marginTop: 10,
        opacity: 0.08,
    },
    {
        swing: {
            animation: `${swing} 2s ease-in-out infinite`,
            transformOrigin: "50% 0%",
        },
        rotate: {
            animation: `${rotate} 1s linear infinite`,
            transformOrigin: "50% 15%",
        },
    },
);

var ConnectedParachute = ({value}) => {
    // value = 8;
    var gust = parseFloat(value, 10);
    if (gust >= 11) {
        return <ParachutePlain rotate />;
    }

    if (gust >= 8) {
        return <ParachutePlain swing />;
    }

    return <ParachutePlain />;
};
ConnectedParachute = addLatestGust(ConnectedParachute);

export default ConnectedParachute;
<commit_msg>Port parachute to emotion<commit_after>import React from "react";
import styled from "@emotion/styled";
import {keyframes} from "@emotion/core";

import {View} from "./core";
import {addLatestGust} from "./LatestWindReadings";

const swing = keyframes`
    0% {
        transform: rotate(30deg);
    }
    50% {
        transform: rotate(-30deg);
    }
    100% {
        transform: rotate(30deg);
    }
`;

const rotate = keyframes`
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
`;

export const ParachutePlain = styled(View)(
    {
        background: "url(/parachute.svg)",
        backgroundSize: "contain",
        backgroundRepeat: "no-repeat !important",
        backgroundPosition: "center",
        flex: 1,
        marginTop: 10,
        opacity: 0.08,
    },
    props => {
        if (props.swing) {
            return {
                animation: `${swing} 2s ease-in-out infinite`,
                transformOrigin: "50% 0%",
            };
        }

        if (props.rotate) {
            return {
                animation: `${rotate} 1s linear infinite`,
                transformOrigin: "50% 15%",
            };
        }

        return {};
    },
);

var ConnectedParachute = ({value}) => {
    // value = 8;
    var gust = parseFloat(value, 10);
    if (gust >= 11) {
        return <ParachutePlain rotate />;
    }

    if (gust >= 8) {
        return <ParachutePlain swing />;
    }

    return <ParachutePlain />;
};
ConnectedParachute = addLatestGust(ConnectedParachute);

export default ConnectedParachute;
<|endoftext|>


<commit_before>$(document).ready(function() {
	var ratyOptions = {
		path: '../images',
		size: 32,
		width: 280,
		// TODO: custom stars (larger)
		cancelOff: 'cancel-off-big.png',
		cancelOn: 'cancel-on-big.png',
		starHalf: 'star-half-big.png',
		starOff: 'star-off-big.png',
		starOn: 'star-on-big.png'
	};
	function submitRating(score, evt) {
		var ratingForm = this.parent('form').first();
		var ratingStars = ratingForm.children('.stars').first();
		var postData = 'score=' + ratingStars.children('input').first().val();
		$.post(ratingForm.attr('action'), postData, function(response) {
			var newRating = $.parseJSON(response).r;
			ratingStars.empty().removeAttr('title').removeAttr('id');
			ratingStars.css({opacity: '0.75'});
			ratingStars.raty($.extend(ratyOptions, {readOnly: true, start: newRating}))
		});
		evt.stopImmediatePropagation();
	}

	$('.updatesubject .stars').each(function() {
		var self = $(this);
		self.raty($.extend(ratyOptions, {click: submitRating}));
	});

	$('.subjects .stars').each(function() {
		var self = $(this);
		self.raty($.extend(ratyOptions, {start: self.attr('rel'), readOnly: true}));
	});

	function submitNewNote() {
		var self = $(this),
			note = self.children('.note').first();
		postData = 'content=' + note.val();
		$.post(self.attr('action'), postData, function(response) {
			self.siblings('.notes').first().append('
' + $.parseJSON(response).n + '
');
			note.val('');
		});
		return false;
	}

	$('form.addnote').submit(submitNewNote);
});<commit_msg>Changing subjects behavior<commit_after>$(document).ready(function() {
	var ratyOptions = {
		path: '../images',
		size: 32,
		width: 280,
		// TODO: custom stars (larger)
		cancelOff: 'cancel-off-big.png',
		cancelOn: 'cancel-on-big.png',
		starHalf: 'star-half-big.png',
		starOff: 'star-off-big.png',
		starOn: 'star-on-big.png'
	};
	function submitRating(score, evt) {
		var ratingForm = this.parent('form').first();
		var ratingStars = ratingForm.children('.stars').first();
		var postData = 'score=' + ratingStars.children('input').first().val();
		$.post(ratingForm.attr('action'), postData, function(response) {
			var newRating = $.parseJSON(response).r;
			ratingStars.empty().removeAttr('title').removeAttr('id');
			ratingStars.css({opacity: '0.75'});
			ratingStars.raty($.extend(ratyOptions, {readOnly: true, start: newRating}))
		});
		evt.stopImmediatePropagation();
	}

	$('.updatesubject .stars').each(function() {
		var self = $(this);
		self.raty($.extend(ratyOptions, {click: submitRating}));
	});

	$('#subjects .stars').each(function() {
		var self = $(this);
		self.raty($.extend(ratyOptions, {start: self.attr('rel'), readOnly: true}));
	});

	function submitNewNote() {
		var self = $(this),
			note = self.children('.note').first();
		postData = 'content=' + note.val();
		$.post(self.attr('action'), postData, function(response) {
			self.siblings('.notes').first().append('
' + $.parseJSON(response).n + '
');
			note.val('');
		});
		return false;
	}

	$('form.addnote').submit(submitNewNote);

	$('#subjects .subject').click(function() {
		window.location = '/' + $(this).attr('rel');
	});
});<|endoftext|>


<commit_before>/**
 * @file 获取代理相关的信息
 * @author zdying
 */

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

var execDirectives = require('../directives').execDirectives;
var Transform = require('hiproxy-conf-parser').Transform;
var utils = require('../helpers/utils');
var clone = utils.clone;
var parseCookie = utils.parseCookie;
var parseQueryString = utils.parseQueryString;

/**
 * 获取代理信息, 用于请求代理的地址
 * @param {Object}  request 请求对象
 * @param {Object}  hostsRules 解析后的hosts规则
 * @param {Array}   rewriteRules 解析后的rewrite规则
 * @private
 * @ignore
 * @returns {Object}
 */
module.exports = function getProxyInfo (request, hostsRules, rewriteRules) {
  var originUrl = request.url;
  var uri = url.parse(originUrl);
  var rewrite = !!rewriteRules && getRewriteRule(uri, rewriteRules);
  var host = !!hostsRules && hostsRules[uri.hostname];
  var hostname, port, path, protocol;
  var proxyInfo = {
    headers: request.headers
  };
  var proxyType = 'DIRECT';

  protocol = uri.protocol;

  // rewrite 优先级高于 hosts
  if (rewrite /* && rewrite.props.proxy */) {
    // 根据请求信息，设置内置变量
    setBuiltInVars(rewrite, request);
    // 再次替换变量的值
    Transform.replaceVar(rewrite, rewrite.variables, ['extends']);

    var rewriteProps = rewrite.variables;
    var proxyPass = rewriteProps.$proxy_pass || '';
    var isBaseRule = rewrite.isBaseRule;
    var alias = rewriteProps.$alias;
    var proxyUrlObj = url.parse(proxyPass);
    var protocolReg = /^(\w+:\/\/)/;
    var newUrl = '';
    var newUrlObj;
    var isLocRegExp = isRegExp(rewrite.location);

    // 如果代理地址中包含具体协议，删除原本url中的协议
    // 最终替换位代理地址的协议
    if (!alias && !isBaseRule && proxyUrlObj.protocol) {
      protocol = proxyUrlObj.protocol;
      originUrl = originUrl.replace(protocolReg, '');
    }

    if (proxyPass) {
      // 将原本url中的部分替换为代理地址
      if (isLocRegExp) {
        // 如果是正则表达式，直接食用proxy_pass的值
        newUrl = proxyPass;
      } else {
        // 普通地址字符串
        // 否则，把url中的source部分替换成proxy
        newUrl = originUrl.replace(rewrite.extends.domain + rewrite.location, proxyPass);
      }
    }

    var context = {
      req: request,
      proxy: proxyInfo,
      rewriteRule: rewrite
    };

    log.debug('newURL ==>', newUrl);
    log.debug('alias  ==>', alias);

    // pre-request
    // set default `Host` header
    if (proxyUrlObj.host) {
      proxyInfo.headers.host = proxyUrlObj.host;
    }
    // pre-request

    execDirectives(rewrite, context, 'request');

    if (alias) {
      // 本地文件系统路径, 删除前面的协议部分
      newUrl = newUrl.replace(/^(\w+:\/\/)/, '').split('?')[0];
      proxyType = 'ALIAS';
    } else {
      newUrlObj = url.parse(newUrl);

      hostname = newUrlObj.hostname || '';
      port = newUrlObj.port;
      path = newUrlObj.path;
      proxyType = proxyPass ? 'REWRITE' : 'DIRECTIVE';
    }
  } else if (host) {
    // TODO 这里的协议，到底应该用什么?
    protocol = 'http:';
    hostname = host.split(':')[0];
    // port = (protocol === 'https:') ? 443 : Number(uri.port || host.split(':')[1]);
    port = host.split(':')[1] || uri.port || (protocol === 'https:' ? 443 : 80);
    path = uri.path;
    proxyType = 'HOSTS';
  } else {
    hostname = uri.hostname;
    port = uri.port;
    path = uri.path;
  }

  request.headers['accept-encoding'] = 'gzip,deflate';
  // TODO add test case.
  // correct the `Content-Length` value.
  if ('content-length' in request.headers) {
    request.headers['content-length'] = Buffer.byteLength(request.body || '');
  }

  var _proxyInfo = {
    hostname: hostname,
    port: port,
    path: path,
    method: proxyInfo.method || request.method,
    // headers: request.headers,
    protocol: protocol,

    proxyType: proxyType,
    proxyPass: proxyPass,
    hostsRule: host,
    hostName: uri.hostname,
    rewriteRule: rewrite,
    alias: alias,
    url: newUrl
  };

  for (var key in _proxyInfo) {
    proxyInfo[key] = _proxyInfo[key];
  }

  return proxyInfo;
};

/**
 * 根据url查找对应的rewrite规则
 * @param urlObj
 * @param rewriteRules
 * @param domainCache
 * @returns {*}
 */
function getRewriteRule (urlObj, rewriteRules) {
  var hostname = urlObj.hostname;
  var href = urlObj.href;
  var rewriteRule = null;
  var lastDeep = -1;

  var domains = rewriteRules[hostname];

  if (!domains || !Array.isArray(domains)) {
    return null;
  }

  domains.forEach(function (domain) {
    var rule = domain;
    var locations = rule.locations;
    var urlPath = urlObj.path;
    var loc = null;
    var currentDeep = 0;
    var location = '';
    var isLocRegExp = false;

    for (var i = 0, len = locations.length; i < len; i++) {
      loc = locations[i];
      location = loc.location;
      isLocRegExp = isRegExp(location);

      log.debug('getRewriteRule - current location path =>'.green, String(location).bold.green);
      log.debug('getRewriteRule - current url path =>'.green, urlPath.green);

      if (isLocRegExp) {
        /** 正则表达式 **/
        // var reg = toRegExp(locPath, 'i');

        if (location.test(urlPath)) {
          currentDeep = location.source.replace(/^\\?\/|\\?\/$/g, '').split(/\\?\//).length;

          if (currentDeep > lastDeep) {
            rewriteRule = loc;
          }

          log.debug(
            'getRewriteRule -',
            'regexp match =>', urlPath.match(location),
            'deep =>', String(currentDeep).bold.green,
            'last deep =>', String(lastDeep).bold.green,
            'should replace last rule =>', String(currentDeep > lastDeep).bold.green
          );
        }
      } else if (urlPath.indexOf(location) === 0) {
        /** 非正则表达式 **/
        // 如果url中path以location中的path开头
        currentDeep = location.replace(/^\/|\/$/g, '').split('/').length;

        // 如果是'/', 长度设置为0
        if (currentDeep === 1 && location === '/') {
          currentDeep = 0;
        }

        log.debug('getRewriteRule -', 'get rewrite rule for url =>', urlObj.href.bold.green);
        log.debug(
          'getRewriteRule -',
          'current match location.path =>', String(location).bold.green,
          'deep =>', String(currentDeep).bold.green,
          'last deep =>', String(lastDeep).bold.green,
          'should replace last rule =>', String(currentDeep > lastDeep).bold.green
        );

        // 如果匹配的深度比上一次匹配的深度深（比上次匹配更精确）
        // 替换成新匹配到的规则
        if (currentDeep > lastDeep) {
          rewriteRule = loc;
          lastDeep = currentDeep;
        }
      }
    }
  });

  log.debug('getProxyInfo -'.red, href, '==>', utils.toJSON(rewriteRule));

  return clone(rewriteRule);
}

/**
 * 设置内置变量
 *
 * @param {Object} rewrite 当前请求匹配的rewrite规则
 * @param {http.IncomingMessage} request 当前请求对象
 */
function setBuiltInVars (rewrite, request) {
  var variables = rewrite.variables;
  var urlObj = url.parse(request.url);
  var headers = request.headers;
  var cookies = parseCookie(headers.cookie);
  var queryObj = parseQueryString(urlObj.search);
  var tmpKey = '';
  var isLocRegExp = isRegExp(rewrite.location);
  var headerHost = headers.host || '';

  var vars = {
    $host: urlObj.host || headerHost,
    $hostname: urlObj.hostname || headerHost.split(':')[0],
    $search: urlObj.search || '',
    $query_string: urlObj.query || '',
    $server_port: urlObj.port || '80',
    $scheme: (urlObj.protocol || '').replace(':', ''),
    $request_uri: urlObj.href,
    $path: urlObj.path,
    $path_name: urlObj.pathname || '',
    $base_name: path.basename(urlObj.pathname),
    $dir_name: path.dirname(urlObj.pathname),
    $hash: urlObj.hash || '',
    $hash_value: (urlObj.hash || '').replace('#', ''),
    $uri: urlObj.href
  };

  // $cookie_name
  for (var cookie in cookies) {
    tmpKey = cookie.toLowerCase().replace(/-/, '_');
    vars['$cookie_' + tmpKey] = cookies[cookie] || '';
  }

  // $http_name
  // arbitrary request header field; the last part of a variable name is the field name
  // converted to lower case with dashes replaced by underscores
  for (var header in headers) {
    tmpKey = header.toLowerCase().replace(/-/, '_');
    vars['$http_' + tmpKey] = headers[header] || '';
  }

  // $arg_name query string value
  for (var arg in queryObj) {
    tmpKey = arg.toLowerCase().replace(/-/, '_');
    vars['$arg_' + tmpKey] = queryObj[arg] || '';
  }

  if (isLocRegExp) {
    // RegExp location
    var urlMatch = urlObj.path.match(rewrite.location);
    if (Array.isArray(urlMatch)) {
      for (var i = 1; i < 9; i++) {
        vars['$' + i] = urlMatch[i] || '';
      }
    }
  }

  for (var key in vars) {
    variables[key] = vars[key];
  }
}

function isRegExp (location) {
  return Object.prototype.toString.call(location) === '[object RegExp]';
}
<commit_msg>fix: hosts domain https request error<commit_after>/**
 * @file 获取代理相关的信息
 * @author zdying
 */

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

var execDirectives = require('../directives').execDirectives;
var Transform = require('hiproxy-conf-parser').Transform;
var utils = require('../helpers/utils');
var clone = utils.clone;
var parseCookie = utils.parseCookie;
var parseQueryString = utils.parseQueryString;

/**
 * 获取代理信息, 用于请求代理的地址
 * @param {Object}  request 请求对象
 * @param {Object}  hostsRules 解析后的hosts规则
 * @param {Array}   rewriteRules 解析后的rewrite规则
 * @private
 * @ignore
 * @returns {Object}
 */
module.exports = function getProxyInfo (request, hostsRules, rewriteRules) {
  var originUrl = request.url;
  var uri = url.parse(originUrl);
  var rewrite = !!rewriteRules && getRewriteRule(uri, rewriteRules);
  var host = !!hostsRules && hostsRules[uri.hostname];
  var hostname, port, path, protocol;
  var proxyInfo = {
    headers: request.headers
  };
  var proxyType = 'DIRECT';

  protocol = uri.protocol;

  // rewrite 优先级高于 hosts
  if (rewrite /* && rewrite.props.proxy */) {
    // 根据请求信息，设置内置变量
    setBuiltInVars(rewrite, request);
    // 再次替换变量的值
    Transform.replaceVar(rewrite, rewrite.variables, ['extends']);

    var rewriteProps = rewrite.variables;
    var proxyPass = rewriteProps.$proxy_pass || '';
    var isBaseRule = rewrite.isBaseRule;
    var alias = rewriteProps.$alias;
    var proxyUrlObj = url.parse(proxyPass);
    var protocolReg = /^(\w+:\/\/)/;
    var newUrl = '';
    var newUrlObj;
    var isLocRegExp = isRegExp(rewrite.location);

    // 如果代理地址中包含具体协议，删除原本url中的协议
    // 最终替换位代理地址的协议
    if (!alias && !isBaseRule && proxyUrlObj.protocol) {
      protocol = proxyUrlObj.protocol;
      originUrl = originUrl.replace(protocolReg, '');
    }

    if (proxyPass) {
      // 将原本url中的部分替换为代理地址
      if (isLocRegExp) {
        // 如果是正则表达式，直接食用proxy_pass的值
        newUrl = proxyPass;
      } else {
        // 普通地址字符串
        // 否则，把url中的source部分替换成proxy
        newUrl = originUrl.replace(rewrite.extends.domain + rewrite.location, proxyPass);
      }
    }

    var context = {
      req: request,
      proxy: proxyInfo,
      rewriteRule: rewrite
    };

    log.debug('newURL ==>', newUrl);
    log.debug('alias  ==>', alias);

    // pre-request
    // set default `Host` header
    if (proxyUrlObj.host) {
      proxyInfo.headers.host = proxyUrlObj.host;
    }
    // pre-request

    execDirectives(rewrite, context, 'request');

    if (alias) {
      // 本地文件系统路径, 删除前面的协议部分
      newUrl = newUrl.replace(/^(\w+:\/\/)/, '').split('?')[0];
      proxyType = 'ALIAS';
    } else {
      newUrlObj = url.parse(newUrl);

      hostname = newUrlObj.hostname || '';
      port = newUrlObj.port;
      path = newUrlObj.path;
      proxyType = proxyPass ? 'REWRITE' : 'DIRECTIVE';
    }
  } else if (host) {
    protocol = uri.protocol || 'http:';
    hostname = host.split(':')[0];
    port = host.split(':')[1] || uri.port || (protocol === 'https:' ? 443 : 80);
    path = uri.path;
    proxyType = 'HOSTS';
  } else {
    hostname = uri.hostname;
    port = uri.port;
    path = uri.path;
  }

  request.headers['accept-encoding'] = 'gzip,deflate';
  // TODO add test case.
  // correct the `Content-Length` value.
  if ('content-length' in request.headers) {
    request.headers['content-length'] = Buffer.byteLength(request.body || '');
  }

  var _proxyInfo = {
    hostname: hostname,
    port: port,
    path: path,
    method: proxyInfo.method || request.method,
    // headers: request.headers,
    protocol: protocol,

    proxyType: proxyType,
    proxyPass: proxyPass,
    hostsRule: host,
    hostName: uri.hostname,
    rewriteRule: rewrite,
    alias: alias,
    url: newUrl
  };

  for (var key in _proxyInfo) {
    proxyInfo[key] = _proxyInfo[key];
  }

  return proxyInfo;
};

/**
 * 根据url查找对应的rewrite规则
 * @param urlObj
 * @param rewriteRules
 * @param domainCache
 * @returns {*}
 */
function getRewriteRule (urlObj, rewriteRules) {
  var hostname = urlObj.hostname;
  var href = urlObj.href;
  var rewriteRule = null;
  var lastDeep = -1;

  var domains = rewriteRules[hostname];

  if (!domains || !Array.isArray(domains)) {
    return null;
  }

  domains.forEach(function (domain) {
    var rule = domain;
    var locations = rule.locations;
    var urlPath = urlObj.path;
    var loc = null;
    var currentDeep = 0;
    var location = '';
    var isLocRegExp = false;

    for (var i = 0, len = locations.length; i < len; i++) {
      loc = locations[i];
      location = loc.location;
      isLocRegExp = isRegExp(location);

      log.debug('getRewriteRule - current location path =>'.green, String(location).bold.green);
      log.debug('getRewriteRule - current url path =>'.green, urlPath.green);

      if (isLocRegExp) {
        /** 正则表达式 **/
        // var reg = toRegExp(locPath, 'i');

        if (location.test(urlPath)) {
          currentDeep = location.source.replace(/^\\?\/|\\?\/$/g, '').split(/\\?\//).length;

          if (currentDeep > lastDeep) {
            rewriteRule = loc;
          }

          log.debug(
            'getRewriteRule -',
            'regexp match =>', urlPath.match(location),
            'deep =>', String(currentDeep).bold.green,
            'last deep =>', String(lastDeep).bold.green,
            'should replace last rule =>', String(currentDeep > lastDeep).bold.green
          );
        }
      } else if (urlPath.indexOf(location) === 0) {
        /** 非正则表达式 **/
        // 如果url中path以location中的path开头
        currentDeep = location.replace(/^\/|\/$/g, '').split('/').length;

        // 如果是'/', 长度设置为0
        if (currentDeep === 1 && location === '/') {
          currentDeep = 0;
        }

        log.debug('getRewriteRule -', 'get rewrite rule for url =>', urlObj.href.bold.green);
        log.debug(
          'getRewriteRule -',
          'current match location.path =>', String(location).bold.green,
          'deep =>', String(currentDeep).bold.green,
          'last deep =>', String(lastDeep).bold.green,
          'should replace last rule =>', String(currentDeep > lastDeep).bold.green
        );

        // 如果匹配的深度比上一次匹配的深度深（比上次匹配更精确）
        // 替换成新匹配到的规则
        if (currentDeep > lastDeep) {
          rewriteRule = loc;
          lastDeep = currentDeep;
        }
      }
    }
  });

  log.debug('getProxyInfo -'.red, href, '==>', utils.toJSON(rewriteRule));

  return clone(rewriteRule);
}

/**
 * 设置内置变量
 *
 * @param {Object} rewrite 当前请求匹配的rewrite规则
 * @param {http.IncomingMessage} request 当前请求对象
 */
function setBuiltInVars (rewrite, request) {
  var variables = rewrite.variables;
  var urlObj = url.parse(request.url);
  var headers = request.headers;
  var cookies = parseCookie(headers.cookie);
  var queryObj = parseQueryString(urlObj.search);
  var tmpKey = '';
  var isLocRegExp = isRegExp(rewrite.location);
  var headerHost = headers.host || '';

  var vars = {
    $host: urlObj.host || headerHost,
    $hostname: urlObj.hostname || headerHost.split(':')[0],
    $search: urlObj.search || '',
    $query_string: urlObj.query || '',
    $server_port: urlObj.port || '80',
    $scheme: (urlObj.protocol || '').replace(':', ''),
    $request_uri: urlObj.href,
    $path: urlObj.path,
    $path_name: urlObj.pathname || '',
    $base_name: path.basename(urlObj.pathname),
    $dir_name: path.dirname(urlObj.pathname),
    $hash: urlObj.hash || '',
    $hash_value: (urlObj.hash || '').replace('#', ''),
    $uri: urlObj.href
  };

  // $cookie_name
  for (var cookie in cookies) {
    tmpKey = cookie.toLowerCase().replace(/-/, '_');
    vars['$cookie_' + tmpKey] = cookies[cookie] || '';
  }

  // $http_name
  // arbitrary request header field; the last part of a variable name is the field name
  // converted to lower case with dashes replaced by underscores
  for (var header in headers) {
    tmpKey = header.toLowerCase().replace(/-/, '_');
    vars['$http_' + tmpKey] = headers[header] || '';
  }

  // $arg_name query string value
  for (var arg in queryObj) {
    tmpKey = arg.toLowerCase().replace(/-/, '_');
    vars['$arg_' + tmpKey] = queryObj[arg] || '';
  }

  if (isLocRegExp) {
    // RegExp location
    var urlMatch = urlObj.path.match(rewrite.location);
    if (Array.isArray(urlMatch)) {
      for (var i = 1; i < 9; i++) {
        vars['$' + i] = urlMatch[i] || '';
      }
    }
  }

  for (var key in vars) {
    variables[key] = vars[key];
  }
}

function isRegExp (location) {
  return Object.prototype.toString.call(location) === '[object RegExp]';
}
<|endoftext|>


<commit_before>var vumigo = require('vumigo_v02');
var AppTester = vumigo.AppTester;
var LocationApp = require('../lib/app').LocationApp;
var location = require('../../lib');
var GoogleMaps = location.GoogleMaps;

describe("app", function() {
    describe("LocationApp", function() {
        var app;
        var tester;
        var locations;

        beforeEach(function(){
            app = new LocationApp();
            tester = new AppTester(app);
            locations = [];

            locations.push({
                request:"Example Street",
                response_data: {
                    results:
                    [{
                        formatted_address:"Example Street, Suburb",
                        geometry: {
                            location:{
                                latitude: '3.1415926535',
                                longitude: '2.7182818284'
                            }
                        }
                    },
                    {
                        formatted_address:"Another Street, Suburb",
                        geometry: {
                            location: {
                                latitude: '2.7182818284',
                                longitude: '3.1415926535'
                            }
                        }
                    }],
                    status:"OK"
                }
            });

            locations.push({
                request:"Single Street",
                response_data: {
                    results:
                    [{
                        formatted_address:"Single Street, Suburb",
                        geometry: {
                            location:{
                                latitude: '1.4142135623',
                                longitude: '1.6180339887'
                            }
                        }
                    }],
                    status:"OK"
                }
            });

            tester
                .setup.config.app({
                    name: 'test_app'
                })
                .setup(function(api) {
                    locations.forEach(function(location) {
                        api.http.fixtures.add(GoogleMaps.fixture(location));
                    });
                });
        });

        describe("When the user starts a session", function(){
            it("should ask the user for a location", function() {
                return tester
                    .start()
                    .check.interaction({
                        state: 'states:start',
                        reply: [
                            "Welcome to the location app.",
                            "What is your current address?"
                        ].join('\n')
                    })
                    .run();
            });
        });

        describe("When the user enters a location prompt with multiple results",
        function() {
            it("should ask the user to refine their choice", function() {
                return tester
                    .input("Example Street")
                    .check.interaction({
                        state: 'states:start',
                        reply: [
                            "Please select your location from the following:",
                            "1. Example Street, Suburb",
                            "2. Another Street, Suburb",
                            "n. Next",
                            "p. Prev"
                        ].join('\n')
                    })
                    .run();
            });
        });

        describe("When the user selects a location from the list", function() {
            it("should display the location data to the user", function() {
                return tester
                    .inputs("Example Street", "1")
                    .check.interaction({
                        state: 'states:end',
                        reply: [
                            'The location "Example Street, Suburb" is located',
                            'at longitude 2.7182818284 and latitude',
                            '3.1415926535'
                        ].join(' ')
                    })
                    .run();
            });
        });

        describe("When the user enters a location prompt with one results",
        function(){
            it("should display the location data to the user", function() {
                return tester
                    .input("Single Street")
                    .check.interaction({
                        state: 'states:end',
                        reply: [
                            'The location "Single Street, Suburb" is located',
                            'at longitude 1.6180339887 and latitude',
                            '1.4142135623'
                        ].join(' ')
                    })
                    .run();
            });
        });

    });
});
<commit_msg>Minor formatting fix for address fixtures.<commit_after>var vumigo = require('vumigo_v02');
var AppTester = vumigo.AppTester;
var LocationApp = require('../lib/app').LocationApp;
var location = require('../../lib');
var GoogleMaps = location.GoogleMaps;

describe("app", function() {
    describe("LocationApp", function() {
        var app;
        var tester;
        var locations;

        beforeEach(function(){
            app = new LocationApp();
            tester = new AppTester(app);
            locations = [];

            locations.push({
                request:"Example Street",
                response_data: {
                    results:
                    [{
                        formatted_address: "Example Street, Suburb",
                        geometry: {
                            location:{
                                latitude: '3.1415926535',
                                longitude: '2.7182818284'
                            }
                        }
                    },
                    {
                        formatted_address: "Another Street, Suburb",
                        geometry: {
                            location: {
                                latitude: '2.7182818284',
                                longitude: '3.1415926535'
                            }
                        }
                    }],
                    status:"OK"
                }
            });

            locations.push({
                request:"Single Street",
                response_data: {
                    results:
                    [{
                        formatted_address: "Single Street, Suburb",
                        geometry: {
                            location:{
                                latitude: '1.4142135623',
                                longitude: '1.6180339887'
                            }
                        }
                    }],
                    status:"OK"
                }
            });

            tester
                .setup.config.app({
                    name: 'test_app'
                })
                .setup(function(api) {
                    locations.forEach(function(location) {
                        api.http.fixtures.add(GoogleMaps.fixture(location));
                    });
                });
        });

        describe("When the user starts a session", function(){
            it("should ask the user for a location", function() {
                return tester
                    .start()
                    .check.interaction({
                        state: 'states:start',
                        reply: [
                            "Welcome to the location app.",
                            "What is your current address?"
                        ].join('\n')
                    })
                    .run();
            });
        });

        describe("When the user enters a location prompt with multiple results",
        function() {
            it("should ask the user to refine their choice", function() {
                return tester
                    .input("Example Street")
                    .check.interaction({
                        state: 'states:start',
                        reply: [
                            "Please select your location from the following:",
                            "1. Example Street, Suburb",
                            "2. Another Street, Suburb",
                            "n. Next",
                            "p. Prev"
                        ].join('\n')
                    })
                    .run();
            });
        });

        describe("When the user selects a location from the list", function() {
            it("should display the location data to the user", function() {
                return tester
                    .inputs("Example Street", "1")
                    .check.interaction({
                        state: 'states:end',
                        reply: [
                            'The location "Example Street, Suburb" is located',
                            'at longitude 2.7182818284 and latitude',
                            '3.1415926535'
                        ].join(' ')
                    })
                    .run();
            });
        });

        describe("When the user enters a location prompt with one results",
        function(){
            it("should display the location data to the user", function() {
                return tester
                    .input("Single Street")
                    .check.interaction({
                        state: 'states:end',
                        reply: [
                            'The location "Single Street, Suburb" is located',
                            'at longitude 1.6180339887 and latitude',
                            '1.4142135623'
                        ].join(' ')
                    })
                    .run();
            });
        });

    });
});
<|endoftext|>


<commit_before>/* eslint sort-keys: ["error", "asc"], quote-props: ["error", "consistent"] */
/* eslint-disable sort-keys */

module.exports = {
    extends: [
        "plugin:import/react"
    ],
    rules: {
        /* eslint-enable sort-keys */
        "no-nested-ternary": "off", // nested ternaries can increase the readability of JSX components
        "react/display-name": "error",
        "react/forbid-component-props": "off",
        "react/jsx-boolean-value": "off",
        "react/jsx-closing-bracket-location": ["error", "line-aligned"],
        "react/jsx-curly-spacing": ["error", "never"],
        "react/jsx-equals-spacing": ["error", "never"],
        "react/jsx-filename-extension": "off",
        "react/jsx-first-prop-new-line": ["error", "multiline"],
        "react/jsx-handler-names": ["error", {
            eventHandlerPrefix: "handle",
            eventHandlerPropPrefix: "on"
        }],
        "react/jsx-indent": ["error", 4],
        "react/jsx-indent-props": ["error", 4],
        "react/jsx-key": "error",
        "react/jsx-max-props-per-line": ["error", {
            maximum: 4,
        }],
        "react/jsx-no-bind": ["error", {
            allowArrowFunctions: false,
            allowBind: false,
            ignoreRefs: false
        }],
        "react/jsx-no-comment-textnodes": "error",
        "react/jsx-no-duplicate-props": ["error", {
            ignoreCase: true,
        }],
        "react/jsx-no-target-blank": "error",
        "react/jsx-no-undef": "error",
        "react/jsx-pascal-case": "error",
        "react/jsx-sort-props": "off",
        "react/jsx-space-before-closing": ["error", "always"],
        "react/jsx-uses-react": "error",
        "react/jsx-uses-vars": "error",
        "react/jsx-wrap-multilines": "error",
        "react/no-children-prop": "error",
        "react/no-danger": "error",
        "react/no-danger-with-children": "error",
        "react/no-deprecated": "error",
        "react/no-did-mount-set-state": ["error", "disallow-in-func"],
        "react/no-did-update-set-state": ["error", "disallow-in-func"],
        "react/no-direct-mutation-state": "error",
        "react/no-find-dom-node": "error",
        "react/no-is-mounted": "error",
        'react/no-multi-comp': ["error", { ignoreStateless: true }],
        "react/no-render-return-value": "error",
        "react/no-set-state": "error",
        "react/no-string-refs": "error",
        "react/no-unescaped-entities": "error",
        "react/no-unknown-property": "error",
        "react/no-unused-prop-types": "error",
        "react/prefer-es6-class": "error",
        "react/prefer-stateless-function": "error",
        "react/prop-types": "error",
        "react/react-in-jsx-scope": "error",
        "react/require-render-return": "error",
        "react/self-closing-comp": "error",
        "react/sort-comp": "off",
        "react/sort-prop-types": "off",
        "react/style-prop-object": "off"
    }
};
<commit_msg>fix: Missing plugin declaration in react rules<commit_after>/* eslint sort-keys: ["error", "asc"], quote-props: ["error", "consistent"] */
/* eslint-disable sort-keys */

module.exports = {
    plugins: [
        "react"
    ],
    extends: [
        "plugin:import/react"
    ],
    rules: {
        /* eslint-enable sort-keys */
        "no-nested-ternary": "off", // nested ternaries can increase the readability of JSX components
        "react/display-name": "error",
        "react/forbid-component-props": "off",
        "react/jsx-boolean-value": "off",
        "react/jsx-closing-bracket-location": ["error", "line-aligned"],
        "react/jsx-curly-spacing": ["error", "never"],
        "react/jsx-equals-spacing": ["error", "never"],
        "react/jsx-filename-extension": "off",
        "react/jsx-first-prop-new-line": ["error", "multiline"],
        "react/jsx-handler-names": ["error", {
            eventHandlerPrefix: "handle",
            eventHandlerPropPrefix: "on"
        }],
        "react/jsx-indent": ["error", 4],
        "react/jsx-indent-props": ["error", 4],
        "react/jsx-key": "error",
        "react/jsx-max-props-per-line": ["error", {
            maximum: 4,
        }],
        "react/jsx-no-bind": ["error", {
            allowArrowFunctions: false,
            allowBind: false,
            ignoreRefs: false
        }],
        "react/jsx-no-comment-textnodes": "error",
        "react/jsx-no-duplicate-props": ["error", {
            ignoreCase: true,
        }],
        "react/jsx-no-target-blank": "error",
        "react/jsx-no-undef": "error",
        "react/jsx-pascal-case": "error",
        "react/jsx-sort-props": "off",
        "react/jsx-space-before-closing": ["error", "always"],
        "react/jsx-uses-react": "error",
        "react/jsx-uses-vars": "error",
        "react/jsx-wrap-multilines": "error",
        "react/no-children-prop": "error",
        "react/no-danger": "error",
        "react/no-danger-with-children": "error",
        "react/no-deprecated": "error",
        "react/no-did-mount-set-state": ["error", "disallow-in-func"],
        "react/no-did-update-set-state": ["error", "disallow-in-func"],
        "react/no-direct-mutation-state": "error",
        "react/no-find-dom-node": "error",
        "react/no-is-mounted": "error",
        'react/no-multi-comp': ["error", { ignoreStateless: true }],
        "react/no-render-return-value": "error",
        "react/no-set-state": "error",
        "react/no-string-refs": "error",
        "react/no-unescaped-entities": "error",
        "react/no-unknown-property": "error",
        "react/no-unused-prop-types": "error",
        "react/prefer-es6-class": "error",
        "react/prefer-stateless-function": "error",
        "react/prop-types": "error",
        "react/react-in-jsx-scope": "error",
        "react/require-render-return": "error",
        "react/self-closing-comp": "error",
        "react/sort-comp": "off",
        "react/sort-prop-types": "off",
        "react/style-prop-object": "off"
    }
};
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { polyglot } from '../polyglot-modules/polyglot'
import Link from 'next/link'
import es from '../translations/es.json'
import en from '../translations/en.json'
import Layout from '../layouts/Layout'
import Header from '../sections/index/containers/Header'
import Cases from '../sections/index/containers/Cases'
import Collaborate from '../sections/index/containers/Collaborate'
import Ebooks from '../sections/index/containers/Ebooks'
import Media from '../sections/index/containers/Media'
import WhoWeAre from '../sections/index/containers/WhoWeAre'
import Publications from '../sections/index/containers/Publications'
import Footer from '../containers/Footer'
import Content from "../sections/about/containers/Content"
import HeroSlider from "../sections/index/components/HeroSlider"
const env = 'undefined' !== process ? process.env.YOUTUBE_API_KEY : null

export default class extends Component {
  static getInitialProps() {
    return { env };
  }

  constructor (props) {
    super(props)
    this.state = {
      currentLang : 'es',
      modal: false,
      content: ''
    }
    if (Object.values(polyglot.phrases).length === 0) {
      polyglot.extend(es)
      polyglot.locale(es.language)
    }
  }

  componentWillMount () {
    if (typeof window !== 'undefined') {
      localStorage.setItem('youtube', this.props.env)
      const lang = localStorage.getItem('lang')
      if (lang === null) {
        localStorage.setItem('lang', 'es')
      } else if (lang !== polyglot.currentLocale) {
        this.changeLang('en')
      }
    }
  }

  componentDidMount () {
    const isSubscribed = this.getQueryVariable('subscripto')
    if (isSubscribed !== undefined) {
      this.setState({
        modal: true,
        content: isSubscribed === 'true' ? 'Ya estás subscripto a Democracia en Red. ¡Pronto recibirás novedades!' : 'Link inválido, asegurate de validar el link antes de dos días y de utilizar el link del último mail de confirmación'
      })
    }
  }

  changeLang = (lang) => {
    const newLang = lang === 'es' ? es : en
    polyglot.clear()
    polyglot.extend(newLang)
    polyglot.locale(newLang.language)
    localStorage.setItem('lang', lang)
    this.setState({currentLang: lang})
  }

  getQueryVariable = (variable) => {
    var query = window.location.search.substring(1)
    var vars = query.split("&")
    for (var i=0;i<vars.length;i++) {
      var pair = vars[i].split("=")
      if(pair[0] == variable){return pair[1]}
    }
  }

  hideModal = () => {
    this.setState({modal: false})
  }

  render () {
    return (

        <Layout changeLang={this.changeLang} currentLang={this.state.currentLang}>
   {/*         */}
          <HeroSlider/>
          <Cases currentLang={this.state.currentLang} />
          <Link href={'/vivo'}>

          </Link>
          <Collaborate />
          <Publications currentLang={this.state.currentLang} />
          <Content />
          <Ebooks />
          <Media />
          <WhoWeAre />

        </Layout>

    )
  }
}
<commit_msg>banner merepresenta eliminado<commit_after>import React, { Component } from "react";
import { polyglot } from "../polyglot-modules/polyglot";
import Link from "next/link";
import es from "../translations/es.json";
import en from "../translations/en.json";
import Layout from "../layouts/Layout";
import Header from "../sections/index/containers/Header";
import Cases from "../sections/index/containers/Cases";
import Collaborate from "../sections/index/containers/Collaborate";
import Ebooks from "../sections/index/containers/Ebooks";
import Media from "../sections/index/containers/Media";
import WhoWeAre from "../sections/index/containers/WhoWeAre";
import Publications from "../sections/index/containers/Publications";
import Footer from "../containers/Footer";
import Content from "../sections/about/containers/Content";
const env = "undefined" !== process ? process.env.YOUTUBE_API_KEY : null;

export default class extends Component {
  static getInitialProps() {
    return { env };
  }

  constructor(props) {
    super(props);
    this.state = {
      currentLang: "es",
      modal: false,
      content: "",
    };
    if (Object.values(polyglot.phrases).length === 0) {
      polyglot.extend(es);
      polyglot.locale(es.language);
    }
  }

  componentWillMount() {
    if (typeof window !== "undefined") {
      localStorage.setItem("youtube", this.props.env);
      const lang = localStorage.getItem("lang");
      if (lang === null) {
        localStorage.setItem("lang", "es");
      } else if (lang !== polyglot.currentLocale) {
        this.changeLang("en");
      }
    }
  }

  componentDidMount() {
    const isSubscribed = this.getQueryVariable("subscripto");
    if (isSubscribed !== undefined) {
      this.setState({
        modal: true,
        content:
          isSubscribed === "true"
            ? "Ya estás subscripto a Democracia en Red. ¡Pronto recibirás novedades!"
            : "Link inválido, asegurate de validar el link antes de dos días y de utilizar el link del último mail de confirmación",
      });
    }
  }

  changeLang = (lang) => {
    const newLang = lang === "es" ? es : en;
    polyglot.clear();
    polyglot.extend(newLang);
    polyglot.locale(newLang.language);
    localStorage.setItem("lang", lang);
    this.setState({ currentLang: lang });
  };

  getQueryVariable = (variable) => {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split("=");
      if (pair[0] == variable) {
        return pair[1];
      }
    }
  };

  hideModal = () => {
    this.setState({ modal: false });
  };

  render() {
    return (

        <Layout
          changeLang={this.changeLang}
          currentLang={this.state.currentLang}
        >

          <Cases currentLang={this.state.currentLang} />
          <Link href={"/vivo"}>

          </Link>
          <Collaborate />
          <Publications currentLang={this.state.currentLang} />
          <Content />
          <Ebooks />
          <Media />
          <WhoWeAre />

        </Layout>

    );
  }
}
<|endoftext|>


<commit_before>/*!
 * JsonRpcService object for RightJS.
 * Copyright (C) 2009  Yesudeep Mangalapilly <yesudeep@gmail.com>.
 *
 * Released under terms of the MIT license.
 *
 * Dependencies:
 *
 * 		* Native JSON or json2.js (http://www.json.org/json2.js).
 */
var JsonRpcService = new Class({
	include: Options,

	/**
	 * Used as the id for an RPC message.
	 * Request-to-response mapping uses this identifier.
	 *
	 * Version 1.0 of the JSON RPC Specification states that this can be any
	 * JavaScript type.  However, the proposal for the latest version 2.0 of the
	 * Specification requires this to be a JSON scalar (an immutable object)
	 * barring fractionals or floating point numbers as they are approximate
	 * and cannot be used to match requests to response reliably.
	 */
	serial_id: 0,

	/**
	 * Namespace for remote API method names.
	 */
	api: {},

	/**
	 * Configurable options.
	 */
	Options: {
		/**
		 * Service Proxy URL.
		 */
		url: '',

		/**
		 * HTTP Headers set per request.
		 */
		headers: {
			'Content-Type': 'application/json',
			'Accept': 'application/json, text/javascript, text/html, ' +
					'text/xml, application/xml, */*'
		},

		/**
		 * Cross-domain requests cannot be asynchronous.
		 */
		async: true,

		/**
		 * Version string.  Can be one of these values: "1.1", "2.0", etc.
		 * If a version number is not specified, version 1.1 will be
		 * used.
		 *
		 * Versions included in remote call messages must be strings (not
		 * numbers).  JSON-RPC Specification version 2.0 adds an additional key
		 * to stringified JSON message called 'jsonrpc' which *must* be included
		 * for it to qualify as a version 2.0 message.  The server must return
		 * this version in the response using the same field name.
		 */
		version: '1.1',

		/**
		 * HTTP Method used for sending the RPC message.
		 * POST is used if no value is provided.
		 *
		 * @note	Currently only POST is supported.
		 */
		method: 'POST',

		/**
		 * List of remote API methods for which local method wrappers will be
		 * generated.  The generated wrapper methods will be placed in the
		 * service.api.* namespace.
		 */
		api: []
	},

	/**
	 * Constructor.
	 *
	 * @url			String	A JsonRpcService instance acts as a proxy for this
	 * 						service URL.
	 * @options  	Object	An object contains various options that you want
	 * 						overridden with your values.
	 */
	initialize: function(url, options){
		this.setOptions(options);
		this.options.url = url;

		var version = this.options.version;
		switch(version){
			case '1.0':
			case '1.1':
				this.message_template = {version: version};
				break;
			default:
				this.message_template = {jsonrpc: version};
				break;
		}

		var methods = options.api;
		for (var i = methods.length - 1, method_name = ''; i > -1; i--){
			method_name = methods[i];
			this.api[method_name] = this.__create_api(method_name);
		}
	},

	// Private methods.
	__create_api: function(method_name){
		var service = this;

		return function(params, onSuccess, onCancel){
			var options = service.options;
			service.__remote_call(options, method_name,
					params, onSuccess, onCancel);
		}
	},

	__remote_call: function(options, method_name, params, onSuccess, onCancel){
		var serial_id = ++this.serial_id;
		var version = options.version;
		var message = Object.merge(this.message_template, {
			method: method_name,
			params: params,
			id: serial_id
		});

		if (onSuccess && !isFunction(onSuccess)){
			throw new Error('invalid parameter - onSuccess is not a function');
		}
		if (onCancel && !isFunction(onCancel)){
			throw new Error('invalid parameter - onSuccess is not a function');
		}

		// Uses the json2.js or native JSON object to stringify.
		var string_message = JSON.stringify(message);

		// Xhr setup
		var xhr = new Xhr(options.url, {
			async: options.async,
			// Stop forcing 'application/x-www-form-urlencoded' content-type.
			urlEncoded: false,
			evalJSON: true,
			onSuccess: function(request){
				var json = request.responseJSON;
				var result = json.result;
				if (json.id == serial_id){
					if (result){
						onSuccess(result);
					} else {
						var error = json.error;
						if (error){
							var error_message = ((error.code)?
									'[' + error.code + ']': '') +
								error.type + ' -- ' + error.message;
							throw new Error(error_message);
						} else {
							throw new Error('JSONRPCError -- ' +
									'undefined error');
						}
					}
				}
			},
			onCancel: function(request){
				onCancel(request);
			}
		});
		var headers = options.headers;
		Object.keys(headers).each(function(key){
			xhr.setHeader(key, headers[key]);
		});
		xhr.send(string_message);
	},

    // Public service methods.
	remote_call: function(method_name, params, onSuccess, onCancel){
		var options = this.options;
		this.__remote_call(options, method_name, params, onSuccess, onCancel);
	}
});

<commit_msg>allow comment eaters to munge all comments including headers<commit_after>/*
 * JsonRpcService object for RightJS.
 * Copyright (C) 2009  Yesudeep Mangalapilly <yesudeep@gmail.com>.
 *
 * Released under terms of the MIT license.
 *
 * Dependencies:
 *
 * 		* Native JSON or json2.js (http://www.json.org/json2.js).
 */
var JsonRpcService = new Class({
	include: Options,

	/**
	 * Used as the id for an RPC message.
	 * Request-to-response mapping uses this identifier.
	 *
	 * Version 1.0 of the JSON RPC Specification states that this can be any
	 * JavaScript type.  However, the proposal for the latest version 2.0 of the
	 * Specification requires this to be a JSON scalar (an immutable object)
	 * barring fractionals or floating point numbers as they are approximate
	 * and cannot be used to match requests to response reliably.
	 */
	serial_id: 0,

	/**
	 * Namespace for remote API method names.
	 */
	api: {},

	/**
	 * Configurable options.
	 */
	Options: {
		/**
		 * Service Proxy URL.
		 */
		url: '',

		/**
		 * HTTP Headers set per request.
		 */
		headers: {
			'Content-Type': 'application/json',
			'Accept': 'application/json, text/javascript, text/html, ' +
					'text/xml, application/xml, */*'
		},

		/**
		 * Cross-domain requests cannot be asynchronous.
		 */
		async: true,

		/**
		 * Version string.  Can be one of these values: "1.1", "2.0", etc.
		 * If a version number is not specified, version 1.1 will be
		 * used.
		 *
		 * Versions included in remote call messages must be strings (not
		 * numbers).  JSON-RPC Specification version 2.0 adds an additional key
		 * to stringified JSON message called 'jsonrpc' which *must* be included
		 * for it to qualify as a version 2.0 message.  The server must return
		 * this version in the response using the same field name.
		 */
		version: '1.1',

		/**
		 * HTTP Method used for sending the RPC message.
		 * POST is used if no value is provided.
		 *
		 * @note	Currently only POST is supported.
		 */
		method: 'POST',

		/**
		 * List of remote API methods for which local method wrappers will be
		 * generated.  The generated wrapper methods will be placed in the
		 * service.api.* namespace.
		 */
		api: []
	},

	/**
	 * Constructor.
	 *
	 * @url			String	A JsonRpcService instance acts as a proxy for this
	 * 						service URL.
	 * @options  	Object	An object contains various options that you want
	 * 						overridden with your values.
	 */
	initialize: function(url, options){
		this.setOptions(options);
		this.options.url = url;

		var version = this.options.version;
		switch(version){
			case '1.0':
			case '1.1':
				this.message_template = {version: version};
				break;
			default:
				this.message_template = {jsonrpc: version};
				break;
		}

		var methods = options.api;
		for (var i = methods.length - 1, method_name = ''; i > -1; i--){
			method_name = methods[i];
			this.api[method_name] = this.__create_api(method_name);
		}
	},

	// Private methods.
	__create_api: function(method_name){
		var service = this;

		return function(params, onSuccess, onCancel){
			var options = service.options;
			service.__remote_call(options, method_name,
					params, onSuccess, onCancel);
		}
	},

	__remote_call: function(options, method_name, params, onSuccess, onCancel){
		var serial_id = ++this.serial_id;
		var version = options.version;
		var message = Object.merge(this.message_template, {
			method: method_name,
			params: params,
			id: serial_id
		});

		if (onSuccess && !isFunction(onSuccess)){
			throw new Error('invalid parameter - onSuccess is not a function');
		}
		if (onCancel && !isFunction(onCancel)){
			throw new Error('invalid parameter - onSuccess is not a function');
		}

		// Uses the json2.js or native JSON object to stringify.
		var string_message = JSON.stringify(message);

		// Xhr setup
		var xhr = new Xhr(options.url, {
			async: options.async,
			// Stop forcing 'application/x-www-form-urlencoded' content-type.
			urlEncoded: false,
			evalJSON: true,
			onSuccess: function(request){
				var json = request.responseJSON;
				var result = json.result;
				if (json.id == serial_id){
					if (result){
						onSuccess(result);
					} else {
						var error = json.error;
						if (error){
							var error_message = ((error.code)?
									'[' + error.code + ']': '') +
								error.type + ' -- ' + error.message;
							throw new Error(error_message);
						} else {
							throw new Error('JSONRPCError -- ' +
									'undefined error');
						}
					}
				}
			},
			onCancel: function(request){
				onCancel(request);
			}
		});
		var headers = options.headers;
		Object.keys(headers).each(function(key){
			xhr.setHeader(key, headers[key]);
		});
		xhr.send(string_message);
	},

    // Public service methods.
	remote_call: function(method_name, params, onSuccess, onCancel){
		var options = this.options;
		this.__remote_call(options, method_name, params, onSuccess, onCancel);
	}
});

<|endoftext|>


<commit_before>var dbURI = 'mongodb://localhost:27017/meaniscule-app-tests';
var clearDB = require('mocha-mongoose')(dbURI);

var expect = require('chai').expect;
var Promise = require('bluebird');
var mongoose = require('mongoose');

var Nodemodule = require('./nodemodule.model.js');

describe('Nodemodule model', function () {
  before('Connect to db', function (done) {
    if (mongoose.connection.db) return done();
    mongoose.connect(dbURI, done);
  });

  after('Clear test database', function (done) {
    clearDB(done);
  });

  it('should exist', function () {
      expect(Nodemodule).to.be.a('function');
  });

  describe('Nodemodule creation', function() {

    it('should create a module in the db', function(done){
      Nodemodule.create({ title: "express", repoUrl: "http://github.com/express" })
        .then(function(data) {
          Nodemodule.findById(data.id).exec()
            .then(function(data) {
              expect(data).to.be.a('object');
              expect(data.title).to.equal("express");
              expect(data.repoUrl).to.equal("http://github.com/express");
              done();
            })
            .then(null, done);
        });
    });

  });
});
<commit_msg>Added model test for validation error.<commit_after>var dbURI = 'mongodb://localhost:27017/meaniscule-app-tests';
var clearDB = require('mocha-mongoose')(dbURI);

var expect = require('chai').expect;
var mongoose = require('mongoose');

var Nodemodule = require('./nodemodule.model.js');

describe('Nodemodule model', function () {

  before('Connect to db', function (done) {
    if (mongoose.connection.db) return done();
    mongoose.connect(dbURI, done);
  });

  after('Clear test database', function (done) {
    clearDB(done);
  });

  describe('Model existence', function() {

    it('should exist', function () {
      expect(Nodemodule).to.be.a('function');
    });

  });

  describe('Nodemodule creation', function() {

    it('should create a module in the db', function(done) {

      Nodemodule.create({ title: "express", repoUrl: "http://github.com/express" })
        .then(function(data) {
          Nodemodule.findById(data.id).exec()
            .then(function(data) {
              expect(data).to.be.a('object');
              expect(data.title).to.equal("express");
              expect(data.repoUrl).to.equal("http://github.com/express");
              done();
            })
            .then(null, done);
        });

    });

    it('should not be able to create a module without a title', function(done) {

      Nodemodule.create({ repoUrl: "http://github.com/express" })
        .then(function(data) {
          expect(data).to.not.exist;
        })
        .then(null, function(err) {
          expect(err).to.exist;
          expect(err.name).to.equal("ValidationError");
          done();
        })
        .then(null, done);

    });

  });
});<|endoftext|>


<commit_before>var app = {};

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

(function($){
    //prompt user for a username if he has not already provided one

    if(readCookie("username")) return;

    function handleSubmit (e) {
        e.preventDefault();
        var username = $("input[name=username]").val();
        if(!username.length){
            return $("input[name=username]").parent().addClass('error');
        }
        createCookie("username", username, 720);
        modal.modal("hide");

    }

    var modal = $('<form id="saveUsername" class="modal hide fade">\

\

Identify yourself
\

\

\

Just type a username, node wiki ain\'t no high security vault.
\

<input placeholder="Username" name="username" required/>

\

\

\
                  <button type="submit" class="btn btn-primary">Save changes</button>\

\
                  </form>')
                  .appendTo("body")
                  .modal("show");
                  $("#saveUsername").on("submit",handleSubmit);

}(jQuery));

(function($){
    //Enable link clicking if editor is not active
    clickingLink = false;
    $(".content.editable").on("mousedown", function(e){
        if(e.target.tagName == "A" && !$(this).hasClass("cke_focus")){
            clickingLink = true;
            e.preventDefault();
            e.stopImmediatePropagation();
        }
    }).on("mouseup", function(e){
        if(clickingLink){
            location.href = e.target.href;
            e.preventDefault();
            e.stopImmediatePropagation();
        }
        clickingLink = false;
    });
}(jQuery));

(function($){
    //provide an interface to display a message to the user
    $.message = function(type, message, delay){
        delay = delay || 5e3;
        var html = '
 \
        <button type="button" class="close" data-dismiss="alert">×</button> \
        ' + message + '\

';

        $(html).appendTo('#messages').delay(delay).fadeOut(remove);
    };

    function remove(){
        $(this).remove();
    }
}(jQuery));

(function(CKEDITOR){
    //initize CK editor and page save events
    if ($(".content.editable").length == 0 ) return;
    var getData = function(){
        return {
            content: $('.content.editable').html().replace(" class=\"aloha-link-text\"", ""),
            title: $('h1.title').html(),
            tags: $(".tags div").html()
        };
    };
    var data = getData();
    var save = function() {
        var newData = getData();
        var changed = ["content", "title", "tags"].some(function(key){
            return data[key] != newData[key];
        });

        if(changed){
            data  = newData;
            $.post(document.location.href, {
                content: $('.content.editable').html(),
                title: $('h1.title').html(),
                tags: $(".tags div").html()
            }).success(saved)
            .error(savingError);
        }
    };

    setInterval(save, 6e4);
    $("body").bind("save", save);

    CKEDITOR.inline('content', {
        on: {
            blur: save
        }
    });

    $('.edit').blur(save).keydown(function(e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            $(this).blur();
        }
    });

    var saved = function() {
        $.message('success', 'Page saved', 2e3);
        $(".modified-by strong").text(readCookie("username"));
    };
    var savingError = function() {
        $.message('error', 'Page could not be saved, please try again later', 2e3);
    };

}(CKEDITOR));

(function ($) {
    //if not changed highlight text for easy replacement
    function getTextNodesIn(node) {
        var textNodes = [];
        if (node.nodeType == 3) {
            textNodes.push(node);
        } else {
            var children = node.childNodes;
            for (var i = 0, len = children.length; i < len; ++i) {
                textNodes.push.apply(textNodes, getTextNodesIn(children[i]));
            }
        }
        return textNodes;
    }

    function setSelectionRange(el, start, end) {
        if (document.createRange && window.getSelection) {
            var range = document.createRange();
            range.selectNodeContents(el);
            var textNodes = getTextNodesIn(el);
            var foundStart = false;
            var charCount = 0, endCharCount;

            for (var i = 0, textNode; textNode = textNodes[i++]; ) {
                endCharCount = charCount + textNode.length;
                if (!foundStart && start >= charCount
                    && (start < endCharCount ||
                        (start == endCharCount && i < textNodes.length))) {
                        range.setStart(textNode, start - charCount);
                        foundStart = true;
                    }
                    if (foundStart && end <= endCharCount) {
                        range.setEnd(textNode, end - charCount);
                        break;
                    }
                    charCount = endCharCount;
            }

            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.selection && document.body.createTextRange) {
            var textRange = document.body.createTextRange();
            textRange.moveToElementText(el);
            textRange.collapse(true);
            textRange.moveEnd("character", end);
            textRange.moveStart("character", start);
            textRange.select();
        }
    }

    $(".tags .edit").focus(function () {
        if (this.innerText == "add tags as comma separated list") {
            var el = this;
            setTimeout(function () {
                setSelectionRange(el, 0, el.innerText.length);
            }, 30);
        }
    });

    $("h1.edit").focus(function () {
        if (this.innerText == "new page") {
            var el = this;
            setTimeout(function () {
                setSelectionRange(el, 0, el.innerText.length);
            }, 30);
        }
    });
}(jQuery));

(function(app) {
    app.ProgressBar = function (target, upload) {
        var self = this;

        this.element = $('<progress min="0" max="100" value="0">0% complete</progress>').appendTo(target)[0];

        upload.onprogress = function(e) {
            if (e.lengthComputable) {
                self.value= (e.loaded / e.total) * 100;
            }
        };

        Object.defineProperties(this, {
            value : {
                get: function(){return this.element.value;},
                set: function(value) {
                    this.element.value = value;
                    this.textContent = this.value; // Fallback for unsupported browsers.

                    if(this.value == 100){
                        this.remove();
                    }

                },
                writeable: true
            },

            textContent : {
                get: function(){return this.element.textContent;},
                set: function(value) {this.element.textContent = value; },
                writeable: true
            }
        });
    };

    app.ProgressBar.prototype.remove = function(){
        $(this.element).fadeOut(function(){
            $(this).remove();
        });
    };

})(app);

(function(app) {
    var Dropzone = function (options) {
        this.element = options.element;
        this.toggleState = options.toggleState || toggleState;
        this.handleDragOver = options.handleDragOver || handleDragOver;
        this.handleFileSelect = options.handleFileSelect || handleFileSelect;

        this.addEventListeners();
    };

    Dropzone.prototype.addEventListeners = function() {
        this.element.addEventListener('dragover'  , this.handleDragOver   , false);
        this.element.addEventListener('dragenter' , this.toggleState      , false);
        this.element.addEventListener('dragleave' , this.toggleState      , false);
        this.element.addEventListener('drop'      , this.handleFileSelect , false);
    };

    function handleDragOver(evt) {
        evt.stopPropagation();
        evt.preventDefault();
        evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
    }

    function toggleState(ev){
        $(ev.target).toggleClass('active');
    }

    app.Dropzone = Dropzone;
}(app));

(function($){
    if ($(".drop-here").length == 0) return;

    $(function(){
        if(!(window.File && window.FileReader && window.FileList && window.Blob)) {
            return $('.drop-here').hide();
        }

        // Setup the dnd listeners.
        new app.Dropzone({
            element: document.getElementById('drop-zone'),
            handleFileSelect: handleFileSelect
        });
    });

    function handleFileSelect(evt) {
        evt.stopPropagation();
        evt.preventDefault();

        uploadFiles(document.location.href, evt.dataTransfer.files);
    }

    function uploadFiles(url, files) {
        var formData = new FormData();

        for (var i = 0, file; file = files[i]; ++i) {
            formData.append("attachments", file);
        }

        var xhr = new XMLHttpRequest();
        var finished = false;
        xhr.open('POST', "/attachments", true);
        xhr.onload = function(e) {
            if(!finished && xhr.status == 200){
                finished = true;
                handleResponse(xhr.responseText);
                $.message("success", "Successfully uploaded");
            }

            if(xhr.status >= 500){
                $.message('error', 'Internal Server Error');
            }

            if(xhr.status == 415){
                $.message('error', 'Unsupported media type');
            }

            if(xhr.status == 400){
                $.message("error", "I don't know");
            }
        };

        var progressBar = new app.ProgressBar('#attachments', xhr.upload);

        xhr.send(formData);  // multipart/form-data
    }

    var handleResponse = function(res){
        var response = JSON.parse(res);
        response.attachments.forEach(function(attachment){
            $('#attachments').append("
" + attachment + "<a href='#' class='icon-remove-sign'
");
        });
    };
}(jQuery));

(function($){
    if ($("#content.edit").length == 0) return;

    $(function(){
        if(!(window.File && window.FileReader && window.FileList && window.Blob)) {
            return $('.drop-here').hide();
        }

        // Setup the dnd listeners.
        new app.Dropzone({
            element: document.getElementById('content'),
            handleFileSelect: handleFileSelect
        });
    });

    function handleFileSelect(evt) {
        evt.stopPropagation();
        evt.preventDefault();

        var uri = evt.dataTransfer.getData("text/uri-list");
        if (uri) {
            return handleUriDrop(uri, evt.target);
        }

        uploadFiles(document.location.href, evt.dataTransfer.files, evt.target);
    }

    function uploadFiles(url, files, targetElement) {
        var formData = new FormData();

        for (var i = 0, file; file = files[i]; ++i) {
            formData.append("images", file);
        }

        var xhr = new XMLHttpRequest();
        var finished = false;
        xhr.open('POST', "/images", true);
        xhr.onload = function(e) {
            if(!finished && xhr.status == 200){
                finished = true;
                handleResponse.bind(targetElement)(xhr.responseText);
                $.message("success", "Successfully uploaded");
            }

            if(xhr.status >= 500){
                $.message('error', 'Internal Server Error');
            }

            if(xhr.status == 415){
                $.message('error', 'Unsupported media type');
            }

            if(xhr.status == 400){
                $.message("error", "I don't know");
            }
        };

        var progressBar = new app.ProgressBar("#content", xhr.upload);

        xhr.send(formData);  // multipart/form-data
    }

    var appendAssetStrategy = {
        image: function(uri) {
            return "";
        },
        video: function(uri) {
            return "<video class='polaroid' width='640' height='480' src='" + uri + "'/>";
        },
        audio: function(uri) {
            return "<audio controls src='" + uri + "'/>";
        },
        text: function(uri) {
            return "Link Title";
        }
    };

    var handleUriDrop = function (uri, targetElement) {
        if(uri.indexOf("youtube.com/watch") !== -1) {
            var youtube = uri.match(/v=(.*?)(?:$|&)/);
            if(!youtube[1]) return;
            $(targetElement).append('');
            $("body").trigger("save");
        } else if(uri.indexOf("vimeo.com/") !== -1) {
            var vimeo = uri.match(/vimeo.com\/(.*?)(?:$|\?)/);
            if(!vimeo[1]) return;
            $(targetElement).append('');
            $("body").trigger("save");
        } else if (uri.indexOf("www.slideshare.net/" !== -1)) {
            $.getJSON("http://www.slideshare.net/api/oembed/2?url="+ uri +"&format=jsonp&callback=?", function(data) {
                $(targetElement).append(data.html);
                $("body").trigger("save");
            });
        } else {
            $.get("/detect-content-type", {uri: uri}, function(data) {
                var type = data.replace(/\/.*/, "");
if (appendAssetStrategy[type]) {
    $(targetElement).append(
        appendAssetStrategy[type](uri)
    );
    $("body").trigger("save");
} else {
    $.message('warn', "I dunno know this ditti");
}
            });
        }
    };

    var handleResponse = function(res){
        var targetElement = $(this);
        var response = JSON.parse(res);
        response.images.forEach(function(image){
            targetElement.append("");
            $('#images').append("
" + image + "<a href='#' class='icon-remove-sign'
");
        });
        $("body").trigger("save");
    };
}(jQuery));

(function($) {
    $(".plain-list").on("click", ".icon-remove-sign", function(e) {
        e.preventDefault();
        e.stopPropagation();
        var li = $(this).closest('li');
        var type = $(this).closest(".plain-list")[0].id;
        $.ajax({
            url: "/" + type,
            type: "DELETE",
            data: {
                file: $(this).prev("a")[0].title
            }
        }).done(function(){
            li.remove();
        });
    });
}(jQuery));

(function($){
    $('pre, code').each(function(i, e) {hljs.highlightBlock(e)});
}(jQuery));
<commit_msg>beautified code<commit_after>"use strict";

var app = {};

function createCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(";");
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == " ") c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

(function ($) {
    //prompt user for a username if he has not already provided one

    if (readCookie("username")) return;

    function handleSubmit(e) {
        e.preventDefault();
        var username = $("input[name=username]").val();
        if (!username.length) {
            return $("input[name=username]")
                .parent()
                .addClass("error");
        }
        createCookie("username", username, 720);
        modal.modal("hide");

    }

    var modal = $('<form id="saveUsername" class="modal hide fade">\

\

Identify yourself
\

\

\

Just type a username, node wiki ain\'t no high security vault.
\

<input placeholder="Username" name="username" required/>

\

\

\
                  <button type="submit" class="btn btn-primary">Save changes</button>\

\
                  </form>')
        .appendTo("body")
        .modal("show");
    $("#saveUsername")
        .on("submit", handleSubmit);

}(jQuery));

(function ($) {
    //Enable link clicking if editor is not active
    clickingLink = false;
    $(".content.editable")
        .on("mousedown", function (e) {
        if (e.target.tagName == "A" && !$(this)
            .hasClass("cke_focus")) {
            clickingLink = true;
            e.preventDefault();
            e.stopImmediatePropagation();
        }
    })
        .on("mouseup", function (e) {
        if (clickingLink) {
            location.href = e.target.href;
            e.preventDefault();
            e.stopImmediatePropagation();
        }
        clickingLink = false;
    });
}(jQuery));

(function ($) {
    //provide an interface to display a message to the user
    $.message = function (type, message, delay) {
        delay = delay ||  5e3;
        var html = '
 \
        <button type="button" class="close" data-dismiss="alert">×</button> \
        ' + message + '\

';

        $(html)
            .appendTo('#messages')
            .delay(delay)
            .fadeOut(remove);
    };

    function remove() {
        $(this).remove();
    }
}(jQuery));

(function (CKEDITOR) {
    //initize CK editor and page save events
    if ($(".content.editable")
        .length == 0) return;
    var getData = function () {
        return {
            content: $('.content.editable')
                .html()
                .replace(" class=\"aloha-link-text\"", ""),
            title: $('h1.title').html(),
            tags: $(".tags div").html()
        };
    };
    var data = getData();
    var save = function () {
        var newData = getData();
        var changed = ["content", "title", "tags"].some(function (key) {
            return data[key] != newData[key];
        });

        if (changed) {
            data = newData;
            $.post(document.location.href, {
                content: $(".content.editable").html(),
                title: $("h1.title").html(),
                tags: $(".tags div").html()
            })
                .success(saved)
                .error(savingError);
        }
    };

    setInterval(save, 6e4);
    $("body")
        .bind("save", save);

    CKEDITOR.inline("content", {
        on: {
            blur: save
        }
    });

    $(".edit")
        .blur(save)
        .keydown(function (e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            $(this)
                .blur();
        }
    });

    var saved = function () {
        $.message("success", "Page saved", 2e3);
        $(".modified-by strong")
            .text(readCookie("username"));
    };
    var savingError = function () {
        $.message("error", "Page could not be saved, please try again later", 2e3);
    };

}(CKEDITOR));

(function ($) {
    //if not changed highlight text for easy replacement
    function getTextNodesIn(node) {
        var textNodes = [];
        if (node.nodeType == 3) {
            textNodes.push(node);
        } else {
            var children = node.childNodes;
            for (var i = 0, len = children.length; i < len; ++i) {
                textNodes.push.apply(textNodes, getTextNodesIn(children[i]));
            }
        }
        return textNodes;
    }

    function setSelectionRange(el, start, end) {
        if (document.createRange && window.getSelection) {
            var range = document.createRange();
            range.selectNodeContents(el);
            var textNodes = getTextNodesIn(el);
            var foundStart = false;
            var charCount = 0,
                endCharCount;

            for (var i = 0, textNode; textNode = textNodes[i++];) {
                endCharCount = charCount + textNode.length;
                if (!foundStart && start >= charCount && (start < endCharCount || (start == endCharCount && i < textNodes.length))) {
                    range.setStart(textNode, start - charCount);
                    foundStart = true;
                }
                if (foundStart && end <= endCharCount) {
                    range.setEnd(textNode, end - charCount);
                    break;
                }
                charCount = endCharCount;
            }

            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.selection && document.body.createTextRange) {
            var textRange = document.body.createTextRange();
            textRange.moveToElementText(el);
            textRange.collapse(true);
            textRange.moveEnd("character", end);
            textRange.moveStart("character", start);
            textRange.select();
        }
    }

    $(".tags .edit")
        .focus(function () {
        if (this.innerText == "add tags as comma separated list") {
            var el = this;
            setTimeout(function () {
                setSelectionRange(el, 0, el.innerText.length);
            }, 30);
        }
    });

    $("h1.edit")
        .focus(function () {
        if (this.innerText == "new page") {
            var el = this;
            setTimeout(function () {
                setSelectionRange(el, 0, el.innerText.length);
            }, 30);
        }
    });
}(jQuery));

(function (app) {
    app.ProgressBar = function (target, upload) {
        var self = this;

        this.element = $('<progress min="0" max="100" value="0">0% complete</progress>')
            .appendTo(target)[0];

        upload.onprogress = function (e) {
            if (e.lengthComputable) {
                self.value = (e.loaded / e.total) * 100;
            }
        };

        Object.defineProperties(this, {
            value: {
                get: function () {
                    return this.element.value;
                },
                set: function (value) {
                    this.element.value = value;
                    this.textContent = this.value; // Fallback for unsupported browsers.

                    if (this.value == 100) {
                        this.remove();
                    }

                },
                writeable: true
            },

            textContent: {
                get: function () {
                    return this.element.textContent;
                },
                set: function (value) {
                    this.element.textContent = value;
                },
                writeable: true
            }
        });
    };

    app.ProgressBar.prototype.remove = function () {
        $(this.element).fadeOut(function () {
            $(this).remove();
        });
    };

})(app);

(function (app) {
    var Dropzone = function (options) {
        this.element = options.element;
        this.toggleState = options.toggleState ||  toggleState;
        this.handleDragOver = options.handleDragOver ||  handleDragOver;
        this.handleFileSelect = options.handleFileSelect ||  handleFileSelect;

        this.addEventListeners();
    };

    Dropzone.prototype.addEventListeners = function () {
        this.element.addEventListener('dragover', this.handleDragOver, false);
        this.element.addEventListener('dragenter', this.toggleState, false);
        this.element.addEventListener('dragleave', this.toggleState, false);
        this.element.addEventListener('drop', this.handleFileSelect, false);
    };

    function handleDragOver(evt) {
        evt.stopPropagation();
        evt.preventDefault();
        evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
    }

    function toggleState(ev) {
        $(ev.target).toggleClass('active');
    }

    app.Dropzone = Dropzone;
}(app));

(function ($) {
    if ($(".drop-here").length == 0) return;

    $(function () {
        if (!(window.File && window.FileReader && window.FileList && window.Blob)) {
            return $('.drop-here').hide();
        }

        // Setup the dnd listeners.
        new app.Dropzone({
            element: document.getElementById('drop-zone'),
            handleFileSelect: handleFileSelect
        });
    });

    function handleFileSelect(evt) {
        evt.stopPropagation();
        evt.preventDefault();

        uploadFiles(document.location.href, evt.dataTransfer.files);
    }

    function uploadFiles(url, files) {
        var formData = new FormData();

        for (var i = 0, file; file = files[i]; ++i) {
            formData.append("attachments", file);
        }

        var xhr = new XMLHttpRequest();
        var finished = false;
        xhr.open('POST', "/attachments", true);
        xhr.onload = function (e) {
            if (!finished && xhr.status == 200) {
                finished = true;
                handleResponse(xhr.responseText);
                $.message("success", "Successfully uploaded");
            }

            if (xhr.status >= 500) {
                $.message('error', 'Internal Server Error');
            }

            if (xhr.status == 415) {
                $.message('error', 'Unsupported media type');
            }

            if (xhr.status == 400) {
                $.message("error", "I don't know");
            }
        };

        var progressBar = new app.ProgressBar('#attachments', xhr.upload);

        xhr.send(formData); // multipart/form-data
    }

    var handleResponse = function (res) {
        var response = JSON.parse(res);
        response.attachments.forEach(function (attachment) {
            $('#attachments').append("
" + attachment + "<a href='#' class='icon-remove-sign'
");
        });
    };
}(jQuery));

(function ($) {
    if ($("#content.edit").length == 0) return;

    $(function () {
        if (!(window.File && window.FileReader && window.FileList && window.Blob)) {
            return $(".drop-here").hide();
        }

        // Setup the dnd listeners.
        new app.Dropzone({
            element: document.getElementById("content"),
            handleFileSelect: handleFileSelect
        });
    });

    function handleFileSelect(evt) {
        evt.stopPropagation();
        evt.preventDefault();

        var uri = evt.dataTransfer.getData("text/uri-list");
        if (uri) {
            return handleUriDrop(uri, evt.target);
        }

        uploadFiles(document.location.href, evt.dataTransfer.files, evt.target);
    }

    function uploadFiles(url, files, targetElement) {
        var formData = new FormData();

        for (var i = 0, file; file = files[i]; ++i) {
            formData.append("images", file);
        }

        var xhr = new XMLHttpRequest();
        var finished = false;
        xhr.open('POST', "/images", true);
        xhr.onload = function (e) {
            if (!finished && xhr.status == 200) {
                finished = true;
                handleResponse.bind(targetElement)(xhr.responseText);
                $.message("success", "Successfully uploaded");
            }

            if (xhr.status >= 500) {
                $.message('error', 'Internal Server Error');
            }

            if (xhr.status == 415) {
                $.message('error', 'Unsupported media type');
            }

            if (xhr.status == 400) {
                $.message("error", "I don't know");
            }
        };

        var progressBar = new app.ProgressBar("#content", xhr.upload);

        xhr.send(formData); // multipart/form-data
    }

    var appendAssetStrategy = {
        image: function (uri) {
            return "";
        },
        video: function (uri) {
            return "<video class='polaroid' width='640' height='480' src='" + uri + "'/>";
        },
        audio: function (uri) {
            return "<audio controls src='" + uri + "'/>";
        },
        text: function (uri) {
            return "Link Title";
        }
    };

    var handleUriDrop = function (uri, targetElement) {
        if (uri.indexOf("youtube.com/watch") !== -1) {
            var youtube = uri.match(/v=(.*?)(?:$|&)/);
            if (!youtube[1]) return;
            $(targetElement)
                .append('');
            $("body")
                .trigger("save");
        } else if (uri.indexOf("vimeo.com/") !== -1) {
            var vimeo = uri.match(/vimeo.com\/(.*?)(?:$|\?)/);
            if (!vimeo[1]) return;
            $(targetElement)
                .append('');
            $("body")
                .trigger("save");
        } else if (uri.indexOf("www.slideshare.net/" !== -1)) {
            $.getJSON("http://www.slideshare.net/api/oembed/2?url=" + uri + "&format=jsonp&callback=?", function (data) {
                $(targetElement).append(data.html);
                $("body").trigger("save");
            });
        } else {
            $.get("/detect-content-type", {
                uri: uri
            }, function (data) {
                var type = data.replace(/\/.*/, "");
                if (appendAssetStrategy[type]) {
                    $(targetElement)
                        .append(
                    appendAssetStrategy[type](uri));
                    $("body")
                        .trigger("save");
                } else {
                    $.message('warn', "I dunno know this ditti");
                }
            });
        }
    };

    var handleResponse = function (res) {
        var targetElement = $(this);
        var response = JSON.parse(res);
        response.images.forEach(function (image) {
            targetElement.append("");
            $('#images')
                .append("
" + image + "<a href='#' class='icon-remove-sign'
");
        });
        $("body")
            .trigger("save");
    };
}(jQuery));

(function ($) {
    $(".plain-list")
        .on("click", ".icon-remove-sign", function (e) {
        e.preventDefault();
        e.stopPropagation();
        var li = $(this)
            .closest('li');
        var type = $(this)
            .closest(".plain-list")[0].id;
        $.ajax({
            url: "/" + type,
            type: "DELETE",
            data: {
                file: $(this)
                    .prev("a")[0].title
            }
        })
            .done(function () {
            li.remove();
        });
    });
}(jQuery));

(function ($) {
    $('pre, code').each(function (i, e) {
        hljs.highlightBlock(e)
    });
}(jQuery));
<|endoftext|>


<commit_before>module.exports = {
  plugins: [
    require('precss')({ /* ...options */ }),
    require('autoprefixer')({ /* ...options */ })
  ]
}<commit_msg>chore: remove unnecessary file<commit_after><|endoftext|>


<commit_before>import Layout from '../components/Layout';
import Instructions from '../components/Instructions';

export default function Index() {
  return (
    <Layout>

isfree.se

          <Instructions />

Andra exempel

              aftonbladet.se
            {' '}
            är upptagen

              extremtledig.se
            {' '}
            är förmodligen ledig

              _,:.se
            {' '}
            är en ogiltig domän

Om isfree.se

          Tjänsten utvecklas, uppdateras och sköts av{' '}
          Kristofer Palmvik bara för
          att det är roligt.

          Källkod

    </Layout>
  );
}
<commit_msg>Change the examples<commit_after>import Layout from '../components/Layout';
import Instructions from '../components/Instructions';

export default function Index() {
  return (
    <Layout>

isfree.se

          <Instructions />

Andra exempel

              isfree.se
            {' '}
            är upptagen

              ledig-doman.se
            {' '}
            är förmodligen ledig

              🦄.se
            {' '}
            är en ogiltig domän

Om isfree.se

          Tjänsten utvecklas, uppdateras och sköts av{' '}
          Kristofer Palmvik bara för
          att det är roligt.

          Källkod

    </Layout>
  );
}
<|endoftext|>