<commit_before>import React from 'react';
import connectToStores from 'alt/utils/connectToStores';
import dateFormat from 'dateformat-light';
import { Link } from 'react-router';
import { Form } from 'formsy-react';

import LoginStore from 'flux/stores/LoginStore';

import DishesStore from 'flux/stores/DishesStore';
import DishesActions from 'flux/actions/DishesActions';

import OrderStore from 'flux/stores/OrderStore';
import OrderActions from 'flux/actions/OrderActions';

import 'assets/style/account';

@connectToStores
export default class AccountPage extends React.Component {
	constructor(props) {
		super(props);

		this.state = {
			needRelations: true
		};
	}

	static getStores(props) {
		return [LoginStore, OrderStore, DishesStore];
	}

	static getPropsFromStores(props) {
		return {
			login: LoginStore.getState(),
			orders: OrderStore.getState(),
			dishes: DishesStore.getState()
		};
	}

	render() {
		let orders, dishes;
		let user = this.props.login.user;

		if(!user) {
			return

;
		}

		if(user && this.state.needRelations) {
			OrderActions.requestUserOrders(user.id);

			if(user.cook) {
				DishesActions.requestUserDishes(user.cook.id);
			}

			this.setState({ needRelations: false });
		}

		let credit = (user.credit / 100).toFixed(2).replace('.', ',');

		let account = (

{user.name}

{user.email}

€{credit} credit

					<button disabled>credits toevoegen</button>

		);

		if(this.props.orders.orders) {
			orders = this.props.orders.orders.map(order => {
				let orderTime = dateFormat(order.date_created, 'd mmmm yyyy').toLowerCase();
				let startTime = dateFormat(order.start_time, 'd mmmm yyyy "om" hh:MM').toLowerCase();
				let price = (order.total_amount / 100).toFixed(2).replace('.', ',');
				let url = '/gerecht/' + order.id;
				let dinnerTime, address;

				if(new Date(order.start_time) < Date.now()) {
					startTime = {startTime};
				}
				else {
					address = {order.cook_address};
				}

				return (

						{order.id}
						<Link to={'/gerecht/' + order.id}>{order.dish_name}</Link>
						<Link to="#">{order.cook_name}</Link>
						€{price}
						{orderTime}
						{startTime}
						{address}

				);
			});
		}

		console.log(this.props.dishes.dishes);

		if(this.props.dishes.dishes) {
			dishes = this.props.dishes.dishes.map(dish => {
				let meals = dish.meals.map(meal => {
					let price = (meal.price / 100).toFixed(2).replace('.', ',');
					let date = dateFormat(new Date(meal.available_from), 'dd-mmm-yyyy');
					let availableFrom = dateFormat(new Date(meal.available_from), 'HH:MM');
					let availableUntil = dateFormat(new Date(meal.available_until), 'HH:MM');

					return (

							{meal.id}
							€{price}
							{date}
							{availableFrom}
							{availableUntil}
							{meal.portions_claimed}/{meal.portions}

					);
				});

				return (

<Link to={'/gerecht/' + dish.id }>{dish.name}</Link>

										#
										Prijs
										Datum
										Van
										Tot
										Porties besteld

									{meals}

				);
			});
		}

		return (

				{account}

Maaltijden

								#
								Gerecht
								Kok
								Prijs
								Besteldatum
								Aanvang
								adres

							{orders}

Mijn gerechten

					<Link className="button" to="/nieuw-gerecht">Nieuw gerecht toevoegen</Link>
					{dishes}

		);
	}
}<commit_msg>Remove dishes if not cook<commit_after>import React from 'react';
import connectToStores from 'alt/utils/connectToStores';
import dateFormat from 'dateformat-light';
import { Link } from 'react-router';
import { Form } from 'formsy-react';

import LoginStore from 'flux/stores/LoginStore';

import DishesStore from 'flux/stores/DishesStore';
import DishesActions from 'flux/actions/DishesActions';

import OrderStore from 'flux/stores/OrderStore';
import OrderActions from 'flux/actions/OrderActions';

import 'assets/style/account';

@connectToStores
export default class AccountPage extends React.Component {
	constructor(props) {
		super(props);

		this.state = {
			needRelations: true
		};
	}

	static getStores(props) {
		return [LoginStore, OrderStore, DishesStore];
	}

	static getPropsFromStores(props) {
		return {
			login: LoginStore.getState(),
			orders: OrderStore.getState(),
			dishes: DishesStore.getState()
		};
	}

	render() {
		let orders, dishes;
		let user = this.props.login.user;

		if(!user) {
			return

;
		}

		if(user && this.state.needRelations) {
			OrderActions.requestUserOrders(user.id);

			if(user.cook) {
				DishesActions.requestUserDishes(user.cook.id);
			}

			this.setState({ needRelations: false });
		}

		let credit = (user.credit / 100).toFixed(2).replace('.', ',');

		let account = (

{user.name}

{user.email}

€{credit} credit

					<button disabled>credits toevoegen</button>

		);

		let dishesContainer;

		if(this.props.orders.orders) {
			orders = this.props.orders.orders.map(order => {
				let orderTime = dateFormat(order.date_created, 'd mmmm yyyy').toLowerCase();
				let startTime = dateFormat(order.start_time, 'd mmmm yyyy "om" hh:MM').toLowerCase();
				let price = (order.total_amount / 100).toFixed(2).replace('.', ',');
				let url = '/gerecht/' + order.id;
				let dinnerTime, address;

				if(new Date(order.start_time) < Date.now()) {
					startTime = {startTime};
				}
				else {
					address = {order.cook_address};
				}

				return (

						{order.id}
						<Link to={'/gerecht/' + order.id}>{order.dish_name}</Link>
						<Link to="#">{order.cook_name}</Link>
						€{price}
						{orderTime}
						{startTime}
						{address}

				);
			});
		}

		if(user.cook) {
			dishes = this.props.dishes.dishes.map(dish => {
				let meals = dish.meals.map(meal => {
					let price = (meal.price / 100).toFixed(2).replace('.', ',');
					let date = dateFormat(new Date(meal.available_from), 'dd-mmm-yyyy');
					let availableFrom = dateFormat(new Date(meal.available_from), 'HH:MM');
					let availableUntil = dateFormat(new Date(meal.available_until), 'HH:MM');

					return (

							{meal.id}
							€{price}
							{date}
							{availableFrom}
							{availableUntil}
							{meal.portions_claimed}/{meal.portions}

					);
				});

				return (

<Link to={'/gerecht/' + dish.id }>{dish.name}</Link>

										#
										Prijs
										Datum
										Van
										Tot
										Porties besteld

									{meals}

				);
			});

			dishesContainer = (

Mijn gerechten

					<Link className="button" to="/nieuw-gerecht">Nieuw gerecht toevoegen</Link>
					{dishes}

			);
		} else {
			dishesContainer = (

			);
		}

		return (

				{account}

Maaltijden

								#
								Gerecht
								Kok
								Prijs
								Besteldatum
								Aanvang
								adres

							{orders}

				{dishesContainer}

		);
	}
}<|endoftext|>


<commit_before>basis.require('basis.dom');
basis.require('basis.dom.event');
basis.require('basis.cssom');
basis.require('basis.ui');

var DOM = basis.dom;

//var transport = resource('../API/transport.js').fetch();

var inspectMode;
var elements = [];

var overlayNode = new basis.ui.Node({
  template: resource('template/heat_overlay.tmpl'),
  action: {
    mouseover: function(e){
      basis.cssom.classList(overlayContent).add('hover');
    },
    mouseout: function(e){
      basis.cssom.classList(overlayContent).remove('hover');
    }
  }
});

var overlay = overlayNode.tmpl.element;
var overlayContent = overlayNode.tmpl.content;

// dom mutation observer

var observer = (function(){
  var names = ['MutationObserver', 'WebKitMutationObserver'];

  for (var i = 0, name; name = names[i]; i++)
  {
    var ObserverClass = global[name];
    if (typeof ObserverClass == 'function')
      return new ObserverClass(updateHighlight);
  }
})();

function startInspect(){
  if (!inspectMode)
  {
    basis.cssom.classList(document.body).add('devpanel-inspectMode');
    updateOnScroll();
    inspectMode = true;
    highlight();

    basis.dom.event.addGlobalHandler('scroll', updateOnScroll);
    basis.dom.event.addHandler(window, 'resize', updateOnResize);
    DOM.event.captureEvent('mousedown', DOM.event.kill);
    DOM.event.captureEvent('mouseup', DOM.event.kill);
    DOM.event.captureEvent('contextmenu', endInspect);
    //DOM.event.captureEvent('click', pickHandler);

    //transport.sendData('startInspect', 'l10n');

    if (observer)
      observer.observe(document.body, {
        subtree: true,
        attributes: true,
        characterData: true,
        childList: true
      });
  }
}

function endInspect(){
  if (inspectMode)
  {
    if (observer)
      observer.disconnect();

    basis.cssom.classList(document.body).remove('devpanel-inspectMode');

    basis.dom.event.removeGlobalHandler('scroll', updateOnScroll);
    basis.dom.event.removeHandler(window, 'resize', updateOnResize);
    DOM.event.releaseEvent('mousedown');
    DOM.event.releaseEvent('mouseup');
    DOM.event.releaseEvent('contextmenu');
    DOM.event.releaseEvent('click');

    unhighlight();
    inspectMode = false;

    //transport.sendData('endInspect', 'l10n');
  }
}

function updateOnScroll(event){
  overlayContent.style.top = -document.body.scrollTop + 'px';
  overlayContent.style.left = -document.body.scrollLeft + 'px';

  if (event && event.target !== document)
    highlight(true);
}

var resizeTimer;
function updateOnResize(){
  clearTimeout(resizeTimer);
  basis.cssom.classList(overlayContent).add('hide');
  resizeTimer = setTimeout(function(){
    basis.cssom.classList(overlayContent).remove('hide');
    highlight(true);
  }, 100);
}

function highlight(keepOverlay){
  unhighlight(keepOverlay);

  domTreeHighlight(document.body);

  var tokenElements = document.createDocumentFragment();
  var min = Infinity;
  var max = -Infinity;

  for (var i = 0, data; data = elements[i]; i++)
  {
    min = Math.min(min, data.updates);
    max = Math.max(max, data.updates);
  }

  for (var i = 0, data; data = elements[i]; i++)
  {
    var temp = max != min ? 1 - ((data.updates - min) / (max - min)) : 1;
    var bgColor = 'rgba(' + [255 - parseInt(128 * temp), parseInt(temp * 255), 0].join(',') + ', .4)';
    var borderColor = 'rgba(' + [200 - parseInt(128 * temp), parseInt(temp * 200), 0].join(',') + ', .75)';
    data.element = tokenElements.appendChild(basis.dom.createElement({
      description: '.devpanel-heat-token',
      css: {
        backgroundColor: bgColor,
        outline: '1px solid ' + borderColor,
        top: document.body.scrollTop + data.rect.top + 'px',
        left: document.body.scrollLeft + data.rect.left + 'px',
        width: data.rect.width + 'px',
        height: data.rect.height + 'px'
      }
    }, data.updates == 1 ? '' : data.updates));
  }

  overlayContent.appendChild(tokenElements);

  if (!keepOverlay)
    DOM.insert(document.body, overlay);
}

function unhighlight(keepOverlay){
  var data;

  while (data = elements.pop())
    DOM.remove(data.element);

  if (!keepOverlay)
  {
    basis.cssom.classList(overlayContent).remove('hover');
    DOM.remove(overlay);
  }
}

function updateHighlight(records){
  for (var i = 0; i < records.length; i++)
    if (records[i].target != overlayContent
        && records[i].target.parentNode != overlayContent
        && records[i].target.id != 'devpanelSharedDom')
    {
      highlight(true);
      break;
    }
}

function domTreeHighlight(root){
  for (var i = 0, child; child = root.childNodes[i]; i++)
  {
    if (child.basisTemplateId)
    {
      var debugInfo = basis.template.getDebugInfoById(child.basisTemplateId);
      if (debugInfo)
      {
        for (var j = 0, binding; binding = debugInfo[j]; j++)
        {
          if (!binding.updates)
            continue;

          var rect;
          var domNode = binding.val instanceof Node ? binding.val : binding.dom;

          if (domNode)
          {
            switch (domNode.nodeType)
            {
              case 1:
                rect = domNode.getBoundingClientRect();
                break;
              case 3:
                var range = document.createRange();
                range.selectNodeContents(domNode);
                rect = range.getBoundingClientRect();
                break;
            }
          }

          if (rect)
          {
            elements.push({
              updates: binding.updates,
              rect: rect
            });
          }
        }
      }
    }

    if (child.nodeType == basis.dom.ELEMENT_NODE)
      domTreeHighlight(child);
  }
}

//
// exports
//

module.exports = {
  startInspect: startInspect,
  endInspect: endInspect,
  isActive: function(){
    return !!inspectMode;
  }
};
<commit_msg>don't kill mousedown/mouseup in heat map mode<commit_after>basis.require('basis.dom');
basis.require('basis.dom.event');
basis.require('basis.cssom');
basis.require('basis.ui');

var DOM = basis.dom;

//var transport = resource('../API/transport.js').fetch();

var inspectMode;
var elements = [];

var overlayNode = new basis.ui.Node({
  template: resource('template/heat_overlay.tmpl'),
  action: {
    mouseover: function(e){
      basis.cssom.classList(overlayContent).add('hover');
    },
    mouseout: function(e){
      basis.cssom.classList(overlayContent).remove('hover');
    }
  }
});

var overlay = overlayNode.tmpl.element;
var overlayContent = overlayNode.tmpl.content;

// dom mutation observer

var observer = (function(){
  var names = ['MutationObserver', 'WebKitMutationObserver'];

  for (var i = 0, name; name = names[i]; i++)
  {
    var ObserverClass = global[name];
    if (typeof ObserverClass == 'function')
      return new ObserverClass(updateHighlight);
  }
})();

function startInspect(){
  if (!inspectMode)
  {
    basis.cssom.classList(document.body).add('devpanel-inspectMode');
    updateOnScroll();
    inspectMode = true;
    highlight();

    basis.dom.event.addGlobalHandler('scroll', updateOnScroll);
    basis.dom.event.addHandler(window, 'resize', updateOnResize);
    DOM.event.captureEvent('contextmenu', endInspect);

    //transport.sendData('startInspect', 'l10n');

    if (observer)
      observer.observe(document.body, {
        subtree: true,
        attributes: true,
        characterData: true,
        childList: true
      });
  }
}

function endInspect(){
  if (inspectMode)
  {
    if (observer)
      observer.disconnect();

    basis.cssom.classList(document.body).remove('devpanel-inspectMode');

    basis.dom.event.removeGlobalHandler('scroll', updateOnScroll);
    basis.dom.event.removeHandler(window, 'resize', updateOnResize);
    DOM.event.releaseEvent('contextmenu');

    unhighlight();
    inspectMode = false;

    //transport.sendData('endInspect', 'l10n');
  }
}

function updateOnScroll(event){
  overlayContent.style.top = -document.body.scrollTop + 'px';
  overlayContent.style.left = -document.body.scrollLeft + 'px';

  if (event && event.target !== document)
    highlight(true);
}

var resizeTimer;
function updateOnResize(){
  clearTimeout(resizeTimer);
  basis.cssom.classList(overlayContent).add('hide');
  resizeTimer = setTimeout(function(){
    basis.cssom.classList(overlayContent).remove('hide');
    highlight(true);
  }, 100);
}

function highlight(keepOverlay){
  unhighlight(keepOverlay);

  domTreeHighlight(document.body);

  var tokenElements = document.createDocumentFragment();
  var min = Infinity;
  var max = -Infinity;

  for (var i = 0, data; data = elements[i]; i++)
  {
    min = Math.min(min, data.updates);
    max = Math.max(max, data.updates);
  }

  for (var i = 0, data; data = elements[i]; i++)
  {
    var temp = max != min ? 1 - ((data.updates - min) / (max - min)) : 1;
    var bgColor = 'rgba(' + [255 - parseInt(128 * temp), parseInt(temp * 255), 0].join(',') + ', .4)';
    var borderColor = 'rgba(' + [200 - parseInt(128 * temp), parseInt(temp * 200), 0].join(',') + ', .75)';
    data.element = tokenElements.appendChild(basis.dom.createElement({
      description: '.devpanel-heat-token',
      css: {
        backgroundColor: bgColor,
        outline: '1px solid ' + borderColor,
        top: document.body.scrollTop + data.rect.top + 'px',
        left: document.body.scrollLeft + data.rect.left + 'px',
        width: data.rect.width + 'px',
        height: data.rect.height + 'px'
      }
    }, data.updates == 1 ? '' : data.updates));
  }

  overlayContent.appendChild(tokenElements);

  if (!keepOverlay)
    DOM.insert(document.body, overlay);
}

function unhighlight(keepOverlay){
  var data;

  while (data = elements.pop())
    DOM.remove(data.element);

  if (!keepOverlay)
  {
    basis.cssom.classList(overlayContent).remove('hover');
    DOM.remove(overlay);
  }
}

function updateHighlight(records){
  for (var i = 0; i < records.length; i++)
    if (records[i].target != overlayContent
        && records[i].target.parentNode != overlayContent
        && records[i].target.id != 'devpanelSharedDom')
    {
      highlight(true);
      break;
    }
}

function domTreeHighlight(root){
  for (var i = 0, child; child = root.childNodes[i]; i++)
  {
    if (child.basisTemplateId)
    {
      var debugInfo = basis.template.getDebugInfoById(child.basisTemplateId);
      if (debugInfo)
      {
        for (var j = 0, binding; binding = debugInfo[j]; j++)
        {
          if (!binding.updates)
            continue;

          var rect;
          var domNode = binding.val instanceof Node ? binding.val : binding.dom;

          if (domNode)
          {
            switch (domNode.nodeType)
            {
              case 1:
                rect = domNode.getBoundingClientRect();
                break;
              case 3:
                var range = document.createRange();
                range.selectNodeContents(domNode);
                rect = range.getBoundingClientRect();
                break;
            }
          }

          if (rect)
          {
            elements.push({
              updates: binding.updates,
              rect: rect
            });
          }
        }
      }
    }

    if (child.nodeType == basis.dom.ELEMENT_NODE)
      domTreeHighlight(child);
  }
}

//
// exports
//

module.exports = {
  startInspect: startInspect,
  endInspect: endInspect,
  isActive: function(){
    return !!inspectMode;
  }
};
<|endoftext|>


<commit_before>export async function runBidiCommandsProcessor(cdpClient, bidiClient, getCurrentTargetId) {
    const targets = {};

    const targetToContext = t => ({
        context: t.targetId,
        parent: t.openerId ? t.openerId : null,
        url: t.url
    });

    const process_browsingContext_getTree = async function (messageId) {
        const cdpTargets = await cdpClient.sendCdpCommand({ method: "Target.getTargets" });
        const contexts = cdpTargets.targetInfos
            // Don't expose any information about the tab with Mapper running.
            .filter(t => t.targetId !== getCurrentTargetId())
            .map(targetToContext);
        bidiClient.sendBidiMessage({
            id: messageId,
            result: { contexts }
        });
    };

    const process_PROTO_browsingContext_createContext = async function (message) {
        const { targetId } = await cdpClient.sendCdpCommand({
            method: "Target.createTarget",
            params: { url: message.params.url }
        });

        bidiClient.sendBidiMessage({
            id: message.id,
            result: targetToContext(targets[targetId])
        });
    };

    const process_DEBUG_Page_close = async function (message) {
        await cdpClient.sendCdpCommand({
            method: "Target.closeTarget",
            params: { targetId: message.params.context }
        });

        bidiClient.sendBidiMessage({
            id: message.id,
            result: {}
        });
    };

    const process_session_status = async function (messageId) {
        bidiClient.sendBidiMessage({
            id: messageId,
            result: { "ready": true, message: "ready" }
        });
    };

    const process_unknown_command = async function (messageId) {
        bidiClient.sendBidiMessage({
            id: messageId,
            "error": "invalid argument",
            "message": "not supported operation"
        });
    };

    const handle_target_attachedToTarget = (message) => {
        targets[message.params.targetInfo.targetId] = message.params.targetInfo;
        bidiClient.sendBidiMessage(
            {
                method: 'browsingContext.contextCreated',
                params: targetToContext(message.params.targetInfo)
            });
    }

    const handle_target_detachedFromTarget = (message) => {
        bidiClient.sendBidiMessage(
            {
                method: 'browsingContext.contextDestroyed',
                params: targetToContext(targets[message.params.targetId])
            });
        delete targets[message.params.targetId];
    }

    const onCdpMessage = function (message) {
        switch (message.method) {
            case "Target.attachedToTarget":
                handle_target_attachedToTarget(message);
                return;
            case "Target.detachedFromTarget":
                handle_target_detachedFromTarget(message);
                return;
        }
    };

    const onBidiMessage = function (message) {
        const messageId = message.id;
        switch (message.method) {
            case 'session.status':
                process_session_status(messageId);
                return;
            case 'browsingContext.getTree':
                process_browsingContext_getTree(messageId);
                return;

            case 'PROTO.browsingContext.createContext':
                process_PROTO_browsingContext_createContext(message);
                return;

            case 'DEBUG.Page.close':
                process_DEBUG_Page_close(message);
                return;

            default:
                process_unknown_command(messageId);
                return;
        }
    }

    cdpClient.setCdpMessageHandler(onCdpMessage);
    bidiClient.setBidiMessageHandler(onBidiMessage);

    await cdpClient.sendCdpCommand({
        method: "Target.setAutoAttach",
        params: {
            autoAttach: true,
            waitForDebuggerOnStart: false,
            flatten: true
        }
    });
};<commit_msg>structure mapper<commit_after>export async function runBidiCommandsProcessor(cdpClient, bidiClient, getCurrentTargetId) {
    const targets = {};

    const getErrorResponse = (commandData, errorCode, errorMessage) => {
        // TODO: this is bizarre per spec. We reparse the payload and
        // extract the ID, regardless of what kind of value it was.
        let commandId = undefined;
        try {
                commandId = commandData.id;
        } catch { }

        return {
            id: commandId,
            error: errorCode,
            message: errorMessage,
            // TODO: optional stacktrace field.
        };
    };

    const respondWithError = (commandData, errorCode, errorMessage) => {
        const errorResponse = getErrorResponse(commandData, errorCode, errorMessage);
        bidiClient.sendBidiMessage(errorResponse);
    };

    const targetToContext = t => ({
        context: t.targetId,
        parent: t.openerId ? t.openerId : null,
        url: t.url
    });

    const process_browsingContext_getTree = async function (params) {
        const cdpTargets = await cdpClient.sendCdpCommand({ method: "Target.getTargets" });
        const contexts = cdpTargets.targetInfos
            // Don't expose any information about the tab with Mapper running.
            .filter(t => t.targetId !== getCurrentTargetId())
            .map(targetToContext);
        return { contexts };
    };

    const process_PROTO_browsingContext_createContext = async function (params) {
        const { targetId } = await cdpClient.sendCdpCommand({
            method: "Target.createTarget",
            params: { url: params.url }
        });
        return targetToContext(targets[targetId]);
    };

    const process_DEBUG_Page_close = async function (params) {
        await cdpClient.sendCdpCommand({
            method: "Target.closeTarget",
            params: { targetId: params.context }
        });
        return {};
    };

    const process_session_status = async function (params) {
        return { "ready": true, message: "ready" };
    };

    const handle_target_attachedToTarget = (message) => {
        targets[message.params.targetInfo.targetId] = message.params.targetInfo;
        bidiClient.sendBidiMessage(
            {
                method: 'browsingContext.contextCreated',
                params: targetToContext(message.params.targetInfo)
            });
    }

    const handle_target_detachedFromTarget = (message) => {
        bidiClient.sendBidiMessage(
            {
                method: 'browsingContext.contextDestroyed',
                params: targetToContext(targets[message.params.targetId])
            });
        delete targets[message.params.targetId];
    }

    const onCdpMessage = function (message) {
        switch (message.method) {
            case "Target.attachedToTarget":
                handle_target_attachedToTarget(message);
                return;
            case "Target.detachedFromTarget":
                handle_target_detachedFromTarget(message);
                return;
        }
    };

    const processCommand = async (commandData) => {
        const response = {};
        response.id = commandData.id;

        switch (commandData.method) {
            case 'session.status':
                return await process_session_status(commandData.params);
            case 'browsingContext.getTree':
                return await process_browsingContext_getTree(commandData.params);

            case 'PROTO.browsingContext.createContext':
                return await process_PROTO_browsingContext_createContext(commandData.params);

            case 'DEBUG.Page.close':
                return await process_DEBUG_Page_close(commandData.params);

            default:
                throw new Error('unknown command');
        }
    };

    const onBidiMessage = async (message) => {
        processCommand(message).then(result => {
            const response = {
                id: message.id,
                result
            };

            bidiClient.sendBidiMessage(response);
        }).catch(e => {
            console.error(e);
            respondWithError(message, "unknown error", e.message);
        });
    }

    cdpClient.setCdpMessageHandler(onCdpMessage);
    bidiClient.setBidiMessageHandler(onBidiMessage);

    await cdpClient.sendCdpCommand({
        method: "Target.setAutoAttach",
        params: {
            autoAttach: true,
            waitForDebuggerOnStart: false,
            flatten: true
        }
    });
};<|endoftext|>


<commit_before>
var React = require('react');
var _ = require('lodash');
var fs = require('fs');
var ejs = require('ejs');

/**
 * Recursive object clone
 *
 * @param     {Object}    obj
 * @return    {Object}
 */
function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  var src = obj.constructor();
  for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      src[key] = deepClone(obj[key]);
    }
  }
  return src;
}

module.exports.setup = function(config, props) {
  /**
   * Configure Asset Factor
   *
   * @type    {Object}
   */
  var AssetFactory = require('./AssetFactory.js')(config);

   /**
   * This object contains methods that return Async.auto objects. Each item has a
   * list of dependencies it requires. Async.auto attempts to run them as many
   * things in parallel as it can.
   *
   * @type    {Object}
   */
  var Workflow = {

    /**
     * Renders a react component.
     *
     * @param     {React}    comp
     * @return    {Async.auto}
     */
    react: function(options) {
      return function(done, results) {
        var html = '';
        try {
          html = React.renderToString(React.createElement(options.component, deepClone(results.props)));
        } catch (err) { // Catch any errors in the front end so they dont' crash the backend
          console.error('ClientError', err);
        } finally {
          done(null, html);
        }
      };
    },

    /**
     * Gets the template
     * @return    {Async.auto}
     */
    template: function(options) {
      return function(done) {
        fs.readFile(options.template || config.render.template, {
          encoding: 'utf8'
        }, function(err, src) {
          if(err) {
            done(err);
            return;
          }

          if(options.minifyHtml || config.render.minifyHtml) {
            // Strip line breaks
            src = src.replace( /[\n\r]+/g, ' ');

            // Strip extra spaces
            src = src.replace( /\s\s+/g, ' ');
          }

          done(null, src);
        });
      };
    },

    /**
     * Read checksums cache file from disk
     *
     * @return    {Async.auto}
     */
    checksums: function(options) {
      return function(done) {
        fs.readFile(options.checksumrc || config.render.checksumrc, {
          encoding: 'utf8'
        }, function(err, src) {
          if (err) {
            done(err);
            return;
          }

          // Parse
          try {
            var checksums = JSON.parse(src);
            done(null, checksums);
          } catch (e) {
            done(e);
          }
        });
      };
    },

    /**
     * Organizes the data for the template
     *
     * @param     {String}    entry    Which js to load
     * @return    {Async.auto}
     */
    payload: function(options) {
      return function(done, results) {
        // Load asset information
        var payload = {
          component: results.component,
          props: JSON.stringify(results.props),
          version: config.version,
          title: options.title,
          env: config.env,
          index: options.index,
          assets: AssetFactory(options.assets, results.checksums).forPayload()
        };
        done(null, payload);
      };
    },

    /**
     * Renders the final html and optimizes it
     * @return    {Async.auto}
   */
    html: function() {
      return function render(done, results) {
        // Render
        var html = ejs.render(results.template, results.payload);

        // Return
        done(null, html);
      };
    }
  };

  return _.extend(Workflow, props);
};
<commit_msg>add more verbose error<commit_after>
var React = require('react');
var _ = require('lodash');
var fs = require('fs');
var ejs = require('ejs');

/**
 * Recursive object clone
 *
 * @param     {Object}    obj
 * @return    {Object}
 */
function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  var src = obj.constructor();
  for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      src[key] = deepClone(obj[key]);
    }
  }
  return src;
}

module.exports.setup = function(config, props) {
  /**
   * Configure Asset Factor
   *
   * @type    {Object}
   */
  var AssetFactory = require('./AssetFactory.js')(config);

   /**
   * This object contains methods that return Async.auto objects. Each item has a
   * list of dependencies it requires. Async.auto attempts to run them as many
   * things in parallel as it can.
   *
   * @type    {Object}
   */
  var Workflow = {

    /**
     * Renders a react component.
     *
     * @param     {React}    comp
     * @return    {Async.auto}
     */
    react: function(options) {
      return function(done, results) {
        var html = '';
        try {
          html = React.renderToString(React.createElement(options.component, deepClone(results.props)));
        } catch (err) { // Catch any errors in the front end so they dont' crash the backend
          console.error('ReactRenderError', err, err.stack);
        } finally {
          done(null, html);
        }
      };
    },

    /**
     * Gets the template
     * @return    {Async.auto}
     */
    template: function(options) {
      return function(done) {
        fs.readFile(options.template || config.render.template, {
          encoding: 'utf8'
        }, function(err, src) {
          if(err) {
            done(err);
            return;
          }

          if(options.minifyHtml || config.render.minifyHtml) {
            // Strip line breaks
            src = src.replace( /[\n\r]+/g, ' ');

            // Strip extra spaces
            src = src.replace( /\s\s+/g, ' ');
          }

          done(null, src);
        });
      };
    },

    /**
     * Read checksums cache file from disk
     *
     * @return    {Async.auto}
     */
    checksums: function(options) {
      return function(done) {
        fs.readFile(options.checksumrc || config.render.checksumrc, {
          encoding: 'utf8'
        }, function(err, src) {
          if (err) {
            done(err);
            return;
          }

          // Parse
          try {
            var checksums = JSON.parse(src);
            done(null, checksums);
          } catch (e) {
            done(e);
          }
        });
      };
    },

    /**
     * Organizes the data for the template
     *
     * @param     {String}    entry    Which js to load
     * @return    {Async.auto}
     */
    payload: function(options) {
      return function(done, results) {
        // Load asset information
        var payload = {
          component: results.component,
          props: JSON.stringify(results.props),
          version: config.version,
          title: options.title,
          env: config.env,
          index: options.index,
          assets: AssetFactory(options.assets, results.checksums).forPayload()
        };
        done(null, payload);
      };
    },

    /**
     * Renders the final html and optimizes it
     * @return    {Async.auto}
   */
    html: function() {
      return function render(done, results) {
        // Render
        var html = ejs.render(results.template, results.payload);

        // Return
        done(null, html);
      };
    }
  };

  return _.extend(Workflow, props);
};
<|endoftext|>


<commit_before>/*
 * This file is part of gorilla-repl. Copyright (C) 2014, Jony Hudson.
 *
 * gorilla-repl is licenced to you under the MIT licence. See the file LICENCE.txt for full details.
 */

// a code segment contains code, and shows the results of running that code.
var codeSegment = function (contents, id) {
    var self = {};
    self.renderTemplate = "code-segment-template";
    self.worksheet = worksheet;
    if (id) self.id = id;
    else self.id = UUID.generate();
    self.type = "code";

    // Segment configuration
    self.liveEvaluationMode = ko.observable(false);

    // Segment UI state
    self.active = ko.observable(false);
    self.errorText = ko.observable("");
    self.consoleText = ko.observable("");
    self.runningIndicator = ko.observable(false);
    self.output = ko.observable("");
    self.warningIndicator = ko.observable(false);
    self.outputVisible = ko.observable(true);

    // The code
    self.content = codemirrorVM(
        self.id,
        contents,
        "text/x-clojure"
    );

    self.getContents = function() {
        return self.content.contents();
    };

    self.clearOutput = function () {
        self.output("");
        self.errorText("");
        self.consoleText("");
    };

    self.handleClick = function () {
        eventBus.trigger("worksheet:segment-clicked", {id: self.id})
    };

    // activation and deactivation - these control whether the segment has the "cursor" outline, and focus
    // the content component.

    // activate the segment. fromTop will be true is the user's focus is coming from above (and so the cursor should
    // be placed at the top), false indicates the focus is coming from below.
    self.activate = function (fromTop) {
        self.active(true);
        if (fromTop) self.content.positionCursorAtContentStart();
        else self.content.positionCursorAtContentEnd();
    };

    self.deactivate = function () {
        self.content.blur();
        self.active(false);
    };

    return self;
};

// a free segment contains markdown
var freeSegment = function (contents, id) {
    var self = {};
    self.renderTemplate = "free-segment-template";
    if (id) self.id = id;
    else self.id = UUID.generate();

    self.type = "free";

    // Segment UI state
    self.active = ko.observable(false);
    self.markupVisible = ko.observable(false);

    // The markup
    self.content = codemirrorVM(
        self.id,
        contents,
        "text/x-markdown"
    );

    // var mdConverter = Markdown.getSanitizingConverter();
    var mdConverter = new Markdown.Converter();

    self.renderedContent = ko.computed(function () {
        return mdConverter.makeHtml(self.content.contents());
    }).extend({throttle: 250});

    self.handleClick = function () {
        eventBus.trigger("worksheet:segment-clicked", {id: self.id})
    };

    // activation and deactivation - these control whether the segment has the "cursor" outline, and focus
    // the content component.

    // activate the segment. fromTop will be true is the user's focus is coming from above (and so the cursor should
    // be placed at the top), false indicates the focus is coming from below.
    self.activate = function (fromTop) {
        self.markupVisible(true);
        self.content.reflow();
        self.active(true);
        if (fromTop) self.content.positionCursorAtContentStart();
        else self.content.positionCursorAtContentEnd();
    };

    self.deactivate = function () {
        self.content.blur();
        self.markupVisible(false);
        self.active(false);

    };

    return self;
};<commit_msg>Fix bug from refactoring getCode.<commit_after>/*
 * This file is part of gorilla-repl. Copyright (C) 2014, Jony Hudson.
 *
 * gorilla-repl is licenced to you under the MIT licence. See the file LICENCE.txt for full details.
 */

// a code segment contains code, and shows the results of running that code.
var codeSegment = function (contents, id) {
    var self = {};
    self.renderTemplate = "code-segment-template";
    self.worksheet = worksheet;
    if (id) self.id = id;
    else self.id = UUID.generate();
    self.type = "code";

    // Segment configuration
    self.liveEvaluationMode = ko.observable(false);

    // Segment UI state
    self.active = ko.observable(false);
    self.errorText = ko.observable("");
    self.consoleText = ko.observable("");
    self.runningIndicator = ko.observable(false);
    self.output = ko.observable("");
    self.warningIndicator = ko.observable(false);
    self.outputVisible = ko.observable(true);

    // The code
    self.content = codemirrorVM(
        self.id,
        contents,
        "text/x-clojure"
    );

    self.getContents = function() {
        return self.content.contents();
    };

    self.clearOutput = function () {
        self.output("");
        self.errorText("");
        self.consoleText("");
    };

    self.handleClick = function () {
        eventBus.trigger("worksheet:segment-clicked", {id: self.id})
    };

    // activation and deactivation - these control whether the segment has the "cursor" outline, and focus
    // the content component.

    // activate the segment. fromTop will be true is the user's focus is coming from above (and so the cursor should
    // be placed at the top), false indicates the focus is coming from below.
    self.activate = function (fromTop) {
        self.active(true);
        if (fromTop) self.content.positionCursorAtContentStart();
        else self.content.positionCursorAtContentEnd();
    };

    self.deactivate = function () {
        self.content.blur();
        self.active(false);
    };

    return self;
};

// a free segment contains markdown
var freeSegment = function (contents, id) {
    var self = {};
    self.renderTemplate = "free-segment-template";
    if (id) self.id = id;
    else self.id = UUID.generate();

    self.type = "free";

    // Segment UI state
    self.active = ko.observable(false);
    self.markupVisible = ko.observable(false);

    // The markup
    self.content = codemirrorVM(
        self.id,
        contents,
        "text/x-markdown"
    );

    self.getContents = function() {
        return self.content.contents();
    };

    // var mdConverter = Markdown.getSanitizingConverter();
    var mdConverter = new Markdown.Converter();

    self.renderedContent = ko.computed(function () {
        return mdConverter.makeHtml(self.content.contents());
    }).extend({throttle: 250});

    self.handleClick = function () {
        eventBus.trigger("worksheet:segment-clicked", {id: self.id})
    };

    // activation and deactivation - these control whether the segment has the "cursor" outline, and focus
    // the content component.

    // activate the segment. fromTop will be true is the user's focus is coming from above (and so the cursor should
    // be placed at the top), false indicates the focus is coming from below.
    self.activate = function (fromTop) {
        self.markupVisible(true);
        self.content.reflow();
        self.active(true);
        if (fromTop) self.content.positionCursorAtContentStart();
        else self.content.positionCursorAtContentEnd();
    };

    self.deactivate = function () {
        self.content.blur();
        self.markupVisible(false);
        self.active(false);

    };

    return self;
};<|endoftext|>


<commit_before>/*
 * Analyze Controller.
 * This manages all actions executed from metrics explorer.
 */

define(['../../helpers/chart-helper'], function (chartHelper) {

  // Used for local storage, which is used to store our metrics selection.
  var STORED_APP_NAME = 'continuuity-analyze';

  // Used to query for available element types from REST.
  var AVAILABLE_TYPES = ['apps', 'streams', 'flows', 'mapreduce', 'datasets', 'procedures'];

  var Controller = Em.Controller.extend(Em.Evented, {

    elementModels: [],

    // Holds available element models.
    elementsCache: [],

    // Holds a per-type cache of available metrics.
    metricsCache: Em.Object.create(),

    // Holds the currently selected metrics.
    selected: Em.ArrayProxy.create({ content: [] }),

    // Holds temporary information from the 'Add Metric' form.
    configuring: Em.Object.extend({
      noSelection: function () {
        return this.get('element.name') === 'Elements' ||
          this.get('metric.name') === 'Metric Names';
      }.property('element', 'metric'),
      element: {
        name: 'Elements'
      },
      metric: {
        name: 'Metric Names'
      }
    }),

    init: function () {

      /*
       * Only 'extend' allows computed properties, as above.
       * Therefore we create / construct here.
       */
      this.set('configuring', this.get('configuring').create());

    },

    load: function (id) {

      var self = this;

      this.set('selected', Em.ArrayProxy.create({ content: [] }));

      /*
       * Prepopulate metrics selection from Local Storage if available.
       */
      if (window.localStorage) {

        var saved = localStorage.getItem(STORED_APP_NAME);
        if (saved) {
          this.set('selected.content', JSON.parse(saved).content);
        }

      }

      function findElement(type, id) {

        var models = self.elementModels, i = models.length;
        while (i--) {
          if (models[i].type === type && models[i].id === id) {
            return models[i];
          }
        }
        return null;

      }

      // Needs time to find elements. Move to run loop.
      setTimeout(function () {

        $("#elementSelector").select2({
            containerCssClass: "analyze-configurator-element-select",
            placeholder: "Select Element",
            query: function(query) {

              var data = [];

              $.each(self.elementsCache, function(){

                var children = [];
                $.each(this.children, function () {
                  if(query.term.length === 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
                      children.push({id: this.id, text: this.text });
                  }
                });
                this.children = children;
                if (children.length) {
                  data.push(this);
                }
              });
              query.callback({results: data});

            }
        });
        $("#elementSelector").on('change', function (e) {

          if (e.added) {
            var id = e.added.id.split('|');
            var element = findElement(id[0], id[1]);
            self.selectElement(element);
          }

        });

        function filterMetrics(term, metrics) {

          var results = [];
          $.each(metrics, function () {
            if(term.length === 0 || this.text.toUpperCase().indexOf(term.toUpperCase()) >= 0 ){
                results.push({id: this.id, text: this.text });
            }
          });
          return results;

        }

        function getUserMetrics(model, term, done) {

          var context = model.get('context');
          var metrics = self.get('metricsList');

          self.HTTP.rest('metrics/user' + model.get('context'), function (response, status) {

            if (response.error) {

              Em.debug(response.error);

            } else {

              if (response.result.length) {

                var userMetrics = [], result = response.result, i = result.length;
                while (i--) {

                  var path = '/user' + context + '/' + window.encodeURIComponent(result[i].metric);
                  var j = metrics.length, found = false;

                  while (j--) {
                    if (metrics[j].id === path) {
                      found = true;
                    }
                  }

                  if (!found) {
                    userMetrics.push({
                      id: path,
                      text: result[i].metric
                    });
                  }
                }

                metrics = metrics.concat(userMetrics);
                self.set('metricsList', metrics);
                done({results: filterMetrics(term, metrics)});

              } else {

                done({results: filterMetrics(term, metrics)});

              }
            }
          });
        }

        $("#metricSelector").select2({
            placeholder: "Select Metric",
            query: function(query) {

              var model = self.configuring.element;
              var metrics = self.metricsCache.get(model.type);

              if (metrics) {

                // The element supports user-defined metrics. (Runnable)
                if (model.get('context')) {
                  getUserMetrics(model, query.term, query.callback);

                } else {
                  query.callback({results: filterMetrics(query.term, metrics)});

                }

              } else {

                self.HTTP.rest('metrics', 'system', model.type, function (metrics, status) {

                  var i = metrics.length;
                  while (i--) {
                    metrics[i] = {
                      id: metrics[i].path,
                      text: metrics[i].name
                    };
                  }

                  self.get('metricsCache').set(model.type, metrics);
                  self.set('metricsList', metrics);

                  // The element supports user-defined metrics. (Runnable)
                  if (model.get('context')) {
                    getUserMetrics(model, query.term, query.callback);

                  } else {
                    query.callback({results: filterMetrics(query.term, metrics)});

                  }

                });

              }

            }

        });
        $("#metricSelector").on('change', function (e) {

          if (e.added) {
            self.selectMetric({
              name: e.added.text,
              path: e.added.id
            });
          }

        });

      }, 500);

      function sortByKey (obj) {

        var keys = [];
        var sorted_obj = {};

        for(var key in obj){
            if(obj.hasOwnProperty(key)){
                keys.push(key);
            }
        }
        keys.sort();
        $.each(keys, function(i, key){
            sorted_obj[key] = obj[key];
        });

        return sorted_obj;

      }

      /*
       * Get all available Elements for selection.
       */
      var i = AVAILABLE_TYPES.length;
      var singular = {
        'apps': 'App',
        'streams': 'Stream',
        'flows': 'Flow',
        'mapreduces': 'Mapreduce',
        'datasets': 'Dataset',
        'procedures': 'Procedure'
      };

      // This format is used by the select2 box to render in groups.
      var byType = {};
      var remaining = i;

      while (i--) {
        (function (nextType) {

          self.HTTP.rest(nextType, function (models, status) {

            var i = models.length;
            while (i--) {
              if (C[singular[nextType]]) {
                models[i] = C[singular[nextType]].create(models[i]);
                self.elementModels.push(models[i]);
              }
            }

            $.each(models, function (i, element) {

              var id = element.type + '|' + element.id;

              if (byType[element.type]) {
                byType[element.type].push({
                  id: id,
                  text: element.name
                });
              } else {
                byType[element.type] = [{
                  id: id,
                  text: element.name
                }];
              }

            });

            if (!--remaining) {

              byType = sortByKey(byType);

              for (var type in byType) {
                self.elementsCache.push({
                  text: type + 's',
                  children: byType[type]
                });
              }

            }

          });

        })(AVAILABLE_TYPES[i]);
      }

      this.set('paused', false);

      this.set('interval', setInterval(function () {

        if (!self.get('paused')) {
          self.update();
        }

      }, 1000));

    },

    unload: function () {

      this.set('elementModels', []);
      this.set('elementsCache', []);
      this.set('metricsCache', Em.Object.create());

      clearInterval(this.get('interval'));

      // This is set in the Analyze embeddable.
      C.removeResizeHandler('metrics-explorer');

    },

    colors: ['#fce94f', '#edd400', '#c4a000', '#fcaf3e', '#f57900', '#ce5c00',
    '#e9b96e', '#c17d11', '#8f5902', '#8ae234', '#73d216', '#4e9a06', '#729fcf',
    '#3465a4', '#204a87', '#ad7fa8', '#75507b', '#5c3566', '#ef2929', '#cc0000'],

    update: function () {

      var self = this;
      var urls = [];

      var selected = this.get('selected');
      var start, now = new Date().getTime();

      // Add a two second buffer to make sure we have a full response.
      start = now - ((C.__timeRange + 2) * 1000);
      start = Math.floor(start / 1000);

      this.get('selected').forEach(function (item) {
        urls.push(item.path + '?start=' + start + '&count=' + C.__timeRange);
      });

      function findMetric (path) {
        var i = selected.content.length;
        while (i --) {
          if (path.indexOf(selected.content[i].path) === 0) {
            return selected.content[i];
          }
        }
      }
      if (!Em.isEmpty(urls)) {
        this.HTTP.post('metrics', urls, function (response, status) {

          if (response.result) {

            var s = null, series = [], selected = self.get('selected.content'),
              result = response.result, metric, d;

            for (var i = 0; i < result.length; i ++) {

              if ((metric = findMetric(result[i].path))) {

                s = {
                  name: metric.metric + ' (' + metric.element + ', ' + metric.type + ')',
                  color: metric.color,
                  data: []
                }, d = response.result[i].result.data;

                for (var j = 0; j < d.length; j ++) {
                  s.data.push({
                    x: d[j].time,
                    y: d[j].value
                  });
                }

                series.push(s);

              }

            }
            self.set('series', series);

          }

        });
      }

    }.observes('selected.[]'),

    paused: false,
    pausedLabel: function () {

      return this.get('paused') ? 'Continue' : 'Pause';

    }.property('paused').cacheable(false),
    togglePause: function () {

      this.set('paused', !this.get('paused'));

    },

    showConfigure: function (metric) {

      var index = Math.floor(Math.random() * this.colors.length);

      this.configuring.set('color', this.colors[index]);
      this.configuring.set('element', { name: 'Elements' });
      this.configuring.set('metric', { name: 'Metric Names' });

      $("#elementSelector").select2('val', null);
      $("#metricSelector").select2('val', null);
      $('#analyze-configurator').fadeIn(100);

    },

    hideConfigure: function () {

      $('#analyze-configurator').fadeOut(100);

    },

    selectColor: function (color) {

      this.configuring.set('color', color);

    },

    selectElement: function (model) {

      this.configuring.set('element', model);
      $("#metricSelector").select2("enable", true);

    },

    selectMetric: function (metric) {

      this.configuring.set('metric', metric);

    },

    addToChart: function () {

      var element = this.get('configuring.element');
      var metric = this.get('configuring.metric');
      var color = this.get('configuring.color');

      var path = element.interpolate(metric.path);
      var selected = {
        element: element.name,
        type: element.type,
        metric: metric.name,
        path: path,
        color: color,
        href: element.get('href')
      };

      this.get('selected').pushObject(selected);

      this.saveLocal();
      this.hideConfigure();

    },

    removeFromChart: function (selected) {

      this.get('selected').removeObject(selected);
      this.saveLocal();
      this.hideConfigure();

    },

    /**
     * Saves selection state to localstorage.
     */
    saveLocal: function() {
      localStorage.setItem(STORED_APP_NAME, JSON.stringify(this.get('selected')));
    }

  });

  Controller.reopenClass({
    type: 'Analyze',
    kind: 'Controller'
  });

  return Controller;

});
<commit_msg>ME quickfix (mapreduces)<commit_after>/*
 * Analyze Controller.
 * This manages all actions executed from metrics explorer.
 */

define(['../../helpers/chart-helper'], function (chartHelper) {

  // Used for local storage, which is used to store our metrics selection.
  var STORED_APP_NAME = 'continuuity-analyze';

  // Used to query for available element types from REST.
  var AVAILABLE_TYPES = ['apps', 'streams', 'flows', 'mapreduces', 'datasets', 'procedures'];

  var Controller = Em.Controller.extend(Em.Evented, {

    elementModels: [],

    // Holds available element models.
    elementsCache: [],

    // Holds a per-type cache of available metrics.
    metricsCache: Em.Object.create(),

    // Holds the currently selected metrics.
    selected: Em.ArrayProxy.create({ content: [] }),

    // Holds temporary information from the 'Add Metric' form.
    configuring: Em.Object.extend({
      noSelection: function () {
        return this.get('element.name') === 'Elements' ||
          this.get('metric.name') === 'Metric Names';
      }.property('element', 'metric'),
      element: {
        name: 'Elements'
      },
      metric: {
        name: 'Metric Names'
      }
    }),

    init: function () {

      /*
       * Only 'extend' allows computed properties, as above.
       * Therefore we create / construct here.
       */
      this.set('configuring', this.get('configuring').create());

    },

    load: function (id) {

      var self = this;

      this.set('selected', Em.ArrayProxy.create({ content: [] }));

      /*
       * Prepopulate metrics selection from Local Storage if available.
       */
      if (window.localStorage) {

        var saved = localStorage.getItem(STORED_APP_NAME);
        if (saved) {
          this.set('selected.content', JSON.parse(saved).content);
        }

      }

      function findElement(type, id) {

        var models = self.elementModels, i = models.length;
        while (i--) {
          if (models[i].type === type && models[i].id === id) {
            return models[i];
          }
        }
        return null;

      }

      // Needs time to find elements. Move to run loop.
      setTimeout(function () {

        $("#elementSelector").select2({
            containerCssClass: "analyze-configurator-element-select",
            placeholder: "Select Element",
            query: function(query) {

              var data = [];

              $.each(self.elementsCache, function(){

                var children = [];
                $.each(this.children, function () {
                  if(query.term.length === 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
                      children.push({id: this.id, text: this.text });
                  }
                });
                this.children = children;
                if (children.length) {
                  data.push(this);
                }
              });
              query.callback({results: data});

            }
        });
        $("#elementSelector").on('change', function (e) {

          if (e.added) {
            var id = e.added.id.split('|');
            var element = findElement(id[0], id[1]);
            self.selectElement(element);
          }

        });

        function filterMetrics(term, metrics) {

          var results = [];
          $.each(metrics, function () {
            if(term.length === 0 || this.text.toUpperCase().indexOf(term.toUpperCase()) >= 0 ){
                results.push({id: this.id, text: this.text });
            }
          });
          return results;

        }

        function getUserMetrics(model, term, done) {

          var context = model.get('context');
          var metrics = self.get('metricsList');

          self.HTTP.rest('metrics/user' + model.get('context'), function (response, status) {

            if (response.error) {

              Em.debug(response.error);

            } else {

              if (response.result.length) {

                var userMetrics = [], result = response.result, i = result.length;
                while (i--) {

                  var path = '/user' + context + '/' + window.encodeURIComponent(result[i].metric);
                  var j = metrics.length, found = false;

                  while (j--) {
                    if (metrics[j].id === path) {
                      found = true;
                    }
                  }

                  if (!found) {
                    userMetrics.push({
                      id: path,
                      text: result[i].metric
                    });
                  }
                }

                metrics = metrics.concat(userMetrics);
                self.set('metricsList', metrics);
                done({results: filterMetrics(term, metrics)});

              } else {

                done({results: filterMetrics(term, metrics)});

              }
            }
          });
        }

        $("#metricSelector").select2({
            placeholder: "Select Metric",
            query: function(query) {

              var model = self.configuring.element;
              var metrics = self.metricsCache.get(model.type);

              if (metrics) {

                // The element supports user-defined metrics. (Runnable)
                if (model.get('context')) {
                  getUserMetrics(model, query.term, query.callback);

                } else {
                  query.callback({results: filterMetrics(query.term, metrics)});

                }

              } else {

                self.HTTP.rest('metrics', 'system', model.type, function (metrics, status) {

                  var i = metrics.length;
                  while (i--) {
                    metrics[i] = {
                      id: metrics[i].path,
                      text: metrics[i].name
                    };
                  }

                  self.get('metricsCache').set(model.type, metrics);
                  self.set('metricsList', metrics);

                  // The element supports user-defined metrics. (Runnable)
                  if (model.get('context')) {
                    getUserMetrics(model, query.term, query.callback);

                  } else {
                    query.callback({results: filterMetrics(query.term, metrics)});

                  }

                });

              }

            }

        });
        $("#metricSelector").on('change', function (e) {

          if (e.added) {
            self.selectMetric({
              name: e.added.text,
              path: e.added.id
            });
          }

        });

      }, 500);

      function sortByKey (obj) {

        var keys = [];
        var sorted_obj = {};

        for(var key in obj){
            if(obj.hasOwnProperty(key)){
                keys.push(key);
            }
        }
        keys.sort();
        $.each(keys, function(i, key){
            sorted_obj[key] = obj[key];
        });

        return sorted_obj;

      }

      /*
       * Get all available Elements for selection.
       */
      var i = AVAILABLE_TYPES.length;
      var singular = {
        'apps': 'App',
        'streams': 'Stream',
        'flows': 'Flow',
        'mapreduces': 'Mapreduce',
        'datasets': 'Dataset',
        'procedures': 'Procedure'
      };

      // This format is used by the select2 box to render in groups.
      var byType = {};
      var remaining = i;

      while (i--) {
        (function (nextType) {

          self.HTTP.rest(nextType, function (models, status) {

            var i = models.length;
            while (i--) {
              if (C[singular[nextType]]) {
                models[i] = C[singular[nextType]].create(models[i]);
                self.elementModels.push(models[i]);
              }
            }

            $.each(models, function (i, element) {

              var id = element.type + '|' + element.id;

              if (byType[element.type]) {
                byType[element.type].push({
                  id: id,
                  text: element.name
                });
              } else {
                byType[element.type] = [{
                  id: id,
                  text: element.name
                }];
              }

            });

            if (!--remaining) {

              byType = sortByKey(byType);

              for (var type in byType) {
                self.elementsCache.push({
                  text: type + 's',
                  children: byType[type]
                });
              }

            }

          });

        })(AVAILABLE_TYPES[i]);
      }

      this.set('paused', false);

      this.set('interval', setInterval(function () {

        if (!self.get('paused')) {
          self.update();
        }

      }, 1000));

    },

    unload: function () {

      this.set('elementModels', []);
      this.set('elementsCache', []);
      this.set('metricsCache', Em.Object.create());

      clearInterval(this.get('interval'));

      // This is set in the Analyze embeddable.
      C.removeResizeHandler('metrics-explorer');

    },

    colors: ['#fce94f', '#edd400', '#c4a000', '#fcaf3e', '#f57900', '#ce5c00',
    '#e9b96e', '#c17d11', '#8f5902', '#8ae234', '#73d216', '#4e9a06', '#729fcf',
    '#3465a4', '#204a87', '#ad7fa8', '#75507b', '#5c3566', '#ef2929', '#cc0000'],

    update: function () {

      var self = this;
      var urls = [];

      var selected = this.get('selected');
      var start, now = new Date().getTime();

      // Add a two second buffer to make sure we have a full response.
      start = now - ((C.__timeRange + 2) * 1000);
      start = Math.floor(start / 1000);

      this.get('selected').forEach(function (item) {
        urls.push(item.path + '?start=' + start + '&count=' + C.__timeRange);
      });

      function findMetric (path) {
        var i = selected.content.length;
        while (i --) {
          if (path.indexOf(selected.content[i].path) === 0) {
            return selected.content[i];
          }
        }
      }
      if (!Em.isEmpty(urls)) {
        this.HTTP.post('metrics', urls, function (response, status) {

          if (response.result) {

            var s = null, series = [], selected = self.get('selected.content'),
              result = response.result, metric, d;

            for (var i = 0; i < result.length; i ++) {

              if ((metric = findMetric(result[i].path))) {

                s = {
                  name: metric.metric + ' (' + metric.element + ', ' + metric.type + ')',
                  color: metric.color,
                  data: []
                }, d = response.result[i].result.data;

                for (var j = 0; j < d.length; j ++) {
                  s.data.push({
                    x: d[j].time,
                    y: d[j].value
                  });
                }

                series.push(s);

              }

            }
            self.set('series', series);

          }

        });
      }

    }.observes('selected.[]'),

    paused: false,
    pausedLabel: function () {

      return this.get('paused') ? 'Continue' : 'Pause';

    }.property('paused').cacheable(false),
    togglePause: function () {

      this.set('paused', !this.get('paused'));

    },

    showConfigure: function (metric) {

      var index = Math.floor(Math.random() * this.colors.length);

      this.configuring.set('color', this.colors[index]);
      this.configuring.set('element', { name: 'Elements' });
      this.configuring.set('metric', { name: 'Metric Names' });

      $("#elementSelector").select2('val', null);
      $("#metricSelector").select2('val', null);
      $('#analyze-configurator').fadeIn(100);

    },

    hideConfigure: function () {

      $('#analyze-configurator').fadeOut(100);

    },

    selectColor: function (color) {

      this.configuring.set('color', color);

    },

    selectElement: function (model) {

      this.configuring.set('element', model);
      $("#metricSelector").select2("enable", true);

    },

    selectMetric: function (metric) {

      this.configuring.set('metric', metric);

    },

    addToChart: function () {

      var element = this.get('configuring.element');
      var metric = this.get('configuring.metric');
      var color = this.get('configuring.color');

      var path = element.interpolate(metric.path);
      var selected = {
        element: element.name,
        type: element.type,
        metric: metric.name,
        path: path,
        color: color,
        href: element.get('href')
      };

      this.get('selected').pushObject(selected);

      this.saveLocal();
      this.hideConfigure();

    },

    removeFromChart: function (selected) {

      this.get('selected').removeObject(selected);
      this.saveLocal();
      this.hideConfigure();

    },

    /**
     * Saves selection state to localstorage.
     */
    saveLocal: function() {
      localStorage.setItem(STORED_APP_NAME, JSON.stringify(this.get('selected')));
    }

  });

  Controller.reopenClass({
    type: 'Analyze',
    kind: 'Controller'
  });

  return Controller;

});
<|endoftext|>


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

function convertHarEntriesToRequests (harObject) {
  var requests = [];
  var excludedRequests = [];

  var firstHost = null;

  harObject.log.entries.forEach(function (entry, index) {
    var parsedUrl = url.parse(entry.request.url);
    if (firstHost == null) firstHost = parsedUrl.host;
    if (parsedUrl.host != firstHost) {
      excludedRequests.push({entryIndex: index, reason: 'Ignored', message: 'URL Host does not match first request: ' + parsedUrl.host});
    } else if (parsedUrl.protocol != 'http:') {
      excludedRequests.push({entryIndex: index, reason: 'Unsupported', message: 'Protocol not supported: ' + parsedUrl.protocol});
    } else if (entry.request.httpVersion != 'HTTP/1.0' && entry.request.httpVersion != 'HTTP/1.1') {
      excludedRequests.push({entryIndex: index, reason: 'Unsupported', message: 'HTTP version not supported: ' + entry.request.httpVersion});
    } else if (entry.request.method != 'GET') {
      excludedRequests.push({entryIndex: index, reason: 'Unsupported', message: 'Method not supported: ' + entry.request.method});
    } else {
      var warnings = [];
      var payload = entry.request.method + ' ' + parsedUrl.path + ' ' + entry.request.httpVersion + '\r\n';
      entry.request.headers.forEach(function (header) {
        if (header.name.toLowerCase() == 'connection') {
          warnings.push('Connection request header not supported.');
        } else {
          payload += header.name + ': ' + header.value + '\r\n';
        }
      });
      payload += '\r\n';
      requests.push({entryIndex: index, payload: payload, warnings: warnings});
    }
  });

  return {
    includedRequests: requests,
    excludedRequests: excludedRequests
  };
}

function generateCleanHarText (harObject) {
  return JSON.stringify(harObject, null, '  ');
}

function parseResponse(rawResponse) {
  var lines = rawResponse.split(/\r\n/);
  if (lines.length == 0) return null;
  var responseLine = lines[0];
  var match = responseLine.match(/^([^\s]+)\s(\d{3})\s*(.*)/);
  if (!match) {
    sails.log.debug('Unexpected response line: ' + responseLine);
    return null;
  }

  var responseObject = {
    protocol: match[1],
    code: match[2],
    comment: match[3],
    headers: []
  };

  var lineIndex = 1;
  while (lineIndex < lines.length) {
    match = lines[lineIndex].match(/^([^:]+):(.*)/);
    if (match) {
      responseObject.headers.push({header: match[1], value: match[2]});
    } else if (lines[lineIndex].length > 0) {
      sails.log.debug('Unexpected header line: ' + lines[lineIndex]);
    }
    lineIndex++;
  }
  // TODO consider multi-line headers

  return responseObject;
}

module.exports = {

  parseHar: function (rawHar, callback) {

    try {
      var parsedHar = JSON.parse(rawHar);
    } catch (ex) {
      return callback('Failed to parse HAR. ' + ex, rawHar);
    }

    return callback(
      null,
      generateCleanHarText(parsedHar),
      convertHarEntriesToRequests(parsedHar)
    );

  },

  correlateResults: function (includedRequests, responses, TODO_varnishlog, callback) {

    var results = includedRequests.map(function (req, index) {
      return {
        request: req,
        response: parseResponse(responses[index])
      };
    });

    return results;
    //callback(null, results);

  }

}<commit_msg>Use the same key for header names in response json as used in HAR<commit_after>var url = require('url');

function convertHarEntriesToRequests (harObject) {
  var requests = [];
  var excludedRequests = [];

  var firstHost = null;

  harObject.log.entries.forEach(function (entry, index) {
    var parsedUrl = url.parse(entry.request.url);
    if (firstHost == null) firstHost = parsedUrl.host;
    if (parsedUrl.host != firstHost) {
      excludedRequests.push({entryIndex: index, reason: 'Ignored', message: 'URL Host does not match first request: ' + parsedUrl.host});
    } else if (parsedUrl.protocol != 'http:') {
      excludedRequests.push({entryIndex: index, reason: 'Unsupported', message: 'Protocol not supported: ' + parsedUrl.protocol});
    } else if (entry.request.httpVersion != 'HTTP/1.0' && entry.request.httpVersion != 'HTTP/1.1') {
      excludedRequests.push({entryIndex: index, reason: 'Unsupported', message: 'HTTP version not supported: ' + entry.request.httpVersion});
    } else if (entry.request.method != 'GET') {
      excludedRequests.push({entryIndex: index, reason: 'Unsupported', message: 'Method not supported: ' + entry.request.method});
    } else {
      var warnings = [];
      var payload = entry.request.method + ' ' + parsedUrl.path + ' ' + entry.request.httpVersion + '\r\n';
      entry.request.headers.forEach(function (header) {
        if (header.name.toLowerCase() == 'connection') {
          warnings.push('Connection request header not supported.');
        } else {
          payload += header.name + ': ' + header.value + '\r\n';
        }
      });
      payload += '\r\n';
      requests.push({entryIndex: index, payload: payload, warnings: warnings});
    }
  });

  return {
    includedRequests: requests,
    excludedRequests: excludedRequests
  };
}

function generateCleanHarText (harObject) {
  return JSON.stringify(harObject, null, '  ');
}

function parseResponse(rawResponse) {
  var lines = rawResponse.split(/\r\n/);
  if (lines.length == 0) return null;
  var responseLine = lines[0];
  var match = responseLine.match(/^([^\s]+)\s(\d{3})\s*(.*)/);
  if (!match) {
    sails.log.debug('Unexpected response line: ' + responseLine);
    return null;
  }

  var responseObject = {
    protocol: match[1],
    code: match[2],
    comment: match[3],
    headers: []
  };

  var lineIndex = 1;
  while (lineIndex < lines.length) {
    match = lines[lineIndex].match(/^([^:]+):(.*)/);
    if (match) {
      responseObject.headers.push({name: match[1], value: match[2]});
    } else if (lines[lineIndex].length > 0) {
      sails.log.debug('Unexpected header line: ' + lines[lineIndex]);
    }
    lineIndex++;
  }
  // TODO consider multi-line headers

  return responseObject;
}

module.exports = {

  parseHar: function (rawHar, callback) {

    try {
      var parsedHar = JSON.parse(rawHar);
    } catch (ex) {
      return callback('Failed to parse HAR. ' + ex, rawHar);
    }

    return callback(
      null,
      generateCleanHarText(parsedHar),
      convertHarEntriesToRequests(parsedHar)
    );

  },

  correlateResults: function (includedRequests, responses, TODO_varnishlog, callback) {

    var results = includedRequests.map(function (req, index) {
      return {
        request: req,
        response: parseResponse(responses[index])
      };
    });

    return results;
    //callback(null, results);

  }

}<|endoftext|>


<commit_before>/**
 * @module src/GetTranslationDraft
 *
 * Component that display GetTranslationDraft
 * Accepts the following properties:
 *  - source language: Which language you want to convert from
 *  - version : Version of source language
 *  - target language: In which tokens have been translated too
 *  - token words: token words showul be entered in the form of xls
*/

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 TargetLanguages from './TargetLanguages';
import $ from 'jquery';
import GlobalURL from './GlobalURL';
import saveAs from 'save-as'
import Checkbox from './Checkbox';
import booksName1 from './BookName';
var JSZip = require("jszip");
var zip;

var tabData = [
  { name: 'Select Books', isActive: true }
];

class Tabs extends Component {
  render() {
    return (

        {tabData.map(function(tab, i){
          return (
            <Tab key={i} data={tab} isActive={this.props.activeTab === tab} handleClick={this.props.changeTab.bind(this,tab)} />
          );
        }.bind(this))}

    );
  }
}

class Tab extends Component{
  render() {
    return (

        {this.props.data.name}

    );
  }
}

class GetTranslationDraft extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sourcelang:'tam',
      targetlang:'mal',
      version: '',
      revision: '',
      bookName: '',
      books: [],
      uploaded:'Uploading',
      activeTab: tabData[0],
      activeTabValue: ''
    }

      // Upload file specific callback handlers
      this.uploadFile = this.uploadFile.bind(this);
      this.onSelect = this.onSelect.bind(this);
      this.exportToUSFMFile = this.exportToUSFMFile.bind(this);
      this.handleClick = this.handleClick.bind(this);

  }

    handleClick(tab){
    this.setState({
      activeTab: tab
    });
  }

  componentWillMount = () => {
    this.selectedCheckboxes1 = new Set();
  }

  toggleCheckbox1 = label => {
    if (this.selectedCheckboxes1.has(label)) {
      this.selectedCheckboxes1.delete(label);
    } else {
      this.selectedCheckboxes1.add(label);
    }
  }

  createCheckboxes1 = (obj) => (
    Object.keys(booksName1[0]).map(function(v, i){

      return (<Checkbox
            label={booksName1[0][v]}
            handleCheckboxChange={obj.toggleCheckbox1}
            bookCode={v}
    />)
    })

  )

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

  uploadFile(e){
    e.preventDefault();
    global.books = [];

    // eslint-disable-next-line
    for (const books of this.selectedCheckboxes1) {
      global.books = Array.from(this.selectedCheckboxes1);
    }

    var _this = this
    var data = {
            "sourcelang": this.state.sourcelang, "version": this.state.version, "revision": this.state.revision,  "targetlang": this.state.targetlang, "books": global.books
    }

    let accessToken = JSON.parse(window.localStorage.getItem('access_token'))
    $.ajax({
      url: GlobalURL["hostURL"]+"/v1/translations",
      contentType: "application/json; charset=utf-8",
      data : JSON.stringify(data),
      method : "POST",
      headers: {
                "Authorization": "bearer " + JSON.stringify(accessToken['access_token']).slice(1,-1)},
      beforeSend: function () {
          $(".modal").show();
      },
      complete: function () {
          $(".modal").hide();
      },
      success: function (result) {
        result = JSON.parse(result)
         if (result.success !== false) {
          _this.exportToUSFMFile(result)
          _this.setState({message: result.message, uploaded: 'success'})
        }else {
          _this.setState({message: result.message, uploaded: 'failure'})
          }
      },
      error: function (error) {
        _this.setState({uploaded: 'failure'})
      }
    });

  }

  exportToUSFMFile(jsonData) {
    var _this = this;
    zip = new JSZip();
    $.each(jsonData, function(key, value) {
      zip.file(key + '.usfm', value)
    });
    zip.generateAsync({type:"blob"})
      .then(function(content) {
          saveAs(content, _this.state.targetlang + '.zip');
      }, function(err){
         _this.setState({uploaded: 'failure'})
      })
  }

  render() {
    return(

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

Download Translation Draft

                Translation Done Successfully !!!

                {this.state.message}

                <lable className="control-label Concord2">  Source Language  </lable>
                    <FormControl value={this.state.sourcelang} onChange={this.onSelect} name="sourcelang" componentClass="select" placeholder="select">
                      {
                        Object.keys(SourceLanguages[0]).map(function(v, i) {
                          return(<option  key={i} value={v}>{SourceLanguages[0][v]}</option>)
                        })
                      }                    </FormControl>
                 <lable className="control-lable Concord2">  Version  </lable>
                    <input value={this.state.version} onChange={this.onSelect} name="version" type="text"  placeholder="version" className="form-control"/>
                <lable className="control-lable Concord2">  Revision  </lable>
                    <input value={this.state.revision} onChange={this.onSelect} name="revision" type="text" placeholder="revision" className="form-control"/>
                <lable className="control-label Concord2">  Target Language  </lable>
                    <FormControl value={this.state.targetlang} onChange={this.onSelect} name="targetlang" componentClass="select" placeholder="select">
                      {
                        Object.keys(TargetLanguages[0]).map(function(v, i) {
                          return(<option  key={i} value={v}>{TargetLanguages[0][v]}</option>)
                        })
                      }
                    </FormControl>

                <Tabs activeTab={this.state.activeTab}  changeTab={this.handleClick}/>

{this.createCheckboxes1(this)}

                  <button id="btnGet" type="button" className="btn btn-success ConcordButton" onClick={this.uploadFile}>  Download Drafts </button>

          </form>

      );
    }
}

export default GetTranslationDraft;
<commit_msg>Changes in path of images<commit_after>/**
 * @module src/GetTranslationDraft
 *
 * Component that display GetTranslationDraft
 * Accepts the following properties:
 *  - source language: Which language you want to convert from
 *  - version : Version of source language
 *  - target language: In which tokens have been translated too
 *  - token words: token words showul be entered in the form of xls
*/

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 TargetLanguages from './TargetLanguages';
import $ from 'jquery';
import GlobalURL from './GlobalURL';
import saveAs from 'save-as'
import Checkbox from './Checkbox';
import booksName1 from './BookName';
var JSZip = require("jszip");
var zip;

var tabData = [
  { name: 'Select Books', isActive: true }
];

class Tabs extends Component {
  render() {
    return (

        {tabData.map(function(tab, i){
          return (
            <Tab key={i} data={tab} isActive={this.props.activeTab === tab} handleClick={this.props.changeTab.bind(this,tab)} />
          );
        }.bind(this))}

    );
  }
}

class Tab extends Component{
  render() {
    return (

        {this.props.data.name}

    );
  }
}

class GetTranslationDraft extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sourcelang:'tam',
      targetlang:'mal',
      version: '',
      revision: '',
      bookName: '',
      books: [],
      uploaded:'Uploading',
      activeTab: tabData[0],
      activeTabValue: ''
    }

      // Upload file specific callback handlers
      this.uploadFile = this.uploadFile.bind(this);
      this.onSelect = this.onSelect.bind(this);
      this.exportToUSFMFile = this.exportToUSFMFile.bind(this);
      this.handleClick = this.handleClick.bind(this);

  }

    handleClick(tab){
    this.setState({
      activeTab: tab
    });
  }

  componentWillMount = () => {
    this.selectedCheckboxes1 = new Set();
  }

  toggleCheckbox1 = label => {
    if (this.selectedCheckboxes1.has(label)) {
      this.selectedCheckboxes1.delete(label);
    } else {
      this.selectedCheckboxes1.add(label);
    }
  }

  createCheckboxes1 = (obj) => (
    Object.keys(booksName1[0]).map(function(v, i){

      return (<Checkbox
            label={booksName1[0][v]}
            handleCheckboxChange={obj.toggleCheckbox1}
            bookCode={v}
    />)
    })

  )

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

  uploadFile(e){
    e.preventDefault();
    global.books = [];

    // eslint-disable-next-line
    for (const books of this.selectedCheckboxes1) {
      global.books = Array.from(this.selectedCheckboxes1);
    }

    var _this = this
    var data = {
            "sourcelang": this.state.sourcelang, "version": this.state.version, "revision": this.state.revision,  "targetlang": this.state.targetlang, "books": global.books
    }

    let accessToken = JSON.parse(window.localStorage.getItem('access_token'))
    $.ajax({
      url: GlobalURL["hostURL"]+"/v1/translations",
      contentType: "application/json; charset=utf-8",
      data : JSON.stringify(data),
      method : "POST",
      headers: {
                "Authorization": "bearer " + JSON.stringify(accessToken['access_token']).slice(1,-1)},
      beforeSend: function () {
          $(".modal").show();
      },
      complete: function () {
          $(".modal").hide();
      },
      success: function (result) {
        result = JSON.parse(result)
         if (result.success !== false) {
          _this.exportToUSFMFile(result)
          _this.setState({message: result.message, uploaded: 'success'})
        }else {
          _this.setState({message: result.message, uploaded: 'failure'})
          }
      },
      error: function (error) {
        _this.setState({uploaded: 'failure'})
      }
    });

  }

  exportToUSFMFile(jsonData) {
    var _this = this;
    zip = new JSZip();
    $.each(jsonData, function(key, value) {
      zip.file(key + '.usfm', value)
    });
    zip.generateAsync({type:"blob"})
      .then(function(content) {
          saveAs(content, _this.state.targetlang + '.zip');
      }, function(err){
         _this.setState({uploaded: 'failure'})
      })
  }

  render() {
    return(

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

Download Translation Draft

                Translation Done Successfully !!!

                {this.state.message}

                <lable className="control-label Concord2">  Source Language  </lable>
                    <FormControl value={this.state.sourcelang} onChange={this.onSelect} name="sourcelang" componentClass="select" placeholder="select">
                      {
                        Object.keys(SourceLanguages[0]).map(function(v, i) {
                          return(<option  key={i} value={v}>{SourceLanguages[0][v]}</option>)
                        })
                      }                    </FormControl>
                 <lable className="control-lable Concord2">  Version  </lable>
                    <input value={this.state.version} onChange={this.onSelect} name="version" type="text"  placeholder="version" className="form-control"/>
                <lable className="control-lable Concord2">  Revision  </lable>
                    <input value={this.state.revision} onChange={this.onSelect} name="revision" type="text" placeholder="revision" className="form-control"/>
                <lable className="control-label Concord2">  Target Language  </lable>
                    <FormControl value={this.state.targetlang} onChange={this.onSelect} name="targetlang" componentClass="select" placeholder="select">
                      {
                        Object.keys(TargetLanguages[0]).map(function(v, i) {
                          return(<option  key={i} value={v}>{TargetLanguages[0][v]}</option>)
                        })
                      }
                    </FormControl>

                <Tabs activeTab={this.state.activeTab}  changeTab={this.handleClick}/>

{this.createCheckboxes1(this)}

                  <button id="btnGet" type="button" className="btn btn-success ConcordButton" onClick={this.uploadFile}>  Download Drafts </button>

          </form>

      );
    }
}

export default GetTranslationDraft;
<|endoftext|>